@simplelayer/graniteer-core 0.2.1 → 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 -334
  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 -217
  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,298 +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
- }
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
+ }