feat(notif): add onAnswerRevealed cloud function — notify partner when answers are opened

This commit is contained in:
null 2026-06-26 12:40:36 -05:00
parent fe104b4a41
commit 8b4c5ba005
6 changed files with 229 additions and 2 deletions

View File

@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.onGameSessionUpdate = exports.onUserDelete = exports.scheduledOutcomesReminder = exports.submitOutcomeCallable = exports.createInviteCallable = exports.acceptInviteCallable = exports.leaveCoupleCallable = exports.onCoupleLeave = exports.onMessageWritten = exports.onAnswerWritten = exports.assignDailyQuestionCallable = exports.assignDailyQuestion = exports.notifyOnDateMatch = exports.checkDeviceIntegrity = exports.sendReengagementReminder = exports.sendDailyQuestionProactiveReminder = exports.unlockDueMemoryCapsules = exports.sendChallengeDayReminders = exports.sendGentleReminderCallable = exports.sendPartnerAnsweredNotification = exports.sendDailyQuestionReminder = exports.syncEntitlement = exports.revenueCatWebhook = void 0;
exports.onGameSessionUpdate = exports.onUserDelete = exports.scheduledOutcomesReminder = exports.submitOutcomeCallable = exports.createInviteCallable = exports.acceptInviteCallable = exports.leaveCoupleCallable = exports.onCoupleLeave = exports.onMessageWritten = exports.onAnswerRevealed = exports.onAnswerWritten = exports.assignDailyQuestionCallable = exports.assignDailyQuestion = exports.notifyOnDateMatch = exports.checkDeviceIntegrity = exports.sendReengagementReminder = exports.sendDailyQuestionProactiveReminder = exports.unlockDueMemoryCapsules = exports.sendChallengeDayReminders = exports.sendGentleReminderCallable = exports.sendPartnerAnsweredNotification = exports.sendDailyQuestionReminder = exports.syncEntitlement = exports.revenueCatWebhook = void 0;
const admin = __importStar(require("firebase-admin"));
// Initialize the Admin SDK once for every function in this codebase.
// Handlers call admin.firestore()/messaging() lazily at invocation time, so a
@ -66,6 +66,8 @@ Object.defineProperty(exports, "assignDailyQuestion", { enumerable: true, get: f
Object.defineProperty(exports, "assignDailyQuestionCallable", { enumerable: true, get: function () { return assignDailyQuestion_1.assignDailyQuestionCallable; } });
var onAnswerWritten_1 = require("./questions/onAnswerWritten");
Object.defineProperty(exports, "onAnswerWritten", { enumerable: true, get: function () { return onAnswerWritten_1.onAnswerWritten; } });
var onAnswerRevealed_1 = require("./questions/onAnswerRevealed");
Object.defineProperty(exports, "onAnswerRevealed", { enumerable: true, get: function () { return onAnswerRevealed_1.onAnswerRevealed; } });
var onMessageWritten_1 = require("./questions/onMessageWritten");
Object.defineProperty(exports, "onMessageWritten", { enumerable: true, get: function () { return onMessageWritten_1.onMessageWritten; } });
var onCoupleLeave_1 = require("./couples/onCoupleLeave");

View File

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAuC;AAEvC,qEAAqE;AACrE,8EAA8E;AAC9E,gFAAgF;AAChF,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;IAC5B,KAAK,CAAC,aAAa,EAAE,CAAA;AACvB,CAAC;AAED,iEAA+D;AAAtD,sHAAA,iBAAiB,OAAA;AAC1B,6DAA2D;AAAlD,kHAAA,eAAe,OAAA;AACxB,uDAGkC;AAFhC,sHAAA,yBAAyB,OAAA;AACzB,4HAAA,+BAA+B,OAAA;AAEjC,yFAAuF;AAA9E,wIAAA,0BAA0B,OAAA;AACnC,+DAGsC;AAFpC,0HAAA,yBAAyB,OAAA;AACzB,wHAAA,uBAAuB,OAAA;AAEzB,+EAA0F;AAAjF,2IAAA,kCAAkC,OAAA;AAC3C,6DAAuE;AAA9D,wHAAA,wBAAwB,OAAA;AACjC,wEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,2DAA2D;AAAlD,oHAAA,iBAAiB,OAAA;AAC1B,uEAGwC;AAFtC,0HAAA,mBAAmB,OAAA;AACnB,kIAAA,2BAA2B,OAAA;AAE7B,+DAA6D;AAApD,kHAAA,eAAe,OAAA;AACxB,iEAA+D;AAAt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,+DAA6D;AAApD,kHAAA,eAAe,OAAA;AACxB,iEAA+D;AAAtD,oHAAA,gBAAgB,OAAA;AACzB,iEAA+D;AAAtD,oHAAA,gBAAgB,OAAA;AACzB,yDAAuD;AAA9C,8GAAA,aAAa,OAAA;AACtB,qEAAmE;AAA1D,0HAAA,mBAAmB,OAAA;AAC5B,uEAAqE;AAA5D,4HAAA,oBAAoB,OAAA;AAC7B,uEAAqE;AAA5D,4HAAA,oBAAoB,OAAA;AAC7B,yEAAuE;AAA9D,8HAAA,qBAAqB,OAAA;AAC9B,iFAA+E;AAAtE,sIAAA,yBAAyB,OAAA;AAClC,qDAAmD;AAA1C,4GAAA,YAAY,OAAA;AACrB,mEAAiE;AAAxD,0HAAA,mBAAmB,OAAA;AAE5B,oFAAoF;AACpF,uEAAuE;AACvE,iFAAiF;AACjF,0DAA0D"}

View File

@ -0,0 +1,119 @@
"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.onAnswerRevealed = void 0;
const functions = __importStar(require("firebase-functions"));
const admin = __importStar(require("firebase-admin"));
/**
* Firestore trigger: when one partner OPENS (reveals) the shared answers i.e. their own
* daily answer doc flips isRevealed false true notify the other partner that they've
* looked, so the pair stays in sync ("[Name] just opened your answers").
*
* Path: couples/{coupleId}/daily_question/{date}/answers/{userId}
*/
exports.onAnswerRevealed = functions.firestore
.document('couples/{coupleId}/daily_question/{date}/answers/{userId}')
.onUpdate(async (change, context) => {
var _a, _b, _c, _d, _e, _f;
const { coupleId, date, userId } = context.params;
const before = change.before.data();
const after = change.after.data();
// Only fire on the false → true reveal transition.
if (before.isRevealed === true || after.isRevealed !== true)
return;
const db = admin.firestore();
const coupleDoc = await db.collection('couples').doc(coupleId).get();
if (!coupleDoc.exists) {
console.warn(`[onAnswerRevealed] couple ${coupleId} not found`);
return;
}
const userIds = ((_b = (_a = coupleDoc.data()) === null || _a === void 0 ? void 0 : _a.userIds) !== null && _b !== void 0 ? _b : []);
if (!userIds.includes(userId)) {
console.warn(`[onAnswerRevealed] revealer ${userId} not a member of ${coupleId}`);
return;
}
const partnerId = userIds.find((uid) => uid !== userId);
if (!partnerId) {
console.warn(`[onAnswerRevealed] no partner for couple ${coupleId}`);
return;
}
// Partner FCM tokens (legacy field + multi-device subcollection).
const tokens = [];
const partnerUserDoc = await db.collection('users').doc(partnerId).get();
if (partnerUserDoc.exists) {
const legacyToken = (_c = partnerUserDoc.data()) === null || _c === void 0 ? void 0 : _c.fcmToken;
if (typeof legacyToken === 'string' && legacyToken.length > 0)
tokens.push(legacyToken);
}
const tokenSnapshot = await db.collection('users').doc(partnerId).collection('fcmTokens').get();
tokenSnapshot.docs.forEach((doc) => {
var _a;
const t = (_a = doc.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) {
console.log(`[onAnswerRevealed] no FCM tokens for partner ${partnerId}`);
return;
}
// Respect the same partner-activity opt-out as the answered ping.
if (((_d = partnerUserDoc.data()) === null || _d === void 0 ? void 0 : _d.notifPartnerAnswered) === false) {
console.log(`[onAnswerRevealed] partner ${partnerId} has partner-activity notifications off`);
return;
}
const questionId = typeof after.questionId === 'string' ? after.questionId : '';
const revealerDoc = await db.collection('users').doc(userId).get();
const revealerName = ((_e = revealerDoc.data()) === null || _e === void 0 ? void 0 : _e.displayName) || 'Your partner';
const revealerAvatar = (_f = revealerDoc.data()) === null || _f === void 0 ? void 0 : _f.photoUrl;
const payload = {
notification: {
title: `${revealerName} opened your answers`,
body: 'Open to see what you each said.',
},
data: Object.assign({ type: 'partner_opened_answer', couple_id: coupleId, question_id: questionId, date }, (typeof revealerAvatar === 'string' && revealerAvatar.length > 0
? { sender_avatar_url: revealerAvatar }
: {})),
};
const sendResults = await Promise.allSettled(tokens.map((token) => admin.messaging().send(Object.assign(Object.assign({}, payload), { token, android: { notification: { channelId: 'partner_activity' } } }))));
const failures = [];
sendResults.forEach((r, i) => {
if (r.status === 'rejected')
failures.push(`${tokens[i]}: ${String(r.reason)}`);
});
if (failures.length > 0)
console.error('[onAnswerRevealed] some notifications failed:', failures);
console.log(`[onAnswerRevealed] notified ${partnerId} that ${userId} opened couple ${coupleId}`);
});
//# sourceMappingURL=onAnswerRevealed.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"onAnswerRevealed.js","sourceRoot":"","sources":["../../src/questions/onAnswerRevealed.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAA+C;AAC/C,sDAAuC;AAEvC;;;;;;GAMG;AACU,QAAA,gBAAgB,GAAG,SAAS,CAAC,SAAS;KAChD,QAAQ,CAAC,2DAA2D,CAAC;KACrE,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;;IAClC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MA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AAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,QAAQ,CAAC,CAAA;IAEjG,OAAO,CAAC,GAAG,CAAC,+BAA+B,SAAS,SAAS,MAAM,kBAAkB,QAAQ,EAAE,CAAC,CAAA;AAClG,CAAC,CAAC,CAAA"}

View File

@ -27,6 +27,7 @@ export {
assignDailyQuestionCallable,
} from './questions/assignDailyQuestion'
export { onAnswerWritten } from './questions/onAnswerWritten'
export { onAnswerRevealed } from './questions/onAnswerRevealed'
export { onMessageWritten } from './questions/onMessageWritten'
export { onCoupleLeave } from './couples/onCoupleLeave'
export { leaveCoupleCallable } from './couples/leaveCoupleCallable'

View File

@ -0,0 +1,104 @@
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
/**
* Firestore trigger: when one partner OPENS (reveals) the shared answers i.e. their own
* daily answer doc flips isRevealed false true notify the other partner that they've
* looked, so the pair stays in sync ("[Name] just opened your answers").
*
* Path: couples/{coupleId}/daily_question/{date}/answers/{userId}
*/
export const onAnswerRevealed = functions.firestore
.document('couples/{coupleId}/daily_question/{date}/answers/{userId}')
.onUpdate(async (change, context) => {
const { coupleId, date, userId } = context.params as {
coupleId: string
date: string
userId: string
}
const before = change.before.data() as Partial<Record<string, unknown>>
const after = change.after.data() as Partial<Record<string, unknown>>
// Only fire on the false → true reveal transition.
if (before.isRevealed === true || after.isRevealed !== true) return
const db = admin.firestore()
const coupleDoc = await db.collection('couples').doc(coupleId).get()
if (!coupleDoc.exists) {
console.warn(`[onAnswerRevealed] couple ${coupleId} not found`)
return
}
const userIds = (coupleDoc.data()?.userIds ?? []) as string[]
if (!userIds.includes(userId)) {
console.warn(`[onAnswerRevealed] revealer ${userId} not a member of ${coupleId}`)
return
}
const partnerId = userIds.find((uid) => uid !== userId)
if (!partnerId) {
console.warn(`[onAnswerRevealed] no partner for couple ${coupleId}`)
return
}
// Partner FCM tokens (legacy field + multi-device subcollection).
const tokens: string[] = []
const partnerUserDoc = await db.collection('users').doc(partnerId).get()
if (partnerUserDoc.exists) {
const legacyToken = partnerUserDoc.data()?.fcmToken
if (typeof legacyToken === 'string' && legacyToken.length > 0) tokens.push(legacyToken)
}
const tokenSnapshot = await db.collection('users').doc(partnerId).collection('fcmTokens').get()
tokenSnapshot.docs.forEach((doc) => {
const t = doc.data()?.token
if (typeof t === 'string' && t.length > 0 && !tokens.includes(t)) tokens.push(t)
})
if (tokens.length === 0) {
console.log(`[onAnswerRevealed] no FCM tokens for partner ${partnerId}`)
return
}
// Respect the same partner-activity opt-out as the answered ping.
if (partnerUserDoc.data()?.notifPartnerAnswered === false) {
console.log(`[onAnswerRevealed] partner ${partnerId} has partner-activity notifications off`)
return
}
const questionId = typeof after.questionId === 'string' ? after.questionId : ''
const revealerDoc = await db.collection('users').doc(userId).get()
const revealerName = (revealerDoc.data()?.displayName as string | undefined) || 'Your partner'
const revealerAvatar = revealerDoc.data()?.photoUrl
const payload: admin.messaging.MessagingPayload = {
notification: {
title: `${revealerName} opened your answers`,
body: 'Open to see what you each said.',
},
data: {
type: 'partner_opened_answer',
couple_id: coupleId,
question_id: questionId,
date,
...(typeof revealerAvatar === 'string' && revealerAvatar.length > 0
? { sender_avatar_url: revealerAvatar }
: {}),
},
}
const sendResults = await Promise.allSettled(
tokens.map((token) =>
admin.messaging().send({
...payload,
token,
android: { notification: { channelId: 'partner_activity' } },
} as admin.messaging.Message)
)
)
const failures: string[] = []
sendResults.forEach((r, i) => {
if (r.status === 'rejected') failures.push(`${tokens[i]}: ${String(r.reason)}`)
})
if (failures.length > 0) console.error('[onAnswerRevealed] some notifications failed:', failures)
console.log(`[onAnswerRevealed] notified ${partnerId} that ${userId} opened couple ${coupleId}`)
})