@simplelayer/graniteer-core 0.2.0 → 0.2.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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -309
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -95
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,349 +1,349 @@
1
- // Unit tests for the migration-collision-alert edge function (plan v13 §4's
2
- // recommended migration-window collision alert), one test per branch.
3
- //
4
- // Run with:
5
- // deno test --no-check --no-lock --node-modules-dir=auto --allow-env --allow-read \
6
- // src/functions/migration-collision-alert.test.ts
7
- //
8
- // PURE MOCK DRY RUN. The code under test is `./migration-collision-alert.copy.ts`, a
9
- // BYTE-IDENTICAL copy of `./migration-collision-alert.ts`, proven identical by
10
- // diff src/functions/migration-collision-alert.ts \
11
- // src/functions/migration-collision-alert.copy.ts
12
- // which must print nothing.
13
- //
14
- // NO NETWORK. The Slack sender is a recording fake, so no message ever leaves
15
- // this process — nothing is posted to the real #ops-alerts channel. Supabase
16
- // is a recording fake with no transport. No Stripe client exists here at all.
17
- // `--allow-net` is deliberately NOT granted.
18
-
19
- import {
20
- assert,
21
- assertEquals,
22
- assertStringIncludes,
23
- } from 'https://deno.land/std@0.224.0/assert/mod.ts';
24
-
25
- import { handleMigrationCollisionAlert, type CollisionAlertDeps } from './migration-collision-alert.copy.ts';
26
- import {
27
- makeFakeSupabase,
28
- type DbResult,
29
- type FakeSupabase,
30
- type RecordedDbCall,
31
- } from 'npm:@simplelayer/graniteer-core/supabaseTestFakes';
32
- import { OPS_ALERTS_CHANNEL_ID } from 'npm:@simplelayer/graniteer-core/slackAlert';
33
-
34
- // Only ever read by the ONE test that exercises the production auth gate, and
35
- // only to keep createClient() from throwing on a missing URL. It is a
36
- // reserved-TLD placeholder; the gate returns 401 before any request is made.
37
- Deno.env.set('SUPABASE_URL', 'https://stub.supabase.test.invalid');
38
- Deno.env.set('SUPABASE_SERVICE_ROLE_KEY', 'stub-service-role-key');
39
-
40
- const NOW = new Date('2026-10-02T18:00:00Z');
41
- const ROSTER_EMAIL = 'rob@natoli-consulting.com';
42
- const OFF_ROSTER_EMAIL = 'stranger@example.com';
43
-
44
- function collisionEvent(over: Record<string, unknown> = {}) {
45
- return {
46
- id: 'ev-1',
47
- created_at: '2026-10-02T17:55:00Z',
48
- severity: 'warning',
49
- detail: {
50
- subscription_id: 'sub_second',
51
- membership_id: 'mem-2',
52
- prior_email: null,
53
- attempted_email: ROSTER_EMAIL,
54
- colliding_ids: ['mem-1'],
55
- adoptable_count: 0,
56
- lookup_error: null,
57
- },
58
- ...over,
59
- };
60
- }
61
-
62
- interface Fixture {
63
- roster?: Array<{ email: string }> | null;
64
- events?: Array<Record<string, unknown>>;
65
- /** Existing dedupe markers, by dedupe_key. */
66
- alreadyAlerted?: string[];
67
- rosterError?: string;
68
- eventsError?: string;
69
- dedupeError?: boolean;
70
- markerInsertError?: string;
71
- }
72
-
73
- interface Harness {
74
- deps: CollisionAlertDeps;
75
- db: FakeSupabase;
76
- sent: Array<{ channelId: string; text: string }>;
77
- }
78
-
79
- function makeHarness(fx: Fixture = {}): Harness {
80
- const responder = (c: RecordedDbCall): DbResult => {
81
- if (c.table === 'migration_checkout_state') {
82
- if (fx.rosterError) return { data: null, error: { message: fx.rosterError } };
83
- return { data: fx.roster ?? [{ email: ROSTER_EMAIL }], error: null };
84
- }
85
- if (c.table === 'ops_events') {
86
- if (c.op === 'insert') {
87
- return fx.markerInsertError
88
- ? { data: null, error: { message: fx.markerInsertError } }
89
- : { data: null, error: null };
90
- }
91
- // The dedupe-marker probe is the only select filtered by dedupe_key.
92
- const dedupeFilter = c.filters.find((f) => f.kind === 'eq' && f.args[0] === 'dedupe_key');
93
- if (dedupeFilter) {
94
- if (fx.dedupeError) return { data: null, error: { message: 'dedupe read failed' } };
95
- const key = String(dedupeFilter.args[1]);
96
- return { data: (fx.alreadyAlerted ?? []).includes(key) ? { id: 'marker-1' } : null, error: null };
97
- }
98
- if (fx.eventsError) return { data: null, error: { message: fx.eventsError } };
99
- return { data: fx.events ?? [collisionEvent()], error: null };
100
- }
101
- return { data: null, error: null };
102
- };
103
-
104
- const db = makeFakeSupabase({ db: responder });
105
- const sent: Array<{ channelId: string; text: string }> = [];
106
- return {
107
- db,
108
- sent,
109
- deps: {
110
- supabase: db as never,
111
- alert: (channelId: string, text: string) => { sent.push({ channelId, text }); return Promise.resolve(); },
112
- now: () => NOW,
113
- },
114
- };
115
- }
116
-
117
- function req(method = 'POST'): Request {
118
- return new Request('https://fn.test.invalid/migration-collision-alert', { method });
119
- }
120
-
121
- // ===========================================================================
122
- // method + auth gates
123
- // ===========================================================================
124
-
125
- Deno.test('an unsupported method -> 405', async () => {
126
- const h = makeHarness();
127
- const res = await handleMigrationCollisionAlert(req('DELETE'), h.deps);
128
- assertEquals(res.status, 405);
129
- assertEquals(h.db.dbCalls.length, 0);
130
- });
131
-
132
- Deno.test('PRODUCTION AUTH GATE: no injected deps and no x-reconcile-secret header -> 401', async () => {
133
- // Exercised with NO injected deps, so the real gate runs. It returns before
134
- // any request is made, so this reaches no network despite building a client.
135
- const res = await handleMigrationCollisionAlert(req('POST'));
136
- assertEquals(res.status, 401);
137
- assertEquals(await res.text(), 'Unauthorized');
138
- });
139
-
140
- // ===========================================================================
141
- // scoping — the 61-person roster
142
- // ===========================================================================
143
-
144
- Deno.test('an empty roster short-circuits: no event read, no alert', async () => {
145
- const h = makeHarness({ roster: [] });
146
- const res = await handleMigrationCollisionAlert(req(), h.deps);
147
- assertEquals(res.status, 200);
148
- assertEquals(await res.json(), { ok: true, roster_size: 0, in_scope: 0, alerted: 0, skipped: 0 });
149
- assertEquals(h.db.callsTo('ops_events').length, 0);
150
- assertEquals(h.sent.length, 0);
151
- });
152
-
153
- Deno.test('a collision for an OFF-ROSTER email is not alerted — the scope is the migration list only', async () => {
154
- const h = makeHarness({
155
- events: [collisionEvent({ detail: { ...collisionEvent().detail, attempted_email: OFF_ROSTER_EMAIL } })],
156
- });
157
- const res = await handleMigrationCollisionAlert(req(), h.deps);
158
- const body = await res.json();
159
- assertEquals(body.in_scope, 0);
160
- assertEquals(body.alerted, 0);
161
- assertEquals(body.skipped, 1);
162
- assertEquals(h.sent.length, 0, 'a non-migrant collision is out of scope for this temporary alert');
163
- });
164
-
165
- Deno.test('email matching is lower(trim(...)) on both sides, per §1\'s convention', async () => {
166
- const h = makeHarness({
167
- roster: [{ email: ROSTER_EMAIL }],
168
- events: [collisionEvent({
169
- detail: { ...collisionEvent().detail, attempted_email: ` ROB@Natoli-Consulting.COM ` },
170
- })],
171
- });
172
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
173
- assertEquals(body.alerted, 1, 'casing and whitespace must not hide a real collision');
174
- });
175
-
176
- Deno.test('an event with no attempted_email at all is skipped, not alerted', async () => {
177
- const h = makeHarness({
178
- events: [collisionEvent({ detail: { subscription_id: 'sub_x' } })],
179
- });
180
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
181
- assertEquals(body.alerted, 0);
182
- assertEquals(h.sent.length, 0);
183
- });
184
-
185
- // ===========================================================================
186
- // the alert itself
187
- // ===========================================================================
188
-
189
- Deno.test('an in-scope collision alerts to #ops-alerts with the facts an operator needs', async () => {
190
- const h = makeHarness();
191
- const res = await handleMigrationCollisionAlert(req(), h.deps);
192
- assertEquals(res.status, 200);
193
- const body = await res.json();
194
- assertEquals(body, { ok: true, roster_size: 1, in_scope: 1, alerted: 1, skipped: 0 });
195
-
196
- assertEquals(h.sent.length, 1);
197
- assertEquals(h.sent[0].channelId, OPS_ALERTS_CHANNEL_ID);
198
- const text = h.sent[0].text;
199
- assertStringIncludes(text, 'MIGRATION email collision');
200
- assertStringIncludes(text, ROSTER_EMAIL);
201
- assertStringIncludes(text, 'sub_second');
202
- assertStringIncludes(text, 'mem-2');
203
- assertStringIncludes(text, 'mem-1');
204
- assertStringIncludes(text, 'warning');
205
- // The operator has to know the expected shape, or they will "fix" the wrong
206
- // thing: this is TWO live subscriptions, and nothing cancels one for them.
207
- assertStringIncludes(text, 'TWO membership rows and TWO live subscriptions');
208
- assertStringIncludes(text, 'nothing does this automatically');
209
- });
210
-
211
- Deno.test('a warning-severity collision IS alerted — this is the gap the function exists to close', async () => {
212
- // _shared/ops.ts only fans out to Slack at severity 'error', so the
213
- // allSameCustomer collision (severity 'warning') otherwise lands in
214
- // ops_events and stops there.
215
- const h = makeHarness({ events: [collisionEvent({ severity: 'warning' })] });
216
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
217
- assertEquals(body.alerted, 1);
218
- });
219
-
220
- Deno.test('an error-severity (cross-customer) collision is alerted too', async () => {
221
- const h = makeHarness({ events: [collisionEvent({ severity: 'error' })] });
222
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
223
- assertEquals(body.alerted, 1);
224
- assertStringIncludes(h.sent[0].text, 'error');
225
- });
226
-
227
- Deno.test('a marker row is written with a per-event dedupe key', async () => {
228
- const h = makeHarness();
229
- await handleMigrationCollisionAlert(req(), h.deps);
230
- const inserts = h.db.callsTo('ops_events').filter((c) => c.op === 'insert');
231
- assertEquals(inserts.length, 1);
232
- const payload = inserts[0].payload as Record<string, unknown>;
233
- assertEquals(payload.kind, 'migration_collision_alerted');
234
- assertEquals(payload.dedupe_key, 'migration_collision_alerted:ev-1');
235
- assertEquals((payload.detail as Record<string, unknown>).collision_event_id, 'ev-1');
236
- });
237
-
238
- // ===========================================================================
239
- // once-only delivery
240
- // ===========================================================================
241
-
242
- Deno.test('an already-alerted event is not alerted a second time', async () => {
243
- const h = makeHarness({ alreadyAlerted: ['migration_collision_alerted:ev-1'] });
244
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
245
- assertEquals(body.alerted, 0);
246
- assertEquals(body.skipped, 1);
247
- assertEquals(h.sent.length, 0, 'the 5-minute cron must not re-alert the same collision forever');
248
- });
249
-
250
- Deno.test('a FAILED dedupe read is treated as already-alerted, so a read fault cannot cause an alert storm', async () => {
251
- const h = makeHarness({ dedupeError: true });
252
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
253
- assertEquals(body.alerted, 0);
254
- assertEquals(h.sent.length, 0);
255
- });
256
-
257
- Deno.test('a failed marker write still counts as alerted and does not swallow the failure', async () => {
258
- const h = makeHarness({ markerInsertError: 'ops_events insert blew up' });
259
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
260
- assertEquals(body.ok, true);
261
- assertEquals(body.alerted, 1);
262
- assertEquals(h.sent.length, 1, 'the alert had already gone out; that is not undone');
263
- });
264
-
265
- Deno.test('multiple in-scope events each get their own alert', async () => {
266
- const h = makeHarness({
267
- events: [
268
- collisionEvent({ id: 'ev-1' }),
269
- collisionEvent({ id: 'ev-2', detail: { ...collisionEvent().detail, subscription_id: 'sub_third' } }),
270
- ],
271
- });
272
- const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
273
- assertEquals(body.alerted, 2);
274
- assertEquals(h.sent.length, 2);
275
- });
276
-
277
- // ===========================================================================
278
- // the query shape
279
- // ===========================================================================
280
-
281
- Deno.test('the event read is filtered to the collision kind and the lookback window', async () => {
282
- const h = makeHarness();
283
- await handleMigrationCollisionAlert(req(), h.deps);
284
- const read = h.db.callsTo('ops_events').find((c) => c.op === 'select' &&
285
- !c.filters.some((f) => f.args[0] === 'dedupe_key'))!;
286
- const kindFilter = read.filters.find((f) => f.kind === 'eq')!;
287
- assertEquals(kindFilter.args, ['kind', 'membership_email_collision_flagged']);
288
- const windowFilter = read.filters.find((f) => f.kind === 'gte')!;
289
- assertEquals(windowFilter.args[0], 'created_at');
290
- // 48 hours before the injected clock.
291
- assertEquals(windowFilter.args[1], new Date(NOW.getTime() - 48 * 3600_000).toISOString());
292
- });
293
-
294
- // ===========================================================================
295
- // error paths
296
- // ===========================================================================
297
-
298
- Deno.test('a roster read failure -> 500 with an ops_events error row, no alert', async () => {
299
- const h = makeHarness({ rosterError: 'roster read blew up' });
300
- const res = await handleMigrationCollisionAlert(req(), h.deps);
301
- assertEquals(res.status, 500);
302
- const body = await res.json();
303
- assertEquals(body.ok, false);
304
- assertEquals(h.sent.length, 0);
305
- const kinds = h.db.callsTo('ops_events').map((c) => (c.payload as Record<string, unknown>)?.kind);
306
- assert(kinds.includes('migration_collision_alert_error'));
307
- });
308
-
309
- Deno.test('an ops_events read failure -> 500, no alert', async () => {
310
- const h = makeHarness({ eventsError: 'events read blew up' });
311
- const res = await handleMigrationCollisionAlert(req(), h.deps);
312
- assertEquals(res.status, 500);
313
- assertEquals(h.sent.length, 0);
314
- });
315
-
316
- // ===========================================================================
317
- // standing invariants
318
- // ===========================================================================
319
-
320
- Deno.test('INVARIANT: this function never touches memberships, and never emits a collision event itself', async () => {
321
- const cases: Fixture[] = [
322
- {},
323
- { roster: [] },
324
- { events: [collisionEvent({ detail: { ...collisionEvent().detail, attempted_email: OFF_ROSTER_EMAIL } })] },
325
- { alreadyAlerted: ['migration_collision_alerted:ev-1'] },
326
- { dedupeError: true },
327
- { rosterError: 'x' },
328
- { eventsError: 'x' },
329
- { markerInsertError: 'x' },
330
- ];
331
- for (const fx of cases) {
332
- const h = makeHarness(fx);
333
- await handleMigrationCollisionAlert(req(), h.deps);
334
- assertEquals(h.db.callsTo('memberships').length, 0, 'must not read or write memberships');
335
- const kinds = h.db.callsTo('ops_events')
336
- .filter((c) => c.op === 'insert')
337
- .map((c) => (c.payload as Record<string, unknown>)?.kind);
338
- assert(
339
- !kinds.includes('membership_email_collision_flagged'),
340
- 'the alerter must never emit the event it reads — that would corrupt its own signal',
341
- );
342
- }
343
- });
344
-
345
- Deno.test('INVARIANT: migration_checkout_state is only ever READ, never written', async () => {
346
- const h = makeHarness();
347
- await handleMigrationCollisionAlert(req(), h.deps);
348
- assertEquals(h.db.writesTo('migration_checkout_state').length, 0);
349
- });
1
+ // Unit tests for the migration-collision-alert edge function (plan v13 §4's
2
+ // recommended migration-window collision alert), one test per branch.
3
+ //
4
+ // Run with:
5
+ // deno test --no-check --no-lock --node-modules-dir=auto --allow-env --allow-read \
6
+ // src/functions/migration-collision-alert.test.ts
7
+ //
8
+ // PURE MOCK DRY RUN. The code under test is `./migration-collision-alert.copy.ts`, a
9
+ // BYTE-IDENTICAL copy of `./migration-collision-alert.ts`, proven identical by
10
+ // diff src/functions/migration-collision-alert.ts \
11
+ // src/functions/migration-collision-alert.copy.ts
12
+ // which must print nothing.
13
+ //
14
+ // NO NETWORK. The Slack sender is a recording fake, so no message ever leaves
15
+ // this process — nothing is posted to the real #ops-alerts channel. Supabase
16
+ // is a recording fake with no transport. No Stripe client exists here at all.
17
+ // `--allow-net` is deliberately NOT granted.
18
+
19
+ import {
20
+ assert,
21
+ assertEquals,
22
+ assertStringIncludes,
23
+ } from 'https://deno.land/std@0.224.0/assert/mod.ts';
24
+
25
+ import { handleMigrationCollisionAlert, type CollisionAlertDeps } from './migration-collision-alert.copy.ts';
26
+ import {
27
+ makeFakeSupabase,
28
+ type DbResult,
29
+ type FakeSupabase,
30
+ type RecordedDbCall,
31
+ } from 'npm:@simplelayer/graniteer-core/supabaseTestFakes';
32
+ import { OPS_ALERTS_CHANNEL_ID } from 'npm:@simplelayer/graniteer-core/slackAlert';
33
+
34
+ // Only ever read by the ONE test that exercises the production auth gate, and
35
+ // only to keep createClient() from throwing on a missing URL. It is a
36
+ // reserved-TLD placeholder; the gate returns 401 before any request is made.
37
+ Deno.env.set('SUPABASE_URL', 'https://stub.supabase.test.invalid');
38
+ Deno.env.set('SUPABASE_SERVICE_ROLE_KEY', 'stub-service-role-key');
39
+
40
+ const NOW = new Date('2026-10-02T18:00:00Z');
41
+ const ROSTER_EMAIL = 'rob@natoli-consulting.com';
42
+ const OFF_ROSTER_EMAIL = 'stranger@example.com';
43
+
44
+ function collisionEvent(over: Record<string, unknown> = {}) {
45
+ return {
46
+ id: 'ev-1',
47
+ created_at: '2026-10-02T17:55:00Z',
48
+ severity: 'warning',
49
+ detail: {
50
+ subscription_id: 'sub_second',
51
+ membership_id: 'mem-2',
52
+ prior_email: null,
53
+ attempted_email: ROSTER_EMAIL,
54
+ colliding_ids: ['mem-1'],
55
+ adoptable_count: 0,
56
+ lookup_error: null,
57
+ },
58
+ ...over,
59
+ };
60
+ }
61
+
62
+ interface Fixture {
63
+ roster?: Array<{ email: string }> | null;
64
+ events?: Array<Record<string, unknown>>;
65
+ /** Existing dedupe markers, by dedupe_key. */
66
+ alreadyAlerted?: string[];
67
+ rosterError?: string;
68
+ eventsError?: string;
69
+ dedupeError?: boolean;
70
+ markerInsertError?: string;
71
+ }
72
+
73
+ interface Harness {
74
+ deps: CollisionAlertDeps;
75
+ db: FakeSupabase;
76
+ sent: Array<{ channelId: string; text: string }>;
77
+ }
78
+
79
+ function makeHarness(fx: Fixture = {}): Harness {
80
+ const responder = (c: RecordedDbCall): DbResult => {
81
+ if (c.table === 'migration_checkout_state') {
82
+ if (fx.rosterError) return { data: null, error: { message: fx.rosterError } };
83
+ return { data: fx.roster ?? [{ email: ROSTER_EMAIL }], error: null };
84
+ }
85
+ if (c.table === 'ops_events') {
86
+ if (c.op === 'insert') {
87
+ return fx.markerInsertError
88
+ ? { data: null, error: { message: fx.markerInsertError } }
89
+ : { data: null, error: null };
90
+ }
91
+ // The dedupe-marker probe is the only select filtered by dedupe_key.
92
+ const dedupeFilter = c.filters.find((f) => f.kind === 'eq' && f.args[0] === 'dedupe_key');
93
+ if (dedupeFilter) {
94
+ if (fx.dedupeError) return { data: null, error: { message: 'dedupe read failed' } };
95
+ const key = String(dedupeFilter.args[1]);
96
+ return { data: (fx.alreadyAlerted ?? []).includes(key) ? { id: 'marker-1' } : null, error: null };
97
+ }
98
+ if (fx.eventsError) return { data: null, error: { message: fx.eventsError } };
99
+ return { data: fx.events ?? [collisionEvent()], error: null };
100
+ }
101
+ return { data: null, error: null };
102
+ };
103
+
104
+ const db = makeFakeSupabase({ db: responder });
105
+ const sent: Array<{ channelId: string; text: string }> = [];
106
+ return {
107
+ db,
108
+ sent,
109
+ deps: {
110
+ supabase: db as never,
111
+ alert: (channelId: string, text: string) => { sent.push({ channelId, text }); return Promise.resolve(); },
112
+ now: () => NOW,
113
+ },
114
+ };
115
+ }
116
+
117
+ function req(method = 'POST'): Request {
118
+ return new Request('https://fn.test.invalid/migration-collision-alert', { method });
119
+ }
120
+
121
+ // ===========================================================================
122
+ // method + auth gates
123
+ // ===========================================================================
124
+
125
+ Deno.test('an unsupported method -> 405', async () => {
126
+ const h = makeHarness();
127
+ const res = await handleMigrationCollisionAlert(req('DELETE'), h.deps);
128
+ assertEquals(res.status, 405);
129
+ assertEquals(h.db.dbCalls.length, 0);
130
+ });
131
+
132
+ Deno.test('PRODUCTION AUTH GATE: no injected deps and no x-reconcile-secret header -> 401', async () => {
133
+ // Exercised with NO injected deps, so the real gate runs. It returns before
134
+ // any request is made, so this reaches no network despite building a client.
135
+ const res = await handleMigrationCollisionAlert(req('POST'));
136
+ assertEquals(res.status, 401);
137
+ assertEquals(await res.text(), 'Unauthorized');
138
+ });
139
+
140
+ // ===========================================================================
141
+ // scoping — the 61-person roster
142
+ // ===========================================================================
143
+
144
+ Deno.test('an empty roster short-circuits: no event read, no alert', async () => {
145
+ const h = makeHarness({ roster: [] });
146
+ const res = await handleMigrationCollisionAlert(req(), h.deps);
147
+ assertEquals(res.status, 200);
148
+ assertEquals(await res.json(), { ok: true, roster_size: 0, in_scope: 0, alerted: 0, skipped: 0 });
149
+ assertEquals(h.db.callsTo('ops_events').length, 0);
150
+ assertEquals(h.sent.length, 0);
151
+ });
152
+
153
+ Deno.test('a collision for an OFF-ROSTER email is not alerted — the scope is the migration list only', async () => {
154
+ const h = makeHarness({
155
+ events: [collisionEvent({ detail: { ...collisionEvent().detail, attempted_email: OFF_ROSTER_EMAIL } })],
156
+ });
157
+ const res = await handleMigrationCollisionAlert(req(), h.deps);
158
+ const body = await res.json();
159
+ assertEquals(body.in_scope, 0);
160
+ assertEquals(body.alerted, 0);
161
+ assertEquals(body.skipped, 1);
162
+ assertEquals(h.sent.length, 0, 'a non-migrant collision is out of scope for this temporary alert');
163
+ });
164
+
165
+ Deno.test('email matching is lower(trim(...)) on both sides, per §1\'s convention', async () => {
166
+ const h = makeHarness({
167
+ roster: [{ email: ROSTER_EMAIL }],
168
+ events: [collisionEvent({
169
+ detail: { ...collisionEvent().detail, attempted_email: ` ROB@Natoli-Consulting.COM ` },
170
+ })],
171
+ });
172
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
173
+ assertEquals(body.alerted, 1, 'casing and whitespace must not hide a real collision');
174
+ });
175
+
176
+ Deno.test('an event with no attempted_email at all is skipped, not alerted', async () => {
177
+ const h = makeHarness({
178
+ events: [collisionEvent({ detail: { subscription_id: 'sub_x' } })],
179
+ });
180
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
181
+ assertEquals(body.alerted, 0);
182
+ assertEquals(h.sent.length, 0);
183
+ });
184
+
185
+ // ===========================================================================
186
+ // the alert itself
187
+ // ===========================================================================
188
+
189
+ Deno.test('an in-scope collision alerts to #ops-alerts with the facts an operator needs', async () => {
190
+ const h = makeHarness();
191
+ const res = await handleMigrationCollisionAlert(req(), h.deps);
192
+ assertEquals(res.status, 200);
193
+ const body = await res.json();
194
+ assertEquals(body, { ok: true, roster_size: 1, in_scope: 1, alerted: 1, skipped: 0 });
195
+
196
+ assertEquals(h.sent.length, 1);
197
+ assertEquals(h.sent[0].channelId, OPS_ALERTS_CHANNEL_ID);
198
+ const text = h.sent[0].text;
199
+ assertStringIncludes(text, 'MIGRATION email collision');
200
+ assertStringIncludes(text, ROSTER_EMAIL);
201
+ assertStringIncludes(text, 'sub_second');
202
+ assertStringIncludes(text, 'mem-2');
203
+ assertStringIncludes(text, 'mem-1');
204
+ assertStringIncludes(text, 'warning');
205
+ // The operator has to know the expected shape, or they will "fix" the wrong
206
+ // thing: this is TWO live subscriptions, and nothing cancels one for them.
207
+ assertStringIncludes(text, 'TWO membership rows and TWO live subscriptions');
208
+ assertStringIncludes(text, 'nothing does this automatically');
209
+ });
210
+
211
+ Deno.test('a warning-severity collision IS alerted — this is the gap the function exists to close', async () => {
212
+ // _shared/ops.ts only fans out to Slack at severity 'error', so the
213
+ // allSameCustomer collision (severity 'warning') otherwise lands in
214
+ // ops_events and stops there.
215
+ const h = makeHarness({ events: [collisionEvent({ severity: 'warning' })] });
216
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
217
+ assertEquals(body.alerted, 1);
218
+ });
219
+
220
+ Deno.test('an error-severity (cross-customer) collision is alerted too', async () => {
221
+ const h = makeHarness({ events: [collisionEvent({ severity: 'error' })] });
222
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
223
+ assertEquals(body.alerted, 1);
224
+ assertStringIncludes(h.sent[0].text, 'error');
225
+ });
226
+
227
+ Deno.test('a marker row is written with a per-event dedupe key', async () => {
228
+ const h = makeHarness();
229
+ await handleMigrationCollisionAlert(req(), h.deps);
230
+ const inserts = h.db.callsTo('ops_events').filter((c) => c.op === 'insert');
231
+ assertEquals(inserts.length, 1);
232
+ const payload = inserts[0].payload as Record<string, unknown>;
233
+ assertEquals(payload.kind, 'migration_collision_alerted');
234
+ assertEquals(payload.dedupe_key, 'migration_collision_alerted:ev-1');
235
+ assertEquals((payload.detail as Record<string, unknown>).collision_event_id, 'ev-1');
236
+ });
237
+
238
+ // ===========================================================================
239
+ // once-only delivery
240
+ // ===========================================================================
241
+
242
+ Deno.test('an already-alerted event is not alerted a second time', async () => {
243
+ const h = makeHarness({ alreadyAlerted: ['migration_collision_alerted:ev-1'] });
244
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
245
+ assertEquals(body.alerted, 0);
246
+ assertEquals(body.skipped, 1);
247
+ assertEquals(h.sent.length, 0, 'the 5-minute cron must not re-alert the same collision forever');
248
+ });
249
+
250
+ Deno.test('a FAILED dedupe read is treated as already-alerted, so a read fault cannot cause an alert storm', async () => {
251
+ const h = makeHarness({ dedupeError: true });
252
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
253
+ assertEquals(body.alerted, 0);
254
+ assertEquals(h.sent.length, 0);
255
+ });
256
+
257
+ Deno.test('a failed marker write still counts as alerted and does not swallow the failure', async () => {
258
+ const h = makeHarness({ markerInsertError: 'ops_events insert blew up' });
259
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
260
+ assertEquals(body.ok, true);
261
+ assertEquals(body.alerted, 1);
262
+ assertEquals(h.sent.length, 1, 'the alert had already gone out; that is not undone');
263
+ });
264
+
265
+ Deno.test('multiple in-scope events each get their own alert', async () => {
266
+ const h = makeHarness({
267
+ events: [
268
+ collisionEvent({ id: 'ev-1' }),
269
+ collisionEvent({ id: 'ev-2', detail: { ...collisionEvent().detail, subscription_id: 'sub_third' } }),
270
+ ],
271
+ });
272
+ const body = await (await handleMigrationCollisionAlert(req(), h.deps)).json();
273
+ assertEquals(body.alerted, 2);
274
+ assertEquals(h.sent.length, 2);
275
+ });
276
+
277
+ // ===========================================================================
278
+ // the query shape
279
+ // ===========================================================================
280
+
281
+ Deno.test('the event read is filtered to the collision kind and the lookback window', async () => {
282
+ const h = makeHarness();
283
+ await handleMigrationCollisionAlert(req(), h.deps);
284
+ const read = h.db.callsTo('ops_events').find((c) => c.op === 'select' &&
285
+ !c.filters.some((f) => f.args[0] === 'dedupe_key'))!;
286
+ const kindFilter = read.filters.find((f) => f.kind === 'eq')!;
287
+ assertEquals(kindFilter.args, ['kind', 'membership_email_collision_flagged']);
288
+ const windowFilter = read.filters.find((f) => f.kind === 'gte')!;
289
+ assertEquals(windowFilter.args[0], 'created_at');
290
+ // 48 hours before the injected clock.
291
+ assertEquals(windowFilter.args[1], new Date(NOW.getTime() - 48 * 3600_000).toISOString());
292
+ });
293
+
294
+ // ===========================================================================
295
+ // error paths
296
+ // ===========================================================================
297
+
298
+ Deno.test('a roster read failure -> 500 with an ops_events error row, no alert', async () => {
299
+ const h = makeHarness({ rosterError: 'roster read blew up' });
300
+ const res = await handleMigrationCollisionAlert(req(), h.deps);
301
+ assertEquals(res.status, 500);
302
+ const body = await res.json();
303
+ assertEquals(body.ok, false);
304
+ assertEquals(h.sent.length, 0);
305
+ const kinds = h.db.callsTo('ops_events').map((c) => (c.payload as Record<string, unknown>)?.kind);
306
+ assert(kinds.includes('migration_collision_alert_error'));
307
+ });
308
+
309
+ Deno.test('an ops_events read failure -> 500, no alert', async () => {
310
+ const h = makeHarness({ eventsError: 'events read blew up' });
311
+ const res = await handleMigrationCollisionAlert(req(), h.deps);
312
+ assertEquals(res.status, 500);
313
+ assertEquals(h.sent.length, 0);
314
+ });
315
+
316
+ // ===========================================================================
317
+ // standing invariants
318
+ // ===========================================================================
319
+
320
+ Deno.test('INVARIANT: this function never touches memberships, and never emits a collision event itself', async () => {
321
+ const cases: Fixture[] = [
322
+ {},
323
+ { roster: [] },
324
+ { events: [collisionEvent({ detail: { ...collisionEvent().detail, attempted_email: OFF_ROSTER_EMAIL } })] },
325
+ { alreadyAlerted: ['migration_collision_alerted:ev-1'] },
326
+ { dedupeError: true },
327
+ { rosterError: 'x' },
328
+ { eventsError: 'x' },
329
+ { markerInsertError: 'x' },
330
+ ];
331
+ for (const fx of cases) {
332
+ const h = makeHarness(fx);
333
+ await handleMigrationCollisionAlert(req(), h.deps);
334
+ assertEquals(h.db.callsTo('memberships').length, 0, 'must not read or write memberships');
335
+ const kinds = h.db.callsTo('ops_events')
336
+ .filter((c) => c.op === 'insert')
337
+ .map((c) => (c.payload as Record<string, unknown>)?.kind);
338
+ assert(
339
+ !kinds.includes('membership_email_collision_flagged'),
340
+ 'the alerter must never emit the event it reads — that would corrupt its own signal',
341
+ );
342
+ }
343
+ });
344
+
345
+ Deno.test('INVARIANT: migration_checkout_state is only ever READ, never written', async () => {
346
+ const h = makeHarness();
347
+ await handleMigrationCollisionAlert(req(), h.deps);
348
+ assertEquals(h.db.writesTo('migration_checkout_state').length, 0);
349
+ });