diff --git a/functions/src/dates/onDateReflectionWritten.ts b/functions/src/dates/onDateReflectionWritten.ts new file mode 100644 index 00000000..ee39cf49 --- /dev/null +++ b/functions/src/dates/onDateReflectionWritten.ts @@ -0,0 +1,94 @@ +import * as functions from 'firebase-functions' +import * as admin from 'firebase-admin' +import { recipientInQuietHours } from '../notifications/quietHours' + +/** + * Fires when a partner writes their post-date reflection + * (`couples/{coupleId}/date_reflections/{dateId}/answers/{userId}`). Notifies the OTHER partner — "your + * turn to reflect" if they haven't yet, or "ready to reveal together" if both now have. Without this the + * second partner never learns to reflect and the mutual reveal stalls. Mirrors `onAnswerWritten`: + * generic copy (no decrypted content, no name — the app renders the real name in-app), gated on + * `notifPartnerAnswered` + quiet hours (push suppressed in quiet hours, but the in-app record is kept). + */ +export const onDateReflectionWritten = functions.firestore + .document('couples/{coupleId}/date_reflections/{dateId}/answers/{userId}') + .onCreate(async (_snap, context) => { + const { coupleId, dateId, userId } = context.params as { + coupleId: string + dateId: string + userId: string + } + const db = admin.firestore() + + const coupleDoc = await db.collection('couples').doc(coupleId).get() + if (!coupleDoc.exists) return + const userIds = (coupleDoc.data()?.userIds ?? []) as string[] + if (!userIds.includes(userId)) return + const partnerId = userIds.find((u) => u !== userId) + if (!partnerId) return + + const partnerUserDoc = await db.collection('users').doc(partnerId).get() + // Partner-activity opt-out (default on). + if (partnerUserDoc.data()?.notifPartnerAnswered === false) { + console.log(`[onDateReflectionWritten] ${partnerId} has partner notifications off`) + return + } + + // Did this complete the pair? If the recipient already reflected, both are done → reveal-ready. + const partnerReflection = await db + .collection('couples').doc(coupleId) + .collection('date_reflections').doc(dateId) + .collection('answers').doc(partnerId).get() + const bothReflected = partnerReflection.exists + + const title = bothReflected ? 'Your date reflections are ready ✨' : 'Your partner reflected on your date 💭' + const body = bothReflected ? 'Open to reveal them together.' : 'Add yours to reveal together.' + const type = bothReflected ? 'date_reflection_ready' : 'date_reflection_partner' + + // In-app record (→ Together feed) — written regardless of quiet hours. + await db.collection('users').doc(partnerId).collection('notification_queue').add({ + type, title, body, read: false, createdAt: admin.firestore.FieldValue.serverTimestamp(), + }) + + // Quiet hours: keep the in-app record, suppress the disruptive push. + if (recipientInQuietHours(partnerUserDoc.data())) { + console.log(`[onDateReflectionWritten] ${partnerId} in quiet hours — push suppressed (in-app kept)`) + return + } + + const senderAvatar = (await db.collection('users').doc(userId).get()).data()?.photoUrl + + const tokens: string[] = [] + const legacy = partnerUserDoc.data()?.fcmToken + if (typeof legacy === 'string' && legacy.length > 0) tokens.push(legacy) + const tokenSnap = await db.collection('users').doc(partnerId).collection('fcmTokens').get() + tokenSnap.docs.forEach((d) => { + const t = d.data()?.token + if (typeof t === 'string' && t.length > 0 && !tokens.includes(t)) tokens.push(t) + }) + if (tokens.length === 0) return + + const payload: admin.messaging.MessagingPayload = { + notification: { title, body }, + data: { + type, + couple_id: coupleId, + date_id: dateId, + ...(typeof senderAvatar === 'string' && senderAvatar.length > 0 + ? { sender_avatar_url: senderAvatar } + : {}), + }, + } + const results = await Promise.allSettled( + tokens.map((token) => + admin.messaging().send({ + ...payload, + token, + android: { notification: { channelId: 'partner_activity' } }, // E-OBS + } as admin.messaging.Message) + ) + ) + results.forEach((r, i) => { + if (r.status === 'rejected') console.warn(`[onDateReflectionWritten] FCM failed for ${tokens[i]}:`, r.reason) + }) + })