@simplelayer/graniteer-core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -309
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -95
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,346 +1,346 @@
1
- // Flat-body shim in front of `create-day-pass-checkout` for the external
2
- // voice-AI system, which can only send flat top-level string fields.
3
- //
4
- // This function owns NO purchase logic: it validates a flat body, forwards the
5
- // request to `create-day-pass-checkout`, and texts the resulting Stripe
6
- // Checkout link to the caller. Plan eligibility, past-date rejection, Stripe
7
- // customer reuse and the Checkout Session itself all stay in
8
- // `create-day-pass-checkout`. Mirrors voice-booking.ts.
9
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
10
- import { createClient, type SupabaseClient } from 'npm:@supabase/supabase-js@2';
11
- import { z } from 'npm:zod@3.23.8';
12
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
13
- import { verifyRetellSignature } from 'npm:@simplelayer/graniteer-core/retellSignature';
14
-
15
- const Body = z.object({
16
- contact_name: z.string().min(1).max(200),
17
- contact_email: z.string().email(),
18
- contact_phone: z.string().max(40).optional(),
19
- visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
20
- // Freeform on purpose ("around 2pm", "first thing"). Passed straight through
21
- // to create-day-pass-checkout, which only stamps it into Stripe metadata for
22
- // the front desk — nothing parses it, so nothing may reject it either. Max
23
- // 20 chars matches that function's own bound.
24
- arrival_time: z.string().max(20).optional(),
25
- // Optional replay guard for the voice agent: a dropped call can make it
26
- // resend the same request. Omitting it behaves exactly as before.
27
- idempotency_key: z.string().min(1).max(200).optional(),
28
- });
29
-
30
- // How long a stored response is replayed. Older rows are treated as a miss and
31
- // simply overwritten by the next write (most recent write wins, no GC job).
32
- // Mirrors voice-booking's own idempotency design.
33
- const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
34
-
35
- const json = (status: number, body: unknown) =>
36
- new Response(JSON.stringify(body), {
37
- status,
38
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
39
- });
40
-
41
- // Business-logic failures always return HTTP 200 so the caller reliably gets
42
- // JSON back; only a malformed request body is a non-200.
43
- const GENERIC_ERROR = "Sorry — I wasn't able to start that day pass just now.";
44
-
45
- // create-day-pass-checkout error strings that are already clean, actionable
46
- // sentences and can be spoken to the caller verbatim. Everything else it can
47
- // return (a zod flatten object, "That plan is not available for one-time
48
- // checkout.", the 500 text) either isn't a sentence or describes a
49
- // configuration problem the caller can do nothing about, so it is logged and
50
- // genericized instead — same split voice-booking applies to create-booking.
51
- const PASSTHROUGH_ERRORS = new Set([
52
- "Visit date can't be in the past.",
53
- 'Too many checkout attempts — please wait a few minutes and try again.',
54
- ]);
55
-
56
- const GHL_BASE = 'https://services.leadconnectorhq.com';
57
- const GHL_VERSION = '2021-07-28';
58
- const GHL_LOCATION_ID = 'BDI8NHA4nkHnQGJ8g3hV';
59
- // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
60
- const BROWSER_UA =
61
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
62
-
63
- /** Tenant-owned inputs to this function. */
64
- export type VoiceDayPassConfig = {
65
- /**
66
- * The one plan slug this phone flow sells. Day passes are the only
67
- * non-monthly billable plan; create-day-pass-checkout rejects anything
68
- * with billing_interval 'month', so this is deliberately not
69
- * caller-supplied.
70
- */
71
- dayPassPlanSlug: string;
72
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
73
- businessName: string;
74
- /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
75
- supportPhoneDisplay: string;
76
- };
77
-
78
- // Calendar-date formatting only — the visit date is a bare YYYY-MM-DD with no
79
- // time component, so it is formatted as a UTC calendar date rather than
80
- // resolved to an LA instant that a DST boundary could shift by a day.
81
- function spokenDate(dateStr: string): string {
82
- const [y, mo, d] = dateStr.split('-').map(Number);
83
- return new Intl.DateTimeFormat('en-US', {
84
- timeZone: 'UTC',
85
- weekday: 'long',
86
- month: 'long',
87
- day: 'numeric',
88
- }).format(new Date(Date.UTC(y, mo - 1, d)));
89
- }
90
-
91
- /**
92
- * Day-pass payment-link SMS via GHL. Never throws, never rejects: a messaging
93
- * hiccup must never turn a successful checkout into a reported failure.
94
- * Awaited (not fire-and-forget) because the edge isolate can be torn down
95
- * right after the response, dropping in-flight fetches.
96
- */
97
- async function sendVoiceDayPassSms(args: {
98
- supabase: SupabaseClient<any, 'public', any>;
99
- phone?: string;
100
- name: string;
101
- email: string;
102
- visitDate: string;
103
- checkoutUrl: string;
104
- config: VoiceDayPassConfig;
105
- }): Promise<boolean> {
106
- const { supabase, visitDate, config } = args;
107
- try {
108
- const phone = (args.phone ?? '').trim();
109
- if (!phone) return false; // nothing to text
110
-
111
- const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
112
- if (!apiKey) {
113
- console.error('[voice-day-pass] GC_VOICE_GHL_API_KEY not set — skipping SMS');
114
- await logOps(
115
- supabase,
116
- 'voice_day_pass_sms_failed',
117
- { visit_date: visitDate, reason: 'GC_VOICE_GHL_API_KEY not set' },
118
- { severity: 'error' },
119
- );
120
- return false;
121
- }
122
-
123
- const message =
124
- `Thanks for booking a Day Pass at ${config.businessName} for ${spokenDate(visitDate)}! ` +
125
- `Here's your payment link: ${args.checkoutUrl}\n` +
126
- `Just check in at the front desk when you arrive. Questions? Call us at ${config.supportPhoneDisplay}.`;
127
-
128
- const headers = {
129
- Authorization: `Bearer ${apiKey}`,
130
- Version: GHL_VERSION,
131
- 'Content-Type': 'application/json',
132
- Accept: 'application/json',
133
- 'User-Agent': BROWSER_UA,
134
- };
135
-
136
- // 1) Upsert the contact. No `tags` field — upsert REPLACES tags and we must
137
- // never clobber an existing contact's tags from here.
138
- const upsertRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
139
- method: 'POST',
140
- headers,
141
- body: JSON.stringify({
142
- locationId: GHL_LOCATION_ID,
143
- name: args.name,
144
- email: args.email,
145
- phone,
146
- }),
147
- });
148
- if (!upsertRes.ok) {
149
- const body = await upsertRes.text().catch(() => '');
150
- console.error('[voice-day-pass] GHL upsert failed', upsertRes.status, body);
151
- await logOps(
152
- supabase,
153
- 'voice_day_pass_sms_failed',
154
- { visit_date: visitDate, reason: 'ghl_upsert_failed', status: upsertRes.status, body: body.slice(0, 500) },
155
- { severity: 'error' },
156
- );
157
- return false;
158
- }
159
- const upsertJson = (await upsertRes.json().catch(() => null)) as
160
- | { contact?: { id?: string }; id?: string }
161
- | null;
162
- const contactId = upsertJson?.contact?.id ?? upsertJson?.id;
163
- if (!contactId) {
164
- console.error('[voice-day-pass] GHL upsert returned no contact id');
165
- await logOps(
166
- supabase,
167
- 'voice_day_pass_sms_failed',
168
- { visit_date: visitDate, reason: 'ghl_upsert_no_contact_id' },
169
- { severity: 'error' },
170
- );
171
- return false;
172
- }
173
-
174
- // 2) Send the SMS.
175
- const smsRes = await fetch(`${GHL_BASE}/conversations/messages`, {
176
- method: 'POST',
177
- headers,
178
- body: JSON.stringify({ contactId, type: 'SMS', message }),
179
- });
180
- if (!smsRes.ok) {
181
- const body = await smsRes.text().catch(() => '');
182
- console.error('[voice-day-pass] GHL SMS failed', smsRes.status, body);
183
- await logOps(
184
- supabase,
185
- 'voice_day_pass_sms_failed',
186
- { visit_date: visitDate, reason: 'ghl_sms_send_failed', status: smsRes.status, body: body.slice(0, 500) },
187
- { severity: 'error' },
188
- );
189
- return false;
190
- }
191
- return true;
192
- } catch (e) {
193
- console.error('[voice-day-pass] GHL SMS error', e);
194
- await logOps(
195
- supabase,
196
- 'voice_day_pass_sms_failed',
197
- { visit_date: visitDate, reason: 'unhandled_error', detail: String(e).slice(0, 500) },
198
- { severity: 'error' },
199
- );
200
- return false;
201
- }
202
- }
203
-
204
- // Bounds how long we block the HTTP response on the outbound SMS. If GHL is
205
- // slow, we still send it -- just not synchronously -- rather than let the
206
- // combined checkout + SMS round trip exceed the calling voice agent's tool
207
- // timeout and cause it to report a false failure to the caller. Same budget
208
- // and mechanism as voice-booking.ts (added there 2026-08-24 after a
209
- // confirmed incident); see that file for the full rationale.
210
- const SMS_RESPONSE_BUDGET_MS = 4000;
211
-
212
- async function runSmsWithBudget(smsPromise: Promise<boolean>): Promise<boolean> {
213
- let settled = false;
214
- const tracked = smsPromise.then((result) => {
215
- settled = true;
216
- return result;
217
- });
218
- // deno-lint-ignore no-explicit-any
219
- const rt = (globalThis as any).EdgeRuntime;
220
- if (rt?.waitUntil) rt.waitUntil(tracked); else tracked.catch(() => {});
221
- const budget = new Promise<boolean>((resolve) => {
222
- setTimeout(() => {
223
- if (!settled) resolve(false);
224
- }, SMS_RESPONSE_BUDGET_MS);
225
- });
226
- return await Promise.race([tracked, budget]);
227
- }
228
-
229
- export async function handle(req: Request, config: VoiceDayPassConfig): Promise<Response> {
230
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
231
-
232
- // Raw text first: the signature is over the exact bytes sent, so the body
233
- // can only be JSON.parse-d after verification.
234
- const rawBody = await req.text().catch(() => '');
235
- if (!(await verifyRetellSignature(req, rawBody, 'voice-day-pass'))) {
236
- return json(401, { ok: false, error: 'unauthorized' });
237
- }
238
-
239
- let raw: unknown = {};
240
- try {
241
- raw = rawBody ? JSON.parse(rawBody) : {};
242
- } catch {
243
- raw = {};
244
- }
245
-
246
- const parsed = Body.safeParse(raw);
247
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
248
-
249
- const {
250
- contact_name, contact_email, contact_phone,
251
- visit_date, arrival_time, idempotency_key,
252
- } = parsed.data;
253
-
254
- const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
255
- const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
256
- const supabase = createClient(supabaseUrl, serviceKey);
257
-
258
- // Every cached call site returns HTTP 200, so only the JSON body is stored
259
- // and a replay is always a 200.
260
- const finish = async (body: unknown): Promise<Response> => {
261
- if (idempotency_key) {
262
- const { error } = await supabase
263
- .from('voice_day_pass_idempotency')
264
- .upsert(
265
- { key: idempotency_key, response: body, created_at: new Date().toISOString() },
266
- { onConflict: 'key' },
267
- );
268
- if (error) console.error('[voice-day-pass] idempotency write failed', error);
269
- }
270
- return json(200, body);
271
- };
272
-
273
- // Replay a recent identical request before doing ANY work: no checkout
274
- // session created, no SMS. A duplicate here would otherwise text the caller
275
- // a second, different payment link for the same day.
276
- if (idempotency_key) {
277
- const { data: cached, error: cacheErr } = await supabase
278
- .from('voice_day_pass_idempotency')
279
- .select('response,created_at')
280
- .eq('key', idempotency_key)
281
- .maybeSingle();
282
- // A cache read must never be able to fail a purchase — log and fall through.
283
- if (cacheErr) console.error('[voice-day-pass] idempotency read failed', cacheErr);
284
- else if (cached) {
285
- const age = Date.now() - Date.parse(cached.created_at as string);
286
- if (Number.isFinite(age) && age >= 0 && age < IDEMPOTENCY_TTL_MS) {
287
- return json(200, cached.response);
288
- }
289
- }
290
- }
291
-
292
- try {
293
- const res = await fetch(`${supabaseUrl}/functions/v1/create-day-pass-checkout`, {
294
- method: 'POST',
295
- headers: {
296
- 'Content-Type': 'application/json',
297
- Authorization: `Bearer ${serviceKey}`,
298
- apikey: serviceKey,
299
- },
300
- body: JSON.stringify({
301
- plan_slug: config.dayPassPlanSlug,
302
- email: contact_email,
303
- visit_date,
304
- ...(arrival_time ? { arrival_time } : {}),
305
- }),
306
- });
307
-
308
- const payload = await res.json().catch(() => null) as
309
- | { url?: string; error?: unknown }
310
- | null;
311
-
312
- if (res.ok && typeof payload?.url === 'string' && payload.url) {
313
- const smsSent = await runSmsWithBudget(sendVoiceDayPassSms({
314
- supabase,
315
- phone: contact_phone,
316
- name: contact_name,
317
- email: contact_email,
318
- visitDate: visit_date,
319
- checkoutUrl: payload.url,
320
- config,
321
- }));
322
- return await finish({
323
- ok: true,
324
- checkout_url: payload.url,
325
- sms_sent: smsSent,
326
- });
327
- }
328
-
329
- if (typeof payload?.error === 'string' && PASSTHROUGH_ERRORS.has(payload.error)) {
330
- // Rate limiting is transient and must stay retryable, so — unlike the
331
- // past-date rejection — a 429 is deliberately not written to the
332
- // idempotency cache.
333
- return res.status === 429
334
- ? json(200, { ok: false, error: payload.error })
335
- : await finish({ ok: false, error: payload.error });
336
- }
337
-
338
- // Everything else (400 zod flatten, plan misconfiguration, 500,
339
- // unparseable body) is logged but never leaked to the caller.
340
- console.error('[voice-day-pass] create-day-pass-checkout failed', res.status, JSON.stringify(payload));
341
- return json(200, { ok: false, error: GENERIC_ERROR });
342
- } catch (e) {
343
- console.error('[voice-day-pass] error', e);
344
- return json(200, { ok: false, error: GENERIC_ERROR });
345
- }
346
- }
1
+ // Flat-body shim in front of `create-day-pass-checkout` for the external
2
+ // voice-AI system, which can only send flat top-level string fields.
3
+ //
4
+ // This function owns NO purchase logic: it validates a flat body, forwards the
5
+ // request to `create-day-pass-checkout`, and texts the resulting Stripe
6
+ // Checkout link to the caller. Plan eligibility, past-date rejection, Stripe
7
+ // customer reuse and the Checkout Session itself all stay in
8
+ // `create-day-pass-checkout`. Mirrors voice-booking.ts.
9
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
10
+ import { createClient, type SupabaseClient } from 'npm:@supabase/supabase-js@2';
11
+ import { z } from 'npm:zod@3.23.8';
12
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
13
+ import { verifyRetellSignature } from 'npm:@simplelayer/graniteer-core/retellSignature';
14
+
15
+ const Body = z.object({
16
+ contact_name: z.string().min(1).max(200),
17
+ contact_email: z.string().email(),
18
+ contact_phone: z.string().max(40).optional(),
19
+ visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
20
+ // Freeform on purpose ("around 2pm", "first thing"). Passed straight through
21
+ // to create-day-pass-checkout, which only stamps it into Stripe metadata for
22
+ // the front desk — nothing parses it, so nothing may reject it either. Max
23
+ // 20 chars matches that function's own bound.
24
+ arrival_time: z.string().max(20).optional(),
25
+ // Optional replay guard for the voice agent: a dropped call can make it
26
+ // resend the same request. Omitting it behaves exactly as before.
27
+ idempotency_key: z.string().min(1).max(200).optional(),
28
+ });
29
+
30
+ // How long a stored response is replayed. Older rows are treated as a miss and
31
+ // simply overwritten by the next write (most recent write wins, no GC job).
32
+ // Mirrors voice-booking's own idempotency design.
33
+ const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
34
+
35
+ const json = (status: number, body: unknown) =>
36
+ new Response(JSON.stringify(body), {
37
+ status,
38
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
39
+ });
40
+
41
+ // Business-logic failures always return HTTP 200 so the caller reliably gets
42
+ // JSON back; only a malformed request body is a non-200.
43
+ const GENERIC_ERROR = "Sorry — I wasn't able to start that day pass just now.";
44
+
45
+ // create-day-pass-checkout error strings that are already clean, actionable
46
+ // sentences and can be spoken to the caller verbatim. Everything else it can
47
+ // return (a zod flatten object, "That plan is not available for one-time
48
+ // checkout.", the 500 text) either isn't a sentence or describes a
49
+ // configuration problem the caller can do nothing about, so it is logged and
50
+ // genericized instead — same split voice-booking applies to create-booking.
51
+ const PASSTHROUGH_ERRORS = new Set([
52
+ "Visit date can't be in the past.",
53
+ 'Too many checkout attempts — please wait a few minutes and try again.',
54
+ ]);
55
+
56
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
57
+ const GHL_VERSION = '2021-07-28';
58
+ const GHL_LOCATION_ID = 'BDI8NHA4nkHnQGJ8g3hV';
59
+ // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
60
+ const BROWSER_UA =
61
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
62
+
63
+ /** Tenant-owned inputs to this function. */
64
+ export type VoiceDayPassConfig = {
65
+ /**
66
+ * The one plan slug this phone flow sells. Day passes are the only
67
+ * non-monthly billable plan; create-day-pass-checkout rejects anything
68
+ * with billing_interval 'month', so this is deliberately not
69
+ * caller-supplied.
70
+ */
71
+ dayPassPlanSlug: string;
72
+ /** Spoken/texted business name, e.g. "Granite City Workspaces". */
73
+ businessName: string;
74
+ /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
75
+ supportPhoneDisplay: string;
76
+ };
77
+
78
+ // Calendar-date formatting only — the visit date is a bare YYYY-MM-DD with no
79
+ // time component, so it is formatted as a UTC calendar date rather than
80
+ // resolved to an LA instant that a DST boundary could shift by a day.
81
+ function spokenDate(dateStr: string): string {
82
+ const [y, mo, d] = dateStr.split('-').map(Number);
83
+ return new Intl.DateTimeFormat('en-US', {
84
+ timeZone: 'UTC',
85
+ weekday: 'long',
86
+ month: 'long',
87
+ day: 'numeric',
88
+ }).format(new Date(Date.UTC(y, mo - 1, d)));
89
+ }
90
+
91
+ /**
92
+ * Day-pass payment-link SMS via GHL. Never throws, never rejects: a messaging
93
+ * hiccup must never turn a successful checkout into a reported failure.
94
+ * Awaited (not fire-and-forget) because the edge isolate can be torn down
95
+ * right after the response, dropping in-flight fetches.
96
+ */
97
+ async function sendVoiceDayPassSms(args: {
98
+ supabase: SupabaseClient<any, 'public', any>;
99
+ phone?: string;
100
+ name: string;
101
+ email: string;
102
+ visitDate: string;
103
+ checkoutUrl: string;
104
+ config: VoiceDayPassConfig;
105
+ }): Promise<boolean> {
106
+ const { supabase, visitDate, config } = args;
107
+ try {
108
+ const phone = (args.phone ?? '').trim();
109
+ if (!phone) return false; // nothing to text
110
+
111
+ const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
112
+ if (!apiKey) {
113
+ console.error('[voice-day-pass] GC_VOICE_GHL_API_KEY not set — skipping SMS');
114
+ await logOps(
115
+ supabase,
116
+ 'voice_day_pass_sms_failed',
117
+ { visit_date: visitDate, reason: 'GC_VOICE_GHL_API_KEY not set' },
118
+ { severity: 'error' },
119
+ );
120
+ return false;
121
+ }
122
+
123
+ const message =
124
+ `Thanks for booking a Day Pass at ${config.businessName} for ${spokenDate(visitDate)}! ` +
125
+ `Here's your payment link: ${args.checkoutUrl}\n` +
126
+ `Just check in at the front desk when you arrive. Questions? Call us at ${config.supportPhoneDisplay}.`;
127
+
128
+ const headers = {
129
+ Authorization: `Bearer ${apiKey}`,
130
+ Version: GHL_VERSION,
131
+ 'Content-Type': 'application/json',
132
+ Accept: 'application/json',
133
+ 'User-Agent': BROWSER_UA,
134
+ };
135
+
136
+ // 1) Upsert the contact. No `tags` field — upsert REPLACES tags and we must
137
+ // never clobber an existing contact's tags from here.
138
+ const upsertRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
139
+ method: 'POST',
140
+ headers,
141
+ body: JSON.stringify({
142
+ locationId: GHL_LOCATION_ID,
143
+ name: args.name,
144
+ email: args.email,
145
+ phone,
146
+ }),
147
+ });
148
+ if (!upsertRes.ok) {
149
+ const body = await upsertRes.text().catch(() => '');
150
+ console.error('[voice-day-pass] GHL upsert failed', upsertRes.status, body);
151
+ await logOps(
152
+ supabase,
153
+ 'voice_day_pass_sms_failed',
154
+ { visit_date: visitDate, reason: 'ghl_upsert_failed', status: upsertRes.status, body: body.slice(0, 500) },
155
+ { severity: 'error' },
156
+ );
157
+ return false;
158
+ }
159
+ const upsertJson = (await upsertRes.json().catch(() => null)) as
160
+ | { contact?: { id?: string }; id?: string }
161
+ | null;
162
+ const contactId = upsertJson?.contact?.id ?? upsertJson?.id;
163
+ if (!contactId) {
164
+ console.error('[voice-day-pass] GHL upsert returned no contact id');
165
+ await logOps(
166
+ supabase,
167
+ 'voice_day_pass_sms_failed',
168
+ { visit_date: visitDate, reason: 'ghl_upsert_no_contact_id' },
169
+ { severity: 'error' },
170
+ );
171
+ return false;
172
+ }
173
+
174
+ // 2) Send the SMS.
175
+ const smsRes = await fetch(`${GHL_BASE}/conversations/messages`, {
176
+ method: 'POST',
177
+ headers,
178
+ body: JSON.stringify({ contactId, type: 'SMS', message }),
179
+ });
180
+ if (!smsRes.ok) {
181
+ const body = await smsRes.text().catch(() => '');
182
+ console.error('[voice-day-pass] GHL SMS failed', smsRes.status, body);
183
+ await logOps(
184
+ supabase,
185
+ 'voice_day_pass_sms_failed',
186
+ { visit_date: visitDate, reason: 'ghl_sms_send_failed', status: smsRes.status, body: body.slice(0, 500) },
187
+ { severity: 'error' },
188
+ );
189
+ return false;
190
+ }
191
+ return true;
192
+ } catch (e) {
193
+ console.error('[voice-day-pass] GHL SMS error', e);
194
+ await logOps(
195
+ supabase,
196
+ 'voice_day_pass_sms_failed',
197
+ { visit_date: visitDate, reason: 'unhandled_error', detail: String(e).slice(0, 500) },
198
+ { severity: 'error' },
199
+ );
200
+ return false;
201
+ }
202
+ }
203
+
204
+ // Bounds how long we block the HTTP response on the outbound SMS. If GHL is
205
+ // slow, we still send it -- just not synchronously -- rather than let the
206
+ // combined checkout + SMS round trip exceed the calling voice agent's tool
207
+ // timeout and cause it to report a false failure to the caller. Same budget
208
+ // and mechanism as voice-booking.ts (added there 2026-08-24 after a
209
+ // confirmed incident); see that file for the full rationale.
210
+ const SMS_RESPONSE_BUDGET_MS = 4000;
211
+
212
+ async function runSmsWithBudget(smsPromise: Promise<boolean>): Promise<boolean> {
213
+ let settled = false;
214
+ const tracked = smsPromise.then((result) => {
215
+ settled = true;
216
+ return result;
217
+ });
218
+ // deno-lint-ignore no-explicit-any
219
+ const rt = (globalThis as any).EdgeRuntime;
220
+ if (rt?.waitUntil) rt.waitUntil(tracked); else tracked.catch(() => {});
221
+ const budget = new Promise<boolean>((resolve) => {
222
+ setTimeout(() => {
223
+ if (!settled) resolve(false);
224
+ }, SMS_RESPONSE_BUDGET_MS);
225
+ });
226
+ return await Promise.race([tracked, budget]);
227
+ }
228
+
229
+ export async function handle(req: Request, config: VoiceDayPassConfig): Promise<Response> {
230
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
231
+
232
+ // Raw text first: the signature is over the exact bytes sent, so the body
233
+ // can only be JSON.parse-d after verification.
234
+ const rawBody = await req.text().catch(() => '');
235
+ if (!(await verifyRetellSignature(req, rawBody, 'voice-day-pass'))) {
236
+ return json(401, { ok: false, error: 'unauthorized' });
237
+ }
238
+
239
+ let raw: unknown = {};
240
+ try {
241
+ raw = rawBody ? JSON.parse(rawBody) : {};
242
+ } catch {
243
+ raw = {};
244
+ }
245
+
246
+ const parsed = Body.safeParse(raw);
247
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
248
+
249
+ const {
250
+ contact_name, contact_email, contact_phone,
251
+ visit_date, arrival_time, idempotency_key,
252
+ } = parsed.data;
253
+
254
+ const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
255
+ const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
256
+ const supabase = createClient(supabaseUrl, serviceKey);
257
+
258
+ // Every cached call site returns HTTP 200, so only the JSON body is stored
259
+ // and a replay is always a 200.
260
+ const finish = async (body: unknown): Promise<Response> => {
261
+ if (idempotency_key) {
262
+ const { error } = await supabase
263
+ .from('voice_day_pass_idempotency')
264
+ .upsert(
265
+ { key: idempotency_key, response: body, created_at: new Date().toISOString() },
266
+ { onConflict: 'key' },
267
+ );
268
+ if (error) console.error('[voice-day-pass] idempotency write failed', error);
269
+ }
270
+ return json(200, body);
271
+ };
272
+
273
+ // Replay a recent identical request before doing ANY work: no checkout
274
+ // session created, no SMS. A duplicate here would otherwise text the caller
275
+ // a second, different payment link for the same day.
276
+ if (idempotency_key) {
277
+ const { data: cached, error: cacheErr } = await supabase
278
+ .from('voice_day_pass_idempotency')
279
+ .select('response,created_at')
280
+ .eq('key', idempotency_key)
281
+ .maybeSingle();
282
+ // A cache read must never be able to fail a purchase — log and fall through.
283
+ if (cacheErr) console.error('[voice-day-pass] idempotency read failed', cacheErr);
284
+ else if (cached) {
285
+ const age = Date.now() - Date.parse(cached.created_at as string);
286
+ if (Number.isFinite(age) && age >= 0 && age < IDEMPOTENCY_TTL_MS) {
287
+ return json(200, cached.response);
288
+ }
289
+ }
290
+ }
291
+
292
+ try {
293
+ const res = await fetch(`${supabaseUrl}/functions/v1/create-day-pass-checkout`, {
294
+ method: 'POST',
295
+ headers: {
296
+ 'Content-Type': 'application/json',
297
+ Authorization: `Bearer ${serviceKey}`,
298
+ apikey: serviceKey,
299
+ },
300
+ body: JSON.stringify({
301
+ plan_slug: config.dayPassPlanSlug,
302
+ email: contact_email,
303
+ visit_date,
304
+ ...(arrival_time ? { arrival_time } : {}),
305
+ }),
306
+ });
307
+
308
+ const payload = await res.json().catch(() => null) as
309
+ | { url?: string; error?: unknown }
310
+ | null;
311
+
312
+ if (res.ok && typeof payload?.url === 'string' && payload.url) {
313
+ const smsSent = await runSmsWithBudget(sendVoiceDayPassSms({
314
+ supabase,
315
+ phone: contact_phone,
316
+ name: contact_name,
317
+ email: contact_email,
318
+ visitDate: visit_date,
319
+ checkoutUrl: payload.url,
320
+ config,
321
+ }));
322
+ return await finish({
323
+ ok: true,
324
+ checkout_url: payload.url,
325
+ sms_sent: smsSent,
326
+ });
327
+ }
328
+
329
+ if (typeof payload?.error === 'string' && PASSTHROUGH_ERRORS.has(payload.error)) {
330
+ // Rate limiting is transient and must stay retryable, so — unlike the
331
+ // past-date rejection — a 429 is deliberately not written to the
332
+ // idempotency cache.
333
+ return res.status === 429
334
+ ? json(200, { ok: false, error: payload.error })
335
+ : await finish({ ok: false, error: payload.error });
336
+ }
337
+
338
+ // Everything else (400 zod flatten, plan misconfiguration, 500,
339
+ // unparseable body) is logged but never leaked to the caller.
340
+ console.error('[voice-day-pass] create-day-pass-checkout failed', res.status, JSON.stringify(payload));
341
+ return json(200, { ok: false, error: GENERIC_ERROR });
342
+ } catch (e) {
343
+ console.error('[voice-day-pass] error', e);
344
+ return json(200, { ok: false, error: GENERIC_ERROR });
345
+ }
346
+ }