@simplelayer/graniteer-core 0.0.1 → 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,521 @@
1
+ // Fully mocked. NO network: the Supabase admin client is a hand-rolled stub
2
+ // (mirrors the fake-client style used in adminBookingCredit.test.ts), so this
3
+ // can run against live-only credentials with zero risk of touching them.
4
+ //
5
+ // This pins down the E10 fix: a reschedule refund must split into up to TWO
6
+ // credit grants — a cash-funded portion at the plain 1-year default, and a
7
+ // credit-funded portion capped at the ORIGINAL credit's own expiry — rather
8
+ // than capping (or failing to cap) the whole sum. It exercises all four
9
+ // acceptance scenarios named in the fix's own spec:
10
+ // (a) cash-only booking -> unchanged 1yr grant, no lookup at all.
11
+ // (b) partly paid via monthly membership credit (System A) -> that
12
+ // portion capped at the real period-end, cash portion still 1yr.
13
+ // (c) partly paid via an existing System-B grant credit with a short
14
+ // expiry -> same capping.
15
+ // (d) the lookup query itself errors (or comes up empty despite
16
+ // credit_applied_cents > 0) -> falls back to 1-year default AND signals
17
+ // the caller to log at ERROR severity (not warning).
18
+
19
+ import { assert, assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
20
+ import {
21
+ buildRescheduleCreditGrants,
22
+ MIN_CREDIT_GRANT_LIFETIME_DAYS,
23
+ nextPeriodMonthStr,
24
+ resolveOriginalCreditExpiry,
25
+ type RescheduleCreditLookupClient,
26
+ } from './rescheduleCredit.ts';
27
+
28
+ const BOOKING_ID = '33333333-3333-3333-3333-333333333333';
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Fake admin client
32
+ // ---------------------------------------------------------------------------
33
+
34
+ interface FakeAdminConfig {
35
+ ledgerRows?: { period_id: string | null }[] | null;
36
+ ledgerError?: { message: string } | null;
37
+ periodRow?: { period_month: string } | null;
38
+ periodError?: { message: string } | null;
39
+ anchorIso?: string | null;
40
+ anchorError?: { message: string } | null;
41
+ grantRows?: { expires_at: string }[] | null;
42
+ grantError?: { message: string } | null;
43
+ }
44
+
45
+ /** A recorded {method, args} call against one specific query chain. */
46
+ type FilterCall = { method: string; args: unknown[] };
47
+
48
+ /**
49
+ * Fake admin client. Beyond routing to the right canned response, this
50
+ * records every filter-chain call (.eq/.in/.not/.order) per query bucket so
51
+ * tests can assert the ACTUAL filter shape sent — not just which table/branch
52
+ * was hit. This is what would have caught the real regression an adversarial
53
+ * review found in this module's first draft: a `.not('redeemed_at', 'is',
54
+ * null)` filter on the System-B query that silently reopened the exact bug
55
+ * this module exists to close (see the "must NOT filter on redeemed_at" test
56
+ * below). A fake that only tracked which branch ran, without recording the
57
+ * filter arguments, would have kept passing right through that regression.
58
+ */
59
+ function makeFakeAdmin(
60
+ cfg: FakeAdminConfig,
61
+ ): RescheduleCreditLookupClient & { calls: string[]; filterCalls: { ledger: FilterCall[]; grant: FilterCall[] } } {
62
+ const calls: string[] = [];
63
+ const filterCalls = { ledger: [] as FilterCall[], grant: [] as FilterCall[] };
64
+ return {
65
+ calls,
66
+ filterCalls,
67
+ from(table: string) {
68
+ let usedIn = false;
69
+ let usedGrantEntryType = false;
70
+ // The two credits-table queries this module runs are distinguished by
71
+ // their FIRST .eq() call's column, matching the real code exactly:
72
+ // ledger keys on booking_id, the System-B fallback keys on
73
+ // redeemed_booking_id.
74
+ let bucket: 'ledger' | 'grant' | null = null;
75
+ const record = (method: string, args: unknown[]) => {
76
+ if (table === 'credits' && bucket) filterCalls[bucket].push({ method, args });
77
+ };
78
+ // deno-lint-ignore no-explicit-any
79
+ const chain: any = {
80
+ select: () => chain,
81
+ eq: (col: string, val: unknown) => {
82
+ if (table === 'credits' && bucket === null) {
83
+ if (col === 'booking_id') bucket = 'ledger';
84
+ else if (col === 'redeemed_booking_id') bucket = 'grant';
85
+ }
86
+ if (table === 'credits' && col === 'entry_type' && val === 'grant') usedGrantEntryType = true;
87
+ record('eq', [col, val]);
88
+ return chain;
89
+ },
90
+ in: (col: string, val: unknown) => {
91
+ usedIn = true;
92
+ record('in', [col, val]);
93
+ return chain;
94
+ },
95
+ not: (col: string, op: string, val: unknown) => {
96
+ record('not', [col, op, val]);
97
+ return chain;
98
+ },
99
+ order: (col: string, opts: unknown) => {
100
+ record('order', [col, opts]);
101
+ return chain;
102
+ },
103
+ limit: () => {
104
+ if (table === 'credits' && usedIn) {
105
+ calls.push('credits:ledger');
106
+ return Promise.resolve({ data: cfg.ledgerRows ?? [], error: cfg.ledgerError ?? null });
107
+ }
108
+ if (table === 'credits' && usedGrantEntryType) {
109
+ calls.push('credits:grant');
110
+ return Promise.resolve({ data: cfg.grantRows ?? [], error: cfg.grantError ?? null });
111
+ }
112
+ throw new Error(`unexpected .limit() on table ${table}`);
113
+ },
114
+ maybeSingle: () => {
115
+ if (table === 'credit_periods') {
116
+ calls.push('credit_periods');
117
+ return Promise.resolve({ data: cfg.periodRow ?? null, error: cfg.periodError ?? null });
118
+ }
119
+ throw new Error(`unexpected .maybeSingle() on table ${table}`);
120
+ },
121
+ };
122
+ return chain;
123
+ },
124
+ rpc(fn: string) {
125
+ if (fn === 'period_anchor') {
126
+ calls.push('rpc:period_anchor');
127
+ return Promise.resolve({ data: cfg.anchorIso ?? null, error: cfg.anchorError ?? null });
128
+ }
129
+ throw new Error(`unexpected rpc ${fn}`);
130
+ },
131
+ };
132
+ }
133
+
134
+ /** True if any recorded call on this bucket filters on the given column. */
135
+ function filtersOnColumn(calls: FilterCall[], column: string): boolean {
136
+ return calls.some((c) => c.args[0] === column && (c.method === 'eq' || c.method === 'not'));
137
+ }
138
+
139
+ // Relative to the real clock (not a fixed calendar date) so this suite can
140
+ // never drift into false failures/successes as real time passes a hardcoded
141
+ // date — see the floor tests below for the incident that taught us this.
142
+ const DEFAULT_EXP = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000); // stand-in "1 year from now"
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // nextPeriodMonthStr
146
+ // ---------------------------------------------------------------------------
147
+
148
+ Deno.test('nextPeriodMonthStr: ordinary month rolls forward within the year', () => {
149
+ assertEquals(nextPeriodMonthStr('2026-08-01'), '2026-09-01');
150
+ });
151
+
152
+ Deno.test('nextPeriodMonthStr: December rolls into January of the following year', () => {
153
+ assertEquals(nextPeriodMonthStr('2026-12-01'), '2027-01-01');
154
+ });
155
+
156
+ Deno.test('nextPeriodMonthStr: single-digit month stays zero-padded', () => {
157
+ assertEquals(nextPeriodMonthStr('2026-01-01'), '2026-02-01');
158
+ assertEquals(nextPeriodMonthStr('2026-09-01'), '2026-10-01');
159
+ });
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // resolveOriginalCreditExpiry
163
+ // ---------------------------------------------------------------------------
164
+
165
+ Deno.test('resolveOriginalCreditExpiry: System A hold/consume row -> period_anchor of NEXT month', async () => {
166
+ const admin = makeFakeAdmin({
167
+ ledgerRows: [{ period_id: 'p1' }],
168
+ periodRow: { period_month: '2026-08-01' },
169
+ anchorIso: '2026-09-01T07:00:00.000Z',
170
+ });
171
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
172
+ assertEquals(r.errored, false);
173
+ assert(!r.errored);
174
+ assertEquals(r.source, 'system_a');
175
+ assertEquals(r.exp.toISOString(), '2026-09-01T07:00:00.000Z');
176
+ // Never falls through to the System-B query once System A resolves.
177
+ assertEquals(admin.calls, ['credits:ledger', 'credit_periods', 'rpc:period_anchor']);
178
+ });
179
+
180
+ Deno.test('resolveOriginalCreditExpiry: no System A row -> falls back to System B grant expires_at', async () => {
181
+ const admin = makeFakeAdmin({
182
+ ledgerRows: [],
183
+ grantRows: [{ expires_at: '2026-09-15T00:00:00.000Z' }],
184
+ });
185
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
186
+ assert(!r.errored);
187
+ assertEquals(r.source, 'system_b');
188
+ assertEquals(r.exp.toISOString(), '2026-09-15T00:00:00.000Z');
189
+ assertEquals(admin.calls, ['credits:ledger', 'credits:grant']);
190
+ });
191
+
192
+ // Regression guard for a real bug an adversarial review caught in this
193
+ // module's first draft: the System-B query used to require
194
+ // `redeemed_at IS NOT NULL`. But redeemed_at is only set once
195
+ // credit_reservation_finalize succeeds, and both its call sites treat a
196
+ // finalize failure as log-only, non-fatal — leaving a PAID booking with
197
+ // redeemed_booking_id set and redeemed_at forever NULL. That filter silently
198
+ // pushed exactly that booking to 'not_found' and the full 1-year default,
199
+ // reopening the exact laundering bug this module exists to close.
200
+ Deno.test('resolveOriginalCreditExpiry: System B row is found even when redeemed_at is still NULL (finalize pending) — the query must never filter on redeemed_at', async () => {
201
+ const admin = makeFakeAdmin({
202
+ ledgerRows: [],
203
+ // No `redeemed_at` field at all in the canned row — mirrors a real row
204
+ // where credit_reservation_finalize never ran.
205
+ grantRows: [{ expires_at: '2026-09-18T00:00:00.000Z' }],
206
+ });
207
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
208
+ assert(!r.errored, 'must be found and used, not silently treated as not_found');
209
+ assertEquals(r.source, 'system_b');
210
+ assertEquals(r.exp.toISOString(), '2026-09-18T00:00:00.000Z');
211
+ assert(
212
+ !filtersOnColumn(admin.filterCalls.grant, 'redeemed_at'),
213
+ 'the System-B query must NOT filter on redeemed_at — see the comment above resolveOriginalCreditExpiry\'s System-B query',
214
+ );
215
+ });
216
+
217
+ Deno.test('resolveOriginalCreditExpiry: System B row found with a NULL expires_at -> not an error, just nothing to cap (defaults, but errored=false)', async () => {
218
+ const admin = makeFakeAdmin({
219
+ ledgerRows: [],
220
+ grantRows: [{ expires_at: null as unknown as string }],
221
+ });
222
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
223
+ assert(!r.errored, 'finding the funding row with no expiry is not a lookup failure');
224
+ assertEquals(r.source, 'system_b');
225
+ assertEquals(r.exp, DEFAULT_EXP);
226
+ });
227
+
228
+ Deno.test('resolveOriginalCreditExpiry: neither system explains a credit-funded booking -> errored, defaults, source=not_found', async () => {
229
+ const admin = makeFakeAdmin({ ledgerRows: [], grantRows: [] });
230
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
231
+ assert(r.errored);
232
+ assertEquals(r.source, 'not_found');
233
+ assertEquals(r.exp, DEFAULT_EXP);
234
+ });
235
+
236
+ Deno.test('resolveOriginalCreditExpiry: ledger query itself errors -> errored, defaults, source=error, detail carries the message', async () => {
237
+ const admin = makeFakeAdmin({ ledgerError: { message: 'connection reset' } });
238
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
239
+ assert(r.errored);
240
+ assertEquals(r.source, 'error');
241
+ assertEquals(r.detail, 'connection reset');
242
+ assertEquals(r.exp, DEFAULT_EXP);
243
+ });
244
+
245
+ Deno.test('resolveOriginalCreditExpiry: period_anchor RPC itself errors -> errored, defaults (never crashes)', async () => {
246
+ const admin = makeFakeAdmin({
247
+ ledgerRows: [{ period_id: 'p1' }],
248
+ periodRow: { period_month: '2026-08-01' },
249
+ anchorError: { message: 'function period_anchor does not exist' },
250
+ });
251
+ const r = await resolveOriginalCreditExpiry(admin, BOOKING_ID, DEFAULT_EXP);
252
+ assert(r.errored);
253
+ assertEquals(r.source, 'error');
254
+ assertEquals(r.exp, DEFAULT_EXP);
255
+ });
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // buildRescheduleCreditGrants — the four acceptance scenarios
259
+ // ---------------------------------------------------------------------------
260
+
261
+ Deno.test('(a) cash-only booking: single 1yr grant, no credit lookup performed at all', async () => {
262
+ const admin = makeFakeAdmin({});
263
+ const res = await buildRescheduleCreditGrants(admin, {
264
+ bookingId: BOOKING_ID,
265
+ contactEmail: 'Member@Example.com',
266
+ ghlContactId: 'ghl-1',
267
+ cashPortionCents: 12000,
268
+ creditPortionCents: 0,
269
+ defaultExp: DEFAULT_EXP,
270
+ });
271
+ assertEquals(res.expiryLookupErrored, false);
272
+ assertEquals(res.grants.length, 1);
273
+ assertEquals(res.grants[0], {
274
+ entry_type: 'grant',
275
+ contact_email: 'member@example.com',
276
+ ghl_contact_id: 'ghl-1',
277
+ delta_cents: 12000,
278
+ reason: 'Booking rescheduled by customer (cash-funded portion)',
279
+ booking_id: BOOKING_ID,
280
+ expires_at: DEFAULT_EXP.toISOString(),
281
+ });
282
+ assertEquals(admin.calls, [], 'no lookup should ever run when there is no credit portion');
283
+ });
284
+
285
+ Deno.test('(b) partly paid via monthly membership credit: that portion capped at real period-end, cash portion still 1yr', async () => {
286
+ // Anchored to "now + 90 days", well beyond MIN_CREDIT_GRANT_LIFETIME_DAYS,
287
+ // so the expired-credit floor never engages here — this test is purely
288
+ // about the cap ITSELF, not the floor (see the dedicated floor tests
289
+ // below). A fixed calendar date would eventually fall into the past as
290
+ // real time passes it, silently starting to exercise the floor instead of
291
+ // the cap and breaking this test's exact-match assertions.
292
+ const futureAnchor = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);
293
+ const admin = makeFakeAdmin({
294
+ ledgerRows: [{ period_id: 'p1' }],
295
+ periodRow: { period_month: '2026-08-01' },
296
+ anchorIso: futureAnchor.toISOString(),
297
+ });
298
+ const res = await buildRescheduleCreditGrants(admin, {
299
+ bookingId: BOOKING_ID,
300
+ contactEmail: 'member@example.com',
301
+ ghlContactId: null,
302
+ cashPortionCents: 5000,
303
+ creditPortionCents: 7000,
304
+ defaultExp: DEFAULT_EXP,
305
+ });
306
+ assertEquals(res.expiryLookupErrored, false);
307
+ assertEquals(res.grants.length, 2);
308
+ const cashGrant = res.grants.find((g) => g.reason.includes('cash-funded'));
309
+ const creditGrant = res.grants.find((g) => g.reason.includes('credit-funded'));
310
+ assert(cashGrant && creditGrant);
311
+ assertEquals(cashGrant!.delta_cents, 5000);
312
+ assertEquals(cashGrant!.expires_at, DEFAULT_EXP.toISOString(), 'cash portion keeps the plain 1yr default');
313
+ assertEquals(creditGrant!.delta_cents, 7000);
314
+ assertEquals(creditGrant!.expires_at, futureAnchor.toISOString(), 'credit portion capped at the real period-end, NOT 1yr');
315
+ assert(
316
+ new Date(creditGrant!.expires_at).getTime() < DEFAULT_EXP.getTime(),
317
+ 'the whole point of the fix: credit portion must expire sooner than the 1yr default',
318
+ );
319
+ assertEquals(creditGrant!.reason, 'Booking rescheduled by customer (credit-funded portion, source=system_a)');
320
+ });
321
+
322
+ Deno.test('(c) partly paid via an existing System-B grant credit with a short expiry: same capping', async () => {
323
+ // See test (b)'s comment: anchored relative to now so this test can never
324
+ // drift into exercising the floor instead of the cap.
325
+ const futureGrantExpiry = new Date(Date.now() + 60 * 24 * 60 * 60 * 1000);
326
+ const admin = makeFakeAdmin({
327
+ ledgerRows: [], // not System-A funded
328
+ grantRows: [{ expires_at: futureGrantExpiry.toISOString() }],
329
+ });
330
+ const res = await buildRescheduleCreditGrants(admin, {
331
+ bookingId: BOOKING_ID,
332
+ contactEmail: 'member@example.com',
333
+ ghlContactId: null,
334
+ cashPortionCents: 3000,
335
+ creditPortionCents: 4000,
336
+ defaultExp: DEFAULT_EXP,
337
+ });
338
+ assertEquals(res.expiryLookupErrored, false);
339
+ const creditGrant = res.grants.find((g) => g.reason.includes('credit-funded'));
340
+ assert(creditGrant);
341
+ assertEquals(creditGrant!.expires_at, futureGrantExpiry.toISOString());
342
+ assertEquals(creditGrant!.reason, 'Booking rescheduled by customer (credit-funded portion, source=system_b)');
343
+ assert(new Date(creditGrant!.expires_at).getTime() < DEFAULT_EXP.getTime());
344
+ });
345
+
346
+ Deno.test('(d) lookup query errors: falls back to 1yr default AND signals the caller to log at ERROR severity', async () => {
347
+ const admin = makeFakeAdmin({ ledgerError: { message: 'db unavailable' } });
348
+ const res = await buildRescheduleCreditGrants(admin, {
349
+ bookingId: BOOKING_ID,
350
+ contactEmail: 'member@example.com',
351
+ ghlContactId: null,
352
+ cashPortionCents: 0,
353
+ creditPortionCents: 9000,
354
+ defaultExp: DEFAULT_EXP,
355
+ });
356
+ assertEquals(res.expiryLookupErrored, true, 'caller must be told to log at ERROR, never silently succeed');
357
+ assertEquals(res.expiryLookupDetail, 'db unavailable');
358
+ assertEquals(res.expirySource, 'error');
359
+ assertEquals(res.grants.length, 1);
360
+ assertEquals(res.grants[0].delta_cents, 9000);
361
+ assertEquals(res.grants[0].expires_at, DEFAULT_EXP.toISOString(), 'still made whole via the safe 1yr fallback, never crashes or drops the credit');
362
+ });
363
+
364
+ Deno.test('(d2) credit_applied_cents > 0 but neither system explains it: same ERROR-signaling fallback as a hard query error', async () => {
365
+ const admin = makeFakeAdmin({ ledgerRows: [], grantRows: [] });
366
+ const res = await buildRescheduleCreditGrants(admin, {
367
+ bookingId: BOOKING_ID,
368
+ contactEmail: 'member@example.com',
369
+ ghlContactId: null,
370
+ cashPortionCents: 0,
371
+ creditPortionCents: 2500,
372
+ defaultExp: DEFAULT_EXP,
373
+ });
374
+ assertEquals(res.expiryLookupErrored, true);
375
+ assertEquals(res.expirySource, 'not_found');
376
+ assertEquals(res.grants[0].expires_at, DEFAULT_EXP.toISOString());
377
+ });
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // Edge cases
381
+ // ---------------------------------------------------------------------------
382
+
383
+ Deno.test('fully credit-funded (no cash portion): exactly one grant, no cash row emitted', async () => {
384
+ const admin = makeFakeAdmin({
385
+ ledgerRows: [{ period_id: 'p1' }],
386
+ periodRow: { period_month: '2026-08-01' },
387
+ anchorIso: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(),
388
+ });
389
+ const res = await buildRescheduleCreditGrants(admin, {
390
+ bookingId: BOOKING_ID,
391
+ contactEmail: 'member@example.com',
392
+ ghlContactId: null,
393
+ cashPortionCents: 0,
394
+ creditPortionCents: 8000,
395
+ defaultExp: DEFAULT_EXP,
396
+ });
397
+ assertEquals(res.grants.length, 1);
398
+ assertEquals(res.grants[0].reason.includes('credit-funded'), true);
399
+ });
400
+
401
+ // ---------------------------------------------------------------------------
402
+ // Expired-credit floor (Kyle's call, E10/GATE-0188 follow-up, 2026-09-10):
403
+ // a capped grant must never be issued already-dead just because the
404
+ // ORIGINAL credit it's capped against had already expired.
405
+ // ---------------------------------------------------------------------------
406
+
407
+ Deno.test('floor: original credit already expired in the past -> new grant floored to EXACTLY now+MIN_CREDIT_GRANT_LIFETIME_DAYS, not the past date', async () => {
408
+ const admin = makeFakeAdmin({
409
+ ledgerRows: [],
410
+ grantRows: [{ expires_at: '2020-01-01T00:00:00.000Z' }], // long expired
411
+ });
412
+ const before = Date.now();
413
+ const res = await buildRescheduleCreditGrants(admin, {
414
+ bookingId: BOOKING_ID,
415
+ contactEmail: 'member@example.com',
416
+ ghlContactId: null,
417
+ cashPortionCents: 0,
418
+ creditPortionCents: 5000,
419
+ defaultExp: DEFAULT_EXP,
420
+ });
421
+ const after = Date.now();
422
+ const gotMs = new Date(res.grants[0].expires_at).getTime();
423
+ const floorLow = before + MIN_CREDIT_GRANT_LIFETIME_DAYS * 24 * 60 * 60 * 1000;
424
+ const floorHigh = after + MIN_CREDIT_GRANT_LIFETIME_DAYS * 24 * 60 * 60 * 1000;
425
+ assert(
426
+ gotMs >= floorLow && gotMs <= floorHigh,
427
+ `expected exactly now+${MIN_CREDIT_GRANT_LIFETIME_DAYS}d (within test execution slack), got ${res.grants[0].expires_at}`,
428
+ );
429
+ });
430
+
431
+ // CRITICAL regression guard: the floor's trigger must be "already expired"
432
+ // (resolved.exp in the past), NOT "expiring within the floor window". An
433
+ // earlier draft of this floor used the broader trigger and — because a
434
+ // System-A (monthly membership credit) cap is USUALLY well under 30 days out
435
+ // by design (it's the real end of the current calendar month) — that draft
436
+ // silently overrode the System-A cap on essentially every real cancellation,
437
+ // re-widening the exact laundering gap E10/GATE-0188 exists to close. Caught
438
+ // on adversarial review before merge. This test pins the fix: a FUTURE
439
+ // expiry under 30 days out must be left exactly as resolved, not floored up.
440
+ Deno.test('floor does NOT engage on a future-but-under-30-days expiry (a normal, correct System-A/B cap) — only on a TRULY expired original', async () => {
441
+ const soonButFuture = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000); // 5 days out, still in the future
442
+ const admin = makeFakeAdmin({
443
+ ledgerRows: [],
444
+ grantRows: [{ expires_at: soonButFuture.toISOString() }],
445
+ });
446
+ const res = await buildRescheduleCreditGrants(admin, {
447
+ bookingId: BOOKING_ID,
448
+ contactEmail: 'member@example.com',
449
+ ghlContactId: null,
450
+ cashPortionCents: 0,
451
+ creditPortionCents: 5000,
452
+ defaultExp: DEFAULT_EXP,
453
+ });
454
+ assertEquals(
455
+ res.grants[0].expires_at,
456
+ soonButFuture.toISOString(),
457
+ 'a genuinely future cap (even one under the floor window) must be left EXACTLY as resolved — flooring it would let a member ratchet a near-expired credit\'s lifetime back up on every reschedule/cancel cycle',
458
+ );
459
+ });
460
+
461
+ // Realistic System-A shape: period_anchor() returns the 1st of NEXT month,
462
+ // so a real monthly-membership-credit cap is typically well under 30 days
463
+ // out. This is the exact case the broader (wrong) floor trigger would have
464
+ // silently overridden — see the regression guard above for the incident.
465
+ Deno.test('realistic System-A cap (period end ~10 days out): capped exactly at period end, NOT floored to 30 days', async () => {
466
+ const realisticPeriodEnd = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000);
467
+ const admin = makeFakeAdmin({
468
+ ledgerRows: [{ period_id: 'p1' }],
469
+ periodRow: { period_month: '2026-08-01' },
470
+ anchorIso: realisticPeriodEnd.toISOString(),
471
+ });
472
+ const res = await buildRescheduleCreditGrants(admin, {
473
+ bookingId: BOOKING_ID,
474
+ contactEmail: 'member@example.com',
475
+ ghlContactId: null,
476
+ cashPortionCents: 0,
477
+ creditPortionCents: 5000,
478
+ defaultExp: DEFAULT_EXP,
479
+ });
480
+ assertEquals(
481
+ res.grants[0].expires_at,
482
+ realisticPeriodEnd.toISOString(),
483
+ 'the whole point of E10: a monthly credit\'s real, intended use-it-or-lose-it deadline must survive untouched, not get quietly extended to 30 days',
484
+ );
485
+ });
486
+
487
+ Deno.test('floor: original credit expiring well beyond the floor window is left EXACTLY as resolved (floor only ever applies to a TRULY expired original)', async () => {
488
+ const wellBeyondFloor = new Date(Date.now() + 60 * 24 * 60 * 60 * 1000); // 60 days out
489
+ const admin = makeFakeAdmin({
490
+ ledgerRows: [],
491
+ grantRows: [{ expires_at: wellBeyondFloor.toISOString() }],
492
+ });
493
+ const res = await buildRescheduleCreditGrants(admin, {
494
+ bookingId: BOOKING_ID,
495
+ contactEmail: 'member@example.com',
496
+ ghlContactId: null,
497
+ cashPortionCents: 0,
498
+ creditPortionCents: 5000,
499
+ defaultExp: DEFAULT_EXP,
500
+ });
501
+ assertEquals(
502
+ res.grants[0].expires_at,
503
+ wellBeyondFloor.toISOString(),
504
+ 'the whole point of the floor: it must never shorten a capping that is already correct',
505
+ );
506
+ });
507
+
508
+ Deno.test('zero cash AND zero credit: no grants at all (a delta_cents=0 grant would violate credits_delta_sign_check)', async () => {
509
+ const admin = makeFakeAdmin({});
510
+ const res = await buildRescheduleCreditGrants(admin, {
511
+ bookingId: BOOKING_ID,
512
+ contactEmail: 'member@example.com',
513
+ ghlContactId: null,
514
+ cashPortionCents: 0,
515
+ creditPortionCents: 0,
516
+ defaultExp: DEFAULT_EXP,
517
+ });
518
+ assertEquals(res.grants.length, 0);
519
+ assertEquals(res.expiryLookupErrored, false);
520
+ assertEquals(admin.calls, []);
521
+ });