Closer/functions/src/notifications/sendThinkingOfYouCallable.ts

124 lines
5.3 KiB
TypeScript
Raw Normal View History

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import { recipientInQuietHours } from './quietHours'
import { pruneDeadTokens } from './pruneTokens'
const THINKING_OF_YOU_MAX_PER_DAY = 10
const THINKING_OF_YOU_WINDOW_MS = 24 * 60 * 60 * 1000 // rolling 24h
/**
* "Thinking of you 💜" a one-tap affectionate nudge from the partner sheet.
*
* Partner-initiated (like the gentle reminder), so it is guarded by a rate limit + quiet hours rather
* than a per-type opt-out:
* - Per-user rolling 24h cap (transaction on `rate_limits/{uid}_thinking_of_you`) so it can't be looped.
* - Quiet hours: during the recipient's window the FCM push is suppressed, but the in-app record is
* still written so the love is waiting when they wake. (Improvement over the gentle reminder.)
*
* Writes a partner-safe `notification_queue` entry (in-app + the "Together" feed) and an FCM push.
*/
export const sendThinkingOfYouCallable = functions.https.onCall(async (_data, context) => {
const callerId = context.auth?.uid
if (!callerId) {
throw new functions.https.HttpsError('unauthenticated', 'Must be signed in.')
}
if (!context.app) {
throw new functions.https.HttpsError('failed-precondition', 'App Check verification required.')
}
const db = admin.firestore()
// ── Resolve couple + partner ─────────────────────────────────────────────
const userDoc = await db.collection('users').doc(callerId).get()
const coupleId = userDoc.data()?.coupleId as string | undefined
if (!coupleId) {
throw new functions.https.HttpsError('failed-precondition', 'Not in a couple.')
}
const coupleDoc = await db.collection('couples').doc(coupleId).get()
if (!coupleDoc.exists) {
throw new functions.https.HttpsError('not-found', 'Couple not found.')
}
const userIds = (coupleDoc.data()?.userIds ?? []) as string[]
const partnerId = userIds.find((id) => id !== callerId)
if (!partnerId) {
throw new functions.https.HttpsError('failed-precondition', 'No partner found.')
}
// ── Per-user rolling rate limit (transactional) ──────────────────────────
const now = admin.firestore.Timestamp.now()
const rateLimitRef = db.collection('rate_limits').doc(`${callerId}_thinking_of_you`)
const throttle = await db.runTransaction(async (tx) => {
const snap = await tx.get(rateLimitRef)
const data = snap.data()
let windowStart = now
let count = 0
if (snap.exists && data) {
windowStart = data.windowStart as admin.firestore.Timestamp
count = typeof data.count === 'number' ? data.count : 0
if (now.toMillis() - windowStart.toMillis() >= THINKING_OF_YOU_WINDOW_MS) {
windowStart = now
count = 0
}
}
if (count >= THINKING_OF_YOU_MAX_PER_DAY) {
return { allowed: false }
}
tx.set(rateLimitRef, { count: count + 1, windowStart, updatedAt: now }, { merge: true })
return { allowed: true }
})
if (!throttle.allowed) {
throw new functions.https.HttpsError(
'resource-exhausted',
"You've sent a few already — give it a moment."
)
}
// ── In-app record (always — shows in-app + the Together feed) ────────────
await db.collection('users').doc(partnerId).collection('notification_queue').add({
type: 'thinking_of_you',
title: 'Your partner is thinking of you 💜',
body: 'Tap to send one back.',
read: false,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
})
// ── Quiet hours: keep the in-app record, suppress the disruptive push ─────
const partnerDoc = await db.collection('users').doc(partnerId).get()
if (recipientInQuietHours(partnerDoc.data())) {
console.log(`[sendThinkingOfYouCallable] ${partnerId} in quiet hours — push suppressed (in-app kept)`)
return { sent: true }
}
// ── FCM push ─────────────────────────────────────────────────────────────
const tokens: string[] = []
const legacy = partnerDoc.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) {
const results = await Promise.allSettled(
tokens.map((token) =>
admin.messaging().send({
token,
notification: { title: 'Your partner is thinking of you 💜', body: 'Tap to send one back.' },
android: { notification: { channelId: 'partner_activity' } }, // E-OBS
data: { type: 'thinking_of_you', couple_id: coupleId },
})
)
)
results.forEach((r, i) => {
if (r.status === 'rejected') {
console.warn(`[sendThinkingOfYouCallable] FCM failed for token ${tokens[i]}:`, r.reason)
}
})
await pruneDeadTokens(db, partnerId, tokens, results)
}
console.log(`[sendThinkingOfYouCallable] sent from ${callerId} to ${partnerId} in couple ${coupleId}`)
return { sent: true }
})