180 lines
7.5 KiB
JavaScript
180 lines
7.5 KiB
JavaScript
"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 functions = __importStar(require("firebase-functions"));
|
|
const admin = __importStar(require("firebase-admin"));
|
|
const quietHours_1 = require("./quietHours");
|
|
const pruneTokens_1 = require("./pruneTokens");
|
|
/**
|
|
* 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.)
|
|
*/
|
|
exports.sendStreakReminder = functions.pubsub
|
|
.schedule('0 19 * * *')
|
|
.timeZone('America/Chicago')
|
|
.onRun(async () => {
|
|
const db = admin.firestore();
|
|
const messaging = admin.messaging();
|
|
const todayKey = 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.
|
|
const lastMs = toMillis(couple.lastAnsweredAt);
|
|
if (lastMs > 0 && 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')
|
|
console.warn('[sendStreakReminder] couple failed:', r.reason);
|
|
});
|
|
console.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) {
|
|
console.log(`[sendStreakReminder] skip ${userId} — streak reminder off`);
|
|
return;
|
|
}
|
|
if ((0, quietHours_1.recipientInQuietHours)(userData)) {
|
|
console.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(),
|
|
});
|
|
const tokens = await getUserTokens(db, userId, userData);
|
|
if (tokens.length === 0)
|
|
return;
|
|
const sendResults = await Promise.allSettled(tokens.map((token) => messaging.send({
|
|
token,
|
|
notification: { title, body },
|
|
android: { notification: { channelId: 'reminders' } },
|
|
data: { type: 'streak', couple_id: coupleId, reminder_date: dateKey },
|
|
})));
|
|
sendResults.forEach((result, i) => {
|
|
if (result.status === 'rejected') {
|
|
console.warn(`[sendStreakReminder] FCM failed for token ${tokens[i]}:`, result.reason);
|
|
}
|
|
});
|
|
await (0, pruneTokens_1.pruneDeadTokens)(db, userId, tokens, sendResults);
|
|
}
|
|
/** YYYY-MM-DD for the given instant in America/Chicago (DST-safe; en-CA gives ISO date order). */
|
|
function chicagoDateKey(d) {
|
|
return new Intl.DateTimeFormat('en-CA', {
|
|
timeZone: 'America/Chicago',
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
}).format(d);
|
|
}
|
|
function toMillis(value) {
|
|
if (value instanceof admin.firestore.Timestamp)
|
|
return value.toMillis();
|
|
if (typeof value === 'number')
|
|
return value;
|
|
return 0;
|
|
}
|
|
async function getUserTokens(db, userId, userData) {
|
|
const tokens = [];
|
|
const data = userData !== null && userData !== void 0 ? userData : (await db.collection('users').doc(userId).get()).data();
|
|
const legacyToken = data === null || data === void 0 ? void 0 : data.fcmToken;
|
|
if (typeof legacyToken === 'string' && legacyToken.length > 0) {
|
|
tokens.push(legacyToken);
|
|
}
|
|
const tokenSnap = await db.collection('users').doc(userId).collection('fcmTokens').get();
|
|
tokenSnap.docs.forEach((doc) => {
|
|
var _a;
|
|
const t = (_a = doc.data()) === null || _a === void 0 ? void 0 : _a.token;
|
|
if (typeof t === 'string' && t.length > 0 && !tokens.includes(t)) {
|
|
tokens.push(t);
|
|
}
|
|
});
|
|
return tokens;
|
|
}
|
|
//# sourceMappingURL=streakReminder.js.map
|