@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.
- package/index.js +2 -2
- package/package.json +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
|
@@ -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
|
+
}
|