@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,355 +1,355 @@
1
- // Flat-body shim in front of `create-subscription-checkout` for the external
2
- // voice-AI system, which can only send flat top-level string fields.
3
- //
4
- // This function owns NO signup logic: it validates a flat body, forwards the
5
- // request to `create-subscription-checkout`, and texts the resulting Stripe
6
- // Checkout link to the caller. Plan eligibility, start-date windowing, Stripe
7
- // customer reuse and the Checkout Session itself all stay in
8
- // `create-subscription-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
- // `.trim()` matches create-subscription-checkout's own `name` schema, which
17
- // this is forwarded to verbatim — a whitespace-only name would otherwise
18
- // pass here and come back as an unspeakable zod flatten from there.
19
- contact_name: z.string().trim().min(1).max(200),
20
- contact_email: z.string().email(),
21
- contact_phone: z.string().max(40).optional(),
22
- // Not a zod enum: the operator's phone-sellable plan catalog is config
23
- // (see VoiceMembershipSignupConfig.sellablePlanSlugs below), so membership
24
- // is checked at runtime instead of being baked into the schema.
25
- plan_slug: z.string().min(1).max(80),
26
- start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
27
- // Optional replay guard for the voice agent: a dropped call can make it
28
- // resend the same request. Omitting it behaves exactly as before.
29
- idempotency_key: z.string().min(1).max(200).optional(),
30
- });
31
-
32
- // How long a stored response is replayed. Older rows are treated as a miss and
33
- // simply overwritten by the next write (most recent write wins, no GC job).
34
- // Mirrors voice-booking's own idempotency design.
35
- const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
36
-
37
- const json = (status: number, body: unknown) =>
38
- new Response(JSON.stringify(body), {
39
- status,
40
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
41
- });
42
-
43
- // Business-logic failures always return HTTP 200 so the caller reliably gets
44
- // JSON back; only a malformed request body is a non-200.
45
- const GENERIC_ERROR = "Sorry — I wasn't able to start that membership sign-up just now.";
46
-
47
- // create-subscription-checkout reports its start-date rejections as machine
48
- // codes ('start_date_in_past'), not as sentences, so unlike voice-booking's
49
- // 409 passthrough they cannot be spoken verbatim. These are the caller's own
50
- // correctable mistakes, so they are translated rather than genericized —
51
- // otherwise someone asking to start six weeks out just hears "sorry".
52
- const START_DATE_ERRORS: Record<string, string> = {
53
- start_date_in_past: "That start date has already passed — what date would you like to start?",
54
- start_date_invalid: "That doesn't look like a real calendar date — could you give me the month and day again?",
55
- start_date_too_far_out:
56
- 'We can only start a membership up to about four weeks out — could you pick a closer start date?',
57
- };
58
-
59
- // The one already-clean sentence it returns that can be spoken verbatim. Its
60
- // other strings ("That plan is not available for online checkout.", the 500
61
- // text) describe a configuration problem the caller can do nothing about, so
62
- // they are logged and genericized instead.
63
- const PASSTHROUGH_ERRORS = new Set([
64
- 'Too many checkout attempts — please wait a few minutes and try again.',
65
- ]);
66
-
67
- const GHL_BASE = 'https://services.leadconnectorhq.com';
68
- const GHL_VERSION = '2021-07-28';
69
- const GHL_LOCATION_ID = 'BDI8NHA4nkHnQGJ8g3hV';
70
- // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
71
- const BROWSER_UA =
72
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
73
-
74
- /** Tenant-owned inputs to this function. */
75
- export type VoiceMembershipSignupConfig = {
76
- /**
77
- * Plan slugs sellable over this phone flow. Everything else in the
78
- * operator's catalog (virtual office, private offices, ...) needs a
79
- * product decision before it can be sold this way — see the caller's own
80
- * comment for the reasoning behind Granite City's exclusions.
81
- */
82
- sellablePlanSlugs: readonly string[];
83
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
84
- businessName: string;
85
- /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
86
- supportPhoneDisplay: string;
87
- };
88
-
89
- /**
90
- * Membership payment-link SMS via GHL. Never throws, never rejects: a
91
- * messaging hiccup must never turn a successful checkout into a reported
92
- * failure. Awaited (not fire-and-forget) because the edge isolate can be torn
93
- * down right after the response, dropping in-flight fetches.
94
- */
95
- async function sendVoiceMembershipSms(args: {
96
- supabase: SupabaseClient<any, 'public', any>;
97
- phone?: string;
98
- name: string;
99
- email: string;
100
- planSlug: string;
101
- checkoutUrl: string;
102
- config: VoiceMembershipSignupConfig;
103
- }): Promise<boolean> {
104
- const { supabase, planSlug, config } = args;
105
- try {
106
- const phone = (args.phone ?? '').trim();
107
- if (!phone) return false; // nothing to text
108
-
109
- const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
110
- if (!apiKey) {
111
- console.error('[voice-membership-signup] GC_VOICE_GHL_API_KEY not set — skipping SMS');
112
- await logOps(
113
- supabase,
114
- 'voice_membership_signup_sms_failed',
115
- { plan_slug: planSlug, reason: 'GC_VOICE_GHL_API_KEY not set' },
116
- { severity: 'error' },
117
- );
118
- return false;
119
- }
120
-
121
- const message =
122
- `Thanks for starting your ${config.businessName} membership sign-up! ` +
123
- `Here's your payment link to complete it: ${args.checkoutUrl}\n` +
124
- `Questions? Call us at ${config.supportPhoneDisplay}.`;
125
-
126
- const headers = {
127
- Authorization: `Bearer ${apiKey}`,
128
- Version: GHL_VERSION,
129
- 'Content-Type': 'application/json',
130
- Accept: 'application/json',
131
- 'User-Agent': BROWSER_UA,
132
- };
133
-
134
- // 1) Upsert the contact. No `tags` field — upsert REPLACES tags and we must
135
- // never clobber an existing contact's tags from here.
136
- const upsertRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
137
- method: 'POST',
138
- headers,
139
- body: JSON.stringify({
140
- locationId: GHL_LOCATION_ID,
141
- name: args.name,
142
- email: args.email,
143
- phone,
144
- }),
145
- });
146
- if (!upsertRes.ok) {
147
- const body = await upsertRes.text().catch(() => '');
148
- console.error('[voice-membership-signup] GHL upsert failed', upsertRes.status, body);
149
- await logOps(
150
- supabase,
151
- 'voice_membership_signup_sms_failed',
152
- { plan_slug: planSlug, reason: 'ghl_upsert_failed', status: upsertRes.status, body: body.slice(0, 500) },
153
- { severity: 'error' },
154
- );
155
- return false;
156
- }
157
- const upsertJson = (await upsertRes.json().catch(() => null)) as
158
- | { contact?: { id?: string }; id?: string }
159
- | null;
160
- const contactId = upsertJson?.contact?.id ?? upsertJson?.id;
161
- if (!contactId) {
162
- console.error('[voice-membership-signup] GHL upsert returned no contact id');
163
- await logOps(
164
- supabase,
165
- 'voice_membership_signup_sms_failed',
166
- { plan_slug: planSlug, reason: 'ghl_upsert_no_contact_id' },
167
- { severity: 'error' },
168
- );
169
- return false;
170
- }
171
-
172
- // 2) Send the SMS.
173
- const smsRes = await fetch(`${GHL_BASE}/conversations/messages`, {
174
- method: 'POST',
175
- headers,
176
- body: JSON.stringify({ contactId, type: 'SMS', message }),
177
- });
178
- if (!smsRes.ok) {
179
- const body = await smsRes.text().catch(() => '');
180
- console.error('[voice-membership-signup] GHL SMS failed', smsRes.status, body);
181
- await logOps(
182
- supabase,
183
- 'voice_membership_signup_sms_failed',
184
- { plan_slug: planSlug, reason: 'ghl_sms_send_failed', status: smsRes.status, body: body.slice(0, 500) },
185
- { severity: 'error' },
186
- );
187
- return false;
188
- }
189
- return true;
190
- } catch (e) {
191
- console.error('[voice-membership-signup] GHL SMS error', e);
192
- await logOps(
193
- supabase,
194
- 'voice_membership_signup_sms_failed',
195
- { plan_slug: planSlug, reason: 'unhandled_error', detail: String(e).slice(0, 500) },
196
- { severity: 'error' },
197
- );
198
- return false;
199
- }
200
- }
201
-
202
- // Bounds how long we block the HTTP response on the outbound SMS. If GHL is
203
- // slow, we still send it -- just not synchronously -- rather than let the
204
- // combined checkout + SMS round trip exceed the calling voice agent's tool
205
- // timeout and cause it to report a false failure to the caller. Same budget
206
- // and mechanism as voice-booking.ts (added there 2026-08-24 after a
207
- // confirmed incident); see that file for the full rationale.
208
- const SMS_RESPONSE_BUDGET_MS = 4000;
209
-
210
- async function runSmsWithBudget(smsPromise: Promise<boolean>): Promise<boolean> {
211
- let settled = false;
212
- const tracked = smsPromise.then((result) => {
213
- settled = true;
214
- return result;
215
- });
216
- // deno-lint-ignore no-explicit-any
217
- const rt = (globalThis as any).EdgeRuntime;
218
- if (rt?.waitUntil) rt.waitUntil(tracked); else tracked.catch(() => {});
219
- const budget = new Promise<boolean>((resolve) => {
220
- setTimeout(() => {
221
- if (!settled) resolve(false);
222
- }, SMS_RESPONSE_BUDGET_MS);
223
- });
224
- return await Promise.race([tracked, budget]);
225
- }
226
-
227
- export async function handle(req: Request, config: VoiceMembershipSignupConfig): Promise<Response> {
228
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
229
-
230
- // Raw text first: the signature is over the exact bytes sent, so the body
231
- // can only be JSON.parse-d after verification.
232
- const rawBody = await req.text().catch(() => '');
233
- if (!(await verifyRetellSignature(req, rawBody, 'voice-membership-signup'))) {
234
- return json(401, { ok: false, error: 'unauthorized' });
235
- }
236
-
237
- let raw: unknown = {};
238
- try {
239
- raw = rawBody ? JSON.parse(rawBody) : {};
240
- } catch {
241
- raw = {};
242
- }
243
-
244
- const parsed = Body.safeParse(raw);
245
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
246
-
247
- const {
248
- contact_name, contact_email, contact_phone,
249
- plan_slug, start_date, idempotency_key,
250
- } = parsed.data;
251
-
252
- if (!config.sellablePlanSlugs.includes(plan_slug)) {
253
- return json(400, { ok: false, error: 'invalid_request' });
254
- }
255
-
256
- const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
257
- const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
258
- const supabase = createClient(supabaseUrl, serviceKey);
259
-
260
- // Every cached call site returns HTTP 200, so only the JSON body is stored
261
- // and a replay is always a 200.
262
- const finish = async (body: unknown): Promise<Response> => {
263
- if (idempotency_key) {
264
- const { error } = await supabase
265
- .from('voice_membership_signup_idempotency')
266
- .upsert(
267
- { key: idempotency_key, response: body, created_at: new Date().toISOString() },
268
- { onConflict: 'key' },
269
- );
270
- if (error) console.error('[voice-membership-signup] idempotency write failed', error);
271
- }
272
- return json(200, body);
273
- };
274
-
275
- // Replay a recent identical request before doing ANY work: no checkout
276
- // session created, no SMS. A duplicate here would otherwise text the caller
277
- // a second, different payment link for the same membership.
278
- if (idempotency_key) {
279
- const { data: cached, error: cacheErr } = await supabase
280
- .from('voice_membership_signup_idempotency')
281
- .select('response,created_at')
282
- .eq('key', idempotency_key)
283
- .maybeSingle();
284
- // A cache read must never be able to fail a signup — log and fall through.
285
- if (cacheErr) console.error('[voice-membership-signup] idempotency read failed', cacheErr);
286
- else if (cached) {
287
- const age = Date.now() - Date.parse(cached.created_at as string);
288
- if (Number.isFinite(age) && age >= 0 && age < IDEMPOTENCY_TTL_MS) {
289
- return json(200, cached.response);
290
- }
291
- }
292
- }
293
-
294
- try {
295
- // `referral_code` is deliberately omitted: this phone flow has no way to
296
- // collect one, and create-subscription-checkout treats it as optional.
297
- const res = await fetch(`${supabaseUrl}/functions/v1/create-subscription-checkout`, {
298
- method: 'POST',
299
- headers: {
300
- 'Content-Type': 'application/json',
301
- Authorization: `Bearer ${serviceKey}`,
302
- apikey: serviceKey,
303
- },
304
- body: JSON.stringify({
305
- plan_slug,
306
- email: contact_email,
307
- name: contact_name,
308
- ...(start_date ? { start_date } : {}),
309
- }),
310
- });
311
-
312
- const payload = await res.json().catch(() => null) as
313
- | { url?: string; error?: unknown }
314
- | null;
315
-
316
- if (res.ok && typeof payload?.url === 'string' && payload.url) {
317
- const smsSent = await runSmsWithBudget(sendVoiceMembershipSms({
318
- supabase,
319
- phone: contact_phone,
320
- name: contact_name,
321
- email: contact_email,
322
- planSlug: plan_slug,
323
- checkoutUrl: payload.url,
324
- config,
325
- }));
326
- return await finish({
327
- ok: true,
328
- checkout_url: payload.url,
329
- sms_sent: smsSent,
330
- });
331
- }
332
-
333
- if (typeof payload?.error === 'string') {
334
- const spoken = START_DATE_ERRORS[payload.error];
335
- if (spoken) return await finish({ ok: false, error: spoken });
336
- if (PASSTHROUGH_ERRORS.has(payload.error)) {
337
- // Rate limiting is transient and must stay retryable, so it is
338
- // deliberately not written to the idempotency cache.
339
- return json(200, { ok: false, error: payload.error });
340
- }
341
- }
342
-
343
- // Everything else (400 zod flatten, plan not self-serve, 500, unparseable
344
- // body) is logged but never leaked to the caller.
345
- console.error(
346
- '[voice-membership-signup] create-subscription-checkout failed',
347
- res.status,
348
- JSON.stringify(payload),
349
- );
350
- return json(200, { ok: false, error: GENERIC_ERROR });
351
- } catch (e) {
352
- console.error('[voice-membership-signup] error', e);
353
- return json(200, { ok: false, error: GENERIC_ERROR });
354
- }
355
- }
1
+ // Flat-body shim in front of `create-subscription-checkout` for the external
2
+ // voice-AI system, which can only send flat top-level string fields.
3
+ //
4
+ // This function owns NO signup logic: it validates a flat body, forwards the
5
+ // request to `create-subscription-checkout`, and texts the resulting Stripe
6
+ // Checkout link to the caller. Plan eligibility, start-date windowing, Stripe
7
+ // customer reuse and the Checkout Session itself all stay in
8
+ // `create-subscription-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
+ // `.trim()` matches create-subscription-checkout's own `name` schema, which
17
+ // this is forwarded to verbatim — a whitespace-only name would otherwise
18
+ // pass here and come back as an unspeakable zod flatten from there.
19
+ contact_name: z.string().trim().min(1).max(200),
20
+ contact_email: z.string().email(),
21
+ contact_phone: z.string().max(40).optional(),
22
+ // Not a zod enum: the operator's phone-sellable plan catalog is config
23
+ // (see VoiceMembershipSignupConfig.sellablePlanSlugs below), so membership
24
+ // is checked at runtime instead of being baked into the schema.
25
+ plan_slug: z.string().min(1).max(80),
26
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
27
+ // Optional replay guard for the voice agent: a dropped call can make it
28
+ // resend the same request. Omitting it behaves exactly as before.
29
+ idempotency_key: z.string().min(1).max(200).optional(),
30
+ });
31
+
32
+ // How long a stored response is replayed. Older rows are treated as a miss and
33
+ // simply overwritten by the next write (most recent write wins, no GC job).
34
+ // Mirrors voice-booking's own idempotency design.
35
+ const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
36
+
37
+ const json = (status: number, body: unknown) =>
38
+ new Response(JSON.stringify(body), {
39
+ status,
40
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
41
+ });
42
+
43
+ // Business-logic failures always return HTTP 200 so the caller reliably gets
44
+ // JSON back; only a malformed request body is a non-200.
45
+ const GENERIC_ERROR = "Sorry — I wasn't able to start that membership sign-up just now.";
46
+
47
+ // create-subscription-checkout reports its start-date rejections as machine
48
+ // codes ('start_date_in_past'), not as sentences, so unlike voice-booking's
49
+ // 409 passthrough they cannot be spoken verbatim. These are the caller's own
50
+ // correctable mistakes, so they are translated rather than genericized —
51
+ // otherwise someone asking to start six weeks out just hears "sorry".
52
+ const START_DATE_ERRORS: Record<string, string> = {
53
+ start_date_in_past: "That start date has already passed — what date would you like to start?",
54
+ start_date_invalid: "That doesn't look like a real calendar date — could you give me the month and day again?",
55
+ start_date_too_far_out:
56
+ 'We can only start a membership up to about four weeks out — could you pick a closer start date?',
57
+ };
58
+
59
+ // The one already-clean sentence it returns that can be spoken verbatim. Its
60
+ // other strings ("That plan is not available for online checkout.", the 500
61
+ // text) describe a configuration problem the caller can do nothing about, so
62
+ // they are logged and genericized instead.
63
+ const PASSTHROUGH_ERRORS = new Set([
64
+ 'Too many checkout attempts — please wait a few minutes and try again.',
65
+ ]);
66
+
67
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
68
+ const GHL_VERSION = '2021-07-28';
69
+ const GHL_LOCATION_ID = 'BDI8NHA4nkHnQGJ8g3hV';
70
+ // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
71
+ const BROWSER_UA =
72
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
73
+
74
+ /** Tenant-owned inputs to this function. */
75
+ export type VoiceMembershipSignupConfig = {
76
+ /**
77
+ * Plan slugs sellable over this phone flow. Everything else in the
78
+ * operator's catalog (virtual office, private offices, ...) needs a
79
+ * product decision before it can be sold this way — see the caller's own
80
+ * comment for the reasoning behind Granite City's exclusions.
81
+ */
82
+ sellablePlanSlugs: readonly string[];
83
+ /** Spoken/texted business name, e.g. "Granite City Workspaces". */
84
+ businessName: string;
85
+ /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
86
+ supportPhoneDisplay: string;
87
+ };
88
+
89
+ /**
90
+ * Membership payment-link SMS via GHL. Never throws, never rejects: a
91
+ * messaging hiccup must never turn a successful checkout into a reported
92
+ * failure. Awaited (not fire-and-forget) because the edge isolate can be torn
93
+ * down right after the response, dropping in-flight fetches.
94
+ */
95
+ async function sendVoiceMembershipSms(args: {
96
+ supabase: SupabaseClient<any, 'public', any>;
97
+ phone?: string;
98
+ name: string;
99
+ email: string;
100
+ planSlug: string;
101
+ checkoutUrl: string;
102
+ config: VoiceMembershipSignupConfig;
103
+ }): Promise<boolean> {
104
+ const { supabase, planSlug, config } = args;
105
+ try {
106
+ const phone = (args.phone ?? '').trim();
107
+ if (!phone) return false; // nothing to text
108
+
109
+ const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
110
+ if (!apiKey) {
111
+ console.error('[voice-membership-signup] GC_VOICE_GHL_API_KEY not set — skipping SMS');
112
+ await logOps(
113
+ supabase,
114
+ 'voice_membership_signup_sms_failed',
115
+ { plan_slug: planSlug, reason: 'GC_VOICE_GHL_API_KEY not set' },
116
+ { severity: 'error' },
117
+ );
118
+ return false;
119
+ }
120
+
121
+ const message =
122
+ `Thanks for starting your ${config.businessName} membership sign-up! ` +
123
+ `Here's your payment link to complete it: ${args.checkoutUrl}\n` +
124
+ `Questions? Call us at ${config.supportPhoneDisplay}.`;
125
+
126
+ const headers = {
127
+ Authorization: `Bearer ${apiKey}`,
128
+ Version: GHL_VERSION,
129
+ 'Content-Type': 'application/json',
130
+ Accept: 'application/json',
131
+ 'User-Agent': BROWSER_UA,
132
+ };
133
+
134
+ // 1) Upsert the contact. No `tags` field — upsert REPLACES tags and we must
135
+ // never clobber an existing contact's tags from here.
136
+ const upsertRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
137
+ method: 'POST',
138
+ headers,
139
+ body: JSON.stringify({
140
+ locationId: GHL_LOCATION_ID,
141
+ name: args.name,
142
+ email: args.email,
143
+ phone,
144
+ }),
145
+ });
146
+ if (!upsertRes.ok) {
147
+ const body = await upsertRes.text().catch(() => '');
148
+ console.error('[voice-membership-signup] GHL upsert failed', upsertRes.status, body);
149
+ await logOps(
150
+ supabase,
151
+ 'voice_membership_signup_sms_failed',
152
+ { plan_slug: planSlug, reason: 'ghl_upsert_failed', status: upsertRes.status, body: body.slice(0, 500) },
153
+ { severity: 'error' },
154
+ );
155
+ return false;
156
+ }
157
+ const upsertJson = (await upsertRes.json().catch(() => null)) as
158
+ | { contact?: { id?: string }; id?: string }
159
+ | null;
160
+ const contactId = upsertJson?.contact?.id ?? upsertJson?.id;
161
+ if (!contactId) {
162
+ console.error('[voice-membership-signup] GHL upsert returned no contact id');
163
+ await logOps(
164
+ supabase,
165
+ 'voice_membership_signup_sms_failed',
166
+ { plan_slug: planSlug, reason: 'ghl_upsert_no_contact_id' },
167
+ { severity: 'error' },
168
+ );
169
+ return false;
170
+ }
171
+
172
+ // 2) Send the SMS.
173
+ const smsRes = await fetch(`${GHL_BASE}/conversations/messages`, {
174
+ method: 'POST',
175
+ headers,
176
+ body: JSON.stringify({ contactId, type: 'SMS', message }),
177
+ });
178
+ if (!smsRes.ok) {
179
+ const body = await smsRes.text().catch(() => '');
180
+ console.error('[voice-membership-signup] GHL SMS failed', smsRes.status, body);
181
+ await logOps(
182
+ supabase,
183
+ 'voice_membership_signup_sms_failed',
184
+ { plan_slug: planSlug, reason: 'ghl_sms_send_failed', status: smsRes.status, body: body.slice(0, 500) },
185
+ { severity: 'error' },
186
+ );
187
+ return false;
188
+ }
189
+ return true;
190
+ } catch (e) {
191
+ console.error('[voice-membership-signup] GHL SMS error', e);
192
+ await logOps(
193
+ supabase,
194
+ 'voice_membership_signup_sms_failed',
195
+ { plan_slug: planSlug, reason: 'unhandled_error', detail: String(e).slice(0, 500) },
196
+ { severity: 'error' },
197
+ );
198
+ return false;
199
+ }
200
+ }
201
+
202
+ // Bounds how long we block the HTTP response on the outbound SMS. If GHL is
203
+ // slow, we still send it -- just not synchronously -- rather than let the
204
+ // combined checkout + SMS round trip exceed the calling voice agent's tool
205
+ // timeout and cause it to report a false failure to the caller. Same budget
206
+ // and mechanism as voice-booking.ts (added there 2026-08-24 after a
207
+ // confirmed incident); see that file for the full rationale.
208
+ const SMS_RESPONSE_BUDGET_MS = 4000;
209
+
210
+ async function runSmsWithBudget(smsPromise: Promise<boolean>): Promise<boolean> {
211
+ let settled = false;
212
+ const tracked = smsPromise.then((result) => {
213
+ settled = true;
214
+ return result;
215
+ });
216
+ // deno-lint-ignore no-explicit-any
217
+ const rt = (globalThis as any).EdgeRuntime;
218
+ if (rt?.waitUntil) rt.waitUntil(tracked); else tracked.catch(() => {});
219
+ const budget = new Promise<boolean>((resolve) => {
220
+ setTimeout(() => {
221
+ if (!settled) resolve(false);
222
+ }, SMS_RESPONSE_BUDGET_MS);
223
+ });
224
+ return await Promise.race([tracked, budget]);
225
+ }
226
+
227
+ export async function handle(req: Request, config: VoiceMembershipSignupConfig): Promise<Response> {
228
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
229
+
230
+ // Raw text first: the signature is over the exact bytes sent, so the body
231
+ // can only be JSON.parse-d after verification.
232
+ const rawBody = await req.text().catch(() => '');
233
+ if (!(await verifyRetellSignature(req, rawBody, 'voice-membership-signup'))) {
234
+ return json(401, { ok: false, error: 'unauthorized' });
235
+ }
236
+
237
+ let raw: unknown = {};
238
+ try {
239
+ raw = rawBody ? JSON.parse(rawBody) : {};
240
+ } catch {
241
+ raw = {};
242
+ }
243
+
244
+ const parsed = Body.safeParse(raw);
245
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
246
+
247
+ const {
248
+ contact_name, contact_email, contact_phone,
249
+ plan_slug, start_date, idempotency_key,
250
+ } = parsed.data;
251
+
252
+ if (!config.sellablePlanSlugs.includes(plan_slug)) {
253
+ return json(400, { ok: false, error: 'invalid_request' });
254
+ }
255
+
256
+ const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
257
+ const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
258
+ const supabase = createClient(supabaseUrl, serviceKey);
259
+
260
+ // Every cached call site returns HTTP 200, so only the JSON body is stored
261
+ // and a replay is always a 200.
262
+ const finish = async (body: unknown): Promise<Response> => {
263
+ if (idempotency_key) {
264
+ const { error } = await supabase
265
+ .from('voice_membership_signup_idempotency')
266
+ .upsert(
267
+ { key: idempotency_key, response: body, created_at: new Date().toISOString() },
268
+ { onConflict: 'key' },
269
+ );
270
+ if (error) console.error('[voice-membership-signup] idempotency write failed', error);
271
+ }
272
+ return json(200, body);
273
+ };
274
+
275
+ // Replay a recent identical request before doing ANY work: no checkout
276
+ // session created, no SMS. A duplicate here would otherwise text the caller
277
+ // a second, different payment link for the same membership.
278
+ if (idempotency_key) {
279
+ const { data: cached, error: cacheErr } = await supabase
280
+ .from('voice_membership_signup_idempotency')
281
+ .select('response,created_at')
282
+ .eq('key', idempotency_key)
283
+ .maybeSingle();
284
+ // A cache read must never be able to fail a signup — log and fall through.
285
+ if (cacheErr) console.error('[voice-membership-signup] idempotency read failed', cacheErr);
286
+ else if (cached) {
287
+ const age = Date.now() - Date.parse(cached.created_at as string);
288
+ if (Number.isFinite(age) && age >= 0 && age < IDEMPOTENCY_TTL_MS) {
289
+ return json(200, cached.response);
290
+ }
291
+ }
292
+ }
293
+
294
+ try {
295
+ // `referral_code` is deliberately omitted: this phone flow has no way to
296
+ // collect one, and create-subscription-checkout treats it as optional.
297
+ const res = await fetch(`${supabaseUrl}/functions/v1/create-subscription-checkout`, {
298
+ method: 'POST',
299
+ headers: {
300
+ 'Content-Type': 'application/json',
301
+ Authorization: `Bearer ${serviceKey}`,
302
+ apikey: serviceKey,
303
+ },
304
+ body: JSON.stringify({
305
+ plan_slug,
306
+ email: contact_email,
307
+ name: contact_name,
308
+ ...(start_date ? { start_date } : {}),
309
+ }),
310
+ });
311
+
312
+ const payload = await res.json().catch(() => null) as
313
+ | { url?: string; error?: unknown }
314
+ | null;
315
+
316
+ if (res.ok && typeof payload?.url === 'string' && payload.url) {
317
+ const smsSent = await runSmsWithBudget(sendVoiceMembershipSms({
318
+ supabase,
319
+ phone: contact_phone,
320
+ name: contact_name,
321
+ email: contact_email,
322
+ planSlug: plan_slug,
323
+ checkoutUrl: payload.url,
324
+ config,
325
+ }));
326
+ return await finish({
327
+ ok: true,
328
+ checkout_url: payload.url,
329
+ sms_sent: smsSent,
330
+ });
331
+ }
332
+
333
+ if (typeof payload?.error === 'string') {
334
+ const spoken = START_DATE_ERRORS[payload.error];
335
+ if (spoken) return await finish({ ok: false, error: spoken });
336
+ if (PASSTHROUGH_ERRORS.has(payload.error)) {
337
+ // Rate limiting is transient and must stay retryable, so it is
338
+ // deliberately not written to the idempotency cache.
339
+ return json(200, { ok: false, error: payload.error });
340
+ }
341
+ }
342
+
343
+ // Everything else (400 zod flatten, plan not self-serve, 500, unparseable
344
+ // body) is logged but never leaked to the caller.
345
+ console.error(
346
+ '[voice-membership-signup] create-subscription-checkout failed',
347
+ res.status,
348
+ JSON.stringify(payload),
349
+ );
350
+ return json(200, { ok: false, error: GENERIC_ERROR });
351
+ } catch (e) {
352
+ console.error('[voice-membership-signup] error', e);
353
+ return json(200, { ok: false, error: GENERIC_ERROR });
354
+ }
355
+ }