@simplelayer/graniteer-core 0.1.2 → 0.2.0

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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  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 -0
  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 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  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 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,231 @@
1
+ // supabase/functions/admin-issue-day-pass/index.ts
2
+ import { createClient } from 'npm:@supabase/supabase-js@2';
3
+ import Stripe from 'npm:stripe@17.5.0';
4
+ import { z } from 'npm:zod@3.23.8';
5
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
6
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
7
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
8
+
9
+ const corsHeaders = {
10
+ 'Access-Control-Allow-Origin': '*',
11
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
12
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
13
+ };
14
+
15
+ const DAY_PASS_SLUG = 'day-pass';
16
+
17
+ interface CallerClaims { sub: string; email?: string; aal?: string }
18
+
19
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
20
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
21
+ function getJwks(supabaseUrl: string) {
22
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
23
+ return jwksCache;
24
+ }
25
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
26
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
27
+ const token = authHeader.slice(7).trim();
28
+ try {
29
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
30
+ const claims = payload as unknown as CallerClaims;
31
+ if (!claims.sub) return null;
32
+ return claims;
33
+ } catch { return null; }
34
+ }
35
+
36
+ function json(status: number, body: unknown) {
37
+ return new Response(JSON.stringify(body), {
38
+ status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
39
+ });
40
+ }
41
+
42
+ function todayLA(): string {
43
+ return new Intl.DateTimeFormat('en-CA', {
44
+ timeZone: 'America/Los_Angeles',
45
+ year: 'numeric', month: '2-digit', day: '2-digit',
46
+ }).format(new Date());
47
+ }
48
+
49
+ const Body = z.object({
50
+ guest_name: z.string().trim().min(1).max(200),
51
+ guest_email: z.string().trim().email().max(255),
52
+ visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
53
+ issue_mode: z.enum(['payment_link', 'paid_offline', 'comp']),
54
+ });
55
+
56
+ export interface AdminIssueDayPassDeps {
57
+ provisionDayPass: (
58
+ admin: ReturnType<typeof createClient>,
59
+ dayPassId: string,
60
+ visitDate: string,
61
+ email: string,
62
+ guestName: string,
63
+ ) => Promise<{
64
+ status: 'provisioned' | 'dry_run' | 'disabled' | 'failed';
65
+ credentialStatus: string | null;
66
+ wifiCode: string | null;
67
+ wifiValidFromIso: string | null;
68
+ wifiValidToIso: string | null;
69
+ error: string | null;
70
+ }>;
71
+ }
72
+
73
+ export async function handle(req: Request, operator: { domain: string }, deps: AdminIssueDayPassDeps): Promise<Response> {
74
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
75
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
76
+
77
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
78
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
79
+
80
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
81
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
82
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
83
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
84
+ const callerEmail = (caller.email ?? '').toLowerCase();
85
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
86
+
87
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
88
+ auth: { persistSession: false, autoRefreshToken: false },
89
+ });
90
+
91
+ const [ipOk, emailOk] = await Promise.all([
92
+ checkRateLimit(admin, 'admin-issue-day-pass-ip', clientIp(req), 30, 300),
93
+ checkRateLimit(admin, 'admin-issue-day-pass-email', callerEmail, 20, 300),
94
+ ]);
95
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
96
+
97
+ const { data: allow, error: allowErr } = await admin
98
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
99
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
100
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
101
+
102
+ let raw: unknown;
103
+ try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
104
+ const parsed = Body.safeParse(raw);
105
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
106
+ const { guest_name, guest_email, visit_date, issue_mode } = parsed.data;
107
+ const emailKey = guest_email.toLowerCase();
108
+
109
+ if (visit_date < todayLA()) return json(400, { ok: false, error: 'visit_date_in_past' });
110
+
111
+ const { data: plan, error: pErr } = await admin
112
+ .from('membership_plans')
113
+ .select('id,slug,name,active,billable,billing_interval,stripe_price_id,price_cents')
114
+ .eq('slug', DAY_PASS_SLUG)
115
+ .maybeSingle();
116
+ if (pErr) return json(500, { ok: false, error: 'load_plan_failed', detail: pErr.message });
117
+ if (!plan || plan.active !== true || plan.billable !== true || plan.billing_interval === 'month') {
118
+ return json(400, { ok: false, error: 'day_pass_plan_unavailable' });
119
+ }
120
+ const planPriceCents = plan.price_cents ?? 0;
121
+
122
+ try {
123
+ if (issue_mode === 'payment_link') {
124
+ if (!plan.stripe_price_id) return json(400, { ok: false, error: 'day_pass_price_not_configured' });
125
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
126
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
127
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
128
+
129
+ let customerId: string | null = null;
130
+ try {
131
+ const listed = await stripe.customers.list({ email: emailKey, limit: 1 });
132
+ if (listed.data.length > 0) customerId = listed.data[0].id;
133
+ } catch (e) {
134
+ console.warn('[admin-issue-day-pass] customers.list failed', e);
135
+ }
136
+ if (!customerId) customerId = (await stripe.customers.create({ email: emailKey, name: guest_name })).id;
137
+
138
+ const origin = req.headers.get('origin');
139
+ const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
140
+
141
+ const session = await stripe.checkout.sessions.create({
142
+ mode: 'payment',
143
+ customer: customerId,
144
+ line_items: [{ price: plan.stripe_price_id, quantity: 1 }],
145
+ allow_promotion_codes: true,
146
+ metadata: {
147
+ checkout_type: 'day_pass',
148
+ plan_slug: plan.slug,
149
+ plan_id: plan.id,
150
+ visit_date,
151
+ issued_by: callerEmail,
152
+ },
153
+ payment_intent_data: { receipt_email: emailKey },
154
+ success_url: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
155
+ cancel_url: `${base}/pricing`,
156
+ });
157
+
158
+ return json(200, {
159
+ ok: true, issue_mode, url: session.url, session_id: session.id,
160
+ amount_cents: planPriceCents,
161
+ });
162
+ }
163
+
164
+ const source = issue_mode === 'comp' ? 'comp' : 'offline';
165
+ const amountCents = issue_mode === 'comp' ? 0 : planPriceCents;
166
+ const localRef = `${source}_${crypto.randomUUID()}`;
167
+
168
+ const { data: row, error: insErr } = await admin
169
+ .from('day_pass_purchases')
170
+ .insert({
171
+ email: emailKey,
172
+ customer_name: guest_name,
173
+ stripe_checkout_session_id: localRef,
174
+ plan_id: plan.id,
175
+ amount_cents: amountCents,
176
+ visit_date,
177
+ payment_source: source,
178
+ created_by: callerEmail,
179
+ })
180
+ .select('id')
181
+ .single();
182
+ if (insErr) return json(500, { ok: false, error: 'insert_failed', detail: insErr.message });
183
+
184
+ let provisioningStatus: "provisioned" | "dry_run" | "disabled" | "failed" = "failed";
185
+ let wifiCode: string | null = null;
186
+ try {
187
+ const outcome = await deps.provisionDayPass(admin, row.id, visit_date, emailKey, guest_name);
188
+ provisioningStatus = outcome.status;
189
+ wifiCode = outcome.wifiCode;
190
+ const { error: provWriteErr } = await admin
191
+ .from('day_pass_purchases')
192
+ .update({
193
+ provisioning_status: outcome.status,
194
+ credential_status: outcome.credentialStatus,
195
+ wifi_code: outcome.wifiCode,
196
+ wifi_valid_from: outcome.wifiValidFromIso,
197
+ wifi_valid_to: outcome.wifiValidToIso,
198
+ provisioned_at: (outcome.status === 'provisioned' || outcome.status === 'dry_run')
199
+ ? new Date().toISOString()
200
+ : null,
201
+ provision_error: outcome.error,
202
+ })
203
+ .eq('id', row.id);
204
+ if (provWriteErr) {
205
+ console.error('[admin-issue-day-pass] provisioning-status write failed', provWriteErr);
206
+ await logOps(admin, 'day_pass_provision_status_write_failed',
207
+ { day_pass_id: row.id, message: provWriteErr.message, pg_code: (provWriteErr as { code?: string }).code },
208
+ { severity: 'error' }).catch(() => {});
209
+ }
210
+ } catch (e) {
211
+ console.error('[admin-issue-day-pass] provisioning threw', e);
212
+ await logOps(admin, 'day_pass_provision_threw',
213
+ { day_pass_id: row.id, message: e instanceof Error ? e.message : String(e) },
214
+ { severity: 'error' }).catch(() => {});
215
+ }
216
+
217
+ return json(200, {
218
+ ok: true, issue_mode, day_pass_id: row.id, amount_cents: amountCents,
219
+ provisioning_status: provisioningStatus,
220
+ wifi_code: wifiCode,
221
+ });
222
+ } catch (e) {
223
+ console.error('admin-issue-day-pass error', e);
224
+ try {
225
+ await logOps(admin, 'admin_issue_day_pass_error',
226
+ { message: e instanceof Error ? e.message : String(e), issue_mode, actor: callerEmail },
227
+ { severity: 'error' });
228
+ } catch { /* ignore */ }
229
+ return json(500, { ok: false, error: 'unexpected_error' });
230
+ }
231
+ }
@@ -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
+ }