@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
@@ -1,204 +1,204 @@
1
- // Read-only tour-availability lookup for the Retell voice agent.
2
- //
3
- // `voice-tour-booking` owns the actual booking write and does its own
4
- // single-slot free/busy check inline (see the comment at the top of that
5
- // file — there was deliberately no separate availability-check tool for
6
- // tours, unlike `check_room_availability` for rooms). That gap forced the
7
- // voice agent to guess exact times one at a time against `book_tour` and
8
- // read the rejection as its only signal, producing a slow, frustrating
9
- // trial-and-error loop for callers (confirmed live on a 2026-08-21 test
10
- // call: three consecutive book_tour misses before the agent gave up and
11
- // promised a callback, while GHL's calendar actually had three real
12
- // afternoon openings that day).
13
- //
14
- // This function closes that gap: given an anchor date, it walks forward
15
- // (default 7 days) through GHL's free-slots endpoint for the requested tour
16
- // calendar and returns a flat, ready-to-read list of open slots — enough for
17
- // the agent to proactively offer several real options on the first attempt
18
- // instead of iterating blind guesses through `book_tour`.
19
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
20
- import { createClient } from 'npm:@supabase/supabase-js@2';
21
- import { z } from 'npm:zod@3.23.8';
22
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
23
- import { laWallToUtc } from 'npm:@simplelayer/graniteer-core/availability';
24
- import { verifyRetellSignature } from 'npm:@simplelayer/graniteer-core/retellSignature';
25
-
26
- const Body = z.object({
27
- tour_type: z.enum(['workspace', 'event-space']),
28
- // Anchor date to start searching from — usually "today" or whatever day
29
- // the caller first asked about. YYYY-MM-DD in America/Los_Angeles time.
30
- date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
31
- // How many calendar days forward to search, inclusive of the anchor date.
32
- // Optional — defaults to 7. Capped at 14 to keep the GHL call and the
33
- // response both small.
34
- days_ahead: z.number().int().min(1).max(14).optional(),
35
- });
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
- const GHL_BASE = 'https://services.leadconnectorhq.com';
44
- const GHL_VERSION = '2021-07-28';
45
- // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
46
- const BROWSER_UA =
47
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
48
-
49
- // Same two calendars as voice-tour-booking — kept in sync deliberately;
50
- // if one changes, change both.
51
- const TOUR_CALENDARS: Record<'workspace' | 'event-space', { calendarId: string; label: string }> = {
52
- workspace: { calendarId: 'SVTXVh2uhJjMBKIY6Sd4', label: 'Workspace Tour w/Megan' },
53
- 'event-space': { calendarId: 'ZpDp17KNsiranwTIrTFw', label: 'Event Space Tour w/Megan' },
54
- };
55
-
56
- // Cap on how many individual slots come back — enough for the agent to offer
57
- // a genuinely useful spread (today's remaining openings plus a couple of
58
- // next-available days) without dumping dozens of half-hour slots on the
59
- // caller.
60
- const MAX_SLOTS = 8;
61
-
62
- function nextDateStr(dateStr: string): string {
63
- const [y, mo, d] = dateStr.split('-').map(Number);
64
- return new Date(Date.UTC(y, mo - 1, d + 1)).toISOString().slice(0, 10);
65
- }
66
-
67
- function addDays(dateStr: string, n: number): string {
68
- const [y, mo, d] = dateStr.split('-').map(Number);
69
- return new Date(Date.UTC(y, mo - 1, d + n)).toISOString().slice(0, 10);
70
- }
71
-
72
- const WEEKDAY_LABELS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
73
-
74
- function friendlyLabel(dateStr: string, hh: number, mm: number, todayStr: string): string {
75
- const [y, mo, d] = dateStr.split('-').map(Number);
76
- const weekday = WEEKDAY_LABELS[new Date(Date.UTC(y, mo - 1, d)).getUTCDay()];
77
- const dayPart = dateStr === todayStr ? 'Today' : dateStr === nextDateStr(todayStr) ? 'Tomorrow' : weekday;
78
- const hour12 = hh % 12 === 0 ? 12 : hh % 12;
79
- const ampm = hh < 12 ? 'AM' : 'PM';
80
- const minutePart = mm === 0 ? '' : `:${String(mm).padStart(2, '0')}`;
81
- return `${dayPart} at ${hour12}${minutePart} ${ampm}`;
82
- }
83
-
84
- export async function handle(req: Request): Promise<Response> {
85
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
86
-
87
- const rawBody = await req.text().catch(() => '');
88
- if (!(await verifyRetellSignature(req, rawBody, 'voice-tour-availability'))) {
89
- return json(401, { ok: false, error: 'unauthorized' });
90
- }
91
-
92
- let raw: unknown = {};
93
- try {
94
- raw = rawBody ? JSON.parse(rawBody) : {};
95
- } catch {
96
- raw = {};
97
- }
98
-
99
- const parsed = Body.safeParse(raw);
100
- if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
101
-
102
- const { tour_type, date, days_ahead } = parsed.data;
103
- const windowDays = days_ahead ?? 7;
104
-
105
- const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
106
- const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
107
- const supabase = createClient(supabaseUrl, serviceKey);
108
-
109
- const GENERIC_ERROR =
110
- "Sorry — I couldn't pull up tour availability right now. I'll have a team member follow up to get you scheduled.";
111
-
112
- try {
113
- const ip = clientIp(req);
114
- // Read-only, but still rate-limited: this is a live call to GHL on every
115
- // invocation, same as voice-tour-booking's own inline check.
116
- const ipOk = await checkRateLimit(supabase, 'voice-tour-availability-ip', ip, 20, 600);
117
- if (!ipOk) {
118
- return json(200, { ok: false, error: 'Too many availability checks — please try again in a few minutes.' });
119
- }
120
-
121
- const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
122
- if (!apiKey) {
123
- console.error('[voice-tour-availability] GC_VOICE_GHL_API_KEY not set');
124
- return json(200, { ok: false, error: GENERIC_ERROR });
125
- }
126
-
127
- const calendar = TOUR_CALENDARS[tour_type];
128
- const endDateExclusive = addDays(date, windowDays);
129
-
130
- const startMs = laWallToUtc(date, 0, 0).getTime();
131
- const endMs = laWallToUtc(endDateExclusive, 0, 0).getTime();
132
-
133
- const url =
134
- `${GHL_BASE}/calendars/${calendar.calendarId}/free-slots?startDate=${startMs}&endDate=${endMs}` +
135
- `&timezone=America%2FLos_Angeles`;
136
- const res = await fetch(url, {
137
- headers: {
138
- Authorization: `Bearer ${apiKey}`,
139
- Version: GHL_VERSION,
140
- Accept: 'application/json',
141
- 'User-Agent': BROWSER_UA,
142
- },
143
- });
144
- if (!res.ok) {
145
- console.error('[voice-tour-availability] free-slots failed', res.status, await res.text().catch(() => ''));
146
- return json(200, { ok: false, error: GENERIC_ERROR });
147
- }
148
-
149
- const data = (await res.json().catch(() => null)) as Record<string, unknown> | null;
150
- if (!data || typeof data !== 'object') return json(200, { ok: false, error: GENERIC_ERROR });
151
-
152
- // GHL keys the response by date (plus a `traceId` key to skip). Flatten
153
- // every slot across every date, sort chronologically, then cap.
154
- type Slot = { date: string; start_time: string; label: string };
155
- const out: Slot[] = [];
156
- const dateKeys = Object.keys(data).filter((k) => /^\d{4}-\d{2}-\d{2}$/.test(k)).sort();
157
- for (const dKey of dateKeys) {
158
- const slots = (data[dKey] as { slots?: unknown } | null)?.slots;
159
- if (!Array.isArray(slots)) continue;
160
- for (const slot of slots) {
161
- if (typeof slot !== 'string') continue;
162
- const dt = new Date(slot);
163
- if (Number.isNaN(dt.getTime())) continue;
164
- // Slot ISO strings come back with the LA offset already applied
165
- // (e.g. "2026-08-24T09:00:00-07:00"), so reading the local wall time
166
- // straight off the string (not via UTC conversion) gives the right
167
- // HH:MM without re-deriving DST.
168
- const m = /T(\d{2}):(\d{2}):/.exec(slot);
169
- if (!m) continue;
170
- const hh = Number(m[1]);
171
- const mm = Number(m[2]);
172
- out.push({
173
- date: dKey,
174
- start_time: `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`,
175
- label: friendlyLabel(dKey, hh, mm, date),
176
- });
177
- }
178
- }
179
-
180
- out.sort((a, b) => (a.date === b.date ? a.start_time.localeCompare(b.start_time) : a.date.localeCompare(b.date)));
181
- const capped = out.slice(0, MAX_SLOTS);
182
-
183
- if (capped.length === 0) {
184
- return json(200, {
185
- ok: false,
186
- error:
187
- `No openings for the ${calendar.label} in the next ${windowDays} days — ` +
188
- `I'll have a team member follow up to get you scheduled.`,
189
- });
190
- }
191
-
192
- return json(200, {
193
- ok: true,
194
- tour_type,
195
- calendar_label: calendar.label,
196
- searched_from: date,
197
- searched_through: addDays(endDateExclusive, -1),
198
- slots: capped,
199
- });
200
- } catch (e) {
201
- console.error('[voice-tour-availability] error', e);
202
- return json(200, { ok: false, error: GENERIC_ERROR });
203
- }
204
- }
1
+ // Read-only tour-availability lookup for the Retell voice agent.
2
+ //
3
+ // `voice-tour-booking` owns the actual booking write and does its own
4
+ // single-slot free/busy check inline (see the comment at the top of that
5
+ // file — there was deliberately no separate availability-check tool for
6
+ // tours, unlike `check_room_availability` for rooms). That gap forced the
7
+ // voice agent to guess exact times one at a time against `book_tour` and
8
+ // read the rejection as its only signal, producing a slow, frustrating
9
+ // trial-and-error loop for callers (confirmed live on a 2026-08-21 test
10
+ // call: three consecutive book_tour misses before the agent gave up and
11
+ // promised a callback, while GHL's calendar actually had three real
12
+ // afternoon openings that day).
13
+ //
14
+ // This function closes that gap: given an anchor date, it walks forward
15
+ // (default 7 days) through GHL's free-slots endpoint for the requested tour
16
+ // calendar and returns a flat, ready-to-read list of open slots — enough for
17
+ // the agent to proactively offer several real options on the first attempt
18
+ // instead of iterating blind guesses through `book_tour`.
19
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
20
+ import { createClient } from 'npm:@supabase/supabase-js@2';
21
+ import { z } from 'npm:zod@3.23.8';
22
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
23
+ import { laWallToUtc } from 'npm:@simplelayer/graniteer-core/availability';
24
+ import { verifyRetellSignature } from 'npm:@simplelayer/graniteer-core/retellSignature';
25
+
26
+ const Body = z.object({
27
+ tour_type: z.enum(['workspace', 'event-space']),
28
+ // Anchor date to start searching from — usually "today" or whatever day
29
+ // the caller first asked about. YYYY-MM-DD in America/Los_Angeles time.
30
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
31
+ // How many calendar days forward to search, inclusive of the anchor date.
32
+ // Optional — defaults to 7. Capped at 14 to keep the GHL call and the
33
+ // response both small.
34
+ days_ahead: z.number().int().min(1).max(14).optional(),
35
+ });
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
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
44
+ const GHL_VERSION = '2021-07-28';
45
+ // Cloudflare in front of the LeadConnector host blocks default fetch UAs.
46
+ const BROWSER_UA =
47
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
48
+
49
+ // Same two calendars as voice-tour-booking — kept in sync deliberately;
50
+ // if one changes, change both.
51
+ const TOUR_CALENDARS: Record<'workspace' | 'event-space', { calendarId: string; label: string }> = {
52
+ workspace: { calendarId: 'SVTXVh2uhJjMBKIY6Sd4', label: 'Workspace Tour w/Megan' },
53
+ 'event-space': { calendarId: 'ZpDp17KNsiranwTIrTFw', label: 'Event Space Tour w/Megan' },
54
+ };
55
+
56
+ // Cap on how many individual slots come back — enough for the agent to offer
57
+ // a genuinely useful spread (today's remaining openings plus a couple of
58
+ // next-available days) without dumping dozens of half-hour slots on the
59
+ // caller.
60
+ const MAX_SLOTS = 8;
61
+
62
+ function nextDateStr(dateStr: string): string {
63
+ const [y, mo, d] = dateStr.split('-').map(Number);
64
+ return new Date(Date.UTC(y, mo - 1, d + 1)).toISOString().slice(0, 10);
65
+ }
66
+
67
+ function addDays(dateStr: string, n: number): string {
68
+ const [y, mo, d] = dateStr.split('-').map(Number);
69
+ return new Date(Date.UTC(y, mo - 1, d + n)).toISOString().slice(0, 10);
70
+ }
71
+
72
+ const WEEKDAY_LABELS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
73
+
74
+ function friendlyLabel(dateStr: string, hh: number, mm: number, todayStr: string): string {
75
+ const [y, mo, d] = dateStr.split('-').map(Number);
76
+ const weekday = WEEKDAY_LABELS[new Date(Date.UTC(y, mo - 1, d)).getUTCDay()];
77
+ const dayPart = dateStr === todayStr ? 'Today' : dateStr === nextDateStr(todayStr) ? 'Tomorrow' : weekday;
78
+ const hour12 = hh % 12 === 0 ? 12 : hh % 12;
79
+ const ampm = hh < 12 ? 'AM' : 'PM';
80
+ const minutePart = mm === 0 ? '' : `:${String(mm).padStart(2, '0')}`;
81
+ return `${dayPart} at ${hour12}${minutePart} ${ampm}`;
82
+ }
83
+
84
+ export async function handle(req: Request): Promise<Response> {
85
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
86
+
87
+ const rawBody = await req.text().catch(() => '');
88
+ if (!(await verifyRetellSignature(req, rawBody, 'voice-tour-availability'))) {
89
+ return json(401, { ok: false, error: 'unauthorized' });
90
+ }
91
+
92
+ let raw: unknown = {};
93
+ try {
94
+ raw = rawBody ? JSON.parse(rawBody) : {};
95
+ } catch {
96
+ raw = {};
97
+ }
98
+
99
+ const parsed = Body.safeParse(raw);
100
+ if (!parsed.success) return json(400, { ok: false, error: 'invalid_request' });
101
+
102
+ const { tour_type, date, days_ahead } = parsed.data;
103
+ const windowDays = days_ahead ?? 7;
104
+
105
+ const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
106
+ const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
107
+ const supabase = createClient(supabaseUrl, serviceKey);
108
+
109
+ const GENERIC_ERROR =
110
+ "Sorry — I couldn't pull up tour availability right now. I'll have a team member follow up to get you scheduled.";
111
+
112
+ try {
113
+ const ip = clientIp(req);
114
+ // Read-only, but still rate-limited: this is a live call to GHL on every
115
+ // invocation, same as voice-tour-booking's own inline check.
116
+ const ipOk = await checkRateLimit(supabase, 'voice-tour-availability-ip', ip, 20, 600);
117
+ if (!ipOk) {
118
+ return json(200, { ok: false, error: 'Too many availability checks — please try again in a few minutes.' });
119
+ }
120
+
121
+ const apiKey = Deno.env.get('GC_VOICE_GHL_API_KEY');
122
+ if (!apiKey) {
123
+ console.error('[voice-tour-availability] GC_VOICE_GHL_API_KEY not set');
124
+ return json(200, { ok: false, error: GENERIC_ERROR });
125
+ }
126
+
127
+ const calendar = TOUR_CALENDARS[tour_type];
128
+ const endDateExclusive = addDays(date, windowDays);
129
+
130
+ const startMs = laWallToUtc(date, 0, 0).getTime();
131
+ const endMs = laWallToUtc(endDateExclusive, 0, 0).getTime();
132
+
133
+ const url =
134
+ `${GHL_BASE}/calendars/${calendar.calendarId}/free-slots?startDate=${startMs}&endDate=${endMs}` +
135
+ `&timezone=America%2FLos_Angeles`;
136
+ const res = await fetch(url, {
137
+ headers: {
138
+ Authorization: `Bearer ${apiKey}`,
139
+ Version: GHL_VERSION,
140
+ Accept: 'application/json',
141
+ 'User-Agent': BROWSER_UA,
142
+ },
143
+ });
144
+ if (!res.ok) {
145
+ console.error('[voice-tour-availability] free-slots failed', res.status, await res.text().catch(() => ''));
146
+ return json(200, { ok: false, error: GENERIC_ERROR });
147
+ }
148
+
149
+ const data = (await res.json().catch(() => null)) as Record<string, unknown> | null;
150
+ if (!data || typeof data !== 'object') return json(200, { ok: false, error: GENERIC_ERROR });
151
+
152
+ // GHL keys the response by date (plus a `traceId` key to skip). Flatten
153
+ // every slot across every date, sort chronologically, then cap.
154
+ type Slot = { date: string; start_time: string; label: string };
155
+ const out: Slot[] = [];
156
+ const dateKeys = Object.keys(data).filter((k) => /^\d{4}-\d{2}-\d{2}$/.test(k)).sort();
157
+ for (const dKey of dateKeys) {
158
+ const slots = (data[dKey] as { slots?: unknown } | null)?.slots;
159
+ if (!Array.isArray(slots)) continue;
160
+ for (const slot of slots) {
161
+ if (typeof slot !== 'string') continue;
162
+ const dt = new Date(slot);
163
+ if (Number.isNaN(dt.getTime())) continue;
164
+ // Slot ISO strings come back with the LA offset already applied
165
+ // (e.g. "2026-08-24T09:00:00-07:00"), so reading the local wall time
166
+ // straight off the string (not via UTC conversion) gives the right
167
+ // HH:MM without re-deriving DST.
168
+ const m = /T(\d{2}):(\d{2}):/.exec(slot);
169
+ if (!m) continue;
170
+ const hh = Number(m[1]);
171
+ const mm = Number(m[2]);
172
+ out.push({
173
+ date: dKey,
174
+ start_time: `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`,
175
+ label: friendlyLabel(dKey, hh, mm, date),
176
+ });
177
+ }
178
+ }
179
+
180
+ out.sort((a, b) => (a.date === b.date ? a.start_time.localeCompare(b.start_time) : a.date.localeCompare(b.date)));
181
+ const capped = out.slice(0, MAX_SLOTS);
182
+
183
+ if (capped.length === 0) {
184
+ return json(200, {
185
+ ok: false,
186
+ error:
187
+ `No openings for the ${calendar.label} in the next ${windowDays} days — ` +
188
+ `I'll have a team member follow up to get you scheduled.`,
189
+ });
190
+ }
191
+
192
+ return json(200, {
193
+ ok: true,
194
+ tour_type,
195
+ calendar_label: calendar.label,
196
+ searched_from: date,
197
+ searched_through: addDays(endDateExclusive, -1),
198
+ slots: capped,
199
+ });
200
+ } catch (e) {
201
+ console.error('[voice-tour-availability] error', e);
202
+ return json(200, { ok: false, error: GENERIC_ERROR });
203
+ }
204
+ }