Closer/functions/dist/notifications/sendThinkingOfYouCallable.js

145 lines
7.2 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.sendThinkingOfYouCallable = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
const quietHours_1 = require("./quietHours");
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.
*/
exports.sendThinkingOfYouCallable = functions.https.onCall(async (_data, context) => {
var _a, _b, _c, _d, _e;
const callerId = (_a = context.auth) === null || _a === void 0 ? void 0 : _a.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 = (_b = userDoc.data()) === null || _b === void 0 ? void 0 : _b.coupleId;
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 = ((_d = (_c = coupleDoc.data()) === null || _c === void 0 ? void 0 : _c.userIds) !== null && _d !== void 0 ? _d : []);
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;
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 ((0, quietHours_1.recipientInQuietHours)(partnerDoc.data())) {
console.log(`[sendThinkingOfYouCallable] ${partnerId} in quiet hours — push suppressed (in-app kept)`);
return { sent: true };
}
// ── FCM push ─────────────────────────────────────────────────────────────
const tokens = [];
const legacy = (_e = partnerDoc.data()) === null || _e === void 0 ? void 0 : _e.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) => {
var _a;
const t = (_a = d.data()) === null || _a === void 0 ? void 0 : _a.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);
}
});
}
console.log(`[sendThinkingOfYouCallable] sent from ${callerId} to ${partnerId} in couple ${coupleId}`);
return { sent: true };
});
//# sourceMappingURL=sendThinkingOfYouCallable.js.map