@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,333 +1,333 @@
1
- // supabase/functions/admin-correct-booking/index.ts
2
- //
3
- // Undo path for the two manual admin actions that have none: "skip contract"
4
- // (admin-skip-commons-contract) and "mark fully paid"
5
- // (admin-mark-booking-paid). Both of those actions log a full "before"
6
- // snapshot of every column they mutate -- AND every column
7
- // bookings_amount_math_check depends on -- into ops_events at the moment
8
- // they run, tagged with an exact event timestamp (mark_event_at /
9
- // skip_event_at) that matches the row's own paid_marked_at /
10
- // contract_skipped_at column exactly. This function's only job is to look
11
- // up that EXACT snapshot (never "the most recent one of this kind" -- a
12
- // swallowed logOps insert or a second mark/undo cycle can leave a stale
13
- // older row sitting there) and write it back verbatim, refusing outright
14
- // whenever anything needed is missing, drifted, or ambiguous.
15
- //
16
- // This is a bookkeeping correction only. It never talks to Stripe and never
17
- // reverses a real payment -- if money actually needs to move, that is a
18
- // separate, explicit action (a Stripe refund, an outgoing Mercury transfer),
19
- // not something this function does as a side effect.
20
- import { createClient } from 'npm:@supabase/supabase-js@2';
21
- import { z } from 'npm:zod@3.23.8';
22
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
23
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
24
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
25
-
26
- const corsHeaders = {
27
- 'Access-Control-Allow-Origin': '*',
28
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
29
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
30
- };
31
-
32
- interface CallerClaims { sub: string; email?: string; aal?: string }
33
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
34
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
35
- function getJwks(supabaseUrl: string) {
36
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
37
- return jwksCache;
38
- }
39
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
40
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
41
- const token = authHeader.slice(7).trim();
42
- try {
43
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
44
- const claims = payload as unknown as CallerClaims;
45
- if (!claims.sub) return null;
46
- return claims;
47
- } catch { return null; }
48
- }
49
- function json(status: number, body: unknown) {
50
- return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
51
- }
52
- function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
53
- return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
54
- }
55
-
56
- const ACTIONS = ['undo_mark_paid', 'undo_skip_contract'] as const;
57
- const Body = z.object({
58
- booking_id: z.string().uuid(),
59
- action: z.enum(ACTIONS),
60
- reason: z.string().trim().min(1).max(500),
61
- });
62
-
63
- // A hold restored to a moment already in the past would leave the booking
64
- // exposed to the 5-minute expire-stale-booking-holds cron with no real
65
- // window for staff to act -- Commons (tier-3) holds are routinely extended
66
- // out to 7 days (see _shared/bookingHoldReclaim.ts), so "already lapsed" is
67
- // an expected state to land in here, not an edge case. Give a real working
68
- // day, not a fuse shorter than the cron interval.
69
- const REVERT_HOLD_GRACE_MS = 24 * 60 * 60 * 1000;
70
- type HoldRestore = { ok: true; value: string | null; extended: boolean } | { ok: false };
71
- function restoreHold(prior: unknown): HoldRestore {
72
- if (prior === null) return { ok: true, value: null, extended: false };
73
- if (typeof prior !== 'string') return { ok: false }; // absent/wrong-typed snapshot -- refuse, never guess
74
- const ms = Date.parse(prior);
75
- if (!Number.isFinite(ms)) return { ok: false };
76
- if (ms > Date.now() + REVERT_HOLD_GRACE_MS) return { ok: true, value: prior, extended: false };
77
- return { ok: true, value: new Date(Date.now() + REVERT_HOLD_GRACE_MS).toISOString(), extended: true };
78
- }
79
-
80
- function isSafeNonNegInt(v: unknown): v is number {
81
- return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
82
- }
83
-
84
- const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
85
- const PAYMENT_SOURCES = new Set(['stripe', 'offline']);
86
-
87
- export async function handle(req: Request): Promise<Response> {
88
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
89
- if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
90
-
91
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
92
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
93
-
94
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
95
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
96
- if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
97
- if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
98
- const callerEmail = (caller.email ?? '').toLowerCase();
99
- if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
100
-
101
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
102
-
103
- const [ipOk, emailOk] = await Promise.all([
104
- checkRateLimit(admin, 'admin-correct-booking-ip', clientIp(req), 15, 300),
105
- checkRateLimit(admin, 'admin-correct-booking-email', callerEmail, 15, 300),
106
- ]);
107
- if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
108
-
109
- const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
110
- if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
111
- if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
112
-
113
- let raw: unknown;
114
- try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
115
- const parsed = Body.safeParse(raw);
116
- if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
117
- const { booking_id, action, reason } = parsed.data;
118
-
119
- if (action === 'undo_mark_paid') {
120
- const { data: booking, error: bErr } = await admin
121
- .from('bookings')
122
- .select('id,status,paid_method,payment_source,paid_marked_at,paid_marked_by_email,charged_amount_cents,discount_applied_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents')
123
- .eq('id', booking_id)
124
- .maybeSingle();
125
- if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
126
- if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
127
- if (booking.status !== 'paid') {
128
- return fail(409, 'not_paid', `Booking status is "${booking.status}"; nothing to undo — it isn't currently marked paid.`);
129
- }
130
- if (!booking.paid_marked_at) {
131
- const isOfflineCreated = booking.payment_source === 'offline';
132
- return fail(409, 'not_manually_marked',
133
- isOfflineCreated
134
- ? 'This booking was recorded paid at creation time (an offline/manually-created booking), not through this action -- there is nothing here for this action to undo. Correct it by hand if it was created wrong.'
135
- : 'This booking was paid through the live Stripe flow, not this manual action -- there is no manual mark-paid to undo. ' +
136
- 'If money needs to be returned, issue a Stripe refund; if the booking itself needs to change, use a different action.');
137
- }
138
-
139
- // Match the EXACT event this row's current paid_marked_at describes --
140
- // never "the most recent row of this kind" for this booking, which a
141
- // swallowed logOps insert error, or a second mark/undo/mark cycle, could
142
- // leave pointing at a stale snapshot that no longer matches this row.
143
- // booking.paid_marked_at comes back from PostgREST as "...+00:00"; the
144
- // logged detail.mark_event_at was written with JS's toISOString(),
145
- // which always produces "...Z". Same instant, different text -- and
146
- // detail->>'x' forces a text comparison with no implicit cast, so they
147
- // must be normalized to the same format before comparing.
148
- const paidMarkedAtIso = new Date(booking.paid_marked_at).toISOString();
149
- const { data: event, error: evErr } = await admin
150
- .from('ops_events')
151
- .select('id,detail')
152
- .eq('booking_id', booking_id)
153
- .eq('kind', 'booking_marked_fully_paid')
154
- .eq('detail->>mark_event_at', paidMarkedAtIso)
155
- .order('created_at', { ascending: false })
156
- .limit(1)
157
- .maybeSingle();
158
- if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
159
- if (!event) {
160
- return fail(409, 'no_audit_snapshot',
161
- 'No recorded snapshot exactly matching this booking\'s current paid_marked_at was found, so there is nothing safe to revert to automatically. ' +
162
- 'Correct it by hand and log an ops_events row before relying on this action for it again.');
163
- }
164
-
165
- const d = (event.detail ?? {}) as Record<string, unknown>;
166
- const priorStatus = typeof d.prior_status === 'string' ? d.prior_status : null;
167
- const priorDiscountCents = d.prior_discount_applied_cents;
168
- const priorChargedRaw = d.prior_charged_amount_cents;
169
- const priorPaymentSource = d.prior_payment_source;
170
-
171
- if (
172
- !priorStatus || !PAYABLE_STATUSES.has(priorStatus)
173
- || !isSafeNonNegInt(priorDiscountCents)
174
- || !(priorChargedRaw === null || isSafeNonNegInt(priorChargedRaw))
175
- || typeof priorPaymentSource !== 'string' || !PAYMENT_SOURCES.has(priorPaymentSource)
176
- ) {
177
- return fail(409, 'incomplete_audit_snapshot',
178
- 'The recorded snapshot for this booking is missing or has invalid values for fields this action needs to revert it safely. Correct it by hand instead.');
179
- }
180
-
181
- // Drift check: bookings_amount_math_check depends on list/dynamic/
182
- // credit too, and nothing else guards those against having changed
183
- // (e.g. a reschedule or a credit adjustment) between the mark-paid and
184
- // this undo. If any of them moved, the snapshot no longer describes a
185
- // state that's safe to restore -- refuse rather than either violate the
186
- // CHECK (a raw Postgres error surfaced to staff) or silently restore a
187
- // stale discount against new inputs.
188
- const driftChecks: Array<[string, unknown, number]> = [
189
- ['list_amount_cents', d.prior_list_amount_cents, Number(booking.list_amount_cents)],
190
- ['dynamic_discount_cents', d.prior_dynamic_discount_cents, Number(booking.dynamic_discount_cents ?? 0)],
191
- ['credit_applied_cents', d.prior_credit_applied_cents, Number(booking.credit_applied_cents ?? 0)],
192
- ];
193
- for (const [label, snapshot, live] of driftChecks) {
194
- if (!isSafeNonNegInt(snapshot) || snapshot !== live) {
195
- return fail(409, 'booking_drifted',
196
- `This booking's ${label} changed since it was marked paid (or the snapshot doesn't record it), so the recorded snapshot no longer describes a state it's safe to restore. Correct it by hand.`);
197
- }
198
- }
199
-
200
- const priorChargedCents = priorChargedRaw === null ? null : (priorChargedRaw as number);
201
- const priorPaidNotes = typeof d.prior_paid_notes === 'string' ? d.prior_paid_notes : null;
202
- const priorDepositPaidAt = typeof d.prior_deposit_paid_at === 'string' ? d.prior_deposit_paid_at : null;
203
- const holdRestore = restoreHold(d.prior_hold_expires_at);
204
- if (!holdRestore.ok) {
205
- return fail(409, 'unrestorable_hold',
206
- 'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand, then undo the rest separately if needed.');
207
- }
208
-
209
- const { data: updated, error: updErr } = await admin
210
- .from('bookings')
211
- .update({
212
- status: priorStatus,
213
- charged_amount_cents: priorChargedCents,
214
- discount_applied_cents: priorDiscountCents,
215
- payment_source: priorPaymentSource,
216
- paid_notes: priorPaidNotes,
217
- paid_method: null,
218
- paid_marked_by_email: null,
219
- paid_marked_at: null,
220
- deposit_paid_at: priorDepositPaidAt,
221
- hold_expires_at: holdRestore.value,
222
- })
223
- .eq('id', booking_id)
224
- .eq('status', 'paid')
225
- .eq('paid_marked_at', booking.paid_marked_at) // CAS
226
- .eq('charged_amount_cents', booking.charged_amount_cents) // CAS -- catch a concurrent money-column write the timestamp CAS alone wouldn't
227
- .eq('discount_applied_cents', booking.discount_applied_cents) // CAS, same reason
228
- .select('id')
229
- .maybeSingle();
230
- if (updErr) return fail(500, 'update_failed', updErr.message);
231
- if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
232
-
233
- // 'sponsored' is the only paid_method that genuinely moved zero dollars.
234
- // Every other value -- including 'other', the catch-all for real money
235
- // that isn't cash/stripe/mercury -- means this warning must fire.
236
- const involvesRealMoney = booking.paid_method !== 'sponsored';
237
-
238
- await logOps(admin, 'booking_paid_mark_undone', {
239
- booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
240
- undone_event_id: event.id, reverted_to_status: priorStatus,
241
- prior_paid_method: booking.paid_method ?? null,
242
- prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
243
- prior_paid_marked_at: booking.paid_marked_at ?? null,
244
- prior_charged_amount_cents_before_undo: booking.charged_amount_cents ?? null,
245
- hold_extended: holdRestore.extended,
246
- }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
247
-
248
- const notes: string[] = [];
249
- if (involvesRealMoney) {
250
- notes.push('This only corrected the booking record. It did NOT reverse any real payment -- if money needs to be returned, handle that separately (Stripe refund / outgoing transfer).');
251
- }
252
- if (holdRestore.extended) {
253
- notes.push(`The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff act.`);
254
- }
255
-
256
- return json(200, {
257
- ok: true, booking_id, status: priorStatus, hold_expires_at: holdRestore.value, hold_extended: holdRestore.extended,
258
- warning: notes.length ? notes.join(' ') : undefined,
259
- });
260
- }
261
-
262
- // action === 'undo_skip_contract'
263
- const { data: booking, error: bErr } = await admin
264
- .from('bookings')
265
- .select('id,status,contract_skipped_at,contract_skipped_by_email,contract_skip_reason')
266
- .eq('id', booking_id)
267
- .maybeSingle();
268
- if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
269
- if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
270
- if (!booking.contract_skipped_at) {
271
- return fail(409, 'not_skipped', "This booking's contract was not marked skipped; nothing to undo.");
272
- }
273
- if (booking.status !== 'pending') {
274
- return fail(409, 'not_pending',
275
- `Booking status is "${booking.status}"; only a still-pending booking's skip can be undone. If it's already been marked paid, undo that first.`);
276
- }
277
-
278
- // Same normalization as undo_mark_paid -- see the comment there.
279
- const contractSkippedAtIso = new Date(booking.contract_skipped_at).toISOString();
280
- const { data: event, error: evErr } = await admin
281
- .from('ops_events')
282
- .select('id,detail')
283
- .eq('booking_id', booking_id)
284
- .eq('kind', 'commons_contract_skipped')
285
- .eq('detail->>skip_event_at', contractSkippedAtIso)
286
- .order('created_at', { ascending: false })
287
- .limit(1)
288
- .maybeSingle();
289
- if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
290
- if (!event) {
291
- return fail(409, 'no_audit_snapshot',
292
- 'No recorded snapshot exactly matching this booking\'s current contract_skipped_at was found, so there is nothing safe to revert to automatically. ' +
293
- 'Correct it by hand and log an ops_events row before relying on this action for it again.');
294
- }
295
- const d = (event.detail ?? {}) as Record<string, unknown>;
296
- const holdRestore = restoreHold(d.prior_hold_expires_at);
297
- if (!holdRestore.ok) {
298
- return fail(409, 'unrestorable_hold',
299
- 'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand instead.');
300
- }
301
-
302
- const { data: updated, error: updErr } = await admin
303
- .from('bookings')
304
- .update({
305
- contract_skipped_at: null,
306
- contract_skipped_by_email: null,
307
- contract_skip_reason: null,
308
- hold_expires_at: holdRestore.value,
309
- })
310
- .eq('id', booking_id)
311
- .eq('status', 'pending')
312
- .eq('contract_skipped_at', booking.contract_skipped_at) // CAS
313
- .select('id')
314
- .maybeSingle();
315
- if (updErr) return fail(500, 'update_failed', updErr.message);
316
- if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
317
-
318
- await logOps(admin, 'commons_contract_skip_undone', {
319
- booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
320
- undone_event_id: event.id,
321
- prior_skip_reason: booking.contract_skip_reason ?? null,
322
- prior_skipped_by_email: booking.contract_skipped_by_email ?? null,
323
- hold_extended: holdRestore.extended,
324
- }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
325
-
326
- return json(200, {
327
- ok: true, booking_id, status: 'pending', contract_skip_cleared: true,
328
- hold_expires_at: holdRestore.value,
329
- warning: holdRestore.extended
330
- ? `The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff send a contract or otherwise act.`
331
- : undefined,
332
- });
333
- }
1
+ // supabase/functions/admin-correct-booking/index.ts
2
+ //
3
+ // Undo path for the two manual admin actions that have none: "skip contract"
4
+ // (admin-skip-commons-contract) and "mark fully paid"
5
+ // (admin-mark-booking-paid). Both of those actions log a full "before"
6
+ // snapshot of every column they mutate -- AND every column
7
+ // bookings_amount_math_check depends on -- into ops_events at the moment
8
+ // they run, tagged with an exact event timestamp (mark_event_at /
9
+ // skip_event_at) that matches the row's own paid_marked_at /
10
+ // contract_skipped_at column exactly. This function's only job is to look
11
+ // up that EXACT snapshot (never "the most recent one of this kind" -- a
12
+ // swallowed logOps insert or a second mark/undo cycle can leave a stale
13
+ // older row sitting there) and write it back verbatim, refusing outright
14
+ // whenever anything needed is missing, drifted, or ambiguous.
15
+ //
16
+ // This is a bookkeeping correction only. It never talks to Stripe and never
17
+ // reverses a real payment -- if money actually needs to move, that is a
18
+ // separate, explicit action (a Stripe refund, an outgoing Mercury transfer),
19
+ // not something this function does as a side effect.
20
+ import { createClient } from 'npm:@supabase/supabase-js@2';
21
+ import { z } from 'npm:zod@3.23.8';
22
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
23
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
24
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
25
+
26
+ const corsHeaders = {
27
+ 'Access-Control-Allow-Origin': '*',
28
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
29
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
30
+ };
31
+
32
+ interface CallerClaims { sub: string; email?: string; aal?: string }
33
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
34
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
35
+ function getJwks(supabaseUrl: string) {
36
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
37
+ return jwksCache;
38
+ }
39
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
40
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
41
+ const token = authHeader.slice(7).trim();
42
+ try {
43
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
44
+ const claims = payload as unknown as CallerClaims;
45
+ if (!claims.sub) return null;
46
+ return claims;
47
+ } catch { return null; }
48
+ }
49
+ function json(status: number, body: unknown) {
50
+ return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
51
+ }
52
+ function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
53
+ return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
54
+ }
55
+
56
+ const ACTIONS = ['undo_mark_paid', 'undo_skip_contract'] as const;
57
+ const Body = z.object({
58
+ booking_id: z.string().uuid(),
59
+ action: z.enum(ACTIONS),
60
+ reason: z.string().trim().min(1).max(500),
61
+ });
62
+
63
+ // A hold restored to a moment already in the past would leave the booking
64
+ // exposed to the 5-minute expire-stale-booking-holds cron with no real
65
+ // window for staff to act -- Commons (tier-3) holds are routinely extended
66
+ // out to 7 days (see _shared/bookingHoldReclaim.ts), so "already lapsed" is
67
+ // an expected state to land in here, not an edge case. Give a real working
68
+ // day, not a fuse shorter than the cron interval.
69
+ const REVERT_HOLD_GRACE_MS = 24 * 60 * 60 * 1000;
70
+ type HoldRestore = { ok: true; value: string | null; extended: boolean } | { ok: false };
71
+ function restoreHold(prior: unknown): HoldRestore {
72
+ if (prior === null) return { ok: true, value: null, extended: false };
73
+ if (typeof prior !== 'string') return { ok: false }; // absent/wrong-typed snapshot -- refuse, never guess
74
+ const ms = Date.parse(prior);
75
+ if (!Number.isFinite(ms)) return { ok: false };
76
+ if (ms > Date.now() + REVERT_HOLD_GRACE_MS) return { ok: true, value: prior, extended: false };
77
+ return { ok: true, value: new Date(Date.now() + REVERT_HOLD_GRACE_MS).toISOString(), extended: true };
78
+ }
79
+
80
+ function isSafeNonNegInt(v: unknown): v is number {
81
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
82
+ }
83
+
84
+ const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
85
+ const PAYMENT_SOURCES = new Set(['stripe', 'offline']);
86
+
87
+ export async function handle(req: Request): Promise<Response> {
88
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
89
+ if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
90
+
91
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
92
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
93
+
94
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
95
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
96
+ if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
97
+ if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
98
+ const callerEmail = (caller.email ?? '').toLowerCase();
99
+ if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
100
+
101
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
102
+
103
+ const [ipOk, emailOk] = await Promise.all([
104
+ checkRateLimit(admin, 'admin-correct-booking-ip', clientIp(req), 15, 300),
105
+ checkRateLimit(admin, 'admin-correct-booking-email', callerEmail, 15, 300),
106
+ ]);
107
+ if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
108
+
109
+ const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
110
+ if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
111
+ if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
112
+
113
+ let raw: unknown;
114
+ try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
115
+ const parsed = Body.safeParse(raw);
116
+ if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
117
+ const { booking_id, action, reason } = parsed.data;
118
+
119
+ if (action === 'undo_mark_paid') {
120
+ const { data: booking, error: bErr } = await admin
121
+ .from('bookings')
122
+ .select('id,status,paid_method,payment_source,paid_marked_at,paid_marked_by_email,charged_amount_cents,discount_applied_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents')
123
+ .eq('id', booking_id)
124
+ .maybeSingle();
125
+ if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
126
+ if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
127
+ if (booking.status !== 'paid') {
128
+ return fail(409, 'not_paid', `Booking status is "${booking.status}"; nothing to undo — it isn't currently marked paid.`);
129
+ }
130
+ if (!booking.paid_marked_at) {
131
+ const isOfflineCreated = booking.payment_source === 'offline';
132
+ return fail(409, 'not_manually_marked',
133
+ isOfflineCreated
134
+ ? 'This booking was recorded paid at creation time (an offline/manually-created booking), not through this action -- there is nothing here for this action to undo. Correct it by hand if it was created wrong.'
135
+ : 'This booking was paid through the live Stripe flow, not this manual action -- there is no manual mark-paid to undo. ' +
136
+ 'If money needs to be returned, issue a Stripe refund; if the booking itself needs to change, use a different action.');
137
+ }
138
+
139
+ // Match the EXACT event this row's current paid_marked_at describes --
140
+ // never "the most recent row of this kind" for this booking, which a
141
+ // swallowed logOps insert error, or a second mark/undo/mark cycle, could
142
+ // leave pointing at a stale snapshot that no longer matches this row.
143
+ // booking.paid_marked_at comes back from PostgREST as "...+00:00"; the
144
+ // logged detail.mark_event_at was written with JS's toISOString(),
145
+ // which always produces "...Z". Same instant, different text -- and
146
+ // detail->>'x' forces a text comparison with no implicit cast, so they
147
+ // must be normalized to the same format before comparing.
148
+ const paidMarkedAtIso = new Date(booking.paid_marked_at).toISOString();
149
+ const { data: event, error: evErr } = await admin
150
+ .from('ops_events')
151
+ .select('id,detail')
152
+ .eq('booking_id', booking_id)
153
+ .eq('kind', 'booking_marked_fully_paid')
154
+ .eq('detail->>mark_event_at', paidMarkedAtIso)
155
+ .order('created_at', { ascending: false })
156
+ .limit(1)
157
+ .maybeSingle();
158
+ if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
159
+ if (!event) {
160
+ return fail(409, 'no_audit_snapshot',
161
+ 'No recorded snapshot exactly matching this booking\'s current paid_marked_at was found, so there is nothing safe to revert to automatically. ' +
162
+ 'Correct it by hand and log an ops_events row before relying on this action for it again.');
163
+ }
164
+
165
+ const d = (event.detail ?? {}) as Record<string, unknown>;
166
+ const priorStatus = typeof d.prior_status === 'string' ? d.prior_status : null;
167
+ const priorDiscountCents = d.prior_discount_applied_cents;
168
+ const priorChargedRaw = d.prior_charged_amount_cents;
169
+ const priorPaymentSource = d.prior_payment_source;
170
+
171
+ if (
172
+ !priorStatus || !PAYABLE_STATUSES.has(priorStatus)
173
+ || !isSafeNonNegInt(priorDiscountCents)
174
+ || !(priorChargedRaw === null || isSafeNonNegInt(priorChargedRaw))
175
+ || typeof priorPaymentSource !== 'string' || !PAYMENT_SOURCES.has(priorPaymentSource)
176
+ ) {
177
+ return fail(409, 'incomplete_audit_snapshot',
178
+ 'The recorded snapshot for this booking is missing or has invalid values for fields this action needs to revert it safely. Correct it by hand instead.');
179
+ }
180
+
181
+ // Drift check: bookings_amount_math_check depends on list/dynamic/
182
+ // credit too, and nothing else guards those against having changed
183
+ // (e.g. a reschedule or a credit adjustment) between the mark-paid and
184
+ // this undo. If any of them moved, the snapshot no longer describes a
185
+ // state that's safe to restore -- refuse rather than either violate the
186
+ // CHECK (a raw Postgres error surfaced to staff) or silently restore a
187
+ // stale discount against new inputs.
188
+ const driftChecks: Array<[string, unknown, number]> = [
189
+ ['list_amount_cents', d.prior_list_amount_cents, Number(booking.list_amount_cents)],
190
+ ['dynamic_discount_cents', d.prior_dynamic_discount_cents, Number(booking.dynamic_discount_cents ?? 0)],
191
+ ['credit_applied_cents', d.prior_credit_applied_cents, Number(booking.credit_applied_cents ?? 0)],
192
+ ];
193
+ for (const [label, snapshot, live] of driftChecks) {
194
+ if (!isSafeNonNegInt(snapshot) || snapshot !== live) {
195
+ return fail(409, 'booking_drifted',
196
+ `This booking's ${label} changed since it was marked paid (or the snapshot doesn't record it), so the recorded snapshot no longer describes a state it's safe to restore. Correct it by hand.`);
197
+ }
198
+ }
199
+
200
+ const priorChargedCents = priorChargedRaw === null ? null : (priorChargedRaw as number);
201
+ const priorPaidNotes = typeof d.prior_paid_notes === 'string' ? d.prior_paid_notes : null;
202
+ const priorDepositPaidAt = typeof d.prior_deposit_paid_at === 'string' ? d.prior_deposit_paid_at : null;
203
+ const holdRestore = restoreHold(d.prior_hold_expires_at);
204
+ if (!holdRestore.ok) {
205
+ return fail(409, 'unrestorable_hold',
206
+ 'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand, then undo the rest separately if needed.');
207
+ }
208
+
209
+ const { data: updated, error: updErr } = await admin
210
+ .from('bookings')
211
+ .update({
212
+ status: priorStatus,
213
+ charged_amount_cents: priorChargedCents,
214
+ discount_applied_cents: priorDiscountCents,
215
+ payment_source: priorPaymentSource,
216
+ paid_notes: priorPaidNotes,
217
+ paid_method: null,
218
+ paid_marked_by_email: null,
219
+ paid_marked_at: null,
220
+ deposit_paid_at: priorDepositPaidAt,
221
+ hold_expires_at: holdRestore.value,
222
+ })
223
+ .eq('id', booking_id)
224
+ .eq('status', 'paid')
225
+ .eq('paid_marked_at', booking.paid_marked_at) // CAS
226
+ .eq('charged_amount_cents', booking.charged_amount_cents) // CAS -- catch a concurrent money-column write the timestamp CAS alone wouldn't
227
+ .eq('discount_applied_cents', booking.discount_applied_cents) // CAS, same reason
228
+ .select('id')
229
+ .maybeSingle();
230
+ if (updErr) return fail(500, 'update_failed', updErr.message);
231
+ if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
232
+
233
+ // 'sponsored' is the only paid_method that genuinely moved zero dollars.
234
+ // Every other value -- including 'other', the catch-all for real money
235
+ // that isn't cash/stripe/mercury -- means this warning must fire.
236
+ const involvesRealMoney = booking.paid_method !== 'sponsored';
237
+
238
+ await logOps(admin, 'booking_paid_mark_undone', {
239
+ booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
240
+ undone_event_id: event.id, reverted_to_status: priorStatus,
241
+ prior_paid_method: booking.paid_method ?? null,
242
+ prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
243
+ prior_paid_marked_at: booking.paid_marked_at ?? null,
244
+ prior_charged_amount_cents_before_undo: booking.charged_amount_cents ?? null,
245
+ hold_extended: holdRestore.extended,
246
+ }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
247
+
248
+ const notes: string[] = [];
249
+ if (involvesRealMoney) {
250
+ notes.push('This only corrected the booking record. It did NOT reverse any real payment -- if money needs to be returned, handle that separately (Stripe refund / outgoing transfer).');
251
+ }
252
+ if (holdRestore.extended) {
253
+ notes.push(`The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff act.`);
254
+ }
255
+
256
+ return json(200, {
257
+ ok: true, booking_id, status: priorStatus, hold_expires_at: holdRestore.value, hold_extended: holdRestore.extended,
258
+ warning: notes.length ? notes.join(' ') : undefined,
259
+ });
260
+ }
261
+
262
+ // action === 'undo_skip_contract'
263
+ const { data: booking, error: bErr } = await admin
264
+ .from('bookings')
265
+ .select('id,status,contract_skipped_at,contract_skipped_by_email,contract_skip_reason')
266
+ .eq('id', booking_id)
267
+ .maybeSingle();
268
+ if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
269
+ if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
270
+ if (!booking.contract_skipped_at) {
271
+ return fail(409, 'not_skipped', "This booking's contract was not marked skipped; nothing to undo.");
272
+ }
273
+ if (booking.status !== 'pending') {
274
+ return fail(409, 'not_pending',
275
+ `Booking status is "${booking.status}"; only a still-pending booking's skip can be undone. If it's already been marked paid, undo that first.`);
276
+ }
277
+
278
+ // Same normalization as undo_mark_paid -- see the comment there.
279
+ const contractSkippedAtIso = new Date(booking.contract_skipped_at).toISOString();
280
+ const { data: event, error: evErr } = await admin
281
+ .from('ops_events')
282
+ .select('id,detail')
283
+ .eq('booking_id', booking_id)
284
+ .eq('kind', 'commons_contract_skipped')
285
+ .eq('detail->>skip_event_at', contractSkippedAtIso)
286
+ .order('created_at', { ascending: false })
287
+ .limit(1)
288
+ .maybeSingle();
289
+ if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
290
+ if (!event) {
291
+ return fail(409, 'no_audit_snapshot',
292
+ 'No recorded snapshot exactly matching this booking\'s current contract_skipped_at was found, so there is nothing safe to revert to automatically. ' +
293
+ 'Correct it by hand and log an ops_events row before relying on this action for it again.');
294
+ }
295
+ const d = (event.detail ?? {}) as Record<string, unknown>;
296
+ const holdRestore = restoreHold(d.prior_hold_expires_at);
297
+ if (!holdRestore.ok) {
298
+ return fail(409, 'unrestorable_hold',
299
+ 'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand instead.');
300
+ }
301
+
302
+ const { data: updated, error: updErr } = await admin
303
+ .from('bookings')
304
+ .update({
305
+ contract_skipped_at: null,
306
+ contract_skipped_by_email: null,
307
+ contract_skip_reason: null,
308
+ hold_expires_at: holdRestore.value,
309
+ })
310
+ .eq('id', booking_id)
311
+ .eq('status', 'pending')
312
+ .eq('contract_skipped_at', booking.contract_skipped_at) // CAS
313
+ .select('id')
314
+ .maybeSingle();
315
+ if (updErr) return fail(500, 'update_failed', updErr.message);
316
+ if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
317
+
318
+ await logOps(admin, 'commons_contract_skip_undone', {
319
+ booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
320
+ undone_event_id: event.id,
321
+ prior_skip_reason: booking.contract_skip_reason ?? null,
322
+ prior_skipped_by_email: booking.contract_skipped_by_email ?? null,
323
+ hold_extended: holdRestore.extended,
324
+ }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
325
+
326
+ return json(200, {
327
+ ok: true, booking_id, status: 'pending', contract_skip_cleared: true,
328
+ hold_expires_at: holdRestore.value,
329
+ warning: holdRestore.extended
330
+ ? `The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff send a contract or otherwise act.`
331
+ : undefined,
332
+ });
333
+ }