Closer/functions/dist/notifications/streakReminder.js

136 lines
6.0 KiB
JavaScript
Raw Permalink Normal View History

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendStreakReminder = void 0;
const admin = __importStar(require("firebase-admin"));
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
const scheduler_1 = require("firebase-functions/v2/scheduler");
const quietHours_1 = require("./quietHours");
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
const push_1 = require("./push");
const time_1 = require("./time");
const log_1 = require("../log");
/**
* Streak reminder an evening "don't lose your streak" nudge.
*
* Schedule: 7 PM America/Chicago. For couples with an active streak (`streakCount > 0`) who have NOT
* recorded a shared action today, nudge each partner to do something together before the day ends.
*
* Gating: per-user `notifStreakReminder` toggle (default on) + quiet hours. Deduped per local day via a
* transactional `couples/{id}/streak_reminders/{dateKey}` marker (scheduled jobs can fire more than once).
*
* Known limitation: the "today" boundary uses America/Chicago (the cron's timezone), not each couple's
* local day true per-timezone firing is a future refinement; quiet-hours suppression keeps a mistimed
* fire from landing at a bad local hour. (Streak day-boundary note in the plan.)
*/
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
exports.sendStreakReminder = (0, scheduler_1.onSchedule)({ schedule: '0 19 * * *', timeZone: 'America/Chicago', timeoutSeconds: 180 }, async () => {
const db = admin.firestore();
const messaging = admin.messaging();
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
const todayKey = (0, time_1.chicagoDateKey)(new Date());
const coupleSnap = await db.collection('couples').where('streakCount', '>', 0).get();
let notified = 0;
let skipped = 0;
const results = await Promise.allSettled(coupleSnap.docs.map(async (coupleDoc) => {
var _a, _b;
const couple = coupleDoc.data();
const streak = ((_a = couple.streakCount) !== null && _a !== void 0 ? _a : 0);
if (streak <= 0) {
skipped++;
return;
}
// Already did a shared action today → the streak is safe, no nudge needed.
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
const lastMs = (0, time_1.toMillis)(couple.lastAnsweredAt);
if (lastMs > 0 && (0, time_1.chicagoDateKey)(new Date(lastMs)) === todayKey) {
skipped++;
return;
}
const userIds = ((_b = couple.userIds) !== null && _b !== void 0 ? _b : []);
if (userIds.length === 0) {
skipped++;
return;
}
// Per-day dedupe (transactional create-if-absent) — idempotent across re-runs.
const markerRef = coupleDoc.ref.collection('streak_reminders').doc(todayKey);
try {
await db.runTransaction(async (tx) => {
const fresh = await tx.get(markerRef);
if (fresh.exists)
throw new Error('already_sent');
tx.set(markerRef, { sentAt: admin.firestore.FieldValue.serverTimestamp(), streak });
});
}
catch (_c) {
skipped++;
return;
}
await Promise.allSettled(userIds.map((userId) => sendStreakNudge(db, messaging, userId, coupleDoc.id, streak, todayKey)));
notified += userIds.length;
}));
results.forEach((r) => {
if (r.status === 'rejected')
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
log_1.logger.warn('[sendStreakReminder] couple failed', { error: String(r.reason) });
});
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
log_1.logger.log(`[sendStreakReminder] scanned ${coupleSnap.size} streak couples; notified ${notified}; skipped ${skipped}`);
});
async function sendStreakNudge(db, messaging, userId, coupleId, streak, dateKey) {
const userDoc = await db.collection('users').doc(userId).get();
const userData = userDoc.data();
// Respect the user's Streak Reminder toggle (default on) and quiet hours.
if ((userData === null || userData === void 0 ? void 0 : userData.notifStreakReminder) === false) {
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
log_1.logger.log(`[sendStreakReminder] skip ${userId} — streak reminder off`);
return;
}
if ((0, quietHours_1.recipientInQuietHours)(userData)) {
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
log_1.logger.log(`[sendStreakReminder] skip ${userId} — quiet hours`);
return;
}
const title = `🔥 Keep your ${streak}-day streak`;
const body = "Answer tonight's question together before the day ends.";
await db
.collection('users')
.doc(userId)
.collection('notification_queue')
.add({
type: 'streak',
title,
body,
read: false,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
});
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
await (0, push_1.sendPushToUser)(db, messaging, userId, {
notification: { title, body },
android: { notification: { channelId: 'reminders' } },
data: { type: 'streak', couple_id: coupleId, reminder_date: dateKey },
refactor(functions): B2 migrate 8 scheduled functions to v2 + harden Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler): sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder, sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export), aggregateOutcomeStats, scheduledOutcomesReminder. Hardening folded in: - Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner), reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no longer abort a whole run. streakReminder / assignDailyQuestion already isolated. - Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s (they iterate all couples); the four fan-out reminders get timeout 180s. - Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the copied send/prune blocks (no plaintext token logging remains here). - Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis), replacing streakReminder's + scheduledOutcomesReminder's per-file copies. assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6. Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1. Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-07 23:50:59 -05:00
}, userData);
}
//# sourceMappingURL=streakReminder.js.map