@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,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
+ }