Closer/functions/dist/billing/onEntitlementChanged.js

122 lines
5.5 KiB
JavaScript
Raw Normal View History

"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.onEntitlementChanged = void 0;
const admin = __importStar(require("firebase-admin"));
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
const firestore_1 = require("firebase-functions/v2/firestore");
const push_1 = require("../notifications/push");
const idempotency_1 = require("../notifications/idempotency");
const log_1 = require("../log");
/**
* Notifies the OTHER partner when a user GAINS premium, so couple-shared premium unlock isn't silent
* for the non-subscriber. (Future.md: `subscription_entitlement_changed`.)
*
* Path: users/{userId}/entitlements/premium (onWrite)
* Edge-triggered: fires only on the inactiveactive transition, so renewals / repeated writes don't
* re-notify. Skips if the partner already had premium (the couple was already unlocked).
*/
function isActive(data) {
if (!data)
return false;
if (data.premium !== true)
return false;
const expiresAt = data.expiresAt;
if (expiresAt && expiresAt.toMillis() <= Date.now())
return false;
return true;
}
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
exports.onEntitlementChanged = (0, firestore_1.onDocumentWritten)('users/{userId}/entitlements/premium', async (event) => {
var _a, _b, _c, _d;
const { userId } = event.params;
const before = isActive((_a = event.data) === null || _a === void 0 ? void 0 : _a.before.data());
const after = isActive((_b = event.data) === null || _b === void 0 ? void 0 : _b.after.data());
if (before || !after)
return; // only a genuine inactive→active gain
const db = admin.firestore();
// Resolve this user's couple + partner.
const coupleSnap = await db
.collection('couples')
.where('userIds', 'array-contains', userId)
.limit(1)
.get();
if (coupleSnap.empty) {
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
log_1.logger.log(`[onEntitlementChanged] no couple for ${userId}`);
return;
}
const coupleDoc = coupleSnap.docs[0];
const coupleId = coupleDoc.id;
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
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 !== userId);
if (!partnerId) {
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
log_1.logger.log(`[onEntitlementChanged] no partner for ${userId} in ${coupleId}`);
return;
}
// If the partner already has premium the couple was already unlocked — nothing new to announce.
const partnerEnt = await db.doc(`users/${partnerId}/entitlements/premium`).get();
if (isActive(partnerEnt.data())) {
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
log_1.logger.log(`[onEntitlementChanged] partner ${partnerId} already premium; skip`);
return;
}
// Dedupe redelivery of this onWrite (at-least-once) so the partner isn't double-notified and
// the in-app record isn't duplicated.
if (!(await (0, idempotency_1.claimOnce)((0, idempotency_1.notifMark)(db, coupleId, `entitlement-${userId}`)))) {
log_1.logger.log(`[onEntitlementChanged] already announced premium for ${userId}; skip`);
return;
}
// displayName is E2EE in users/{uid}, so use a generic label (this copy is stored server-side in
// notification_queue + the push, neither of which can decrypt).
const payload = {
type: 'subscription_entitlement_changed',
title: 'Premium unlocked ✨',
body: 'Your partner upgraded — you both have Premium now.',
};
// In-app record for the partner.
await db
.collection('users')
.doc(partnerId)
.collection('notification_queue')
.add(Object.assign(Object.assign({}, payload), { read: false, createdAt: admin.firestore.FieldValue.serverTimestamp() }));
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
const res = await (0, push_1.sendPushToUser)(db, admin.messaging(), partnerId, {
notification: { title: payload.title, body: payload.body },
android: { notification: { channelId: 'partner_activity' } },
data: { type: payload.type, couple_id: coupleId },
});
refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore (onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data, change.before/after→event.data.before/after. Region stays us-central1 (global option). Hardening folded in (all reuse in-repo patterns): - Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer logged in plaintext anywhere here (redacted inside push.ts). - console.* → firebase-functions/logger (structured). - Idempotency: new claimOnce() (atomic create-if-absent marker under couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged, onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/ onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved. - onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker would wrongly block legitimate re-requests (restore docs are deleted+recreated by design). Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept); the trigger split and read reorder are deferred to B6 as separate commits. Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump deferred to B6). dist rebuilt. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
if (res.sent === 0 && res.failed === 0) {
log_1.logger.log(`[onEntitlementChanged] no FCM tokens for ${partnerId}`);
return;
}
log_1.logger.log(`[onEntitlementChanged] notified ${partnerId} of couple premium (${coupleId})`);
});
//# sourceMappingURL=onEntitlementChanged.js.map