@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,298 @@
1
+ // Tier 3 (Commons) event deposit: Stripe Checkout payload construction and the
2
+ // two customer emails (deposit link, deposit receipt).
3
+ //
4
+ // Same GHL transport, headers, timeouts and error classification as
5
+ // bookingAgreementEmail.ts — do not introduce a second email channel.
6
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
7
+ import type Stripe from 'npm:stripe@17.5.0';
8
+ import { logOps } from './ops.ts';
9
+
10
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
11
+
12
+ export type CommonsEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
13
+
14
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
15
+ const LA_TZ = 'America/Los_Angeles';
16
+
17
+ export function esc(v: unknown): string {
18
+ return String(v ?? '')
19
+ .replace(/&/g, '&amp;')
20
+ .replace(/</g, '&lt;')
21
+ .replace(/>/g, '&gt;')
22
+ .replace(/"/g, '&quot;')
23
+ .replace(/'/g, '&#39;');
24
+ }
25
+
26
+ export function usd(cents: number | null | undefined): string {
27
+ const c = Number(cents ?? 0);
28
+ return `$${(c / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
29
+ }
30
+
31
+ /** 'YYYY-MM-DD' -> 'September 14, 2027' (no timezone shift: parsed as parts). */
32
+ export function longDateFromYmd(ymd: string | null | undefined): string | null {
33
+ if (!ymd) return null;
34
+ const m = String(ymd).match(/^(\d{4})-(\d{2})-(\d{2})$/);
35
+ if (!m) return null;
36
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
37
+ return new Intl.DateTimeFormat('en-US', {
38
+ timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric',
39
+ }).format(d);
40
+ }
41
+
42
+ /** ISO instant -> 'September 14, 2027' in Pacific. */
43
+ export function longDateFromIso(iso: string | null | undefined): string | null {
44
+ if (!iso) return null;
45
+ const d = new Date(String(iso));
46
+ if (!Number.isFinite(d.getTime())) return null;
47
+ return new Intl.DateTimeFormat('en-US', {
48
+ timeZone: LA_TZ, month: 'long', day: 'numeric', year: 'numeric',
49
+ }).format(d);
50
+ }
51
+
52
+ /** The `metadata.commons` snapshot written once by send-booking-agreement. */
53
+ export interface CommonsSnapshot {
54
+ total_cents?: number;
55
+ deposit_cents?: number;
56
+ balance_cents?: number;
57
+ security_deposit_cents?: number;
58
+ arrival_at?: string;
59
+ checkout_at?: string;
60
+ event_date?: string;
61
+ balance_due_date?: string | null;
62
+ coi_due_date?: string | null;
63
+ client_legal_name?: string;
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Stripe Checkout payload
68
+ // ---------------------------------------------------------------------------
69
+
70
+ export interface CommonsDepositSessionInput {
71
+ bookingId: string;
72
+ agreementId: string;
73
+ signerEmail: string;
74
+ depositCents: number;
75
+ totalCents: number;
76
+ eventDateLabel: string;
77
+ balanceCents: number;
78
+ balanceDueLabel: string;
79
+ successUrl: string;
80
+ cancelUrl: string;
81
+ }
82
+
83
+ /**
84
+ * Build the exact `stripe.checkout.sessions.create` params for a Commons
85
+ * deposit. Pure — no network — so it can be dry-run logged and unit checked.
86
+ */
87
+ export function buildCommonsDepositSessionParams(
88
+ input: CommonsDepositSessionInput,
89
+ ): Stripe.Checkout.SessionCreateParams {
90
+ const metadata = {
91
+ booking_id: input.bookingId,
92
+ payment_type: 'commons_deposit',
93
+ agreement_id: input.agreementId,
94
+ room_slug: 'commons',
95
+ total_cents: String(input.totalCents),
96
+ deposit_cents: String(input.depositCents),
97
+ };
98
+
99
+ return {
100
+ mode: 'payment',
101
+ payment_method_types: ['card'],
102
+ line_items: [{
103
+ quantity: 1,
104
+ price_data: {
105
+ currency: 'usd',
106
+ unit_amount: input.depositCents,
107
+ product_data: {
108
+ name: `Event deposit (50%) — The Commons — ${input.eventDateLabel}`,
109
+ description:
110
+ `Nonrefundable deposit. Balance of ${usd(input.balanceCents)} due by ${input.balanceDueLabel}.`,
111
+ },
112
+ },
113
+ }],
114
+ customer_email: input.signerEmail,
115
+ client_reference_id: input.bookingId,
116
+ metadata,
117
+ // Mirrored so refund/dispute tooling can resolve the booking from the PI alone.
118
+ payment_intent_data: { metadata: { ...metadata } },
119
+ success_url: input.successUrl,
120
+ cancel_url: input.cancelUrl,
121
+ };
122
+ }
123
+
124
+ /** Deterministic per booking — a retry can never create a second session. */
125
+ export function commonsDepositIdempotencyKey(bookingId: string): string {
126
+ return `commons-deposit-${bookingId}`;
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Email
131
+ // ---------------------------------------------------------------------------
132
+
133
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
134
+ const name = e instanceof Error ? e.name : '';
135
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
136
+ const msg = e instanceof Error ? e.message : String(e);
137
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
138
+ if (m) {
139
+ const code = Number(m[1]);
140
+ if (code === 429 || code >= 500) return 'failed_retryable';
141
+ }
142
+ return 'failed_permanent';
143
+ }
144
+
145
+ const p = (t: string) =>
146
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
147
+
148
+ async function sendViaGhl(
149
+ supabase: SupabaseLike,
150
+ opts: {
151
+ email: string;
152
+ name?: string | null;
153
+ subject: string;
154
+ body: (greeting: string) => string;
155
+ opsPrefix: string;
156
+ bookingId?: string | null;
157
+ operatorShortName: string;
158
+ staffCc: string[];
159
+ },
160
+ ): Promise<CommonsEmailResult> {
161
+ try {
162
+ const apiKey = Deno.env.get('GHL_API_KEY');
163
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
164
+ if (!apiKey || !locationId) {
165
+ await logOps(supabase, `${opts.opsPrefix}_skipped`,
166
+ { email: opts.email, reason: 'ghl_not_configured' },
167
+ { severity: 'warning', bookingId: opts.bookingId ?? null }).catch(() => {});
168
+ return 'skipped';
169
+ }
170
+ const headers = {
171
+ Authorization: `Bearer ${apiKey}`,
172
+ Version: '2021-07-28',
173
+ 'Content-Type': 'application/json',
174
+ Accept: 'application/json',
175
+ };
176
+
177
+ const parts = (opts.name || '').trim().split(/\s+/).filter(Boolean);
178
+ const greetingName = parts[0] || 'there';
179
+ const crmName: { firstName?: string; lastName?: string } = {};
180
+ if (parts[0]) crmName.firstName = parts[0];
181
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
182
+
183
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
184
+ method: 'POST', headers,
185
+ signal: AbortSignal.timeout(8000),
186
+ body: JSON.stringify({
187
+ locationId, ...crmName, email: opts.email,
188
+ source: `${opts.operatorShortName} Website — Commons Event`,
189
+ }),
190
+ });
191
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
192
+ const upJson = await upRes.json();
193
+ const contactId = upJson.contact?.id || upJson.id || null;
194
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
195
+
196
+ const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
197
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
198
+ ${opts.body(esc(greetingName))}
199
+ </td></tr></table></td></tr></table></div>`;
200
+
201
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
202
+ method: 'POST', headers,
203
+ signal: AbortSignal.timeout(8000),
204
+ body: JSON.stringify({
205
+ type: 'Email',
206
+ contactId,
207
+ subject: opts.subject,
208
+ html,
209
+ emailCc: opts.staffCc,
210
+ }),
211
+ });
212
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
213
+
214
+ await logOps(supabase, `${opts.opsPrefix}_sent`, { email: opts.email },
215
+ { severity: 'info', bookingId: opts.bookingId ?? null }).catch(() => {});
216
+ return 'sent';
217
+ } catch (e) {
218
+ const classification = classifyError(e);
219
+ await logOps(supabase, `${opts.opsPrefix}_failed`,
220
+ { email: opts.email, message: e instanceof Error ? e.message : String(e) },
221
+ {
222
+ severity: classification === 'failed_permanent' ? 'error' : 'warning',
223
+ bookingId: opts.bookingId ?? null,
224
+ }).catch(() => {});
225
+ return classification;
226
+ }
227
+ }
228
+
229
+ /** Contract completed — pay the 50% deposit to lock the date. */
230
+ export function sendCommonsDepositLinkEmail(
231
+ supabase: SupabaseLike,
232
+ { email, name, checkoutUrl, eventDateLabel, depositCents, balanceCents, balanceDueLabel, bookingId }: {
233
+ email: string;
234
+ name?: string | null;
235
+ checkoutUrl: string;
236
+ eventDateLabel: string;
237
+ depositCents: number;
238
+ balanceCents: number;
239
+ balanceDueLabel: string;
240
+ bookingId?: string | null;
241
+ },
242
+ operator: { name: string; shortName: string; supportEmail: string },
243
+ staffCc: string[],
244
+ ): Promise<CommonsEmailResult> {
245
+ const subject = `Your ${operator.shortName} event agreement is signed — pay your deposit`;
246
+ return sendViaGhl(supabase, {
247
+ email, name, subject, bookingId, opsPrefix: 'commons_deposit_link_email',
248
+ operatorShortName: operator.shortName, staffCc,
249
+ body: (greeting) => [
250
+ p(`Hi ${greeting},`),
251
+ p(`Thanks for signing your agreement for The Commons on ${esc(eventDateLabel)}. The last step to lock the date is your 50% deposit of ${esc(usd(depositCents))}.`),
252
+ p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Pay your deposit →</a>`),
253
+ p(`The remaining balance of ${esc(usd(balanceCents))} is due by ${esc(balanceDueLabel)}. This link is unique to your event, so please don't forward it.`),
254
+ p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
255
+ p(`— The ${operator.name} team`),
256
+ ].join(''),
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Deposit captured. This REPLACES the standard booking-confirmation email for
262
+ * Commons events — the space is not access-provisioned and there is no
263
+ * calendar invite yet, so the standard copy would be wrong.
264
+ */
265
+ export function sendCommonsDepositReceiptEmail(
266
+ supabase: SupabaseLike,
267
+ { email, name, eventDateLabel, depositCents, balanceCents, balanceDueLabel, coiDueLabel, contractUrl, bookingId }: {
268
+ email: string;
269
+ name?: string | null;
270
+ eventDateLabel: string;
271
+ depositCents: number;
272
+ balanceCents: number;
273
+ balanceDueLabel: string;
274
+ coiDueLabel: string;
275
+ contractUrl?: string | null;
276
+ bookingId?: string | null;
277
+ },
278
+ operator: { name: string; shortName: string; supportEmail: string },
279
+ staffCc: string[],
280
+ ): Promise<CommonsEmailResult> {
281
+ const subject = `Deposit received — your ${operator.shortName} event on ${eventDateLabel}`;
282
+ return sendViaGhl(supabase, {
283
+ email, name, subject, bookingId, opsPrefix: 'commons_deposit_receipt_email',
284
+ operatorShortName: operator.shortName, staffCc,
285
+ body: (greeting) => [
286
+ p(`Hi ${greeting},`),
287
+ p(`We've received your deposit of ${esc(usd(depositCents))} — your event in The Commons on ${esc(eventDateLabel)} is locked in.`),
288
+ p(`<strong>Balance:</strong> ${esc(usd(balanceCents))}, due by ${esc(balanceDueLabel)}.`),
289
+ p(`<strong>Certificate of insurance:</strong> due by ${esc(coiDueLabel)}. Your agreement requires a COI naming ${esc(operator.name)} as an additional insured for the date of your event.`),
290
+ contractUrl
291
+ ? p(`<a href="${esc(contractUrl)}" style="color:#C98A5E">View your signed agreement →</a>`)
292
+ : p(`A copy of your signed agreement was emailed to you when signing completed.`),
293
+ p(`We'll be in touch before your date to confirm setup, timing and access details.`),
294
+ p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
295
+ p(`— The ${operator.name} team`),
296
+ ].join(''),
297
+ });
298
+ }
@@ -0,0 +1,237 @@
1
+ // Tier 3 (Commons) "contract completed -> collect the 50% deposit" branch of
2
+ // the boldsign-webhook booking-agreement handler.
3
+ //
4
+ // Contract with the caller (bookingAgreementWebhook.ts):
5
+ // - returns { processed: true } -> caller may mark the boldsign_events row processed
6
+ // - returns { processed: false } -> caller MUST leave the ledger row unprocessed
7
+ // so the existing stale-row reprocessing retries the side effect.
8
+ // Either way the caller returns 200 to BoldSign.
9
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
10
+ import Stripe from 'npm:stripe@17.5.0';
11
+ import { logOps } from './ops.ts';
12
+ import {
13
+ buildCommonsDepositSessionParams,
14
+ commonsDepositIdempotencyKey,
15
+ longDateFromIso,
16
+ longDateFromYmd,
17
+ sendCommonsDepositLinkEmail,
18
+ type CommonsSnapshot,
19
+ } from './commonsDeposit.ts';
20
+
21
+ type Supa = SupabaseClient<any, 'public', any>;
22
+
23
+ const HOLD_EXTENSION_MS = 7 * 24 * 60 * 60 * 1000;
24
+
25
+ export interface CommonsAgreementRow {
26
+ id: string;
27
+ booking_id: string;
28
+ signer_email: string | null;
29
+ signer_name: string | null;
30
+ metadata: Record<string, unknown> | null;
31
+ }
32
+
33
+ export interface CommonsBookingRow {
34
+ id: string;
35
+ status: string;
36
+ deposit_amount_cents: number | null;
37
+ list_amount_cents: number | null;
38
+ hold_expires_at: string | null;
39
+ contact_email: string | null;
40
+ contact_name: string | null;
41
+ }
42
+
43
+ export interface CommonsDepositOutcome {
44
+ processed: boolean;
45
+ result: string;
46
+ detail?: Record<string, unknown>;
47
+ }
48
+
49
+ async function fail(
50
+ supabase: Supa,
51
+ agreementId: string,
52
+ bookingId: string,
53
+ kind: string,
54
+ message: string,
55
+ detail: Record<string, unknown>,
56
+ ): Promise<CommonsDepositOutcome> {
57
+ await supabase.from('booking_agreements')
58
+ .update({ last_error: message.slice(0, 500) })
59
+ .eq('id', agreementId);
60
+ await logOps(supabase, kind, { agreement_id: agreementId, ...detail },
61
+ { severity: 'error', bookingId }).catch(() => {});
62
+ return { processed: false, result: kind, detail };
63
+ }
64
+
65
+ /**
66
+ * Runs on a genuine tier-3 `Completed` transition. Never throws.
67
+ */
68
+ export async function handleCommonsDepositCompleted(
69
+ supabase: Supa,
70
+ agreement: CommonsAgreementRow,
71
+ booking: CommonsBookingRow | null,
72
+ opts: {
73
+ baseUrl?: string;
74
+ defaultBaseUrl: string;
75
+ operator: { name: string; shortName: string; supportEmail: string };
76
+ staffCc: string[];
77
+ },
78
+ ): Promise<CommonsDepositOutcome> {
79
+ const bookingId = String(agreement.booking_id);
80
+
81
+ if (!booking) {
82
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
83
+ 'booking_not_found', { reason: 'booking_not_found' });
84
+ }
85
+
86
+ // Guard 1 — only a live hold gets a deposit link. Anything else (already
87
+ // deposit_paid, cancelled, expired) is a no-op with no side effects.
88
+ if (booking.status !== 'pending') {
89
+ console.log(`[commons-deposit] booking ${bookingId} status=${booking.status} — skipping deposit session`);
90
+ return { processed: true, result: 'booking_not_pending', detail: { status: booking.status } };
91
+ }
92
+
93
+ const deposit = booking.deposit_amount_cents;
94
+ if (deposit == null || !Number.isFinite(Number(deposit)) || Number(deposit) <= 0) {
95
+ // Never guess an amount.
96
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_missing',
97
+ 'deposit_amount_missing', { deposit_amount_cents: deposit });
98
+ }
99
+
100
+ const snapshot = ((agreement.metadata ?? {}) as Record<string, unknown>).commons as
101
+ | CommonsSnapshot
102
+ | undefined;
103
+ if (!snapshot) {
104
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
105
+ 'commons_snapshot_missing', { reason: 'metadata_commons_missing' });
106
+ }
107
+
108
+ // Tamper check — the money on the booking must still match what the signed
109
+ // document says. Any drift means the document and the charge disagree: stop.
110
+ const totalCents = Number(booking.list_amount_cents ?? -1);
111
+ if (Number(deposit) !== Number(snapshot.deposit_cents) ||
112
+ totalCents !== Number(snapshot.total_cents)) {
113
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
114
+ 'commons_amount_drift', {
115
+ booking_deposit_cents: Number(deposit),
116
+ snapshot_deposit_cents: snapshot.deposit_cents ?? null,
117
+ booking_total_cents: totalCents,
118
+ snapshot_total_cents: snapshot.total_cents ?? null,
119
+ });
120
+ }
121
+
122
+ const depositCents = Number(deposit);
123
+ const balanceCents = Number(snapshot.balance_cents ?? Math.max(0, totalCents - depositCents));
124
+ const eventDateLabel = longDateFromYmd(snapshot.event_date) ??
125
+ longDateFromIso(snapshot.arrival_at) ?? 'your event date';
126
+ const balanceDueLabel = longDateFromYmd(snapshot.balance_due_date) ??
127
+ 'the date shown in your agreement';
128
+
129
+ const signerEmail = String(agreement.signer_email ?? booking.contact_email ?? '').trim();
130
+ if (!signerEmail) {
131
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
132
+ 'signer_email_missing', { reason: 'signer_email_missing' });
133
+ }
134
+
135
+ const base = opts.baseUrl ?? opts.defaultBaseUrl;
136
+ const params = buildCommonsDepositSessionParams({
137
+ bookingId,
138
+ agreementId: String(agreement.id),
139
+ signerEmail,
140
+ depositCents,
141
+ totalCents,
142
+ balanceCents,
143
+ eventDateLabel,
144
+ balanceDueLabel,
145
+ successUrl: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
146
+ cancelUrl: `${base}/contact?commons_deposit=canceled`,
147
+ });
148
+ const idempotencyKey = commonsDepositIdempotencyKey(bookingId);
149
+
150
+ // Dry-run escape hatch used during staged rollout / verification: log the
151
+ // exact payload that WOULD be sent and take no live Stripe action.
152
+ if (Deno.env.get('COMMONS_DEPOSIT_DRY_RUN') === '1') {
153
+ console.log('[commons-deposit][dry-run] checkout.sessions.create',
154
+ JSON.stringify({ params, idempotencyKey }));
155
+ return { processed: false, result: 'dry_run', detail: { idempotency_key: idempotencyKey } };
156
+ }
157
+
158
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
159
+ if (!stripeKey) {
160
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
161
+ 'stripe_not_configured', { reason: 'stripe_not_configured' });
162
+ }
163
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
164
+
165
+ let session: Stripe.Checkout.Session;
166
+ try {
167
+ session = await stripe.checkout.sessions.create(params, { idempotencyKey });
168
+ } catch (e) {
169
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
170
+ e instanceof Error ? e.message : String(e), { step: 'checkout_session_create' });
171
+ }
172
+
173
+ // CAS: only claim the session slot while it is still empty, so a concurrent
174
+ // invocation cannot overwrite an already-persisted session id.
175
+ const { data: claimed } = await supabase
176
+ .from('bookings')
177
+ .update({ stripe_session_id: session.id })
178
+ .eq('id', bookingId)
179
+ .is('stripe_session_id', null)
180
+ .select('id')
181
+ .maybeSingle();
182
+ if (!claimed) {
183
+ console.log(`[commons-deposit] booking ${bookingId} already had a stripe_session_id — keeping the existing one`);
184
+ }
185
+
186
+ // Relative extension only — never shrink a hold that is already longer.
187
+ const target = new Date(Date.now() + HOLD_EXTENSION_MS);
188
+ const currentHold = booking.hold_expires_at ? new Date(booking.hold_expires_at) : null;
189
+ const extended = currentHold && currentHold.getTime() > target.getTime() ? currentHold : target;
190
+ await supabase.from('bookings')
191
+ .update({ hold_expires_at: extended.toISOString() })
192
+ .eq('id', bookingId)
193
+ .eq('status', 'pending');
194
+
195
+ // CAS-guarded send authorization: the same conditional update that stamps
196
+ // deposit_link_email_sent_at is what grants the right to send.
197
+ const claimTs = new Date().toISOString();
198
+ const { data: emailClaim } = await supabase
199
+ .from('booking_agreements')
200
+ .update({ deposit_link_email_sent_at: claimTs })
201
+ .eq('id', agreement.id)
202
+ .is('deposit_link_email_sent_at', null)
203
+ .select('id')
204
+ .maybeSingle();
205
+
206
+ if (emailClaim) {
207
+ const outcome = await sendCommonsDepositLinkEmail(supabase, {
208
+ email: signerEmail,
209
+ name: agreement.signer_name ?? booking.contact_name ?? null,
210
+ checkoutUrl: String(session.url ?? ''),
211
+ eventDateLabel,
212
+ depositCents,
213
+ balanceCents,
214
+ balanceDueLabel,
215
+ bookingId,
216
+ }, opts.operator, opts.staffCc).catch((e) => {
217
+ console.error('[commons-deposit] deposit link email threw', e);
218
+ return 'failed_permanent' as const;
219
+ });
220
+
221
+ if (outcome !== 'sent') {
222
+ // Release the claim so a retry can send, and leave the ledger unprocessed.
223
+ await supabase.from('booking_agreements')
224
+ .update({ deposit_link_email_sent_at: null })
225
+ .eq('id', agreement.id)
226
+ .eq('deposit_link_email_sent_at', claimTs);
227
+ return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
228
+ `deposit_link_email_${outcome}`, { step: 'deposit_link_email', session_id: session.id });
229
+ }
230
+ }
231
+
232
+ return {
233
+ processed: true,
234
+ result: 'deposit_session_created',
235
+ detail: { session_id: session.id, deposit_cents: depositCents },
236
+ };
237
+ }