@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,683 @@
1
+ // Membership welcome emails (Virtual Office magic link + door/WiFi onboarding).
2
+ //
3
+ // Phase 8 of the Graniteer/Granite-City split: the generic half of
4
+ // gc-connect's _shared/membershipWelcome.ts. That file now keeps only the
5
+ // tenant-owned pieces -- the UniFi 24/7 group ids, the staff CC list, the
6
+ // magic-link portal redirect, the commons-room slug the postal address is read
7
+ // from, the host-hours fallback copy and the plan slugs -- and passes them in
8
+ // as the `config` parameter on each sender below.
9
+ //
10
+ // Behaviour, rendered HTML, subject lines, GHL endpoints/headers/timeouts,
11
+ // tags, escaping and every logOps kind/severity are unchanged from the
12
+ // pre-split file: the only difference is where the tenant values come from.
13
+
14
+ import { createClient, type SupabaseClient } from 'npm:@supabase/supabase-js@2';
15
+ import { logOps } from './ops.ts';
16
+ import { pacificMidnightUtc } from './pacificDate.ts';
17
+
18
+ // deno-lint-ignore no-explicit-any
19
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
20
+
21
+ export type WelcomeResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
22
+
23
+ /**
24
+ * Plan row resolved ONCE by the caller (maybeSendWelcomes) before the
25
+ * once-only claim is taken. Senders never re-query it: a transient read
26
+ * failure inside a sender used to be indistinguishable from "not my plan"
27
+ * and silently cost the member their welcome forever.
28
+ */
29
+ export type WelcomePlan = {
30
+ slug: string | null;
31
+ name?: string | null;
32
+ price_display?: string | null;
33
+ unit?: string | null;
34
+ unifi_group_ids?: unknown;
35
+ wifi_enabled?: boolean | null;
36
+ active?: boolean | null;
37
+ category?: string | null;
38
+ is_private_office?: boolean | null;
39
+ };
40
+
41
+ /** The operator (venue/business) identity interpolated into the emails. */
42
+ export type WelcomeOperator = {
43
+ /** Full legal/brand name, e.g. "Granite City Workspaces". */
44
+ name: string;
45
+ /** Short brand name used in subject lines and GHL `source`. */
46
+ shortName: string;
47
+ /** Bare apex domain, used as a GHL tag and in the portal login link. */
48
+ domain: string;
49
+ /** The tenant's own customer-facing support inbox. */
50
+ supportEmail: string;
51
+ };
52
+
53
+ /** Only a paying (or trialing) member may ever receive a welcome email. */
54
+ export const WELCOME_OK_STATUSES = new Set(['active', 'trialing']);
55
+
56
+ export async function logWelcomeSkipped(
57
+ supabase: SupabaseLike,
58
+ email: string,
59
+ reason: string,
60
+ extra: Record<string, unknown> = {},
61
+ ) {
62
+ await logOps(supabase, 'membership_welcome_email_skipped',
63
+ { email, reason, ...extra }, { severity: 'warning' }).catch(() => {});
64
+ }
65
+
66
+ /** Escape untrusted values interpolated into outbound HTML. */
67
+ function esc(v: unknown): string {
68
+ return String(v ?? '')
69
+ .replace(/&/g, '&amp;')
70
+ .replace(/</g, '&lt;')
71
+ .replace(/>/g, '&gt;')
72
+ .replace(/"/g, '&quot;')
73
+ .replace(/'/g, '&#39;');
74
+ }
75
+
76
+ /** Classify a caught error as transient (worth another event) or hopeless. */
77
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
78
+ const name = e instanceof Error ? e.name : '';
79
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
80
+ const msg = e instanceof Error ? e.message : String(e);
81
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
82
+ if (m) {
83
+ const code = Number(m[1]);
84
+ if (code === 429 || code >= 500) return 'failed_retryable';
85
+ }
86
+ return 'failed_permanent';
87
+ }
88
+
89
+ export type VirtualOfficeWelcomeConfig = {
90
+ /**
91
+ * Plan slug of the operator's Virtual Office product. Used only for the
92
+ * defence-in-depth guard below -- routing already guarantees it.
93
+ */
94
+ virtualOfficeSlug: string;
95
+ /** Absolute URL the magic link lands on once the member clicks it. */
96
+ portalRedirectUrl: string;
97
+ };
98
+
99
+ export async function sendVirtualOfficeWelcome(
100
+ supabase: SupabaseLike,
101
+ email: string,
102
+ planId: string | null,
103
+ plan: WelcomePlan,
104
+ config: VirtualOfficeWelcomeConfig,
105
+ ): Promise<WelcomeResult> {
106
+ try {
107
+ // Defence in depth: routing already guarantees this, but never send the
108
+ // Virtual Office magic link to a non-VO plan.
109
+ if (plan.slug !== config.virtualOfficeSlug) return 'skipped';
110
+
111
+ const { error: createErr } = await supabase.auth.admin.createUser({
112
+ email,
113
+ email_confirm: true,
114
+ });
115
+ if (createErr) {
116
+ const msg = (createErr.message || '').toLowerCase();
117
+ const alreadyExists =
118
+ msg.includes('already been registered') ||
119
+ msg.includes('already registered') ||
120
+ msg.includes('already exists') ||
121
+ // deno-lint-ignore no-explicit-any
122
+ (createErr as any).code === 'email_exists' ||
123
+ createErr.status === 422;
124
+ if (!alreadyExists) throw createErr;
125
+ }
126
+
127
+ const anon = createClient(
128
+ Deno.env.get('SUPABASE_URL')!,
129
+ Deno.env.get('SUPABASE_ANON_KEY')!,
130
+ { auth: { persistSession: false, autoRefreshToken: false } },
131
+ );
132
+ const { error: otpErr } = await anon.auth.signInWithOtp({
133
+ email,
134
+ options: { emailRedirectTo: config.portalRedirectUrl },
135
+ });
136
+ if (otpErr) throw otpErr;
137
+ await logOps(supabase, 'virtual_office_welcome_email_sent',
138
+ { email, plan_id: planId }, { severity: 'info' }).catch(() => {});
139
+ return 'sent';
140
+ } catch (e) {
141
+ await logOps(supabase, 'virtual_office_welcome_email_failed',
142
+ { email, plan_id: planId, message: e instanceof Error ? e.message : String(e) },
143
+ { severity: 'warning' });
144
+ return classifyError(e);
145
+ }
146
+ }
147
+
148
+ const WEEKDAY_LONG = [
149
+ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
150
+ ];
151
+
152
+ function fmtTime12(t: unknown): string | null {
153
+ const m = typeof t === 'string' ? t.match(/^(\d{2}):(\d{2})/) : null;
154
+ if (!m) return null;
155
+ const h = Number(m[1]);
156
+ const mer = h >= 12 ? 'pm' : 'am';
157
+ const h12 = h % 12 === 0 ? 12 : h % 12;
158
+ return `${h12}:${m[2]}${mer}`;
159
+ }
160
+
161
+ /** Tenant-owned inputs to the host-hours card. */
162
+ export type HostHoursConfig = {
163
+ /**
164
+ * Copy used when app_settings has no usable host_hours_* rows. Tenant copy
165
+ * (it typically names the operator's own site), so it is never built here.
166
+ */
167
+ fallbackLine: string;
168
+ /**
169
+ * Door-group ids whose holders have round-the-clock access. Membership plans
170
+ * carrying any of these get the explicit "24/7" note.
171
+ */
172
+ always247GroupIds: readonly string[];
173
+ };
174
+
175
+ /**
176
+ * "Host hours" card. Staffed hours are read from app_settings (never
177
+ * hardcoded, and deliberately NOT business_hours — that table is the
178
+ * meeting-room booking window, open until 18:00, and is load-bearing booking
179
+ * enforcement). Plans with 24/7 or dedicated/office door groups also get an
180
+ * explicit note that their own access is round-the-clock.
181
+ */
182
+ async function buildHostHoursCard(
183
+ supabase: SupabaseLike,
184
+ groups: unknown[],
185
+ card: (title: string, inner: string) => string,
186
+ p: (t: string) => string,
187
+ hostHours: HostHoursConfig,
188
+ ): Promise<string> {
189
+ let hoursLine = hostHours.fallbackLine;
190
+ try {
191
+ const { data: rows } = await supabase
192
+ .from('app_settings')
193
+ .select('key,value')
194
+ .in('key', ['host_hours_open', 'host_hours_close', 'host_hours_days']);
195
+ const map = new Map<string, string>();
196
+ for (const r of (rows ?? []) as Record<string, unknown>[]) {
197
+ if (typeof r.key === 'string' && typeof r.value === 'string') map.set(r.key, r.value);
198
+ }
199
+ const open = fmtTime12(map.get('host_hours_open'));
200
+ const close = fmtTime12(map.get('host_hours_close'));
201
+ const daysRaw = (map.get('host_hours_days') ?? '').trim();
202
+ const dm = daysRaw.match(/^(\d)\s*-\s*(\d)$/) ?? daysRaw.match(/^(\d)$/);
203
+ if (open && close && dm) {
204
+ const start = Number(dm[1]);
205
+ const end = dm[2] === undefined ? start : Number(dm[2]);
206
+ const valid = Number.isFinite(start) && Number.isFinite(end) &&
207
+ start >= 0 && start <= 6 && end >= 0 && end <= 6 && end >= start;
208
+ if (valid) {
209
+ const range = start === end
210
+ ? WEEKDAY_LONG[start]
211
+ : `${WEEKDAY_LONG[start]}–${WEEKDAY_LONG[end]}`;
212
+ hoursLine = `${range}, ${open}–${close} Pacific.`;
213
+ }
214
+ }
215
+ } catch (_e) { /* fallback line stands */ }
216
+
217
+ const ids = groups.map((g) => String(g));
218
+ const is247 = ids.some((id) => hostHours.always247GroupIds.includes(id));
219
+ const inner = [
220
+ p(esc(hoursLine)),
221
+ p('Host hours are when a member of our team is on site — they are not your access hours.'),
222
+ is247 ? p('<strong>Your plan includes 24/7 access</strong>, so you can come and go any time.') : '',
223
+ ].join('');
224
+ return card('Host hours', inner);
225
+ }
226
+
227
+ export type MembershipWelcomeConfig = {
228
+ operator: WelcomeOperator;
229
+ /**
230
+ * Plan slug of the operator's Virtual Office product. Those members get
231
+ * sendVirtualOfficeWelcome instead and must never receive both.
232
+ */
233
+ virtualOfficeSlug: string;
234
+ /**
235
+ * `rooms.slug` of the room whose `address` column is the operator's postal
236
+ * address. Falls back to operator.name when the row is missing.
237
+ */
238
+ addressRoomSlug: string;
239
+ hostHours: HostHoursConfig;
240
+ };
241
+
242
+ export async function sendMembershipWelcome(
243
+ supabase: SupabaseLike,
244
+ email: string,
245
+ planId: string | null,
246
+ customerName: string | null,
247
+ status: string | null,
248
+ plan: WelcomePlan,
249
+ config: MembershipWelcomeConfig,
250
+ startsOnIso: string | null,
251
+ ): Promise<WelcomeResult> {
252
+ const { operator } = config;
253
+ try {
254
+ // Mirrors MembershipSuccess.tsx's approach exactly. Unlike that page,
255
+ // startsOnIso is already a real instant (an ISO string from
256
+ // pacificMidnightUtc(...).toISOString()), so no noon-UTC anchoring is
257
+ // needed here -- formatting it with an explicit America/Los_Angeles
258
+ // timeZone is sufficient and correct.
259
+ const startsOnLabel = startsOnIso && new Date(startsOnIso).getTime() > Date.now()
260
+ ? new Date(startsOnIso).toLocaleDateString('en-US', {
261
+ timeZone: 'America/Los_Angeles', weekday: 'long', month: 'long', day: 'numeric',
262
+ })
263
+ : null;
264
+
265
+ if (!planId) {
266
+ await logWelcomeSkipped(supabase, email, 'no_plan_id', { status });
267
+ return 'skipped';
268
+ }
269
+ // Non-paying subscriptions (incomplete / past_due / canceled …) reach the
270
+ // INSERT path too. They are never provisioned and must never be welcomed.
271
+ if (!WELCOME_OK_STATUSES.has(String(status))) {
272
+ await logWelcomeSkipped(supabase, email, 'status_not_paid', { plan_id: planId, status });
273
+ return 'skipped';
274
+ }
275
+ // Defence in depth: Virtual Office already gets sendVirtualOfficeWelcome
276
+ // and has no door or WiFi access — a member must never receive both.
277
+ if (plan.slug === config.virtualOfficeSlug) return 'skipped';
278
+
279
+ const apiKey = Deno.env.get('GHL_API_KEY');
280
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
281
+ if (!apiKey || !locationId) {
282
+ console.log('[stripe-webhook] GHL not configured; skip membership welcome');
283
+ await logWelcomeSkipped(supabase, email, 'ghl_not_configured', { plan_slug: plan.slug });
284
+ return 'skipped';
285
+ }
286
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
287
+ const headers = {
288
+ Authorization: `Bearer ${apiKey}`,
289
+ Version: '2021-07-28',
290
+ 'Content-Type': 'application/json',
291
+ Accept: 'application/json',
292
+ };
293
+
294
+ const name = (customerName || '').trim();
295
+ const parts = name.split(/\s+/).filter(Boolean);
296
+ // Greeting is display-only. The CRM name is OMITTED when Stripe has no name —
297
+ // never defaulted, or we would overwrite a real contact with "there".
298
+ const greetingName = parts[0] || 'there';
299
+ const crmName: { firstName?: string; lastName?: string } = {};
300
+ if (parts[0]) crmName.firstName = parts[0];
301
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
302
+
303
+ // Address comes from the same source bookingEffects uses (rooms.address),
304
+ // with the same operator-name fallback.
305
+ let address: string = operator.name;
306
+ try {
307
+ const { data: room } = await supabase
308
+ .from('rooms')
309
+ .select('address')
310
+ .eq('slug', config.addressRoomSlug)
311
+ .maybeSingle();
312
+ if (room?.address) address = room.address as string;
313
+ } catch (_e) { /* fallback stands */ }
314
+
315
+ const groups = Array.isArray(plan.unifi_group_ids) ? plan.unifi_group_ids : [];
316
+ const hasDoor = groups.length > 0;
317
+ const hasWifi = plan.wifi_enabled === true;
318
+
319
+ const planLine = [plan.name, plan.price_display, plan.unit]
320
+ .filter((v) => typeof v === 'string' && v.trim().length > 0)
321
+ .join(' · ');
322
+
323
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
324
+ method: 'POST', headers,
325
+ signal: AbortSignal.timeout(8000),
326
+ body: JSON.stringify({
327
+ locationId, ...crmName, email,
328
+ source: `${operator.shortName} Website — Membership`,
329
+ tags: ['Membership', `plan:${plan.slug}`, operator.domain],
330
+ }),
331
+ });
332
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
333
+ const upJson = await upRes.json();
334
+ const contactId = upJson.contact?.id || upJson.id || null;
335
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
336
+
337
+ const card = (title: string, inner: string) =>
338
+ `<tr><td style="padding:0 0 16px 0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;border:1px solid #E5E1D8;border-radius:8px"><tr><td style="padding:16px"><h3 style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px">${title}</h3>${inner}</td></tr></table></td></tr>`;
339
+ const p = (t: string) =>
340
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
341
+
342
+ const doorCard = hasDoor
343
+ ? card('How the doors work', [
344
+ p('Once your access is active and you\'ve accepted the UniFi Endpoint invite, here\'s how each entrance behaves:'),
345
+ p('<strong>Commons Hub front door:</strong> keypad PIN entry and Face Unlock are both supported here.'),
346
+ p('<strong>Rear entrance and Back Door:</strong> phone/NFC unlock only — there is no keypad and no camera at these doors, so a PIN will not open them.'),
347
+ p('If a door doesn\'t open after you\'ve accepted the invite, reply to this email and we\'ll sort it out — please don\'t assume you did something wrong.'),
348
+ ].join(''))
349
+ : '';
350
+ const wifiCard = hasWifi
351
+ ? card('WiFi', [
352
+ p('The member network is <strong>GC-Members</strong> (WPA2 Enterprise).'),
353
+ p('Your WiFi credentials arrive in a separate message once your access is active — they are not included here.'),
354
+ ].join(''))
355
+ : '';
356
+
357
+ // Host hours come from app_settings, never hardcoded here.
358
+ const hostHoursCard = await buildHostHoursCard(supabase, groups, card, p, config.hostHours);
359
+
360
+ 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">
361
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.shortName} — your access is being set up</h2>
362
+ ${p(`Hi ${esc(greetingName)},`)}
363
+ ${p(`Thanks for joining us. You're all set on <strong>${esc(planLine)}</strong>.`)}
364
+ ${startsOnLabel
365
+ ? p(`<strong>Your membership starts ${esc(startsOnLabel)}.</strong> Nothing is charged today, and your door and WiFi access will be set up on that date — not before.`)
366
+ : p('<strong>Your door and WiFi access is being set up right now — it usually takes a few minutes.</strong> Nothing is wrong if you don\'t have access the moment you finish reading this.')}
367
+ ${p('<strong>You\'ll get a separate email inviting you to an app called UniFi Endpoint. That invitation is from us — it\'s how you unlock the door with your phone.</strong> It arrives with Ubiquiti branding, so please don\'t delete it as spam.')}
368
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${doorCard}${wifiCard}${hostHoursCard}</table>
369
+ ${p(`We're at ${esc(address)}.`)}
370
+ ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
371
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name} · ${esc(address)}</p>
372
+ </td></tr></table></td></tr></table></div>`;
373
+
374
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
375
+ method: 'POST', headers,
376
+ signal: AbortSignal.timeout(8000),
377
+ body: JSON.stringify({
378
+ type: 'Email',
379
+ contactId,
380
+ subject: `Welcome to ${operator.shortName} — your access is being set up`,
381
+ html,
382
+ }),
383
+ });
384
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
385
+
386
+ await logOps(supabase, 'membership_welcome_email_sent',
387
+ { email, plan_slug: plan.slug }, { severity: 'info' }).catch(() => {});
388
+ return 'sent';
389
+ } catch (e) {
390
+ // Never rethrow — this must not fail the webhook or the membership write.
391
+ await logOps(supabase, 'membership_welcome_email_failed',
392
+ { email, plan_id: planId, message: e instanceof Error ? e.message : String(e) },
393
+ { severity: 'warning' }).catch(() => {});
394
+ return classifyError(e);
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Private office welcome. Routed to by maybeSendWelcomes when the plan carries
400
+ * the is_private_office capability flag. Office door/WiFi provisioning is
401
+ * automatic as of 2026-08-11 (offices flow through membership-door-sync like
402
+ * Dedicated Desk), but this mail still promises follow-ups rather than
403
+ * rendering the door/WiFi cards, because move-in is scheduled by a human
404
+ * either way.
405
+ */
406
+ export type PrivateOfficeBilling = {
407
+ monthlyCents: number;
408
+ retainerCents: number;
409
+ startDateIso: string | null;
410
+ };
411
+
412
+ /**
413
+ * Best-effort billing lookup for the private-office welcome card.
414
+ * NEVER throws: any failure returns null so the plain welcome still goes out.
415
+ */
416
+ export async function loadPrivateOfficeBilling(
417
+ supabase: SupabaseLike,
418
+ subscriptionId: string | null | undefined,
419
+ ): Promise<PrivateOfficeBilling | null> {
420
+ if (!subscriptionId) return null;
421
+ try {
422
+ const { data: sd } = await supabase
423
+ .from('signature_documents')
424
+ .select('field_values,start_date')
425
+ .eq('stripe_subscription_id', subscriptionId)
426
+ .maybeSingle();
427
+ if (!sd) return null;
428
+ const v = (sd.field_values ?? {}) as Record<string, unknown>;
429
+ const monthlyCents = Math.round(Number(String(v.monthly_fee ?? '').replace(/[^0-9.]/g, '')) * 100);
430
+ const retainerCents = Math.round(Number(String(v.service_retainer ?? '').replace(/[^0-9.]/g, '')) * 100);
431
+ if (!Number.isFinite(monthlyCents) || monthlyCents <= 0) return null;
432
+ if (!Number.isFinite(retainerCents) || retainerCents <= 0) return null;
433
+ return { monthlyCents, retainerCents, startDateIso: (sd.start_date as string | null) ?? null };
434
+ } catch (e) {
435
+ await logOps(supabase, 'private_office_welcome_billing_lookup_failed',
436
+ { subscription_id: subscriptionId, message: e instanceof Error ? e.message : String(e) },
437
+ { severity: 'warning' }).catch(() => {});
438
+ return null;
439
+ }
440
+ }
441
+
442
+ const usd = (cents: number) =>
443
+ (cents / 100).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
444
+
445
+ export type PrivateOfficeWelcomeConfig = {
446
+ operator: WelcomeOperator;
447
+ /**
448
+ * Staff addresses CC'd on the office welcome so a human knows to schedule
449
+ * move-in. Tenant-owned; pass [] to send without a CC.
450
+ */
451
+ staffCc: readonly string[];
452
+ };
453
+
454
+ export async function sendPrivateOfficeWelcome(
455
+ supabase: SupabaseLike,
456
+ email: string,
457
+ name: string | null,
458
+ plan: WelcomePlan,
459
+ config: PrivateOfficeWelcomeConfig,
460
+ billing?: PrivateOfficeBilling | null,
461
+ ): Promise<WelcomeResult> {
462
+ const { operator } = config;
463
+
464
+ try {
465
+ // Defence in depth: routing already guarantees this, but never send the
466
+ // office welcome for a non-office plan.
467
+ if (plan.is_private_office !== true) return 'skipped';
468
+
469
+ const apiKey = Deno.env.get('GHL_API_KEY');
470
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
471
+ if (!apiKey || !locationId) {
472
+ console.log('[stripe-webhook] GHL not configured; skip private office welcome');
473
+ await logOps(supabase, 'private_office_welcome_email_skipped',
474
+ { email, reason: 'ghl_not_configured', plan_slug: plan.slug },
475
+ { severity: 'warning' }).catch(() => {});
476
+ return 'skipped';
477
+ }
478
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
479
+ const headers = {
480
+ Authorization: `Bearer ${apiKey}`,
481
+ Version: '2021-07-28',
482
+ 'Content-Type': 'application/json',
483
+ Accept: 'application/json',
484
+ };
485
+
486
+ const trimmed = (name || '').trim();
487
+ const parts = trimmed.split(/\s+/).filter(Boolean);
488
+ // Greeting is display-only. The CRM name is OMITTED when there is no name —
489
+ // never defaulted, or we would overwrite a real contact with "there".
490
+ const greetingName = parts[0] || 'there';
491
+ const crmName: { firstName?: string; lastName?: string } = {};
492
+ if (parts[0]) crmName.firstName = parts[0];
493
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
494
+
495
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
496
+ method: 'POST', headers,
497
+ signal: AbortSignal.timeout(8000),
498
+ body: JSON.stringify({
499
+ locationId, ...crmName, email,
500
+ source: `${operator.shortName} Website — Private Office`,
501
+ tags: ['Private Office', operator.domain],
502
+ }),
503
+ });
504
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
505
+ const upJson = await upRes.json();
506
+ const contactId = upJson.contact?.id || upJson.id || null;
507
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
508
+
509
+ const card = (title: string, inner: string) =>
510
+ `<tr><td style="padding:0 0 16px 0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;border:1px solid #E5E1D8;border-radius:8px"><tr><td style="padding:16px"><h3 style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px">${title}</h3>${inner}</td></tr></table></td></tr>`;
511
+ const p = (t: string) =>
512
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
513
+ const li = (t: string) =>
514
+ `<li style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</li>`;
515
+
516
+ const nextCard = card('Here\'s what\'s next', [
517
+ `<ul style="margin:0;padding:0 0 0 18px">`,
518
+ li('<strong>Move-in:</strong> We\'ll be in touch shortly to schedule your move-in.'),
519
+ li('<strong>Access:</strong> Your door access is being set up now — it usually takes a few minutes. You\'ll also get a separate email inviting you to an app called <strong>UniFi Endpoint</strong> — that\'s from us and is how you unlock the door with your phone. It arrives with Ubiquiti branding, so please don\'t mark it as spam.'),
520
+ li('<strong>WiFi:</strong> Your WiFi access is being set up at the same time — credentials arrive in a separate message.'),
521
+ li('<strong>Community:</strong> We host regular member events — keep an eye on your inbox.'),
522
+ `</ul>`,
523
+ ].join(''));
524
+
525
+ let billingCard = '';
526
+ if (billing) {
527
+ const startInstant = pacificMidnightUtc(billing.startDateIso);
528
+ const startInFuture = startInstant !== null && startInstant.getTime() > Date.now();
529
+ const monthly = usd(billing.monthlyCents);
530
+ const lines = [p(`Your one-time service retainer of ${usd(billing.retainerCents)} has been received.`)];
531
+ if (startInFuture) {
532
+ const when = new Intl.DateTimeFormat('en-US', {
533
+ timeZone: 'America/Los_Angeles', year: 'numeric', month: 'long', day: 'numeric',
534
+ }).format(startInstant as Date);
535
+ lines.push(p(`Your monthly rate of ${monthly}/month will begin billing automatically on ${when} — nothing further is due until then.`));
536
+ } else {
537
+ lines.push(p(`Your monthly rate of ${monthly}/month is now active and will bill automatically each month going forward.`));
538
+ }
539
+ billingCard = card('Your billing', lines.join(''));
540
+ }
541
+
542
+ 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">
543
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.name} — here's what's next</h2>
544
+ ${p(`Hi ${esc(greetingName)},`)}
545
+ ${p(`You're all set — welcome to ${operator.name}. We're glad to have you as part of the community.`)}
546
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${nextCard}${billingCard}</table>
547
+
548
+ ${p(`If anything's unclear or you need something before you move in, just reply here or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a> — we're happy to help.`)}
549
+ ${p(`Welcome again,<br>The ${operator.name} team`)}
550
+ </td></tr></table></td></tr></table></div>`;
551
+
552
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
553
+ method: 'POST', headers,
554
+ signal: AbortSignal.timeout(8000),
555
+ body: JSON.stringify({
556
+ type: 'Email',
557
+ contactId,
558
+ subject: `Welcome to ${operator.name} — here's what's next`,
559
+ html,
560
+ emailCc: [...config.staffCc],
561
+ }),
562
+ });
563
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
564
+
565
+ await logOps(supabase, 'private_office_welcome_email_sent',
566
+ { email, plan_slug: plan.slug }, { severity: 'info' }).catch(() => {});
567
+ return 'sent';
568
+ } catch (e) {
569
+ // Never rethrow — this must not fail the webhook or the membership write.
570
+ const classification = classifyError(e);
571
+ await logOps(supabase, 'private_office_welcome_email_failed',
572
+ { email, plan_slug: plan.slug, message: e instanceof Error ? e.message : String(e) },
573
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
574
+ return classification;
575
+ }
576
+ }
577
+
578
+ export type TeamSeatWelcomeConfig = {
579
+ operator: WelcomeOperator;
580
+ /** Plan slug of the operator's sponsored-seat ("company member") plan. */
581
+ teamSeatSlug: string;
582
+ };
583
+
584
+ /**
585
+ * Team-seat ("Company member") welcome.
586
+ *
587
+ * Sponsored seats sit on the team-seat plan, which is deliberately
588
+ * category='office', price 0 and active=false — it is not a purchasable plan.
589
+ * That combination would otherwise route them into sendPrivateOfficeWelcome
590
+ * (wrong: they are not moving into a private office) or be dropped entirely by
591
+ * the plan_inactive skip. Callers must route the team-seat slug here BEFORE the
592
+ * office/active checks — see maybeSendWelcomes in stripe-webhook and
593
+ * admin-resend-welcome-email.
594
+ */
595
+ export async function sendTeamSeatWelcome(
596
+ supabase: SupabaseLike,
597
+ email: string,
598
+ name: string | null,
599
+ companyName: string | null,
600
+ plan: WelcomePlan,
601
+ config: TeamSeatWelcomeConfig,
602
+ ): Promise<WelcomeResult> {
603
+ const { operator } = config;
604
+ try {
605
+ // Defence in depth: never send this to anything but a sponsored seat.
606
+ if (plan.slug !== config.teamSeatSlug) return 'skipped';
607
+
608
+ const apiKey = Deno.env.get('GHL_API_KEY');
609
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
610
+ if (!apiKey || !locationId) {
611
+ await logOps(supabase, 'team_seat_welcome_email_skipped',
612
+ { email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
613
+ return 'skipped';
614
+ }
615
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
616
+ const headers = {
617
+ Authorization: `Bearer ${apiKey}`,
618
+ Version: '2021-07-28',
619
+ 'Content-Type': 'application/json',
620
+ Accept: 'application/json',
621
+ };
622
+
623
+ const trimmed = (name || '').trim();
624
+ const parts = trimmed.split(/\s+/).filter(Boolean);
625
+ const greetingName = parts[0] || 'there';
626
+ const crmName: { firstName?: string; lastName?: string } = {};
627
+ if (parts[0]) crmName.firstName = parts[0];
628
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
629
+
630
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
631
+ method: 'POST', headers,
632
+ signal: AbortSignal.timeout(8000),
633
+ body: JSON.stringify({
634
+ locationId, ...crmName, email,
635
+ source: `${operator.shortName} Website — Team Member`,
636
+ tags: ['Team Member', `plan:${config.teamSeatSlug}`, operator.domain],
637
+ }),
638
+ });
639
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
640
+ const upJson = await upRes.json();
641
+ const contactId = upJson.contact?.id || upJson.id || null;
642
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
643
+
644
+ const p = (t: string) =>
645
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
646
+
647
+ const companyLine = companyName && companyName.trim()
648
+ ? `You've been added as a team member on <strong>${esc(companyName.trim())}</strong>'s membership at ${esc(operator.shortName)}.`
649
+ : `You've been added as a team member on your company's membership at ${esc(operator.shortName)}.`;
650
+
651
+ 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">
652
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">You've been added as a team member</h2>
653
+ ${p(`Hi ${esc(greetingName)},`)}
654
+ ${p(companyLine)}
655
+ ${p(`<strong>Setting up your login:</strong> go to <a href="https://${operator.domain}/portal/login" style="color:#C98A5E">${operator.domain}/portal/login</a> and enter this email address (${esc(email)}). We'll email you a sign-in link — there's no password to remember.`)}
656
+ ${p('<strong>Door and WiFi access:</strong> if your seat includes it, access is being set up now and can take a little while to go live. You may also receive a separate invite to an app called <strong>UniFi Endpoint</strong> — that\'s from us, and it\'s how you unlock the door with your phone.')}
657
+ ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
658
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
659
+ </td></tr></table></td></tr></table></div>`;
660
+
661
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
662
+ method: 'POST', headers,
663
+ signal: AbortSignal.timeout(8000),
664
+ body: JSON.stringify({
665
+ type: 'Email',
666
+ contactId,
667
+ subject: `You've been added as a team member at ${operator.shortName}`,
668
+ html,
669
+ }),
670
+ });
671
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
672
+
673
+ await logOps(supabase, 'team_seat_welcome_email_sent',
674
+ { email, plan_slug: plan.slug }, { severity: 'info' }).catch(() => {});
675
+ return 'sent';
676
+ } catch (e) {
677
+ const classification = classifyError(e);
678
+ await logOps(supabase, 'team_seat_welcome_email_failed',
679
+ { email, message: e instanceof Error ? e.message : String(e) },
680
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
681
+ return classification;
682
+ }
683
+ }