@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.
Files changed (175) hide show
  1. package/package.json +169 -15
  2. package/src/adminBookingCredit.test.ts +451 -0
  3. package/src/adminBookingCredit.ts +239 -0
  4. package/src/agreementCheckout.ts +250 -0
  5. package/src/agreementPortalEmail.ts +128 -0
  6. package/src/availability.test.ts +25 -0
  7. package/src/availability.ts +201 -0
  8. package/src/billingPortalLinkEmail.ts +117 -0
  9. package/src/bookingAgreementEmail.ts +149 -0
  10. package/src/bookingEffects.ts +388 -0
  11. package/src/bookingHoldReclaim.ts +94 -0
  12. package/src/busClient.ts +268 -0
  13. package/src/busSignature.ts +71 -0
  14. package/src/checkoutCoupon.test.ts +675 -0
  15. package/src/checkoutCoupon.ts +455 -0
  16. package/src/checkoutSessionParams.ts +56 -0
  17. package/src/commonsContract.ts +175 -0
  18. package/src/commonsDeposit.ts +298 -0
  19. package/src/commonsDepositWebhook.ts +237 -0
  20. package/src/conductorAdmin.ts +141 -0
  21. package/src/dayPassConfirmation.ts +230 -0
  22. package/src/dunningEmails.test.ts +263 -0
  23. package/src/dunningEmails.ts +203 -0
  24. package/src/email-templates/brand.ts +93 -0
  25. package/src/email-templates/email-change.tsx +92 -0
  26. package/src/email-templates/invite.tsx +79 -0
  27. package/src/email-templates/magic-link.tsx +59 -0
  28. package/src/email-templates/reauthentication.tsx +60 -0
  29. package/src/email-templates/recovery.tsx +59 -0
  30. package/src/email-templates/signup.tsx +67 -0
  31. package/src/functions/admin-cancel-membership.ts +311 -0
  32. package/src/functions/admin-change-membership-plan.ts +312 -0
  33. package/src/functions/admin-charge-guest-print.ts +229 -0
  34. package/src/functions/admin-correct-booking.ts +333 -0
  35. package/src/functions/admin-create-booking.ts +460 -0
  36. package/src/functions/admin-create-commons-event.ts +244 -0
  37. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  38. package/src/functions/admin-door-write.ts +272 -0
  39. package/src/functions/admin-issue-day-pass.ts +231 -0
  40. package/src/functions/admin-mark-booking-paid.ts +203 -0
  41. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  42. package/src/functions/admin-mint-portal-link.ts +62 -0
  43. package/src/functions/admin-photo-upload.ts +128 -0
  44. package/src/functions/admin-remove-team-member.ts +150 -0
  45. package/src/functions/admin-request-trial.ts +366 -0
  46. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  47. package/src/functions/admin-reset-mfa.ts +138 -0
  48. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  49. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  50. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  51. package/src/functions/admin-revoke-agreement.ts +467 -0
  52. package/src/functions/admin-send-commons-agreement.ts +214 -0
  53. package/src/functions/admin-set-credit-amount.ts +123 -0
  54. package/src/functions/admin-skip-commons-contract.ts +165 -0
  55. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  56. package/src/functions/admin-wall-photo-write.ts +141 -0
  57. package/src/functions/auth-email-hook.ts +259 -0
  58. package/src/functions/boldsign-sender-identity.ts +114 -0
  59. package/src/functions/booking-availability.ts +419 -0
  60. package/src/functions/booking-member-preview.ts +136 -0
  61. package/src/functions/booking-status.ts +149 -0
  62. package/src/functions/conductor.ts +505 -0
  63. package/src/functions/create-agreement.ts +537 -0
  64. package/src/functions/create-booking.ts +648 -0
  65. package/src/functions/create-day-pass-checkout.ts +218 -0
  66. package/src/functions/create-portal-session.ts +142 -0
  67. package/src/functions/create-subscription-checkout.test.ts +222 -0
  68. package/src/functions/create-subscription-checkout.ts +440 -0
  69. package/src/functions/day-pass-status.ts +89 -0
  70. package/src/functions/dayStatus.ts +71 -0
  71. package/src/functions/diag-webpush-test.ts +45 -0
  72. package/src/functions/event-access-admin.ts +277 -0
  73. package/src/functions/event-access-store.ts +309 -0
  74. package/src/functions/ezeep-print-webhook.ts +213 -0
  75. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  76. package/src/functions/fetch-avatar-original.ts +457 -0
  77. package/src/functions/get-provider-sign-link.ts +155 -0
  78. package/src/functions/get-signing-link.ts +211 -0
  79. package/src/functions/guest-print-setup-confirm.ts +128 -0
  80. package/src/functions/guest-print-submit.ts +149 -0
  81. package/src/functions/luma-webhook.ts +165 -0
  82. package/src/functions/manage-booking.ts +472 -0
  83. package/src/functions/mcp.ts +67 -0
  84. package/src/functions/member-door-action.test.ts +1248 -0
  85. package/src/functions/member-door-action.ts +863 -0
  86. package/src/functions/member-unifi-mapping.test.ts +516 -0
  87. package/src/functions/member-unifi-mapping.ts +206 -0
  88. package/src/functions/membership-door-sync.ts +956 -0
  89. package/src/functions/migration-collision-alert.copy.ts +232 -0
  90. package/src/functions/migration-collision-alert.test.ts +349 -0
  91. package/src/functions/migration-collision-alert.ts +232 -0
  92. package/src/functions/office-assignment-end.ts +146 -0
  93. package/src/functions/portal-booking-access.ts +95 -0
  94. package/src/functions/portal-list-invoices.ts +99 -0
  95. package/src/functions/portal-request-login.ts +192 -0
  96. package/src/functions/portal-resend-invite.ts +248 -0
  97. package/src/functions/portal-submit-event.ts +168 -0
  98. package/src/functions/print-billing-recover.ts +97 -0
  99. package/src/functions/print-billing-run.ts +183 -0
  100. package/src/functions/public-facts.ts +168 -0
  101. package/src/functions/push-send.ts +348 -0
  102. package/src/functions/push-test.ts +234 -0
  103. package/src/functions/request-portal-link.ts +211 -0
  104. package/src/functions/reschedule-booking.ts +649 -0
  105. package/src/functions/review-ratings.ts +113 -0
  106. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  107. package/src/functions/space-availability-range.ts +142 -0
  108. package/src/functions/stripe-db-reconcile.ts +319 -0
  109. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  110. package/src/functions/stripe-webhook.ts +2595 -0
  111. package/src/functions/sync-gcal-blackouts.ts +298 -0
  112. package/src/functions/timetable-event-register.ts +162 -0
  113. package/src/functions/timetable-event-status.ts +90 -0
  114. package/src/functions/timetable-spaces.ts +219 -0
  115. package/src/functions/touch-pass-reconciler.ts +689 -0
  116. package/src/functions/touch-pass-signup.ts +478 -0
  117. package/src/functions/upload-booking-display-image.ts +179 -0
  118. package/src/functions/virtual-onboarding-purge.ts +134 -0
  119. package/src/functions/virtual-onboarding-submit.ts +315 -0
  120. package/src/functions/voice-booking.ts +453 -0
  121. package/src/functions/voice-day-pass.ts +346 -0
  122. package/src/functions/voice-inquiry.test.ts +301 -0
  123. package/src/functions/voice-inquiry.ts +198 -0
  124. package/src/functions/voice-membership-signup.ts +355 -0
  125. package/src/functions/voice-tour-availability.ts +204 -0
  126. package/src/functions/voice-tour-booking.ts +429 -0
  127. package/src/gcalSync.ts +142 -0
  128. package/src/ghlEventInquiry.ts +143 -0
  129. package/src/ghlNote.ts +34 -0
  130. package/src/ghlTask.ts +48 -0
  131. package/src/ghlVoiceInquiry.ts +90 -0
  132. package/src/guestPrintCapture.test.ts +722 -0
  133. package/src/guestPrintCapture.ts +538 -0
  134. package/src/lumaGhl.ts +195 -0
  135. package/src/mailArrivalEmail.ts +121 -0
  136. package/src/manageToken.ts +363 -0
  137. package/src/membership.ts +109 -0
  138. package/src/membershipBusClient.ts +537 -0
  139. package/src/membershipWelcome.ts +683 -0
  140. package/src/migrationCheckout.ts +366 -0
  141. package/src/money.ts +36 -0
  142. package/src/ops.ts +97 -0
  143. package/src/pacificDate.ts +88 -0
  144. package/src/paymentLinkEmail.ts +123 -0
  145. package/src/policyAcknowledgment.test.ts +50 -0
  146. package/src/policyAcknowledgment.ts +96 -0
  147. package/src/portalSession.ts +46 -0
  148. package/src/pricing.test.ts +660 -0
  149. package/src/pricing.ts +1025 -0
  150. package/src/printBilling.test.ts +750 -0
  151. package/src/printBilling.ts +891 -0
  152. package/src/printBillingAdapters.ts +169 -0
  153. package/src/printCorrections.test.ts +348 -0
  154. package/src/printCorrections.ts +496 -0
  155. package/src/rateLimit.ts +82 -0
  156. package/src/referralCredits.test.ts +31 -0
  157. package/src/referralCredits.ts +34 -0
  158. package/src/referralGrant.ts +321 -0
  159. package/src/rescheduleCredit.test.ts +521 -0
  160. package/src/rescheduleCredit.ts +337 -0
  161. package/src/reservationWifiCode.test.ts +69 -0
  162. package/src/reservationWifiCode.ts +81 -0
  163. package/src/retellCallAnalyzed.test.ts +167 -0
  164. package/src/retellCallAnalyzed.ts +113 -0
  165. package/src/retellSignature.test.ts +137 -0
  166. package/src/retellSignature.ts +82 -0
  167. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  168. package/src/signedUnpaidReminderEmail.ts +132 -0
  169. package/src/slackAlert.ts +38 -0
  170. package/src/stripeCoworkingPortal.ts +91 -0
  171. package/src/supabaseTestFakes.ts +131 -0
  172. package/src/supportTicketEmail.ts +119 -0
  173. package/src/tier1Agreement.ts +125 -0
  174. package/src/unifiAccessPolicies.ts +228 -0
  175. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,201 @@
1
+ // Shared availability primitives for room booking surfaces.
2
+ //
3
+ // Extracted verbatim (behaviour-identical) from booking-availability so that
4
+ // every consumer answers "is this room busy?" the same way. Do NOT fork these
5
+ // helpers — add a caller instead.
6
+
7
+ // Structural client type: the concrete SupabaseClient generics differ between
8
+ // call sites, so we only describe the query surface these helpers use.
9
+ interface QueryResult {
10
+ data: unknown[] | null;
11
+ error: { message: string } | null;
12
+ }
13
+ interface FilterBuilder extends PromiseLike<QueryResult> {
14
+ eq(column: string, value: unknown): FilterBuilder;
15
+ in(column: string, values: unknown[]): FilterBuilder;
16
+ or(filters: string): FilterBuilder;
17
+ filter(column: string, operator: string, value: unknown): FilterBuilder;
18
+ }
19
+ interface QueryClient {
20
+ from(table: string): { select(columns: string): FilterBuilder };
21
+ }
22
+ /**
23
+ * Minimal accepted shape. Kept deliberately loose: the concrete
24
+ * SupabaseClient generics vary per call site and matching the full builder
25
+ * type structurally is prohibitively expensive for the type checker.
26
+ */
27
+ export interface SupabaseLike {
28
+ from(table: string): unknown;
29
+ }
30
+
31
+ /** LA offset in hours (integer: -7 DST, -8 STD) for a given UTC instant. */
32
+ export function laOffsetHours(atUtc: Date): number {
33
+ const parts = new Intl.DateTimeFormat('en-US', {
34
+ timeZone: 'America/Los_Angeles',
35
+ timeZoneName: 'longOffset',
36
+ }).formatToParts(atUtc);
37
+ const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
38
+ const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
39
+ if (!m) return -8;
40
+ const sign = m[1] === '+' ? 1 : -1;
41
+ return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
42
+ }
43
+
44
+ /** Convert an LA wall-clock (YYYY-MM-DD + HH:MM) to a real UTC Date. */
45
+ export function laWallToUtc(dateStr: string, hh: number, mm: number): Date {
46
+ const [y, mo, d] = dateStr.split('-').map(Number);
47
+ // Use noon-UTC that day to pick a stable offset (no DST edge case at noon).
48
+ const guess = new Date(Date.UTC(y, mo - 1, d, 12));
49
+ const off = laOffsetHours(guess); // negative integer
50
+ return new Date(Date.UTC(y, mo - 1, d, hh - Math.trunc(off), mm));
51
+ }
52
+
53
+ export function laWeekday(dateStr: string): number {
54
+ const [y, mo, d] = dateStr.split('-').map(Number);
55
+ const guess = new Date(Date.UTC(y, mo - 1, d, 12));
56
+ const s = new Intl.DateTimeFormat('en-US', {
57
+ timeZone: 'America/Los_Angeles',
58
+ weekday: 'short',
59
+ }).format(guess);
60
+ return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(s);
61
+ }
62
+
63
+ /**
64
+ * The America/Los_Angeles calendar date (YYYY-MM-DD) for a UTC instant.
65
+ * Added so callers never hand-roll a second timezone conversion.
66
+ */
67
+ export function laDateStr(atUtc: Date): string {
68
+ const parts = new Intl.DateTimeFormat('en-CA', {
69
+ timeZone: 'America/Los_Angeles',
70
+ year: 'numeric',
71
+ month: '2-digit',
72
+ day: '2-digit',
73
+ }).formatToParts(atUtc);
74
+ const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';
75
+ return `${get('year')}-${get('month')}-${get('day')}`;
76
+ }
77
+
78
+ /**
79
+ * Normalise a Postgres timestamptz text value into something V8 parses
80
+ * unambiguously: space separator -> "T", bare "+00"/"-00" -> "+00:00"/"-00:00".
81
+ * Defensive only — current data already parses.
82
+ */
83
+ function normalizeTimestamp(s: string): string {
84
+ return s
85
+ .trim()
86
+ .replace(' ', 'T')
87
+ .replace(/([+-]\d{2})$/, '$1:00');
88
+ }
89
+
90
+ /** Parse a Postgres tstzrange text literal `[start,end)` into epoch ms bounds. */
91
+ export function parsePgRange(r: string): [number, number] | null {
92
+ if (typeof r !== 'string' || r.length < 2) return null;
93
+ const inner = r.slice(1, -1);
94
+ const parts = inner.split(',').map((s) => s.replace(/^"|"$/g, ''));
95
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
96
+ const a = new Date(normalizeTimestamp(parts[0])).getTime();
97
+ const b = new Date(normalizeTimestamp(parts[1])).getTime();
98
+ if (Number.isNaN(a) || Number.isNaN(b)) return null;
99
+ return [a, b];
100
+ }
101
+
102
+ /**
103
+ * business_hours row for a room + weekday. A room-specific row wins over the
104
+ * global (room_id IS NULL) row. Returns null/undefined when closed.
105
+ */
106
+ export interface BusinessHoursRow {
107
+ room_id: string | null;
108
+ open_time: string;
109
+ close_time: string;
110
+ }
111
+
112
+ export async function getBusinessHoursRow(
113
+ supabase: SupabaseLike,
114
+ roomId: string,
115
+ weekday: number,
116
+ ): Promise<BusinessHoursRow | undefined> {
117
+ const db = supabase as unknown as QueryClient;
118
+ const { data, error } = await db
119
+ .from('business_hours')
120
+ .select('*')
121
+ .eq('weekday', weekday)
122
+ .or(`room_id.eq.${roomId},room_id.is.null`);
123
+ if (error) throw error;
124
+ const rows = (data ?? []) as BusinessHoursRow[];
125
+ // Room-specific row wins over the global (room_id IS NULL) row.
126
+ return rows.sort((a, b) => (a.room_id ? -1 : 1))[0];
127
+ }
128
+
129
+ /**
130
+ * Busy intervals (epoch ms pairs) for a room overlapping `rangeLiteral`:
131
+ * pending/paid bookings (pending only while its hold is still valid) plus
132
+ * blackouts.
133
+ */
134
+ export async function getBusyRanges(
135
+ supabase: SupabaseLike,
136
+ roomId: string,
137
+ rangeLiteral: string,
138
+ ): Promise<[number, number][]> {
139
+ return (await getBusyRangesDetailed(supabase, roomId, rangeLiteral)).busy;
140
+ }
141
+
142
+ /**
143
+ * Same query and same busy computation as `getBusyRanges`, but also reports
144
+ * how many rows had a `during` value that could not be parsed.
145
+ *
146
+ * `getBusyRanges` silently skips those rows (a skipped row reads as *free*).
147
+ * That is fine for the booking flow, where the DB exclusion constraint is the
148
+ * real gate, but a read-only "what's open right now?" surface must fail the
149
+ * other way — an unparseable row has to be treated as busy. Callers that need
150
+ * that safety use this function; the historical behaviour of `getBusyRanges`
151
+ * is unchanged (it simply delegates here and drops the count).
152
+ */
153
+ export async function getBusyRangesDetailed(
154
+ supabase: SupabaseLike,
155
+ roomId: string,
156
+ rangeLiteral: string,
157
+ ): Promise<{ busy: [number, number][]; unparsed: number }> {
158
+ const db = supabase as unknown as QueryClient;
159
+ const [bRes, blRes] = await Promise.all([
160
+ db
161
+ .from('bookings')
162
+ .select('during,status,hold_expires_at')
163
+ .eq('room_id', roomId)
164
+ .in('status', ['pending', 'paid'])
165
+ .filter('during', 'ov', rangeLiteral),
166
+ db
167
+ .from('blackouts')
168
+ .select('during')
169
+ .eq('room_id', roomId)
170
+ .filter('during', 'ov', rangeLiteral),
171
+ ]);
172
+ if (bRes.error) throw bRes.error;
173
+ if (blRes.error) throw blRes.error;
174
+
175
+ const bookingRows = (bRes.data ?? []) as Array<{
176
+ during: string;
177
+ status: string;
178
+ hold_expires_at: string | null;
179
+ }>;
180
+ const blackoutRows = (blRes.data ?? []) as Array<{ during: string }>;
181
+
182
+ const busy: [number, number][] = [];
183
+ let unparsed = 0;
184
+ const nowMs = Date.now();
185
+ for (const row of bookingRows) {
186
+ // Paid bookings always block; pending only blocks while the hold is still valid.
187
+ if (row.status === 'pending') {
188
+ const holdMs = row.hold_expires_at ? new Date(row.hold_expires_at).getTime() : null;
189
+ if (holdMs !== null && holdMs < nowMs) continue;
190
+ }
191
+ const p = parsePgRange(row.during);
192
+ if (p) busy.push(p);
193
+ else unparsed += 1;
194
+ }
195
+ for (const row of blackoutRows) {
196
+ const p = parsePgRange(row.during);
197
+ if (p) busy.push(p);
198
+ else unparsed += 1;
199
+ }
200
+ return { busy, unparsed };
201
+ }
@@ -0,0 +1,117 @@
1
+ // Staff-triggered "update your billing" email, sent when an admin mints a
2
+ // Stripe billing-portal link for a member from the admin console.
3
+ //
4
+ // Mirrors the GHL request shape, headers, escaping and error classification
5
+ // of sendPaymentLinkEmail in ./paymentLinkEmail.ts -- same transport, same
6
+ // safety properties, different copy (this is for an EXISTING member updating
7
+ // a card on file, not a new signup completing checkout).
8
+
9
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
10
+ import { logOps } from './ops.ts';
11
+
12
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
13
+
14
+ export type BillingPortalLinkEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
15
+
16
+ function esc(v: unknown): string {
17
+ return String(v ?? '')
18
+ .replace(/&/g, '&amp;')
19
+ .replace(/</g, '&lt;')
20
+ .replace(/>/g, '&gt;')
21
+ .replace(/"/g, '&quot;')
22
+ .replace(/'/g, '&#39;');
23
+ }
24
+
25
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
26
+ const name = e instanceof Error ? e.name : '';
27
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
28
+ const msg = e instanceof Error ? e.message : String(e);
29
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
30
+ if (m) {
31
+ const code = Number(m[1]);
32
+ if (code === 429 || code >= 500) return 'failed_retryable';
33
+ }
34
+ return 'failed_permanent';
35
+ }
36
+
37
+ export async function sendBillingPortalLinkEmail(
38
+ supabase: SupabaseLike,
39
+ { email, name, portalUrl }: {
40
+ email: string;
41
+ name?: string | null;
42
+ portalUrl: string;
43
+ },
44
+ operator: { name: string; shortName: string; domain: string; supportEmail: string },
45
+ ): Promise<BillingPortalLinkEmailResult> {
46
+ try {
47
+ const apiKey = Deno.env.get('GHL_API_KEY');
48
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
49
+ if (!apiKey || !locationId) {
50
+ await logOps(supabase, 'billing_portal_link_email_skipped',
51
+ { email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
52
+ return 'skipped';
53
+ }
54
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
55
+ const headers = {
56
+ Authorization: `Bearer ${apiKey}`,
57
+ Version: '2021-07-28',
58
+ 'Content-Type': 'application/json',
59
+ Accept: 'application/json',
60
+ };
61
+
62
+ const trimmed = (name || '').trim();
63
+ const parts = trimmed.split(/\s+/).filter(Boolean);
64
+ const greetingName = parts[0] || 'there';
65
+ const crmName: { firstName?: string; lastName?: string } = {};
66
+ if (parts[0]) crmName.firstName = parts[0];
67
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
68
+
69
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
70
+ method: 'POST', headers,
71
+ signal: AbortSignal.timeout(8000),
72
+ body: JSON.stringify({
73
+ locationId, ...crmName, email,
74
+ source: `${operator.shortName} Admin — Billing Update`,
75
+ tags: ['Billing Update', operator.domain],
76
+ }),
77
+ });
78
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
79
+ const upJson = await upRes.json();
80
+ const contactId = upJson.contact?.id || upJson.id || null;
81
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
82
+
83
+ const p = (t: string) =>
84
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
85
+
86
+ const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
87
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Update your ${operator.shortName} billing details</h2>
88
+ ${p(`Hi ${esc(greetingName)},`)}
89
+ ${p(`Our team wanted to make it easy for you to update the payment method on your ${operator.name} membership. Use the secure link below:`)}
90
+ ${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Update payment method →</a>`)}
91
+ ${p("This link is unique to your account and takes you straight to our payment processor, Stripe, where you can update your card, view invoices, and manage your subscription. Please don't forward it.")}
92
+ ${p(`Questions? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
93
+ ${p(`Thanks,<br />The ${operator.name} team`)}
94
+ </td></tr></table></td></tr></table></div>`;
95
+
96
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
97
+ method: 'POST', headers,
98
+ signal: AbortSignal.timeout(8000),
99
+ body: JSON.stringify({
100
+ type: 'Email',
101
+ contactId,
102
+ subject: `Update your ${operator.shortName} billing details`,
103
+ html,
104
+ }),
105
+ });
106
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
107
+
108
+ await logOps(supabase, 'billing_portal_link_email_sent', { email }, { severity: 'info' }).catch(() => {});
109
+ return 'sent';
110
+ } catch (e) {
111
+ const classification = classifyError(e);
112
+ await logOps(supabase, 'billing_portal_link_email_failed',
113
+ { email, message: e instanceof Error ? e.message : String(e) },
114
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
115
+ return classification;
116
+ }
117
+ }
@@ -0,0 +1,149 @@
1
+ // Customer emails for the Tier 2 (day-rate) booking agreement flow.
2
+ //
3
+ // Same GHL transport, headers, timeouts and error classification as
4
+ // _shared/paymentLinkEmail.ts — do not introduce a second email channel.
5
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
6
+ import { logOps } from './ops.ts';
7
+
8
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
9
+
10
+ export type BookingAgreementEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
11
+
12
+ type Operator = { name: string; shortName: string; supportEmail: string };
13
+
14
+ function esc(v: unknown): string {
15
+ return String(v ?? '')
16
+ .replace(/&/g, '&amp;')
17
+ .replace(/</g, '&lt;')
18
+ .replace(/>/g, '&gt;')
19
+ .replace(/"/g, '&quot;')
20
+ .replace(/'/g, '&#39;');
21
+ }
22
+
23
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
24
+ const name = e instanceof Error ? e.name : '';
25
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
26
+ const msg = e instanceof Error ? e.message : String(e);
27
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
28
+ if (m) {
29
+ const code = Number(m[1]);
30
+ if (code === 429 || code >= 500) return 'failed_retryable';
31
+ }
32
+ return 'failed_permanent';
33
+ }
34
+
35
+ async function sendViaGhl(
36
+ supabase: SupabaseLike,
37
+ opts: { email: string; name?: string | null; subject: string; body: (greeting: string) => string; opsPrefix: string; operator: Operator },
38
+ ): Promise<BookingAgreementEmailResult> {
39
+ try {
40
+ const apiKey = Deno.env.get('GHL_API_KEY');
41
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
42
+ if (!apiKey || !locationId) {
43
+ await logOps(supabase, `${opts.opsPrefix}_skipped`,
44
+ { email: opts.email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
45
+ return 'skipped';
46
+ }
47
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
48
+ const headers = {
49
+ Authorization: `Bearer ${apiKey}`,
50
+ Version: '2021-07-28',
51
+ 'Content-Type': 'application/json',
52
+ Accept: 'application/json',
53
+ };
54
+
55
+ const trimmed = (opts.name || '').trim();
56
+ const parts = trimmed.split(/\s+/).filter(Boolean);
57
+ const greetingName = parts[0] || 'there';
58
+ const crmName: { firstName?: string; lastName?: string } = {};
59
+ if (parts[0]) crmName.firstName = parts[0];
60
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
61
+
62
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
63
+ method: 'POST', headers,
64
+ signal: AbortSignal.timeout(8000),
65
+ body: JSON.stringify({
66
+ locationId, ...crmName, email: opts.email,
67
+ source: `${opts.operator.shortName} Website — Room Booking`,
68
+ }),
69
+ });
70
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
71
+ const upJson = await upRes.json();
72
+ const contactId = upJson.contact?.id || upJson.id || null;
73
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
74
+
75
+ const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
76
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
77
+ ${opts.body(esc(greetingName))}
78
+ </td></tr></table></td></tr></table></div>`;
79
+
80
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
81
+ method: 'POST', headers,
82
+ signal: AbortSignal.timeout(8000),
83
+ body: JSON.stringify({ type: 'Email', contactId, subject: opts.subject, html }),
84
+ });
85
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
86
+
87
+ await logOps(supabase, `${opts.opsPrefix}_sent`, { email: opts.email }, { severity: 'info' }).catch(() => {});
88
+ return 'sent';
89
+ } catch (e) {
90
+ const classification = classifyError(e);
91
+ await logOps(supabase, `${opts.opsPrefix}_failed`,
92
+ { email: opts.email, message: e instanceof Error ? e.message : String(e) },
93
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
94
+ return classification;
95
+ }
96
+ }
97
+
98
+ const p = (t: string) =>
99
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
100
+
101
+ /** Agreement signed — the customer may now pay for the held slot. */
102
+ export function sendBookingAgreementSignedEmail(
103
+ supabase: SupabaseLike,
104
+ { email, name, roomName, checkoutUrl }: {
105
+ email: string; name?: string | null; roomName?: string | null; checkoutUrl?: string | null;
106
+ },
107
+ operator: Operator,
108
+ ): Promise<BookingAgreementEmailResult> {
109
+ const room = (roomName || '').trim();
110
+ const subject = `Your ${operator.shortName} room agreement is signed — complete payment`;
111
+ return sendViaGhl(supabase, {
112
+ email, name, subject, opsPrefix: 'booking_agreement_signed_email', operator,
113
+ body: (greeting) => [
114
+ p(`Hi ${greeting},`),
115
+ p(`Thanks for signing your room use agreement${room ? ` for ${esc(room)}` : ''} — the last step is payment.`),
116
+ checkoutUrl
117
+ ? p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Complete your payment →</a>`)
118
+ : p(`Reply to this email and we'll send you a payment link right away.`),
119
+ p(`Your booking isn't confirmed until payment is complete. This link is unique to your booking, so please don't forward it.`),
120
+ p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
121
+ p(`— The ${operator.name} team`),
122
+ ].join(''),
123
+ });
124
+ }
125
+
126
+ /** Agreement declined/expired — the held slot was released. */
127
+ export function sendBookingAgreementNotCompletedEmail(
128
+ supabase: SupabaseLike,
129
+ { email, name, roomName, reason }: {
130
+ email: string; name?: string | null; roomName?: string | null; reason: 'declined' | 'expired';
131
+ },
132
+ operator: Operator,
133
+ ): Promise<BookingAgreementEmailResult> {
134
+ const room = (roomName || '').trim();
135
+ const subject = `Your ${operator.shortName} booking wasn't completed`;
136
+ const why = reason === 'declined'
137
+ ? 'the room use agreement was declined'
138
+ : 'the room use agreement wasn\'t signed in time';
139
+ return sendViaGhl(supabase, {
140
+ email, name, subject, opsPrefix: 'booking_agreement_not_completed_email', operator,
141
+ body: (greeting) => [
142
+ p(`Hi ${greeting},`),
143
+ p(`We released your hold${room ? ` on ${esc(room)}` : ''} because ${why}. You haven't been charged.`),
144
+ p(`If you'd still like the space, just book again and we'll send a fresh agreement.`),
145
+ p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
146
+ p(`— The ${operator.name} team`),
147
+ ].join(''),
148
+ });
149
+ }