@simplelayer/graniteer-core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -309
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -95
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,388 +1,388 @@
1
- // Post-paid booking side effects: notify GHL (upsert contact, set booking
2
- // custom fields incl. Manage Link, add note, send the confirmation email).
3
- //
4
- // Phase 8 of the Graniteer/Granite-City split: the generic half of
5
- // gc-connect's _shared/bookingEffects.ts. Tenant values (operator identity,
6
- // the manage-link origin, the GHL custom-field display names) are now passed
7
- // in as `config` rather than read from a tenant module.
8
- //
9
- // createCalendarEvent deliberately did NOT move: it signs the calendar event's
10
- // extended properties via gc-connect's _shared/busClient.ts (gc_sig /
11
- // gc_sig_v2, a pinned cross-repo contract with ftw-middleware's reconciler).
12
- // That whole door/calendar-signing group is deferred to a later phase gated on
13
- // a dedicated security review, so createCalendarEvent stays in gc-connect,
14
- // untouched, and imports isDepositOnly/parseTstzRange/formatDollars from here.
15
-
16
- import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
17
- import { buildManageUrl } from './manageToken.ts';
18
- import { deriveReservationWifiCode, isReservationWifiRoom } from './reservationWifiCode.ts';
19
-
20
- const LA_TZ = 'America/Los_Angeles';
21
- const GHL_BASE = 'https://services.leadconnectorhq.com';
22
-
23
- // Loose generics, matching ./ops.ts. A real createClient(url, key, opts)
24
- // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
25
- // assignable to the un-inferred ReturnType<typeof createClient> default — that
26
- // mismatch is what made every call site here fail deno check.
27
- // deno-lint-ignore no-explicit-any
28
- type SupabaseLike = SupabaseClient<any, any, any>;
29
-
30
- export interface BookingRow {
31
- id: string;
32
- contact_name: string | null;
33
- contact_email: string;
34
- contact_phone: string | null;
35
- during: string;
36
- charged_amount_cents: number | null;
37
- list_amount_cents: number | null;
38
- google_event_id: string | null;
39
- ghl_contact_id?: string | null;
40
- /** Present on callers that select it; used only by isDepositOnly() below. */
41
- status?: string | null;
42
- rooms: {
43
- id: string;
44
- name: string;
45
- address: string | null;
46
- google_calendar_id: string | null;
47
- slug: string | null;
48
- /**
49
- * Free-text "About this room" copy (rooms.usage_instructions). Optional so
50
- * a caller that doesn't select it simply omits the email section; NULL/
51
- * absent = this room has no instructions and nothing is rendered.
52
- */
53
- usage_instructions?: string | null;
54
- } | null;
55
- }
56
-
57
- /**
58
- * The door credential minted for this reservation, when the door bus issued
59
- * one. Structurally identical to gc-connect's _shared/busClient.ts `DoorAccess`
60
- * — declared here so this module carries no dependency on that (deferred,
61
- * security-reviewed) file.
62
- */
63
- export interface BookingDoorAccess {
64
- pin: string;
65
- validFromUtc?: string;
66
- validToUtc?: string;
67
- }
68
-
69
- /**
70
- * A Commons (tier 3) event that has only paid its 50% deposit. The space is not
71
- * access-provisioned, the calendar hold is staff-managed and the standard
72
- * booking-confirmation copy would be wrong, so the whole post-paid chain
73
- * (busProvision / createCalendarEvent / notifyGhl confirmation) is suppressed.
74
- * Discriminated on STATUS, never on room slug.
75
- */
76
- export function isDepositOnly(booking: { status?: string | null } | null | undefined): boolean {
77
- return booking?.status === 'deposit_paid';
78
- }
79
-
80
-
81
-
82
- export function parseTstzRange(range: string): { startISO: string; endISO: string } | null {
83
- const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
84
- if (!m) return null;
85
- const normalize = (raw: string): string => {
86
- let v = raw.trim().replace(/ /g, 'T');
87
- v = v.replace(/([+-]\d{2})$/, '$1:00');
88
- return v;
89
- };
90
- const s = new Date(normalize(m[1]));
91
- const e = new Date(normalize(m[2]));
92
- if (isNaN(s.getTime()) || isNaN(e.getTime())) return null;
93
- return { startISO: s.toISOString(), endISO: e.toISOString() };
94
- }
95
-
96
- function formatWhen(startISO: string, endISO: string): string {
97
- const s = new Date(startISO);
98
- const e = new Date(endISO);
99
- const day = new Intl.DateTimeFormat('en-US', {
100
- timeZone: LA_TZ, weekday: 'short', month: 'short', day: 'numeric',
101
- }).format(s);
102
- const timeFmt = (d: Date) => new Intl.DateTimeFormat('en-US', {
103
- timeZone: LA_TZ, hour: 'numeric', minute: '2-digit', hour12: true,
104
- }).format(d).replace(/[\u202F\u00A0]/g, ' ');
105
- const [startTime, startMer] = timeFmt(s).split(' ');
106
- const [endTime, endMer] = timeFmt(e).split(' ');
107
- const left = startMer === endMer ? startTime : `${startTime} ${startMer}`;
108
- return `${day} · ${left}–${endTime} ${endMer} PT`;
109
- }
110
-
111
- // Same escaper as every other email module here (dayPassConfirmation.ts,
112
- // paymentLinkEmail.ts, …). Room usage instructions are staff-entered free text
113
- // going into an HTML email, so they get escaped, never interpolated raw.
114
- function esc(v: unknown): string {
115
- return String(v ?? '')
116
- .replace(/&/g, '&amp;')
117
- .replace(/</g, '&lt;')
118
- .replace(/>/g, '&gt;')
119
- .replace(/"/g, '&quot;')
120
- .replace(/'/g, '&#39;');
121
- }
122
-
123
- /** Plain text with line breaks preserved — no markdown, by design. */
124
- function textToHtmlParagraphs(text: string): string {
125
- return text
126
- .split(/\n{2,}/)
127
- .map((block) => block.trim())
128
- .filter((block) => block.length > 0)
129
- .map((block) => `<p style='margin:0 0 10px 0;color:#22263B;font-size:14px'>${esc(block).replace(/\n/g, '<br />')}</p>`)
130
- .join('');
131
- }
132
-
133
- export function formatDollars(cents: number | null | undefined): string {
134
- const c = cents ?? 0;
135
- return `$${(c / 100).toFixed(c % 100 === 0 ? 0 : 2)}`;
136
- }
137
-
138
- export function googleCalendarUrl(startISO: string, endISO: string, title: string, details: string, location: string): string {
139
- const compact = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
140
- const dates = `${compact(startISO)}/${compact(endISO)}`;
141
- const params = `action=TEMPLATE&text=${encodeURIComponent(title)}&dates=${dates}&details=${encodeURIComponent(details)}&location=${encodeURIComponent(location)}`;
142
- return `https://calendar.google.com/calendar/render?${params}`;
143
- }
144
-
145
- function ghlHeaders(apiKey: string) {
146
- return {
147
- Authorization: `Bearer ${apiKey}`,
148
- Version: '2021-07-28',
149
- 'Content-Type': 'application/json',
150
- Accept: 'application/json',
151
- };
152
- }
153
-
154
- async function ensureCustomFields(
155
- apiKey: string,
156
- locationId: string,
157
- names: readonly string[],
158
- ): Promise<Record<string, string>> {
159
- const map: Record<string, string> = {};
160
- const listRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
161
- headers: ghlHeaders(apiKey),
162
- });
163
- const existing: Array<{ id: string; name: string; fieldKey?: string }> = listRes.ok
164
- ? ((await listRes.json()).customFields ?? [])
165
- : [];
166
- for (const name of names) {
167
- const found = existing.find((f) => (f.name || '').toLowerCase() === name.toLowerCase());
168
- if (found) { map[name] = found.id; continue; }
169
- try {
170
- const createRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
171
- method: 'POST', headers: ghlHeaders(apiKey),
172
- body: JSON.stringify({ name, dataType: 'TEXT', position: 0 }),
173
- });
174
- if (createRes.ok) {
175
- const cf = (await createRes.json()).customField;
176
- if (cf?.id) map[name] = cf.id;
177
- } else {
178
- console.warn('[bookingEffects] custom field create failed', name, createRes.status, await createRes.text());
179
- }
180
- } catch (e) {
181
- console.warn('[bookingEffects] custom field create error', name, e);
182
- }
183
- }
184
- return map;
185
- }
186
-
187
- /**
188
- * Display names of the GHL contact custom fields this module reads/creates in
189
- * the operator's own GHL location. They are free-text labels a human picked in
190
- * GHL, so they are tenant config, not platform constants.
191
- */
192
- export type BookingCustomFieldNames = {
193
- room: string;
194
- when: string;
195
- amount: string;
196
- address: string;
197
- calendarLink: string;
198
- manageLink: string;
199
- reminderWaitHours: string;
200
- };
201
-
202
- export type NotifyGhlConfig = {
203
- operator: {
204
- /** Full brand name, e.g. "Granite City Workspaces". */
205
- name: string;
206
- /** Short brand name used in the GHL contact `source`. */
207
- shortName: string;
208
- /** Bare apex domain, applied as a GHL tag. */
209
- domain: string;
210
- };
211
- /** Absolute origin the signed manage-booking link is built against. */
212
- manageUrlBase: string;
213
- customFieldNames: BookingCustomFieldNames;
214
- };
215
-
216
- export async function notifyGhl(
217
- supabase: SupabaseLike,
218
- booking: BookingRow,
219
- config: NotifyGhlConfig,
220
- doorAccess?: BookingDoorAccess | null,
221
- ) {
222
- const { operator, customFieldNames: cf } = config;
223
- if (isDepositOnly(booking)) {
224
- console.log('[bookingEffects] deposit-only booking; skip GHL confirmation', booking.id);
225
- return;
226
- }
227
- const apiKey = Deno.env.get('GHL_API_KEY');
228
- const locationId = Deno.env.get('GHL_LOCATION_ID');
229
- if (!apiKey || !locationId) { console.log('[bookingEffects] GHL not configured'); return; }
230
- if (!booking.rooms) { console.log('[bookingEffects] no room joined; skip GHL'); return; }
231
-
232
- const parsed = parseTstzRange(booking.during);
233
- if (!parsed) { console.warn('[bookingEffects] could not parse booking.during'); return; }
234
- const { startISO, endISO } = parsed;
235
-
236
- const reminderTargetMs = new Date(startISO).getTime() - 24 * 60 * 60 * 1000;
237
- const hoursUntilReminder = Math.max(1, Math.round((reminderTargetMs - Date.now()) / (60 * 60 * 1000)));
238
-
239
- const name = (booking.contact_name || '').trim();
240
- const parts = name.split(/\s+/);
241
- const firstName = parts[0] || 'Guest';
242
- const lastName = parts.slice(1).join(' ') || '';
243
- const roomName = booking.rooms.name;
244
- const whenStr = formatWhen(startISO, endISO);
245
- const amountStr = formatDollars(booking.charged_amount_cents ?? booking.list_amount_cents);
246
-
247
- const gcalTitle = `${roomName} — ${operator.name}`;
248
- const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
249
- const gcalLocation = booking.rooms?.address || operator.name;
250
- const gcalUrl = googleCalendarUrl(startISO, endISO, gcalTitle, gcalDetails, gcalLocation);
251
-
252
- const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET') ?? '';
253
- let manageUrl = '';
254
- if (manageSecret) {
255
- try {
256
- const exp = Math.floor(new Date(endISO).getTime() / 1000) + 30 * 24 * 60 * 60;
257
- manageUrl = await buildManageUrl(
258
- config.manageUrlBase,
259
- { bid: booking.id, eml: (booking.contact_email || '').toLowerCase(), exp },
260
- manageSecret,
261
- );
262
- } catch (e) {
263
- console.warn('[bookingEffects] manage url build failed', e);
264
- }
265
- }
266
-
267
- const headers = ghlHeaders(apiKey);
268
-
269
- let contactId: string | null = null;
270
- try {
271
- const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
272
- method: 'POST', headers,
273
- body: JSON.stringify({
274
- locationId, firstName, lastName,
275
- email: booking.contact_email,
276
- phone: booking.contact_phone || '',
277
- source: `${operator.shortName} Website — Meeting Room`,
278
- tags: ['Meeting Room Booking', operator.domain],
279
- }),
280
- });
281
- if (!upRes.ok) {
282
- console.warn('[bookingEffects] GHL upsert failed', upRes.status, await upRes.text());
283
- return;
284
- }
285
- const j = await upRes.json();
286
- contactId = j.contact?.id || j.id || null;
287
- if (!contactId) { console.warn('[bookingEffects] no contact id from upsert'); return; }
288
- } catch (e) {
289
- console.warn('[bookingEffects] GHL upsert error', e);
290
- return;
291
- }
292
-
293
- try {
294
- await supabase.from('bookings').update({ ghl_contact_id: contactId }).eq('id', booking.id);
295
- } catch (e) {
296
- console.warn('[bookingEffects] save ghl_contact_id failed', e);
297
- }
298
-
299
- try {
300
- // Ordered explicitly, not via Object.values(cf), so the create-if-missing
301
- // order in GHL is a property of this module and not of how a caller
302
- // happened to spell its config object.
303
- const cfMap = await ensureCustomFields(apiKey, locationId, [
304
- cf.room, cf.when, cf.amount,
305
- cf.address, cf.calendarLink, cf.manageLink,
306
- cf.reminderWaitHours,
307
- ]);
308
- const customFields: Array<{ id: string; value: string }> = [];
309
- if (cfMap[cf.room]) customFields.push({ id: cfMap[cf.room], value: roomName });
310
- if (cfMap[cf.when]) customFields.push({ id: cfMap[cf.when], value: whenStr });
311
- if (cfMap[cf.amount]) customFields.push({ id: cfMap[cf.amount], value: amountStr });
312
- if (cfMap[cf.address]) customFields.push({ id: cfMap[cf.address], value: booking.rooms.address || '' });
313
- if (cfMap[cf.calendarLink]) customFields.push({ id: cfMap[cf.calendarLink], value: gcalUrl });
314
- if (cfMap[cf.manageLink] && manageUrl) customFields.push({ id: cfMap[cf.manageLink], value: manageUrl });
315
- if (cfMap[cf.reminderWaitHours]) customFields.push({ id: cfMap[cf.reminderWaitHours], value: String(hoursUntilReminder) });
316
- if (customFields.length > 0) {
317
- const putRes = await fetch(`${GHL_BASE}/contacts/${contactId}`, {
318
- method: 'PUT', headers, body: JSON.stringify({ customFields }),
319
- });
320
- if (!putRes.ok) console.warn('[bookingEffects] contact customFields update failed', putRes.status, await putRes.text());
321
- }
322
- } catch (e) {
323
- console.warn('[bookingEffects] custom fields step error', e);
324
- }
325
-
326
- try {
327
- const noteBody =
328
- `Meeting Room Booking\n` +
329
- `Room: ${roomName}\n` +
330
- `When: ${whenStr}\n` +
331
- `Amount: ${amountStr}\n` +
332
- `Email: ${booking.contact_email}\n` +
333
- `Phone: ${booking.contact_phone || '—'}\n` +
334
- `Booking ID: ${booking.id}`;
335
- const noteRes = await fetch(`${GHL_BASE}/contacts/${contactId}/notes`, {
336
- method: 'POST', headers, body: JSON.stringify({ body: noteBody }),
337
- });
338
- if (!noteRes.ok) console.warn('[bookingEffects] note create failed', noteRes.status, await noteRes.text());
339
- } catch (e) {
340
- console.warn('[bookingEffects] note error', e);
341
- }
342
-
343
- // Confirmation email — sent directly (no GHL workflow exists for this).
344
- try {
345
- const address = booking.rooms.address || operator.name;
346
- const manageParagraph = manageUrl
347
- ? `<p>Need to change plans? <a href='${manageUrl}' style='color:#C98A5E'>Manage your booking</a> — free cancellation with credit up to 48 hours before your start time.</p>`
348
- : '';
349
- let doorSection = '';
350
- if (doorAccess?.pin) {
351
- const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
352
- ? `<p style='margin:6px 0 0 0;color:#5f6c5d;font-size:13px'>Active ${formatWhen(doorAccess.validFromUtc, doorAccess.validToUtc)}</p>`
353
- : '';
354
- doorSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Door access</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${doorAccess.pin}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Your PIN works at the Commons Hub door &mdash; the building's main entrance. The other entrances are badge and mobile-unlock only.</p>${activeLine}</div>`;
355
- }
356
- // Guest WiFi code — derived fresh (never stored), gated to the 4 hourly
357
- // meeting rooms per RESERVATION-SCOPED-GUEST-WIFI-DESIGN.md. A cancelled
358
- // booking needs no special handling here: ftw-middleware only ever
359
- // validates against currently live/paid bookings, and this whole email
360
- // only sends on the paid path anyway.
361
- let wifiSection = '';
362
- const wifiSecret = Deno.env.get('RESERVATION_WIFI_CODE_SECRET');
363
- if (wifiSecret && isReservationWifiRoom(booking.rooms.slug)) {
364
- const wifiCode = await deriveReservationWifiCode(wifiSecret, booking.id);
365
- wifiSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Guest WiFi</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${wifiCode}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Guest WiFi code for your visit — valid for your reservation window in ${roomName}.</p></div>`;
366
- }
367
- // "About this room" — the room's own usage_instructions, when set. Same
368
- // bordered-card shape as the door/wifi sections above.
369
- let instructionsSection = '';
370
- const usageInstructions = booking.rooms.usage_instructions;
371
- if (typeof usageInstructions === 'string' && usageInstructions.trim().length > 0) {
372
- instructionsSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>About this room</h3>${textToHtmlParagraphs(usageInstructions)}</div>`;
373
- }
374
- const confirmationHtml = `<div style='font-family:Inter,Arial,sans-serif;max-width:560px;margin:0 auto;color:#22263B'><h2 style='color:#22263B'>Your booking is confirmed</h2><p>Hi ${firstName},</p><p>Thanks for booking with ${operator.name}. Here are your details:</p><table style='border-collapse:collapse;width:100%'><tr><td style='padding:6px 0;color:#5f6c5d;width:110px'>Room</td><td style='padding:6px 0'><strong>${roomName}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>When</td><td style='padding:6px 0'><strong>${whenStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Amount</td><td style='padding:6px 0'><strong>${amountStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Address</td><td style='padding:6px 0'>${address}</td></tr></table><p style='margin:20px 0'><a href='${gcalUrl}' style='background:#748272;color:#F6F6F6;padding:10px 18px;text-decoration:none;border-radius:6px;display:inline-block'>Add to Google Calendar</a></p>${doorSection}${wifiSection}${instructionsSection}${manageParagraph}<p style='color:#5f6c5d;font-size:13px;margin-top:28px'>${operator.name} · ${address}</p></div>`;
375
- const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
376
- method: 'POST', headers,
377
- body: JSON.stringify({
378
- type: 'Email',
379
- contactId,
380
- subject: `Your booking is confirmed — ${roomName}, ${whenStr.split(' · ')[0]}`,
381
- html: confirmationHtml,
382
- }),
383
- });
384
- if (!emailRes.ok) console.warn('[bookingEffects] confirmation email failed', emailRes.status, await emailRes.text());
385
- } catch (e) {
386
- console.warn('[bookingEffects] confirmation email error', e);
387
- }
388
- }
1
+ // Post-paid booking side effects: notify GHL (upsert contact, set booking
2
+ // custom fields incl. Manage Link, add note, send the confirmation email).
3
+ //
4
+ // Phase 8 of the Graniteer/Granite-City split: the generic half of
5
+ // gc-connect's _shared/bookingEffects.ts. Tenant values (operator identity,
6
+ // the manage-link origin, the GHL custom-field display names) are now passed
7
+ // in as `config` rather than read from a tenant module.
8
+ //
9
+ // createCalendarEvent deliberately did NOT move: it signs the calendar event's
10
+ // extended properties via gc-connect's _shared/busClient.ts (gc_sig /
11
+ // gc_sig_v2, a pinned cross-repo contract with ftw-middleware's reconciler).
12
+ // That whole door/calendar-signing group is deferred to a later phase gated on
13
+ // a dedicated security review, so createCalendarEvent stays in gc-connect,
14
+ // untouched, and imports isDepositOnly/parseTstzRange/formatDollars from here.
15
+
16
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
17
+ import { buildManageUrl } from './manageToken.ts';
18
+ import { deriveReservationWifiCode, isReservationWifiRoom } from './reservationWifiCode.ts';
19
+
20
+ const LA_TZ = 'America/Los_Angeles';
21
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
22
+
23
+ // Loose generics, matching ./ops.ts. A real createClient(url, key, opts)
24
+ // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
25
+ // assignable to the un-inferred ReturnType<typeof createClient> default — that
26
+ // mismatch is what made every call site here fail deno check.
27
+ // deno-lint-ignore no-explicit-any
28
+ type SupabaseLike = SupabaseClient<any, any, any>;
29
+
30
+ export interface BookingRow {
31
+ id: string;
32
+ contact_name: string | null;
33
+ contact_email: string;
34
+ contact_phone: string | null;
35
+ during: string;
36
+ charged_amount_cents: number | null;
37
+ list_amount_cents: number | null;
38
+ google_event_id: string | null;
39
+ ghl_contact_id?: string | null;
40
+ /** Present on callers that select it; used only by isDepositOnly() below. */
41
+ status?: string | null;
42
+ rooms: {
43
+ id: string;
44
+ name: string;
45
+ address: string | null;
46
+ google_calendar_id: string | null;
47
+ slug: string | null;
48
+ /**
49
+ * Free-text "About this room" copy (rooms.usage_instructions). Optional so
50
+ * a caller that doesn't select it simply omits the email section; NULL/
51
+ * absent = this room has no instructions and nothing is rendered.
52
+ */
53
+ usage_instructions?: string | null;
54
+ } | null;
55
+ }
56
+
57
+ /**
58
+ * The door credential minted for this reservation, when the door bus issued
59
+ * one. Structurally identical to gc-connect's _shared/busClient.ts `DoorAccess`
60
+ * — declared here so this module carries no dependency on that (deferred,
61
+ * security-reviewed) file.
62
+ */
63
+ export interface BookingDoorAccess {
64
+ pin: string;
65
+ validFromUtc?: string;
66
+ validToUtc?: string;
67
+ }
68
+
69
+ /**
70
+ * A Commons (tier 3) event that has only paid its 50% deposit. The space is not
71
+ * access-provisioned, the calendar hold is staff-managed and the standard
72
+ * booking-confirmation copy would be wrong, so the whole post-paid chain
73
+ * (busProvision / createCalendarEvent / notifyGhl confirmation) is suppressed.
74
+ * Discriminated on STATUS, never on room slug.
75
+ */
76
+ export function isDepositOnly(booking: { status?: string | null } | null | undefined): boolean {
77
+ return booking?.status === 'deposit_paid';
78
+ }
79
+
80
+
81
+
82
+ export function parseTstzRange(range: string): { startISO: string; endISO: string } | null {
83
+ const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
84
+ if (!m) return null;
85
+ const normalize = (raw: string): string => {
86
+ let v = raw.trim().replace(/ /g, 'T');
87
+ v = v.replace(/([+-]\d{2})$/, '$1:00');
88
+ return v;
89
+ };
90
+ const s = new Date(normalize(m[1]));
91
+ const e = new Date(normalize(m[2]));
92
+ if (isNaN(s.getTime()) || isNaN(e.getTime())) return null;
93
+ return { startISO: s.toISOString(), endISO: e.toISOString() };
94
+ }
95
+
96
+ function formatWhen(startISO: string, endISO: string): string {
97
+ const s = new Date(startISO);
98
+ const e = new Date(endISO);
99
+ const day = new Intl.DateTimeFormat('en-US', {
100
+ timeZone: LA_TZ, weekday: 'short', month: 'short', day: 'numeric',
101
+ }).format(s);
102
+ const timeFmt = (d: Date) => new Intl.DateTimeFormat('en-US', {
103
+ timeZone: LA_TZ, hour: 'numeric', minute: '2-digit', hour12: true,
104
+ }).format(d).replace(/[\u202F\u00A0]/g, ' ');
105
+ const [startTime, startMer] = timeFmt(s).split(' ');
106
+ const [endTime, endMer] = timeFmt(e).split(' ');
107
+ const left = startMer === endMer ? startTime : `${startTime} ${startMer}`;
108
+ return `${day} · ${left}–${endTime} ${endMer} PT`;
109
+ }
110
+
111
+ // Same escaper as every other email module here (dayPassConfirmation.ts,
112
+ // paymentLinkEmail.ts, …). Room usage instructions are staff-entered free text
113
+ // going into an HTML email, so they get escaped, never interpolated raw.
114
+ function esc(v: unknown): string {
115
+ return String(v ?? '')
116
+ .replace(/&/g, '&amp;')
117
+ .replace(/</g, '&lt;')
118
+ .replace(/>/g, '&gt;')
119
+ .replace(/"/g, '&quot;')
120
+ .replace(/'/g, '&#39;');
121
+ }
122
+
123
+ /** Plain text with line breaks preserved — no markdown, by design. */
124
+ function textToHtmlParagraphs(text: string): string {
125
+ return text
126
+ .split(/\n{2,}/)
127
+ .map((block) => block.trim())
128
+ .filter((block) => block.length > 0)
129
+ .map((block) => `<p style='margin:0 0 10px 0;color:#22263B;font-size:14px'>${esc(block).replace(/\n/g, '<br />')}</p>`)
130
+ .join('');
131
+ }
132
+
133
+ export function formatDollars(cents: number | null | undefined): string {
134
+ const c = cents ?? 0;
135
+ return `$${(c / 100).toFixed(c % 100 === 0 ? 0 : 2)}`;
136
+ }
137
+
138
+ export function googleCalendarUrl(startISO: string, endISO: string, title: string, details: string, location: string): string {
139
+ const compact = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
140
+ const dates = `${compact(startISO)}/${compact(endISO)}`;
141
+ const params = `action=TEMPLATE&text=${encodeURIComponent(title)}&dates=${dates}&details=${encodeURIComponent(details)}&location=${encodeURIComponent(location)}`;
142
+ return `https://calendar.google.com/calendar/render?${params}`;
143
+ }
144
+
145
+ function ghlHeaders(apiKey: string) {
146
+ return {
147
+ Authorization: `Bearer ${apiKey}`,
148
+ Version: '2021-07-28',
149
+ 'Content-Type': 'application/json',
150
+ Accept: 'application/json',
151
+ };
152
+ }
153
+
154
+ async function ensureCustomFields(
155
+ apiKey: string,
156
+ locationId: string,
157
+ names: readonly string[],
158
+ ): Promise<Record<string, string>> {
159
+ const map: Record<string, string> = {};
160
+ const listRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
161
+ headers: ghlHeaders(apiKey),
162
+ });
163
+ const existing: Array<{ id: string; name: string; fieldKey?: string }> = listRes.ok
164
+ ? ((await listRes.json()).customFields ?? [])
165
+ : [];
166
+ for (const name of names) {
167
+ const found = existing.find((f) => (f.name || '').toLowerCase() === name.toLowerCase());
168
+ if (found) { map[name] = found.id; continue; }
169
+ try {
170
+ const createRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
171
+ method: 'POST', headers: ghlHeaders(apiKey),
172
+ body: JSON.stringify({ name, dataType: 'TEXT', position: 0 }),
173
+ });
174
+ if (createRes.ok) {
175
+ const cf = (await createRes.json()).customField;
176
+ if (cf?.id) map[name] = cf.id;
177
+ } else {
178
+ console.warn('[bookingEffects] custom field create failed', name, createRes.status, await createRes.text());
179
+ }
180
+ } catch (e) {
181
+ console.warn('[bookingEffects] custom field create error', name, e);
182
+ }
183
+ }
184
+ return map;
185
+ }
186
+
187
+ /**
188
+ * Display names of the GHL contact custom fields this module reads/creates in
189
+ * the operator's own GHL location. They are free-text labels a human picked in
190
+ * GHL, so they are tenant config, not platform constants.
191
+ */
192
+ export type BookingCustomFieldNames = {
193
+ room: string;
194
+ when: string;
195
+ amount: string;
196
+ address: string;
197
+ calendarLink: string;
198
+ manageLink: string;
199
+ reminderWaitHours: string;
200
+ };
201
+
202
+ export type NotifyGhlConfig = {
203
+ operator: {
204
+ /** Full brand name, e.g. "Granite City Workspaces". */
205
+ name: string;
206
+ /** Short brand name used in the GHL contact `source`. */
207
+ shortName: string;
208
+ /** Bare apex domain, applied as a GHL tag. */
209
+ domain: string;
210
+ };
211
+ /** Absolute origin the signed manage-booking link is built against. */
212
+ manageUrlBase: string;
213
+ customFieldNames: BookingCustomFieldNames;
214
+ };
215
+
216
+ export async function notifyGhl(
217
+ supabase: SupabaseLike,
218
+ booking: BookingRow,
219
+ config: NotifyGhlConfig,
220
+ doorAccess?: BookingDoorAccess | null,
221
+ ) {
222
+ const { operator, customFieldNames: cf } = config;
223
+ if (isDepositOnly(booking)) {
224
+ console.log('[bookingEffects] deposit-only booking; skip GHL confirmation', booking.id);
225
+ return;
226
+ }
227
+ const apiKey = Deno.env.get('GHL_API_KEY');
228
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
229
+ if (!apiKey || !locationId) { console.log('[bookingEffects] GHL not configured'); return; }
230
+ if (!booking.rooms) { console.log('[bookingEffects] no room joined; skip GHL'); return; }
231
+
232
+ const parsed = parseTstzRange(booking.during);
233
+ if (!parsed) { console.warn('[bookingEffects] could not parse booking.during'); return; }
234
+ const { startISO, endISO } = parsed;
235
+
236
+ const reminderTargetMs = new Date(startISO).getTime() - 24 * 60 * 60 * 1000;
237
+ const hoursUntilReminder = Math.max(1, Math.round((reminderTargetMs - Date.now()) / (60 * 60 * 1000)));
238
+
239
+ const name = (booking.contact_name || '').trim();
240
+ const parts = name.split(/\s+/);
241
+ const firstName = parts[0] || 'Guest';
242
+ const lastName = parts.slice(1).join(' ') || '';
243
+ const roomName = booking.rooms.name;
244
+ const whenStr = formatWhen(startISO, endISO);
245
+ const amountStr = formatDollars(booking.charged_amount_cents ?? booking.list_amount_cents);
246
+
247
+ const gcalTitle = `${roomName} — ${operator.name}`;
248
+ const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
249
+ const gcalLocation = booking.rooms?.address || operator.name;
250
+ const gcalUrl = googleCalendarUrl(startISO, endISO, gcalTitle, gcalDetails, gcalLocation);
251
+
252
+ const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET') ?? '';
253
+ let manageUrl = '';
254
+ if (manageSecret) {
255
+ try {
256
+ const exp = Math.floor(new Date(endISO).getTime() / 1000) + 30 * 24 * 60 * 60;
257
+ manageUrl = await buildManageUrl(
258
+ config.manageUrlBase,
259
+ { bid: booking.id, eml: (booking.contact_email || '').toLowerCase(), exp },
260
+ manageSecret,
261
+ );
262
+ } catch (e) {
263
+ console.warn('[bookingEffects] manage url build failed', e);
264
+ }
265
+ }
266
+
267
+ const headers = ghlHeaders(apiKey);
268
+
269
+ let contactId: string | null = null;
270
+ try {
271
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
272
+ method: 'POST', headers,
273
+ body: JSON.stringify({
274
+ locationId, firstName, lastName,
275
+ email: booking.contact_email,
276
+ phone: booking.contact_phone || '',
277
+ source: `${operator.shortName} Website — Meeting Room`,
278
+ tags: ['Meeting Room Booking', operator.domain],
279
+ }),
280
+ });
281
+ if (!upRes.ok) {
282
+ console.warn('[bookingEffects] GHL upsert failed', upRes.status, await upRes.text());
283
+ return;
284
+ }
285
+ const j = await upRes.json();
286
+ contactId = j.contact?.id || j.id || null;
287
+ if (!contactId) { console.warn('[bookingEffects] no contact id from upsert'); return; }
288
+ } catch (e) {
289
+ console.warn('[bookingEffects] GHL upsert error', e);
290
+ return;
291
+ }
292
+
293
+ try {
294
+ await supabase.from('bookings').update({ ghl_contact_id: contactId }).eq('id', booking.id);
295
+ } catch (e) {
296
+ console.warn('[bookingEffects] save ghl_contact_id failed', e);
297
+ }
298
+
299
+ try {
300
+ // Ordered explicitly, not via Object.values(cf), so the create-if-missing
301
+ // order in GHL is a property of this module and not of how a caller
302
+ // happened to spell its config object.
303
+ const cfMap = await ensureCustomFields(apiKey, locationId, [
304
+ cf.room, cf.when, cf.amount,
305
+ cf.address, cf.calendarLink, cf.manageLink,
306
+ cf.reminderWaitHours,
307
+ ]);
308
+ const customFields: Array<{ id: string; value: string }> = [];
309
+ if (cfMap[cf.room]) customFields.push({ id: cfMap[cf.room], value: roomName });
310
+ if (cfMap[cf.when]) customFields.push({ id: cfMap[cf.when], value: whenStr });
311
+ if (cfMap[cf.amount]) customFields.push({ id: cfMap[cf.amount], value: amountStr });
312
+ if (cfMap[cf.address]) customFields.push({ id: cfMap[cf.address], value: booking.rooms.address || '' });
313
+ if (cfMap[cf.calendarLink]) customFields.push({ id: cfMap[cf.calendarLink], value: gcalUrl });
314
+ if (cfMap[cf.manageLink] && manageUrl) customFields.push({ id: cfMap[cf.manageLink], value: manageUrl });
315
+ if (cfMap[cf.reminderWaitHours]) customFields.push({ id: cfMap[cf.reminderWaitHours], value: String(hoursUntilReminder) });
316
+ if (customFields.length > 0) {
317
+ const putRes = await fetch(`${GHL_BASE}/contacts/${contactId}`, {
318
+ method: 'PUT', headers, body: JSON.stringify({ customFields }),
319
+ });
320
+ if (!putRes.ok) console.warn('[bookingEffects] contact customFields update failed', putRes.status, await putRes.text());
321
+ }
322
+ } catch (e) {
323
+ console.warn('[bookingEffects] custom fields step error', e);
324
+ }
325
+
326
+ try {
327
+ const noteBody =
328
+ `Meeting Room Booking\n` +
329
+ `Room: ${roomName}\n` +
330
+ `When: ${whenStr}\n` +
331
+ `Amount: ${amountStr}\n` +
332
+ `Email: ${booking.contact_email}\n` +
333
+ `Phone: ${booking.contact_phone || '—'}\n` +
334
+ `Booking ID: ${booking.id}`;
335
+ const noteRes = await fetch(`${GHL_BASE}/contacts/${contactId}/notes`, {
336
+ method: 'POST', headers, body: JSON.stringify({ body: noteBody }),
337
+ });
338
+ if (!noteRes.ok) console.warn('[bookingEffects] note create failed', noteRes.status, await noteRes.text());
339
+ } catch (e) {
340
+ console.warn('[bookingEffects] note error', e);
341
+ }
342
+
343
+ // Confirmation email — sent directly (no GHL workflow exists for this).
344
+ try {
345
+ const address = booking.rooms.address || operator.name;
346
+ const manageParagraph = manageUrl
347
+ ? `<p>Need to change plans? <a href='${manageUrl}' style='color:#C98A5E'>Manage your booking</a> — free cancellation with credit up to 48 hours before your start time.</p>`
348
+ : '';
349
+ let doorSection = '';
350
+ if (doorAccess?.pin) {
351
+ const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
352
+ ? `<p style='margin:6px 0 0 0;color:#5f6c5d;font-size:13px'>Active ${formatWhen(doorAccess.validFromUtc, doorAccess.validToUtc)}</p>`
353
+ : '';
354
+ doorSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Door access</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${doorAccess.pin}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Your PIN works at the Commons Hub door &mdash; the building's main entrance. The other entrances are badge and mobile-unlock only.</p>${activeLine}</div>`;
355
+ }
356
+ // Guest WiFi code — derived fresh (never stored), gated to the 4 hourly
357
+ // meeting rooms per RESERVATION-SCOPED-GUEST-WIFI-DESIGN.md. A cancelled
358
+ // booking needs no special handling here: ftw-middleware only ever
359
+ // validates against currently live/paid bookings, and this whole email
360
+ // only sends on the paid path anyway.
361
+ let wifiSection = '';
362
+ const wifiSecret = Deno.env.get('RESERVATION_WIFI_CODE_SECRET');
363
+ if (wifiSecret && isReservationWifiRoom(booking.rooms.slug)) {
364
+ const wifiCode = await deriveReservationWifiCode(wifiSecret, booking.id);
365
+ wifiSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Guest WiFi</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${wifiCode}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Guest WiFi code for your visit — valid for your reservation window in ${roomName}.</p></div>`;
366
+ }
367
+ // "About this room" — the room's own usage_instructions, when set. Same
368
+ // bordered-card shape as the door/wifi sections above.
369
+ let instructionsSection = '';
370
+ const usageInstructions = booking.rooms.usage_instructions;
371
+ if (typeof usageInstructions === 'string' && usageInstructions.trim().length > 0) {
372
+ instructionsSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>About this room</h3>${textToHtmlParagraphs(usageInstructions)}</div>`;
373
+ }
374
+ const confirmationHtml = `<div style='font-family:Inter,Arial,sans-serif;max-width:560px;margin:0 auto;color:#22263B'><h2 style='color:#22263B'>Your booking is confirmed</h2><p>Hi ${firstName},</p><p>Thanks for booking with ${operator.name}. Here are your details:</p><table style='border-collapse:collapse;width:100%'><tr><td style='padding:6px 0;color:#5f6c5d;width:110px'>Room</td><td style='padding:6px 0'><strong>${roomName}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>When</td><td style='padding:6px 0'><strong>${whenStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Amount</td><td style='padding:6px 0'><strong>${amountStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Address</td><td style='padding:6px 0'>${address}</td></tr></table><p style='margin:20px 0'><a href='${gcalUrl}' style='background:#748272;color:#F6F6F6;padding:10px 18px;text-decoration:none;border-radius:6px;display:inline-block'>Add to Google Calendar</a></p>${doorSection}${wifiSection}${instructionsSection}${manageParagraph}<p style='color:#5f6c5d;font-size:13px;margin-top:28px'>${operator.name} · ${address}</p></div>`;
375
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
376
+ method: 'POST', headers,
377
+ body: JSON.stringify({
378
+ type: 'Email',
379
+ contactId,
380
+ subject: `Your booking is confirmed — ${roomName}, ${whenStr.split(' · ')[0]}`,
381
+ html: confirmationHtml,
382
+ }),
383
+ });
384
+ if (!emailRes.ok) console.warn('[bookingEffects] confirmation email failed', emailRes.status, await emailRes.text());
385
+ } catch (e) {
386
+ console.warn('[bookingEffects] confirmation email error', e);
387
+ }
388
+ }