@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,203 +1,203 @@
1
- // supabase/functions/admin-mark-booking-paid/index.ts
2
- //
3
- // Manual "mark fully paid" admin action, for payments collected outside the
4
- // normal Stripe checkout flow -- cash, a Mercury wire/ACH, a sponsorship, or
5
- // anything else staff need to record by hand. Works on any booking tier; the
6
- // Commons (tier-3) contract flow is the main consumer since its remaining
7
- // balance is explicitly collected by check/ACH per the contract, never
8
- // through Stripe.
9
- import { createClient } from 'npm:@supabase/supabase-js@2';
10
- import { z } from 'npm:zod@3.23.8';
11
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
12
- import Stripe from 'npm:stripe@17.5.0';
13
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
-
16
- const corsHeaders = {
17
- 'Access-Control-Allow-Origin': '*',
18
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
19
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
20
- };
21
-
22
- interface CallerClaims { sub: string; email?: string; aal?: string }
23
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
- function getJwks(supabaseUrl: string) {
26
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
- return jwksCache;
28
- }
29
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
30
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
31
- const token = authHeader.slice(7).trim();
32
- try {
33
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
34
- const claims = payload as unknown as CallerClaims;
35
- if (!claims.sub) return null;
36
- return claims;
37
- } catch { return null; }
38
- }
39
- function json(status: number, body: unknown) {
40
- return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
41
- }
42
- function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
43
- return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
44
- }
45
-
46
- const PAYMENT_METHODS = ['cash', 'stripe', 'mercury', 'sponsored', 'other'] as const;
47
- const Body = z.object({
48
- booking_id: z.string().uuid(),
49
- payment_method: z.enum(PAYMENT_METHODS),
50
- notes: z.string().trim().max(500).optional(),
51
- }).refine(
52
- (b) => b.payment_method !== 'stripe' || !!b.notes?.trim(),
53
- { message: 'notes (e.g. the Stripe payment/charge ID) are required when payment_method is "stripe" -- this action does not itself touch Stripe.', path: ['notes'] },
54
- );
55
-
56
- // Only a live, still-collectible booking can be marked paid. Deliberately an
57
- // allowlist, not a denylist of terminal statuses -- a new booking_status
58
- // value added later (e.g. a dispute/chargeback state) should default to
59
- // NOT payable until someone explicitly decides otherwise.
60
- const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
61
-
62
- export async function handle(req: Request): Promise<Response> {
63
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
64
- if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
65
-
66
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
67
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
68
-
69
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
70
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
71
- if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
72
- if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
73
- const callerEmail = (caller.email ?? '').toLowerCase();
74
- if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
75
-
76
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
77
-
78
- const [ipOk, emailOk] = await Promise.all([
79
- checkRateLimit(admin, 'admin-mark-booking-paid-ip', clientIp(req), 20, 300),
80
- checkRateLimit(admin, 'admin-mark-booking-paid-email', callerEmail, 20, 300),
81
- ]);
82
- if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
83
-
84
- const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
85
- if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
86
- if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
87
-
88
- let raw: unknown;
89
- try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
90
- const parsed = Body.safeParse(raw);
91
- if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
92
- const { booking_id, payment_method, notes } = parsed.data;
93
-
94
- const { data: booking, error: bErr } = await admin
95
- .from('bookings')
96
- .select('id,status,list_amount_cents,dynamic_discount_cents,credit_applied_cents,discount_applied_cents,charged_amount_cents,paid_method,stripe_session_id,hold_expires_at,deposit_paid_at,payment_source,paid_notes,paid_marked_by_email,paid_marked_at')
97
- .eq('id', booking_id)
98
- .maybeSingle();
99
- if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
100
- if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
101
- const priorStatus = String(booking.status);
102
- if (!PAYABLE_STATUSES.has(priorStatus)) {
103
- return fail(409, 'not_payable', `Booking status is "${priorStatus}"; nothing to mark paid.`);
104
- }
105
-
106
- // Never guess an amount -- a null list price means the booking isn't
107
- // priced yet. (Number(null ?? 0) would silently treat that as $0 and a
108
- // Postgres CHECK constraint passes on a NULL comparison, so nothing else
109
- // would have caught this.)
110
- if (booking.list_amount_cents == null) {
111
- return fail(409, 'missing_list_amount', 'This booking has no list amount set; fix the booking before marking it paid.');
112
- }
113
-
114
- const grossCents = Number(booking.list_amount_cents)
115
- - Number(booking.dynamic_discount_cents ?? 0)
116
- - Number(booking.credit_applied_cents ?? 0)
117
- - Number(booking.discount_applied_cents ?? 0);
118
-
119
- // 'sponsored' means the venue comped it -- $0 actually changed hands, so
120
- // charged_amount_cents must be $0. We fold the remainder into
121
- // discount_applied_cents so bookings_amount_math_check is satisfied
122
- // truthfully instead of recording full list revenue for a comped event.
123
- const isSponsored = payment_method === 'sponsored';
124
- const netCents = isSponsored ? 0 : grossCents;
125
- if (!isSponsored && netCents <= 0) {
126
- return fail(409, 'invalid_amount', `Computed amount is $${(netCents / 100).toFixed(2)}, which isn't a valid amount to mark paid. Check the booking's discounts/credits.`);
127
- }
128
- const extraDiscountForSponsored = isSponsored ? grossCents : 0;
129
-
130
- // If there's still a live, unpaid Stripe checkout session on this booking
131
- // (the deposit link emailed on contract signature), void it before
132
- // recording an out-of-band payment. The real deposit-paid webhook is
133
- // CAS-guarded on status='pending' so it can no longer corrupt this row
134
- // once we flip to 'paid' below -- but Stripe would still capture real
135
- // money if the customer clicks that live link later, which is the actual
136
- // harm this guards against.
137
- if (booking.stripe_session_id && priorStatus === 'pending') {
138
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
139
- if (!stripeKey) {
140
- return fail(500, 'stripe_not_configured', 'STRIPE_SECRET_KEY is not set; cannot safely void the outstanding deposit link.');
141
- }
142
- try {
143
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
144
- const session = await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
145
- if (session.status === 'open') {
146
- await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
147
- }
148
- } catch (e) {
149
- return fail(502, 'stripe_session_expire_failed',
150
- `Could not void the outstanding Stripe deposit link (${e instanceof Error ? e.message : String(e)}). Void it manually in the Stripe dashboard, then retry.`);
151
- }
152
- }
153
-
154
- const markedAt = new Date().toISOString();
155
-
156
- const { data: updated, error: updErr } = await admin
157
- .from('bookings')
158
- .update({
159
- status: 'paid',
160
- charged_amount_cents: netCents,
161
- discount_applied_cents: Number(booking.discount_applied_cents ?? 0) + extraDiscountForSponsored,
162
- paid_method: payment_method,
163
- payment_source: payment_method === 'stripe' ? 'stripe' : 'offline',
164
- paid_notes: notes ?? null,
165
- paid_marked_by_email: callerEmail,
166
- paid_marked_at: markedAt,
167
- hold_expires_at: null,
168
- })
169
- .eq('id', booking_id)
170
- .eq('status', priorStatus) // CAS -- refuse a stale double-click racing a real webhook
171
- .select('id')
172
- .maybeSingle();
173
- if (updErr) return fail(500, 'update_failed', updErr.message);
174
- if (!updated) return fail(409, 'status_changed', "This booking's status changed before the update landed — reload and try again.");
175
-
176
- await logOps(admin, 'booking_marked_fully_paid', {
177
- booking_id, actor: callerEmail, actor_user_id: caller.sub, payment_method, notes: notes ?? null,
178
- prior_status: priorStatus, charged_amount_cents: netCents,
179
- // mark_event_at ties this exact log row to the exact row mutation it
180
- // describes -- admin-correct-booking matches on this instead of trusting
181
- // "most recent row of this kind," which a swallowed insert error (or a
182
- // second mark-paid/undo cycle) could otherwise make stale-but-present.
183
- mark_event_at: markedAt,
184
- // Full "before" snapshot of every column this action mutates AND every
185
- // column bookings_amount_math_check depends on, so admin-correct-booking
186
- // can both revert this exact row and detect drift instead of guessing.
187
- prior_charged_amount_cents: booking.charged_amount_cents ?? null,
188
- prior_discount_applied_cents: Number(booking.discount_applied_cents ?? 0),
189
- prior_list_amount_cents: Number(booking.list_amount_cents),
190
- prior_dynamic_discount_cents: Number(booking.dynamic_discount_cents ?? 0),
191
- prior_credit_applied_cents: Number(booking.credit_applied_cents ?? 0),
192
- prior_paid_method: booking.paid_method ?? null,
193
- prior_payment_source: booking.payment_source ?? null,
194
- prior_paid_notes: booking.paid_notes ?? null,
195
- prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
196
- prior_paid_marked_at: booking.paid_marked_at ?? null,
197
- prior_hold_expires_at: booking.hold_expires_at ?? null,
198
- prior_deposit_paid_at: booking.deposit_paid_at ?? null,
199
- }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
200
-
201
-
202
- return json(200, { ok: true, booking_id, status: 'paid', charged_amount_cents: netCents });
203
- }
1
+ // supabase/functions/admin-mark-booking-paid/index.ts
2
+ //
3
+ // Manual "mark fully paid" admin action, for payments collected outside the
4
+ // normal Stripe checkout flow -- cash, a Mercury wire/ACH, a sponsorship, or
5
+ // anything else staff need to record by hand. Works on any booking tier; the
6
+ // Commons (tier-3) contract flow is the main consumer since its remaining
7
+ // balance is explicitly collected by check/ACH per the contract, never
8
+ // through Stripe.
9
+ import { createClient } from 'npm:@supabase/supabase-js@2';
10
+ import { z } from 'npm:zod@3.23.8';
11
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
12
+ import Stripe from 'npm:stripe@17.5.0';
13
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
14
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
15
+
16
+ const corsHeaders = {
17
+ 'Access-Control-Allow-Origin': '*',
18
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
19
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
20
+ };
21
+
22
+ interface CallerClaims { sub: string; email?: string; aal?: string }
23
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
+ function getJwks(supabaseUrl: string) {
26
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
30
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
31
+ const token = authHeader.slice(7).trim();
32
+ try {
33
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
34
+ const claims = payload as unknown as CallerClaims;
35
+ if (!claims.sub) return null;
36
+ return claims;
37
+ } catch { return null; }
38
+ }
39
+ function json(status: number, body: unknown) {
40
+ return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
41
+ }
42
+ function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
43
+ return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
44
+ }
45
+
46
+ const PAYMENT_METHODS = ['cash', 'stripe', 'mercury', 'sponsored', 'other'] as const;
47
+ const Body = z.object({
48
+ booking_id: z.string().uuid(),
49
+ payment_method: z.enum(PAYMENT_METHODS),
50
+ notes: z.string().trim().max(500).optional(),
51
+ }).refine(
52
+ (b) => b.payment_method !== 'stripe' || !!b.notes?.trim(),
53
+ { message: 'notes (e.g. the Stripe payment/charge ID) are required when payment_method is "stripe" -- this action does not itself touch Stripe.', path: ['notes'] },
54
+ );
55
+
56
+ // Only a live, still-collectible booking can be marked paid. Deliberately an
57
+ // allowlist, not a denylist of terminal statuses -- a new booking_status
58
+ // value added later (e.g. a dispute/chargeback state) should default to
59
+ // NOT payable until someone explicitly decides otherwise.
60
+ const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
61
+
62
+ export async function handle(req: Request): Promise<Response> {
63
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
64
+ if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
65
+
66
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
67
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
68
+
69
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
70
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
71
+ if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
72
+ if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
73
+ const callerEmail = (caller.email ?? '').toLowerCase();
74
+ if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
75
+
76
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
77
+
78
+ const [ipOk, emailOk] = await Promise.all([
79
+ checkRateLimit(admin, 'admin-mark-booking-paid-ip', clientIp(req), 20, 300),
80
+ checkRateLimit(admin, 'admin-mark-booking-paid-email', callerEmail, 20, 300),
81
+ ]);
82
+ if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
83
+
84
+ const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
85
+ if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
86
+ if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
87
+
88
+ let raw: unknown;
89
+ try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
90
+ const parsed = Body.safeParse(raw);
91
+ if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
92
+ const { booking_id, payment_method, notes } = parsed.data;
93
+
94
+ const { data: booking, error: bErr } = await admin
95
+ .from('bookings')
96
+ .select('id,status,list_amount_cents,dynamic_discount_cents,credit_applied_cents,discount_applied_cents,charged_amount_cents,paid_method,stripe_session_id,hold_expires_at,deposit_paid_at,payment_source,paid_notes,paid_marked_by_email,paid_marked_at')
97
+ .eq('id', booking_id)
98
+ .maybeSingle();
99
+ if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
100
+ if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
101
+ const priorStatus = String(booking.status);
102
+ if (!PAYABLE_STATUSES.has(priorStatus)) {
103
+ return fail(409, 'not_payable', `Booking status is "${priorStatus}"; nothing to mark paid.`);
104
+ }
105
+
106
+ // Never guess an amount -- a null list price means the booking isn't
107
+ // priced yet. (Number(null ?? 0) would silently treat that as $0 and a
108
+ // Postgres CHECK constraint passes on a NULL comparison, so nothing else
109
+ // would have caught this.)
110
+ if (booking.list_amount_cents == null) {
111
+ return fail(409, 'missing_list_amount', 'This booking has no list amount set; fix the booking before marking it paid.');
112
+ }
113
+
114
+ const grossCents = Number(booking.list_amount_cents)
115
+ - Number(booking.dynamic_discount_cents ?? 0)
116
+ - Number(booking.credit_applied_cents ?? 0)
117
+ - Number(booking.discount_applied_cents ?? 0);
118
+
119
+ // 'sponsored' means the venue comped it -- $0 actually changed hands, so
120
+ // charged_amount_cents must be $0. We fold the remainder into
121
+ // discount_applied_cents so bookings_amount_math_check is satisfied
122
+ // truthfully instead of recording full list revenue for a comped event.
123
+ const isSponsored = payment_method === 'sponsored';
124
+ const netCents = isSponsored ? 0 : grossCents;
125
+ if (!isSponsored && netCents <= 0) {
126
+ return fail(409, 'invalid_amount', `Computed amount is $${(netCents / 100).toFixed(2)}, which isn't a valid amount to mark paid. Check the booking's discounts/credits.`);
127
+ }
128
+ const extraDiscountForSponsored = isSponsored ? grossCents : 0;
129
+
130
+ // If there's still a live, unpaid Stripe checkout session on this booking
131
+ // (the deposit link emailed on contract signature), void it before
132
+ // recording an out-of-band payment. The real deposit-paid webhook is
133
+ // CAS-guarded on status='pending' so it can no longer corrupt this row
134
+ // once we flip to 'paid' below -- but Stripe would still capture real
135
+ // money if the customer clicks that live link later, which is the actual
136
+ // harm this guards against.
137
+ if (booking.stripe_session_id && priorStatus === 'pending') {
138
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
139
+ if (!stripeKey) {
140
+ return fail(500, 'stripe_not_configured', 'STRIPE_SECRET_KEY is not set; cannot safely void the outstanding deposit link.');
141
+ }
142
+ try {
143
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
144
+ const session = await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
145
+ if (session.status === 'open') {
146
+ await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
147
+ }
148
+ } catch (e) {
149
+ return fail(502, 'stripe_session_expire_failed',
150
+ `Could not void the outstanding Stripe deposit link (${e instanceof Error ? e.message : String(e)}). Void it manually in the Stripe dashboard, then retry.`);
151
+ }
152
+ }
153
+
154
+ const markedAt = new Date().toISOString();
155
+
156
+ const { data: updated, error: updErr } = await admin
157
+ .from('bookings')
158
+ .update({
159
+ status: 'paid',
160
+ charged_amount_cents: netCents,
161
+ discount_applied_cents: Number(booking.discount_applied_cents ?? 0) + extraDiscountForSponsored,
162
+ paid_method: payment_method,
163
+ payment_source: payment_method === 'stripe' ? 'stripe' : 'offline',
164
+ paid_notes: notes ?? null,
165
+ paid_marked_by_email: callerEmail,
166
+ paid_marked_at: markedAt,
167
+ hold_expires_at: null,
168
+ })
169
+ .eq('id', booking_id)
170
+ .eq('status', priorStatus) // CAS -- refuse a stale double-click racing a real webhook
171
+ .select('id')
172
+ .maybeSingle();
173
+ if (updErr) return fail(500, 'update_failed', updErr.message);
174
+ if (!updated) return fail(409, 'status_changed', "This booking's status changed before the update landed — reload and try again.");
175
+
176
+ await logOps(admin, 'booking_marked_fully_paid', {
177
+ booking_id, actor: callerEmail, actor_user_id: caller.sub, payment_method, notes: notes ?? null,
178
+ prior_status: priorStatus, charged_amount_cents: netCents,
179
+ // mark_event_at ties this exact log row to the exact row mutation it
180
+ // describes -- admin-correct-booking matches on this instead of trusting
181
+ // "most recent row of this kind," which a swallowed insert error (or a
182
+ // second mark-paid/undo cycle) could otherwise make stale-but-present.
183
+ mark_event_at: markedAt,
184
+ // Full "before" snapshot of every column this action mutates AND every
185
+ // column bookings_amount_math_check depends on, so admin-correct-booking
186
+ // can both revert this exact row and detect drift instead of guessing.
187
+ prior_charged_amount_cents: booking.charged_amount_cents ?? null,
188
+ prior_discount_applied_cents: Number(booking.discount_applied_cents ?? 0),
189
+ prior_list_amount_cents: Number(booking.list_amount_cents),
190
+ prior_dynamic_discount_cents: Number(booking.dynamic_discount_cents ?? 0),
191
+ prior_credit_applied_cents: Number(booking.credit_applied_cents ?? 0),
192
+ prior_paid_method: booking.paid_method ?? null,
193
+ prior_payment_source: booking.payment_source ?? null,
194
+ prior_paid_notes: booking.paid_notes ?? null,
195
+ prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
196
+ prior_paid_marked_at: booking.paid_marked_at ?? null,
197
+ prior_hold_expires_at: booking.hold_expires_at ?? null,
198
+ prior_deposit_paid_at: booking.deposit_paid_at ?? null,
199
+ }, { severity: 'warning', bookingId: booking_id }).catch(() => {});
200
+
201
+
202
+ return json(200, { ok: true, booking_id, status: 'paid', charged_amount_cents: netCents });
203
+ }