@simplelayer/graniteer-core 0.0.2 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
@@ -0,0 +1,337 @@
1
+ // Money-path helper for reschedule-booking/index.ts: splits a reschedule's
2
+ // refund into up to TWO separate credit grants so a reschedule can never
3
+ // launder a short-lived credit into a longer-lived one.
4
+ //
5
+ // Two independent, mutually-exclusive credit mechanisms can fund a booking's
6
+ // `credit_applied_cents`:
7
+ // - System A (monthly membership credit): a `credits` ledger row with
8
+ // `booking_id` set directly and entry_type 'hold'/'consume', tied via
9
+ // `period_id` to a `credit_periods` row (create-booking / admin-create-
10
+ // booking's credit_hold/credit_consume — see _shared/adminBookingCredit.ts).
11
+ // This credit is "use it or lose it" for that calendar month and has no
12
+ // `expires_at` of its own — its equivalent expiry is the Pacific-anchored
13
+ // START of the FOLLOWING period_month (period_anchor() of next month),
14
+ // the same boundary the credit system itself uses to define a period's
15
+ // end.
16
+ // - System B (a previously-issued, since-redeemed credit grant): a
17
+ // `credits` row with `redeemed_booking_id` set, entry_type 'grant',
18
+ // already redeemed, carrying its own `expires_at` (how a PRIOR
19
+ // reschedule's own cancellation credit funds a booking — see
20
+ // reschedule-booking/index.ts's own credit-reservation step).
21
+ //
22
+ // A booking is funded by at most one of the two: create-booking / admin-
23
+ // create-booking never touch System B, and reschedule-booking's own credit
24
+ // application never calls credit_hold. Checking System A first and falling
25
+ // back to System B is therefore unambiguous, not a guess.
26
+ //
27
+ // F6 fix, corrected: the first attempt at this fix summed both the cash and
28
+ // credit portions into ONE grant, and capped the WHOLE thing only if it
29
+ // happened to find a System-B entry_type='grant' row. A System-A-funded
30
+ // (monthly membership credit) booking found zero rows there — no error, no
31
+ // log — and silently got the full 1-year grant on the entire charged+credit
32
+ // sum. This module fixes that by (a) querying System A first, and (b)
33
+ // treating "credit_applied_cents > 0 but neither system explains it" as
34
+ // exactly as dangerous as an outright query error.
35
+
36
+ /**
37
+ * Floor applied to a capped credit-funded grant so it's never issued
38
+ * already-dead (or nearly so) just because the ORIGINAL credit it's capped
39
+ * against had already expired by refund/cancellation time. Kyle's call,
40
+ * E10/GATE-0188 follow-up, 2026-09-10.
41
+ */
42
+ export const MIN_CREDIT_GRANT_LIFETIME_DAYS = 30;
43
+
44
+ /** Minimal structural client surface this module needs. */
45
+ export interface RescheduleCreditLookupClient {
46
+ // deno-lint-ignore no-explicit-any
47
+ from(table: string): any;
48
+ // deno-lint-ignore no-explicit-any
49
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: any; error: any }>;
50
+ }
51
+
52
+ /**
53
+ * period_month is always the 1st of a calendar month (DB CHECK
54
+ * credit_periods_period_month_is_first) — pure calendar arithmetic, no
55
+ * timezone ambiguity in computing "the following month" from it.
56
+ */
57
+ export function nextPeriodMonthStr(periodMonthStr: string): string {
58
+ const [y, m] = periodMonthStr.split('-').map((n) => parseInt(n, 10));
59
+ const ny = m === 12 ? y + 1 : y;
60
+ const nm = m === 12 ? 1 : m + 1;
61
+ return `${ny}-${String(nm).padStart(2, '0')}-01`;
62
+ }
63
+
64
+ export type OrigCreditExpiryResult =
65
+ | { exp: Date; source: 'system_a' | 'system_b'; errored: false }
66
+ | { exp: Date; source: 'error' | 'not_found'; errored: true; detail: string };
67
+
68
+ /**
69
+ * Finds the real expiry that must cap a reschedule's credit-funded refund
70
+ * portion, by tracing which of the two credit mechanisms actually funded
71
+ * `bookingId`'s `credit_applied_cents`. See the module doc comment above.
72
+ *
73
+ * Returns `errored: true` whenever the real expiry could not be confirmed —
74
+ * a query failure OR (just as importantly) a *clean, zero-row* result
75
+ * despite the caller already knowing credit_applied_cents > 0. Both failure
76
+ * shapes are treated identically: fall back to `defaultExp`, but tell the
77
+ * caller so it can log at ERROR severity rather than silently over-granting.
78
+ */
79
+ export async function resolveOriginalCreditExpiry(
80
+ admin: RescheduleCreditLookupClient,
81
+ bookingId: string,
82
+ defaultExp: Date,
83
+ ): Promise<OrigCreditExpiryResult> {
84
+ try {
85
+ // System A: monthly membership credit, hold/consume rows keyed directly
86
+ // by booking_id (NOT entry_type='grant' — that's System B and was the
87
+ // first attempt's bug).
88
+ const { data: ledgerRows, error: ledgerErr } = await admin
89
+ .from('credits')
90
+ .select('period_id, entry_type, created_at')
91
+ .eq('booking_id', bookingId)
92
+ .in('entry_type', ['hold', 'consume'])
93
+ .order('created_at', { ascending: false })
94
+ .limit(1);
95
+ if (ledgerErr) throw ledgerErr;
96
+ const periodId = ledgerRows && ledgerRows.length > 0 ? ledgerRows[0].period_id : null;
97
+ if (periodId) {
98
+ const { data: periodRow, error: periodErr } = await admin
99
+ .from('credit_periods')
100
+ .select('period_month')
101
+ .eq('id', periodId)
102
+ .maybeSingle();
103
+ if (periodErr) throw periodErr;
104
+ if (periodRow?.period_month) {
105
+ const { data: anchor, error: anchorErr } = await admin.rpc('period_anchor', {
106
+ p_period_month: nextPeriodMonthStr(String(periodRow.period_month)),
107
+ });
108
+ if (anchorErr) throw anchorErr;
109
+ if (anchor) return { exp: new Date(anchor as string), source: 'system_a', errored: false };
110
+ }
111
+ }
112
+
113
+ // System B: a prior reschedule's own cancellation credit, funding this
114
+ // booking via redeemed_booking_id. Deliberately NOT filtered on
115
+ // `redeemed_at IS NOT NULL`: that column is only set once
116
+ // credit_reservation_finalize succeeds, and both its call sites
117
+ // (reschedule-booking's own 4A branch, stripe-webhook) treat a finalize
118
+ // failure as log-only, non-fatal — leaving a PAID booking with
119
+ // redeemed_booking_id set and redeemed_at forever NULL. Requiring
120
+ // redeemed_at here would silently push exactly that booking down to
121
+ // 'not_found' and the full 1-year default, reopening the bug this module
122
+ // exists to close. redeemed_booking_id alone is already the real funding
123
+ // link (credit_reservation_release nulls it on an abandoned reservation,
124
+ // so a released grant can never false-positive here).
125
+ const { data: grantRows, error: grantErr } = await admin
126
+ .from('credits')
127
+ .select('expires_at')
128
+ .eq('redeemed_booking_id', bookingId)
129
+ .eq('entry_type', 'grant')
130
+ .order('expires_at', { ascending: true, nullsFirst: false })
131
+ .limit(1);
132
+ if (grantErr) throw grantErr;
133
+ if (grantRows && grantRows.length > 0) {
134
+ const rawExpiry = grantRows[0].expires_at;
135
+ // A funding row was found either way — this is NOT an error case. Every
136
+ // known producer of a System-B grant sets expires_at, but if one ever
137
+ // doesn't, there's simply nothing to cap against: fall back to the
138
+ // plain 1-year default without flagging it as a lookup failure.
139
+ return {
140
+ exp: rawExpiry ? new Date(rawExpiry) : defaultExp,
141
+ source: 'system_b',
142
+ errored: false,
143
+ };
144
+ }
145
+
146
+ // credit_applied_cents > 0 but neither system explains it — a data-
147
+ // integrity gap, not the ordinary "no credit used" case (the caller only
148
+ // reaches this function when credit_applied_cents > 0). Never let this
149
+ // silently default to the full 1-year grant.
150
+ return {
151
+ exp: defaultExp,
152
+ source: 'not_found',
153
+ errored: true,
154
+ detail: 'no_funding_row_found_for_credit_applied_cents',
155
+ };
156
+ } catch (e) {
157
+ // Supabase/PostgREST errors thrown above (ledgerErr, periodErr, anchorErr,
158
+ // grantErr) are plain {message, code, ...} objects, NOT Error instances —
159
+ // `e instanceof Error` would miss them and collapse the detail down to
160
+ // the useless literal "[object Object]".
161
+ const message = typeof e === 'object' && e !== null && 'message' in e
162
+ ? String((e as { message: unknown }).message)
163
+ : String(e);
164
+ return {
165
+ exp: defaultExp,
166
+ source: 'error',
167
+ errored: true,
168
+ detail: message,
169
+ };
170
+ }
171
+ }
172
+
173
+ export interface RescheduleCreditGrant {
174
+ entry_type: 'grant';
175
+ contact_email: string;
176
+ ghl_contact_id: string | null;
177
+ delta_cents: number;
178
+ reason: string;
179
+ booking_id: string;
180
+ expires_at: string;
181
+ }
182
+
183
+ export interface BuildRescheduleCreditGrantsResult {
184
+ grants: RescheduleCreditGrant[];
185
+ /** True when the credit-portion expiry lookup failed/came up empty — caller should log at ERROR. */
186
+ expiryLookupErrored: boolean;
187
+ expiryLookupDetail?: string;
188
+ expirySource?: string;
189
+ }
190
+
191
+ /**
192
+ * Shared core: splits a refund/credit-issuance into up to two 'grant' rows
193
+ * with caller-supplied reason text for each portion. Used by both the
194
+ * reschedule path (buildRescheduleCreditGrants) and the cancellation paths
195
+ * (buildCancellationCreditGrants) below — the credit-system lookup and
196
+ * splitting logic is identical; only the ledger reason text differs.
197
+ */
198
+ async function buildSplitCreditGrants(
199
+ admin: RescheduleCreditLookupClient,
200
+ opts: {
201
+ bookingId: string;
202
+ contactEmail: string;
203
+ ghlContactId: string | null;
204
+ cashPortionCents: number;
205
+ creditPortionCents: number;
206
+ defaultExp: Date;
207
+ cashReason: string;
208
+ creditReason: (source: string) => string;
209
+ },
210
+ ): Promise<BuildRescheduleCreditGrantsResult> {
211
+ const { bookingId, contactEmail, ghlContactId, cashPortionCents, creditPortionCents, defaultExp, cashReason, creditReason } = opts;
212
+ const emailLower = contactEmail.toLowerCase();
213
+ const grants: RescheduleCreditGrant[] = [];
214
+ let expiryLookupErrored = false;
215
+ let expiryLookupDetail: string | undefined;
216
+ let expirySource: string | undefined;
217
+
218
+ if (cashPortionCents > 0) {
219
+ grants.push({
220
+ entry_type: 'grant',
221
+ contact_email: emailLower,
222
+ ghl_contact_id: ghlContactId,
223
+ delta_cents: cashPortionCents,
224
+ reason: cashReason,
225
+ booking_id: bookingId,
226
+ expires_at: defaultExp.toISOString(),
227
+ });
228
+ }
229
+
230
+ if (creditPortionCents > 0) {
231
+ const resolved = await resolveOriginalCreditExpiry(admin, bookingId, defaultExp);
232
+ expirySource = resolved.source;
233
+ if (resolved.errored) {
234
+ expiryLookupErrored = true;
235
+ expiryLookupDetail = resolved.detail;
236
+ }
237
+ // Floor: never issue a grant that's ALREADY DEAD ON ARRIVAL just because
238
+ // the ORIGINAL credit it's being capped against had already expired by
239
+ // the time of this reschedule/cancellation. Kyle's call (E10/GATE-0188
240
+ // follow-up, 2026-09-10).
241
+ //
242
+ // The trigger is deliberately narrow — `resolved.exp` in the PAST, full
243
+ // stop — not "expiring within the floor window". A System-A (monthly
244
+ // membership credit) cap is USUALLY well under 30 days out (it's the
245
+ // real end of the current calendar month, per period_anchor()); a
246
+ // System-B grant capped at a genuinely short remaining lifetime is
247
+ // equally a correct, intended cap. Flooring either of those up to 30
248
+ // days would silently re-widen the exact laundering gap this module
249
+ // exists to close (an earlier draft of this floor made precisely that
250
+ // mistake — caught on review before merge — and would have let a member
251
+ // ratchet a near-expired credit's lifetime back up to 30 days on every
252
+ // cancel/rebook cycle). Only a TRULY expired original (already in the
253
+ // past) is a stale reference point rather than an intentional cap.
254
+ const finalExp = resolved.exp.getTime() < Date.now()
255
+ ? new Date(Date.now() + MIN_CREDIT_GRANT_LIFETIME_DAYS * 24 * 60 * 60 * 1000)
256
+ : resolved.exp;
257
+ grants.push({
258
+ entry_type: 'grant',
259
+ contact_email: emailLower,
260
+ ghl_contact_id: ghlContactId,
261
+ delta_cents: creditPortionCents,
262
+ reason: creditReason(resolved.source),
263
+ booking_id: bookingId,
264
+ expires_at: finalExp.toISOString(),
265
+ });
266
+ }
267
+
268
+ return { grants, expiryLookupErrored, expiryLookupDetail, expirySource };
269
+ }
270
+
271
+ /**
272
+ * Builds the credits-table INSERT payload for a reschedule's refund: up to
273
+ * two 'grant' rows — a cash-funded portion at the plain 1-year default, and
274
+ * (only if > 0) a credit-funded portion capped at the ORIGINAL credit's own
275
+ * expiry. A zero-cents portion is omitted entirely (a 'grant' row with
276
+ * delta_cents = 0 would violate credits_delta_sign_check).
277
+ */
278
+ export async function buildRescheduleCreditGrants(
279
+ admin: RescheduleCreditLookupClient,
280
+ opts: {
281
+ bookingId: string;
282
+ contactEmail: string;
283
+ ghlContactId: string | null;
284
+ cashPortionCents: number;
285
+ creditPortionCents: number;
286
+ defaultExp: Date;
287
+ },
288
+ ): Promise<BuildRescheduleCreditGrantsResult> {
289
+ return buildSplitCreditGrants(admin, {
290
+ ...opts,
291
+ cashReason: 'Booking rescheduled by customer (cash-funded portion)',
292
+ creditReason: (source) => `Booking rescheduled by customer (credit-funded portion, source=${source})`,
293
+ });
294
+ }
295
+
296
+ /**
297
+ * Same split as buildRescheduleCreditGrants, for the two cancellation paths
298
+ * (manage-booking's customer-initiated cancel, admin-cancel-booking's
299
+ * staff-initiated cancel/refund) — a cancellation credit carries exactly the
300
+ * same laundering risk a reschedule credit does: it must not extend a
301
+ * short-lived credit into a fresh 1-year grant just because it passed
302
+ * through a cancellation instead of a reschedule. See E10/GATE-0188.
303
+ *
304
+ * `reasonOverride`, when given (admin-cancel-booking's optional free-text
305
+ * reason field), replaces the whole default reason string for BOTH portions
306
+ * verbatim — matching this codebase's pre-existing behavior where an admin's
307
+ * stated reason describes the whole cancellation, not which system funded
308
+ * which slice of it.
309
+ */
310
+ export async function buildCancellationCreditGrants(
311
+ admin: RescheduleCreditLookupClient,
312
+ opts: {
313
+ bookingId: string;
314
+ contactEmail: string;
315
+ ghlContactId: string | null;
316
+ cashPortionCents: number;
317
+ creditPortionCents: number;
318
+ defaultExp: Date;
319
+ actor: 'customer' | 'admin';
320
+ reasonOverride?: string | null;
321
+ },
322
+ ): Promise<BuildRescheduleCreditGrantsResult> {
323
+ const actorLabel = opts.actor === 'admin' ? 'Booking cancelled by staff' : 'Booking cancelled by customer';
324
+ const cashReason = opts.reasonOverride || `${actorLabel} — credit issued (cash-funded portion)`;
325
+ const creditReason = (source: string) =>
326
+ opts.reasonOverride || `${actorLabel} — credit issued (credit-funded portion, source=${source})`;
327
+ return buildSplitCreditGrants(admin, {
328
+ bookingId: opts.bookingId,
329
+ contactEmail: opts.contactEmail,
330
+ ghlContactId: opts.ghlContactId,
331
+ cashPortionCents: opts.cashPortionCents,
332
+ creditPortionCents: opts.creditPortionCents,
333
+ defaultExp: opts.defaultExp,
334
+ cashReason,
335
+ creditReason,
336
+ });
337
+ }
@@ -0,0 +1,69 @@
1
+ import { assert, assertEquals, assertFalse } from 'https://deno.land/std@0.224.0/assert/mod.ts';
2
+ import {
3
+ deriveReservationWifiCode,
4
+ isReservationWifiRoom,
5
+ RESERVATION_WIFI_ENABLED_ROOM_SLUGS,
6
+ } from './reservationWifiCode.ts';
7
+
8
+ // Known-answer vectors cross-checked against ftw-middleware's own Python
9
+ // reference (reservation_wifi_code.py's `derive_code`), computed by running
10
+ // that exact algorithm in a scratch script:
11
+ //
12
+ // import hmac, hashlib
13
+ // _ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
14
+ // def derive_code(secret, booking_id):
15
+ // digest = hmac.new(secret.encode("utf-8"), booking_id.encode("utf-8"), hashlib.sha256).digest()
16
+ // num = int.from_bytes(digest[:5], byteorder="big")
17
+ // chars = []
18
+ // for _ in range(7):
19
+ // num, rem = divmod(num, 32)
20
+ // chars.append(_ALPHABET[rem])
21
+ // return "".join(reversed(chars))
22
+ //
23
+ // Output for these three (secret, booking_id) pairs:
24
+ // ("test-signing-secret", "18bc51ff-8d9d-4081-9cc8-4b87a1901e38") -> "RCET8NR"
25
+ // ("another-secret-xyz", "00000000-0000-0000-0000-000000000000") -> "6ZQ52X9"
26
+ // ("k", "payload") -> "HJWXRCP"
27
+ const KNOWN_ANSWERS: Array<[secret: string, bookingId: string, expected: string]> = [
28
+ ['test-signing-secret', '18bc51ff-8d9d-4081-9cc8-4b87a1901e38', 'RCET8NR'],
29
+ ['another-secret-xyz', '00000000-0000-0000-0000-000000000000', '6ZQ52X9'],
30
+ ['k', 'payload', 'HJWXRCP'],
31
+ ];
32
+
33
+ for (const [secret, bookingId, expected] of KNOWN_ANSWERS) {
34
+ Deno.test(`deriveReservationWifiCode: matches Python reference for (${secret}, ${bookingId})`, async () => {
35
+ const code = await deriveReservationWifiCode(secret, bookingId);
36
+ assertEquals(code, expected);
37
+ });
38
+ }
39
+
40
+ Deno.test('deriveReservationWifiCode: output is always 7 characters from the restricted alphabet', async () => {
41
+ const code = await deriveReservationWifiCode('some-secret', 'b1');
42
+ assertEquals(code.length, 7);
43
+ assert(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{7}$/.test(code));
44
+ });
45
+
46
+ Deno.test('deriveReservationWifiCode: different booking ids produce different codes', async () => {
47
+ const a = await deriveReservationWifiCode('same-secret', 'booking-a');
48
+ const b = await deriveReservationWifiCode('same-secret', 'booking-b');
49
+ assert(a !== b);
50
+ });
51
+
52
+ Deno.test('deriveReservationWifiCode: different secrets produce different codes for the same booking', async () => {
53
+ const a = await deriveReservationWifiCode('secret-one', 'booking-x');
54
+ const b = await deriveReservationWifiCode('secret-two', 'booking-x');
55
+ assert(a !== b);
56
+ });
57
+
58
+ Deno.test('isReservationWifiRoom: true only for the 4 enabled hourly meeting room slugs', () => {
59
+ for (const slug of RESERVATION_WIFI_ENABLED_ROOM_SLUGS) {
60
+ assert(isReservationWifiRoom(slug));
61
+ }
62
+ assertFalse(isReservationWifiRoom('executive-office'));
63
+ assertFalse(isReservationWifiRoom('cove'));
64
+ assertFalse(isReservationWifiRoom('midtown'));
65
+ assertFalse(isReservationWifiRoom('commons'));
66
+ assertFalse(isReservationWifiRoom(null));
67
+ assertFalse(isReservationWifiRoom(undefined));
68
+ assertFalse(isReservationWifiRoom(''));
69
+ });
@@ -0,0 +1,81 @@
1
+ // Derived, per-booking guest-WiFi code -- NEVER stored. Computed fresh from
2
+ // RESERVATION_WIFI_CODE_SECRET + the booking's own id, wherever it's needed
3
+ // (confirmation email, manage-booking page). ftw-middleware's
4
+ // reservation_wifi_code.py implements the IDENTICAL algorithm against the
5
+ // same secret and validates guest connections against it live -- this file
6
+ // must keep byte-for-byte parity with that reference or every code shown to
7
+ // a guest here will fail to validate there. See
8
+ // RESERVATION-SCOPED-GUEST-WIFI-DESIGN.md's 2026-09-02 addendum.
9
+ //
10
+ // Because the code is derived, not stored, a cancelled booking's code simply
11
+ // stops being honored on the middleware side (which only trusts currently
12
+ // live/paid bookings) -- there is nothing to invalidate here.
13
+
14
+ // 32 symbols, no 0/O/1/I -- chosen to avoid transcription errors when a guest
15
+ // reads this off a screen and types it into a WiFi captive portal.
16
+ const ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
17
+ const CODE_LENGTH = 7;
18
+ const DIGEST_BYTES_NEEDED = 5;
19
+
20
+ // Rollout scope: the 4 hourly meeting rooms only (room slugs, confirmed
21
+ // against private.room_contract_tier()'s tier-1 list minus 'executive-office',
22
+ // which is a private office, not a bookable meeting room). Do NOT add Cove,
23
+ // Midtown, or Commons here without a deliberate follow-up decision -- this is
24
+ // an explicit allowlist, not a "hourly booking_mode" inference, so adding a
25
+ // future hourly room to `rooms` does NOT silently enable this feature for it.
26
+ export const RESERVATION_WIFI_ENABLED_ROOM_SLUGS = new Set([
27
+ 'gallery',
28
+ 'town-hall',
29
+ 'loft',
30
+ 'nook',
31
+ ]);
32
+
33
+ export function isReservationWifiRoom(slug: string | null | undefined): boolean {
34
+ return typeof slug === 'string' && RESERVATION_WIFI_ENABLED_ROOM_SLUGS.has(slug);
35
+ }
36
+
37
+ /**
38
+ * HMAC-SHA256(secret, booking_id), truncated to the first 5 digest bytes,
39
+ * read as a big-endian integer, then repeatedly divmod-32'd into 7 symbols.
40
+ * The LAST computed remainder is the FIRST output character (the digits come
41
+ * out least-significant-first from repeated divmod, so the char list is
42
+ * built in that order and then reversed) -- this must match
43
+ * reservation_wifi_code.py's `derive_code` exactly:
44
+ *
45
+ * digest = hmac.new(secret, booking_id, sha256).digest()
46
+ * num = int.from_bytes(digest[:5], byteorder="big")
47
+ * chars = []
48
+ * for _ in range(7):
49
+ * num, rem = divmod(num, 32)
50
+ * chars.append(ALPHABET[rem])
51
+ * return "".join(reversed(chars))
52
+ */
53
+ export async function deriveReservationWifiCode(secret: string, bookingId: string): Promise<string> {
54
+ const key = await crypto.subtle.importKey(
55
+ 'raw',
56
+ new TextEncoder().encode(secret),
57
+ { name: 'HMAC', hash: 'SHA-256' },
58
+ false,
59
+ ['sign'],
60
+ );
61
+ const digest = new Uint8Array(
62
+ await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(bookingId)),
63
+ );
64
+
65
+ // Big-endian bytes -> bigint (bigint, not number, so this is exact for the
66
+ // full 5-byte/40-bit range -- Number.MAX_SAFE_INTEGER only covers 53 bits
67
+ // but there's no reason to trust that margin here for something guests
68
+ // depend on).
69
+ let num = 0n;
70
+ for (let i = 0; i < DIGEST_BYTES_NEEDED; i++) {
71
+ num = (num << 8n) | BigInt(digest[i]);
72
+ }
73
+
74
+ const chars: string[] = [];
75
+ for (let i = 0; i < CODE_LENGTH; i++) {
76
+ const rem = num % 32n;
77
+ num = num / 32n;
78
+ chars.push(ALPHABET[Number(rem)]);
79
+ }
80
+ return chars.reverse().join('');
81
+ }
@@ -0,0 +1,167 @@
1
+ import { assert, assertEquals, assertFalse } from 'https://deno.land/std@0.224.0/assert/mod.ts';
2
+ import { isCallAnalyzedEvent, parseCallAnalyzed } from './retellCallAnalyzed.ts';
3
+
4
+ Deno.test('isCallAnalyzedEvent: true for call_analyzed', () => {
5
+ assert(isCallAnalyzedEvent({ event: 'call_analyzed' }));
6
+ });
7
+
8
+ Deno.test('isCallAnalyzedEvent: false for other Retell event types', () => {
9
+ assertFalse(isCallAnalyzedEvent({ event: 'call_started' }));
10
+ assertFalse(isCallAnalyzedEvent({ event: 'call_ended' }));
11
+ });
12
+
13
+ Deno.test('isCallAnalyzedEvent: false for a malformed/eventless payload', () => {
14
+ assertFalse(isCallAnalyzedEvent({}));
15
+ assertFalse(isCallAnalyzedEvent(null));
16
+ assertFalse(isCallAnalyzedEvent('garbage'));
17
+ });
18
+
19
+ Deno.test('parseCallAnalyzed: extracts every custom_analysis_data field', () => {
20
+ const parsed = parseCallAnalyzed({
21
+ event: 'call_analyzed',
22
+ call: {
23
+ call_id: 'call_abc123',
24
+ duration_ms: 45000,
25
+ from_number: '+19165559999',
26
+ call_analysis: {
27
+ custom_analysis_data: {
28
+ call_outcome: 'booking_completed',
29
+ caller_name: 'Jane Doe',
30
+ callback_number: '+19165551234',
31
+ inquiry_reason: 'Asked about day passes',
32
+ had_tool_error: false,
33
+ callback_promised: true,
34
+ },
35
+ },
36
+ },
37
+ });
38
+ assert(parsed);
39
+ assertEquals(parsed.callId, 'call_abc123');
40
+ assertEquals(parsed.callOutcome, 'booking_completed');
41
+ assertEquals(parsed.callerName, 'Jane Doe');
42
+ assertEquals(parsed.callbackNumber, '+19165551234');
43
+ assertEquals(parsed.inquiryReason, 'Asked about day passes');
44
+ assertEquals(parsed.hadToolError, false);
45
+ assertEquals(parsed.durationMs, 45000);
46
+ assertFalse(parsed.needsAlert);
47
+ assertEquals(parsed.fromNumber, '+19165559999');
48
+ assertEquals(parsed.callbackPromised, true);
49
+ });
50
+
51
+ Deno.test('parseCallAnalyzed: every custom_analysis_data field is optional', () => {
52
+ const parsed = parseCallAnalyzed({ event: 'call_analyzed', call: { call_id: 'call_xyz' } });
53
+ assert(parsed);
54
+ assertEquals(parsed.callId, 'call_xyz');
55
+ assertEquals(parsed.callOutcome, null);
56
+ assertEquals(parsed.callerName, null);
57
+ assertEquals(parsed.callbackNumber, null);
58
+ assertEquals(parsed.inquiryReason, null);
59
+ assertEquals(parsed.hadToolError, null);
60
+ assertFalse(parsed.needsAlert);
61
+ assertEquals(parsed.fromNumber, null);
62
+ assertEquals(parsed.callbackPromised, null);
63
+ });
64
+
65
+ Deno.test('parseCallAnalyzed: from_number is read from call, not custom_analysis_data', () => {
66
+ const parsed = parseCallAnalyzed({
67
+ event: 'call_analyzed',
68
+ call: { call_id: 'call_from_number', from_number: '+19165550000' },
69
+ });
70
+ assert(parsed);
71
+ assertEquals(parsed.fromNumber, '+19165550000');
72
+ });
73
+
74
+ Deno.test('parseCallAnalyzed: callback_promised absent parses as null, not false', () => {
75
+ const parsed = parseCallAnalyzed({
76
+ event: 'call_analyzed',
77
+ call: { call_analysis: { custom_analysis_data: { call_outcome: 'booking_completed' } } },
78
+ });
79
+ assert(parsed);
80
+ assertEquals(parsed.callbackPromised, null);
81
+ });
82
+
83
+ Deno.test('parseCallAnalyzed: missing call/call_analysis entirely still parses', () => {
84
+ const parsed = parseCallAnalyzed({ event: 'call_analyzed' });
85
+ assert(parsed);
86
+ assertEquals(parsed.callId, null);
87
+ assertFalse(parsed.needsAlert);
88
+ });
89
+
90
+ Deno.test('parseCallAnalyzed: derives duration from start/end timestamps when duration_ms is absent', () => {
91
+ const parsed = parseCallAnalyzed({
92
+ event: 'call_analyzed',
93
+ call: { start_timestamp: 1000, end_timestamp: 9500 },
94
+ });
95
+ assert(parsed);
96
+ assertEquals(parsed.durationMs, 8500);
97
+ });
98
+
99
+ Deno.test('parseCallAnalyzed: returns null for a non-call_analyzed payload', () => {
100
+ assertEquals(parseCallAnalyzed({ event: 'call_started' }), null);
101
+ });
102
+
103
+ for (const outcome of ['transfer_failed_no_answer', 'tool_error_occurred']) {
104
+ Deno.test(`parseCallAnalyzed: needsAlert is true for call_outcome=${outcome}`, () => {
105
+ const parsed = parseCallAnalyzed({
106
+ event: 'call_analyzed',
107
+ call: { call_analysis: { custom_analysis_data: { call_outcome: outcome } } },
108
+ });
109
+ assert(parsed);
110
+ assert(parsed.needsAlert);
111
+ });
112
+ }
113
+
114
+ for (const outcome of [
115
+ 'booking_completed',
116
+ 'transferred_to_staff',
117
+ 'transferred_to_event_day',
118
+ 'inquiry_only_no_action',
119
+ 'abandoned_unclear',
120
+ 'day_pass_purchased',
121
+ 'membership_signup_completed',
122
+ 'callback_logged_after_hours',
123
+ ]) {
124
+ Deno.test(`parseCallAnalyzed: needsAlert is false for call_outcome=${outcome}`, () => {
125
+ const parsed = parseCallAnalyzed({
126
+ event: 'call_analyzed',
127
+ call: { call_analysis: { custom_analysis_data: { call_outcome: outcome } } },
128
+ });
129
+ assert(parsed);
130
+ assertFalse(parsed.needsAlert);
131
+ });
132
+ }
133
+
134
+ // Regression test for the 2026-08-25 incident: these two outcomes were added
135
+ // to the live Retell agent's post_call_analysis_data on 2026-08-24 but this
136
+ // module's CallOutcome enum wasn't updated to match, so any call_analyzed
137
+ // payload carrying one of them failed the whole parse and the webhook
138
+ // handler silently no-opped. This test exists so that gap can never recur
139
+ // silently again — see the gc-voice-ai-agent skill's dated log for the full
140
+ // incident.
141
+ for (const outcome of ['day_pass_purchased', 'membership_signup_completed', 'callback_logged_after_hours']) {
142
+ Deno.test(`parseCallAnalyzed: does not reject call_outcome=${outcome} (2026-08-25 regression)`, () => {
143
+ const parsed = parseCallAnalyzed({
144
+ event: 'call_analyzed',
145
+ call: { call_id: 'call_regression_check', call_analysis: { custom_analysis_data: { call_outcome: outcome } } },
146
+ });
147
+ assert(parsed, `expected a parsed result for call_outcome=${outcome}, got null`);
148
+ assertEquals(parsed.callOutcome, outcome);
149
+ });
150
+ }
151
+
152
+ Deno.test('parseCallAnalyzed: needsAlert is true when had_tool_error is true regardless of outcome', () => {
153
+ const parsed = parseCallAnalyzed({
154
+ event: 'call_analyzed',
155
+ call: { call_analysis: { custom_analysis_data: { call_outcome: 'booking_completed', had_tool_error: true } } },
156
+ });
157
+ assert(parsed);
158
+ assert(parsed.needsAlert);
159
+ });
160
+
161
+ Deno.test('parseCallAnalyzed: rejects an unknown call_outcome value rather than passing it through', () => {
162
+ const parsed = parseCallAnalyzed({
163
+ event: 'call_analyzed',
164
+ call: { call_analysis: { custom_analysis_data: { call_outcome: 'not_a_real_outcome' } } },
165
+ });
166
+ assertEquals(parsed, null);
167
+ });