113 lines
4.9 KiB
TypeScript
113 lines
4.9 KiB
TypeScript
import * as admin from 'firebase-admin'
|
|
import { onCall, HttpsError } from 'firebase-functions/v2/https'
|
|
import { recipientInQuietHours } from './quietHours'
|
|
import { sendPushToUser } from './push'
|
|
import { logger } from '../log'
|
|
|
|
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 = onCall(async (request) => {
|
|
const callerId = request.auth?.uid
|
|
if (!callerId) {
|
|
throw new HttpsError('unauthenticated', 'Must be signed in.')
|
|
}
|
|
if (!request.app) {
|
|
throw new 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 HttpsError('failed-precondition', 'Not in a couple.')
|
|
}
|
|
const coupleDoc = await db.collection('couples').doc(coupleId).get()
|
|
if (!coupleDoc.exists) {
|
|
throw new HttpsError('not-found', 'Couple not found.')
|
|
}
|
|
const userIds = (coupleDoc.data()?.userIds ?? []) as string[]
|
|
const partnerId = userIds.find((id) => id !== callerId)
|
|
if (!partnerId) {
|
|
throw new HttpsError('failed-precondition', 'No partner found.')
|
|
}
|
|
|
|
try {
|
|
// ── 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 as const }
|
|
}
|
|
tx.set(rateLimitRef, { count: count + 1, windowStart, updatedAt: now }, { merge: true })
|
|
return { allowed: true as const }
|
|
})
|
|
if (!throttle.allowed) {
|
|
throw new 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()
|
|
const partnerData = partnerDoc.data()
|
|
if (recipientInQuietHours(partnerData)) {
|
|
logger.log(`[sendThinkingOfYouCallable] ${partnerId} in quiet hours — push suppressed (in-app kept)`)
|
|
return { sent: true }
|
|
}
|
|
|
|
// ── FCM push ─────────────────────────────────────────────────────────────
|
|
await sendPushToUser(
|
|
db,
|
|
admin.messaging(),
|
|
partnerId,
|
|
{
|
|
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 },
|
|
},
|
|
partnerData,
|
|
)
|
|
|
|
logger.log(`[sendThinkingOfYouCallable] sent from ${callerId} to ${partnerId} in couple ${coupleId}`)
|
|
return { sent: true }
|
|
} catch (e) {
|
|
if (e instanceof HttpsError) throw e
|
|
logger.error('[sendThinkingOfYouCallable] failed', { error: String(e) })
|
|
throw new HttpsError('internal', 'Failed to send. Please try again.')
|
|
}
|
|
})
|