@simplelayer/graniteer-core 0.0.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.
- package/package.json +169 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +312 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-request-trial.ts +366 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/booking-status.ts +149 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/fetch-avatar-original.ts +457 -0
- package/src/functions/get-provider-sign-link.ts +155 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/push-send.ts +348 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/stripe-db-reconcile.ts +319 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/touch-pass-signup.ts +478 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-booking.ts +453 -0
- package/src/functions/voice-day-pass.ts +346 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membership.ts +109 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +88 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/slackAlert.ts +38 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/supportTicketEmail.ts +119 -0
- package/src/tier1Agreement.ts +125 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -0,0 +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, '&')
|
|
117
|
+
.replace(/</g, '<')
|
|
118
|
+
.replace(/>/g, '>')
|
|
119
|
+
.replace(/"/g, '"')
|
|
120
|
+
.replace(/'/g, ''');
|
|
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 — 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
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { logOps } from './ops.ts';
|
|
3
|
+
|
|
4
|
+
// Loose generics, matching _shared/ops.ts. A real createClient(url, key, opts)
|
|
5
|
+
// call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
|
|
6
|
+
// assignable to the un-inferred ReturnType<typeof createClient> default — that
|
|
7
|
+
// mismatch is what made every call site here fail deno check.
|
|
8
|
+
// deno-lint-ignore no-explicit-any
|
|
9
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
10
|
+
|
|
11
|
+
const HOLD_EXTENSION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Reclaims stale ('pending', hold expired) bookings overlapping `rangeLiteral`
|
|
15
|
+
* in `room_id` — same candidate set the inline reclaim block used to select —
|
|
16
|
+
* EXCEPT a booking backed by a completed Tier 3 (Commons) booking_agreements
|
|
17
|
+
* row is never expired here: signing that agreement is a real commitment, and
|
|
18
|
+
* the lazy 15-minute-hold-style reclaim was never meant to unwind it. Instead
|
|
19
|
+
* its hold is pushed out 7 days and an ops event is raised so staff can follow
|
|
20
|
+
* up (this should be rare — Commons deposits move the booking to
|
|
21
|
+
* 'deposit_paid' well before the hold would ever go stale).
|
|
22
|
+
*
|
|
23
|
+
* Every other candidate is expired exactly as before.
|
|
24
|
+
*/
|
|
25
|
+
export async function reclaimStaleHoldsExceptCompletedTier3(
|
|
26
|
+
supabase: SupabaseLike,
|
|
27
|
+
room_id: string,
|
|
28
|
+
rangeLiteral: string,
|
|
29
|
+
): Promise<void> {
|
|
30
|
+
const { data: candidates, error: selErr } = await supabase
|
|
31
|
+
.from('bookings')
|
|
32
|
+
.select('id,hold_expires_at')
|
|
33
|
+
.eq('room_id', room_id)
|
|
34
|
+
.eq('status', 'pending')
|
|
35
|
+
.lt('hold_expires_at', new Date().toISOString())
|
|
36
|
+
.filter('during', 'ov', rangeLiteral);
|
|
37
|
+
if (selErr) {
|
|
38
|
+
await logOps(supabase, 'booking_hold_reclaim_select_failed',
|
|
39
|
+
{ room_id, range: rangeLiteral, detail: selErr.message }, { severity: 'error' });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (!candidates || candidates.length === 0) return;
|
|
43
|
+
|
|
44
|
+
for (const candidate of candidates as { id: string; hold_expires_at: string | null }[]) {
|
|
45
|
+
try {
|
|
46
|
+
const { data: agreement, error: agErr } = await supabase
|
|
47
|
+
.from('booking_agreements')
|
|
48
|
+
.select('status')
|
|
49
|
+
.eq('booking_id', candidate.id)
|
|
50
|
+
.eq('tier', 3)
|
|
51
|
+
.order('created_at', { ascending: false })
|
|
52
|
+
.limit(1)
|
|
53
|
+
.maybeSingle();
|
|
54
|
+
if (agErr) {
|
|
55
|
+
await logOps(supabase, 'booking_hold_reclaim_agreement_lookup_failed',
|
|
56
|
+
{ room_id, booking_id: candidate.id, detail: agErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (agreement && (agreement as { status: string }).status === 'completed') {
|
|
61
|
+
const oldHoldExpiresAt = candidate.hold_expires_at;
|
|
62
|
+
const newHoldExpiresAt = new Date(Date.now() + HOLD_EXTENSION_MS).toISOString();
|
|
63
|
+
const { error: extendErr } = await supabase
|
|
64
|
+
.from('bookings')
|
|
65
|
+
.update({ hold_expires_at: newHoldExpiresAt })
|
|
66
|
+
.eq('id', candidate.id);
|
|
67
|
+
if (extendErr) {
|
|
68
|
+
await logOps(supabase, 'booking_hold_reclaim_extend_failed',
|
|
69
|
+
{ room_id, booking_id: candidate.id, detail: extendErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
await logOps(supabase, 'commons_completed_hold_would_have_expired', {
|
|
73
|
+
room_id,
|
|
74
|
+
booking_id: candidate.id,
|
|
75
|
+
old_hold_expires_at: oldHoldExpiresAt,
|
|
76
|
+
new_hold_expires_at: newHoldExpiresAt,
|
|
77
|
+
}, { severity: 'error', bookingId: candidate.id });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const { error: expireErr } = await supabase
|
|
82
|
+
.from('bookings')
|
|
83
|
+
.update({ status: 'expired' })
|
|
84
|
+
.eq('id', candidate.id);
|
|
85
|
+
if (expireErr) {
|
|
86
|
+
await logOps(supabase, 'booking_hold_reclaim_expire_failed',
|
|
87
|
+
{ room_id, booking_id: candidate.id, detail: expireErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
88
|
+
}
|
|
89
|
+
} catch (e) {
|
|
90
|
+
await logOps(supabase, 'booking_hold_reclaim_row_error',
|
|
91
|
+
{ room_id, booking_id: candidate.id, detail: String(e) }, { severity: 'error', bookingId: candidate.id });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|