@simplelayer/graniteer-core 0.1.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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,366 @@
1
+ // Shared plumbing for the two legacy-migration checkout edge functions
2
+ // (plan v13 §2.4): migration-checkout-confirm (GET) and
3
+ // migration-checkout-redirect (POST).
4
+ //
5
+ // §2.4 step 7 requires the POST function to "independently re-run steps 1-4 in
6
+ // full" — the SAME token verification, the SAME state load, the SAME
7
+ // already-converted check, the SAME plan lookup. That is only literally true if
8
+ // both functions call one implementation, so steps 1-4 live here.
9
+ //
10
+ // Also here: the three §9.2 blocks the plan says to REPLICATE rather than
11
+ // import, because they are inline inside create-subscription-checkout and not
12
+ // exported — the eligibility gate, the lineItem construction, and the
13
+ // search-then-list-then-create customer logic. They are replicated once, here,
14
+ // rather than a second time inside the redirect function.
15
+ //
16
+ // NOTHING in this module reads or writes `memberships` except the one
17
+ // read-only existence check §2.4 step 3 specifies. It never writes a
18
+ // membership row and never emits `membership_email_collision_flagged` — that
19
+ // remains exclusively stripe-webhook's job, unmodified.
20
+
21
+ import { createClient } from 'npm:@supabase/supabase-js@2';
22
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
23
+ import Stripe from 'npm:stripe@17.5.0';
24
+ import {
25
+ verifyMigrationCheckoutToken,
26
+ migrationCheckoutTokenIsRevoked,
27
+ type MigrationCheckoutTokenPayload,
28
+ } from './manageToken.ts';
29
+
30
+ export type SupabaseLike = SupabaseClient<any, any, any>;
31
+
32
+ /**
33
+ * Structural subset of the Stripe client the migration functions actually
34
+ * touch. Declared explicitly so the pure-mock tests can pass a recording fake
35
+ * without constructing a real `Stripe` instance (and therefore without any
36
+ * possibility of a live call — this account is LIVE-ONLY, there is no test
37
+ * secret key anywhere in this project).
38
+ */
39
+ export interface StripeLike {
40
+ checkout: {
41
+ sessions: {
42
+ retrieve(id: string): Promise<{ id: string; status?: string | null; url?: string | null; metadata?: Record<string, string> | null }>;
43
+ expire(id: string): Promise<unknown>;
44
+ create(params: Stripe.Checkout.SessionCreateParams): Promise<{ id: string; url?: string | null }>;
45
+ };
46
+ };
47
+ customers: {
48
+ search(params: { query: string; limit?: number }): Promise<{ data: Array<{ id: string }> }>;
49
+ list(params: { email: string; limit?: number }): Promise<{ data: Array<{ id: string }> }>;
50
+ update(id: string, params: { name: string }): Promise<unknown>;
51
+ create(params: { email: string; name: string }): Promise<{ id: string }>;
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Injectable dependency bundle. `now` is a seam, not a design flourish: §2.4
57
+ * step 8's whole purpose is the midnight-boundary case (a GET at 23:59:59
58
+ * disclosing 2026-10-01, a POST at 00:00:01 recomputing "immediate"), and that
59
+ * is untestable against a wall clock.
60
+ */
61
+ export interface MigrationCheckoutDeps {
62
+ supabase: SupabaseLike;
63
+ /** null when STRIPE_SECRET_KEY is absent. The GET function never needs it. */
64
+ stripe: StripeLike | null;
65
+ now: () => Date;
66
+ tokenSecret: string | null;
67
+ /** Absolute base for building the POST action + success/cancel URLs. */
68
+ baseUrl: string;
69
+ functionsBaseUrl: string;
70
+ }
71
+
72
+ export const MIGRATION_CONFIRM_PATH = '/functions/v1/migration-checkout-confirm';
73
+ export const MIGRATION_REDIRECT_PATH = '/functions/v1/migration-checkout-redirect';
74
+
75
+ export function resolveDeps(req: Request, defaultBaseUrl: string): MigrationCheckoutDeps {
76
+ const supabase = createClient(
77
+ Deno.env.get('SUPABASE_URL')!,
78
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
79
+ );
80
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
81
+ const stripe = stripeKey
82
+ ? (new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion }) as unknown as StripeLike)
83
+ : null;
84
+
85
+ // Same origin-or-default shape create-subscription-checkout uses for its
86
+ // success/cancel URLs (§9.2), so a migration checkout lands on the same host
87
+ // an ordinary one would.
88
+ const origin = req.headers.get('origin');
89
+ const baseUrl = origin && /^https?:\/\//.test(origin) ? origin : defaultBaseUrl;
90
+
91
+ return {
92
+ supabase,
93
+ stripe,
94
+ now: () => new Date(),
95
+ tokenSecret: Deno.env.get('MANAGE_TOKEN_SECRET') ?? null,
96
+ baseUrl,
97
+ functionsBaseUrl: (Deno.env.get('SUPABASE_URL') ?? '').replace(/\/+$/, ''),
98
+ };
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Row shapes
103
+ // ---------------------------------------------------------------------------
104
+
105
+ export interface MigrationCheckoutStateRow {
106
+ email: string;
107
+ customer_name: string;
108
+ plan_slug: string;
109
+ intended_start_date: string;
110
+ token_minted_at: string | null;
111
+ token_revoked_at: string | null;
112
+ completed_at: string | null;
113
+ last_session_id: string | null;
114
+ last_session_created_at: string | null;
115
+ session_creation_started_at: string | null;
116
+ attempt_window_started_at: string | null;
117
+ attempt_count_in_window: number;
118
+ last_redirect_error: string | null;
119
+ created_at: string;
120
+ }
121
+
122
+ export const MIGRATION_STATE_SELECT =
123
+ 'email,customer_name,plan_slug,intended_start_date,token_minted_at,token_revoked_at,' +
124
+ 'completed_at,last_session_id,last_session_created_at,session_creation_started_at,' +
125
+ 'attempt_window_started_at,attempt_count_in_window,last_redirect_error,created_at';
126
+
127
+ export interface MembershipPlanRow {
128
+ id: string;
129
+ slug: string;
130
+ name: string;
131
+ category: string | null;
132
+ active: boolean | null;
133
+ billable: boolean | null;
134
+ billing_interval: string | null;
135
+ stripe_price_id: string | null;
136
+ stripe_product_id: string | null;
137
+ price_cents: number | null;
138
+ }
139
+
140
+ /** Identical column list to §9.2's plan select — same order, same columns. */
141
+ export const PLAN_SELECT =
142
+ 'id,slug,name,category,active,billable,billing_interval,stripe_price_id,stripe_product_id,price_cents';
143
+
144
+ /**
145
+ * §2.4 step 3's status set, verbatim. Note it deliberately INCLUDES
146
+ * 'incomplete' and 'unpaid': the question this check answers is "does a real
147
+ * Stripe subscription already exist for this email", not "is it in good
148
+ * standing". A member mid-dunning must not be handed a second subscription.
149
+ */
150
+ export const EXISTING_MEMBERSHIP_STATUSES = [
151
+ 'active', 'trialing', 'past_due', 'incomplete', 'unpaid', 'paused',
152
+ ] as const;
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // §2.4 steps 1-4, shared verbatim between the two functions
156
+ // ---------------------------------------------------------------------------
157
+
158
+ export type LoadResult =
159
+ | { kind: 'token_error' }
160
+ | { kind: 'already_complete'; state: MigrationCheckoutStateRow }
161
+ | { kind: 'ok'; payload: MigrationCheckoutTokenPayload; state: MigrationCheckoutStateRow; plan: MembershipPlanRow | null };
162
+
163
+ /**
164
+ * Steps 1-4:
165
+ * 1. verify the token (phase 1 — pure).
166
+ * 2. load migration_checkout_state by payload.eml; check token_revoked_at
167
+ * (phase 2). Missing OR revoked -> the same static error page, which is
168
+ * also the `unknown_email` page, so nothing here confirms or denies
169
+ * roster membership.
170
+ * 3. check memberships for an existing row for this email with a non-null
171
+ * stripe_subscription_id in one of the live-ish statuses. Found -> stamp
172
+ * completed_at if unset -> "you're all set".
173
+ * 4. look up the plan by plan_slug.
174
+ */
175
+ export async function loadTokenStateAndPlan(
176
+ deps: MigrationCheckoutDeps,
177
+ token: string | null,
178
+ ): Promise<LoadResult> {
179
+ // --- step 1 ---
180
+ if (!token || !deps.tokenSecret) return { kind: 'token_error' };
181
+ const payload = await verifyMigrationCheckoutToken(token, deps.tokenSecret);
182
+ if (!payload) return { kind: 'token_error' };
183
+
184
+ // --- step 2 ---
185
+ const { data: stateRow, error: stateErr } = await deps.supabase
186
+ .from('migration_checkout_state')
187
+ .select(MIGRATION_STATE_SELECT)
188
+ .eq('email', payload.eml)
189
+ .maybeSingle();
190
+ if (stateErr) throw new Error('migration_checkout_state read failed: ' + stateErr.message);
191
+ if (!stateRow) return { kind: 'token_error' };
192
+ const state = stateRow as unknown as MigrationCheckoutStateRow;
193
+ if (migrationCheckoutTokenIsRevoked(payload, state.token_revoked_at)) return { kind: 'token_error' };
194
+
195
+ // --- step 3 ---
196
+ // Read-only. This is the ONLY `memberships` access anywhere in the migration
197
+ // flow, and it is a select: the row itself is created exclusively by the
198
+ // unmodified stripe-webhook insert path (§9.4).
199
+ const { data: existing, error: memErr } = await deps.supabase
200
+ .from('memberships')
201
+ .select('id')
202
+ .eq('email', payload.eml)
203
+ .not('stripe_subscription_id', 'is', null)
204
+ .in('status', EXISTING_MEMBERSHIP_STATUSES as unknown as string[])
205
+ .limit(1);
206
+ if (memErr) throw new Error('memberships read failed: ' + memErr.message);
207
+ if ((existing ?? []).length > 0) {
208
+ if (state.completed_at === null) {
209
+ await deps.supabase
210
+ .from('migration_checkout_state')
211
+ .update({ completed_at: deps.now().toISOString() })
212
+ .eq('email', payload.eml);
213
+ state.completed_at = deps.now().toISOString();
214
+ }
215
+ return { kind: 'already_complete', state };
216
+ }
217
+
218
+ // The RPC's own `already_complete` guard covers the case where completed_at
219
+ // was stamped by a prior click but the webhook has not landed yet; the GET
220
+ // page short-circuits on it here for the same reason, so a member who has
221
+ // already paid never sees a "Continue to payment" button.
222
+ if (state.completed_at !== null) return { kind: 'already_complete', state };
223
+
224
+ // --- step 4 ---
225
+ const { data: plan, error: planErr } = await deps.supabase
226
+ .from('membership_plans')
227
+ .select(PLAN_SELECT)
228
+ .eq('slug', state.plan_slug)
229
+ .maybeSingle();
230
+ if (planErr) throw new Error('membership_plans read failed: ' + planErr.message);
231
+
232
+ return { kind: 'ok', payload, state, plan: (plan as unknown as MembershipPlanRow) ?? null };
233
+ }
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // §9.2 replications — the eligibility gate, the lineItem, the customer logic
237
+ // ---------------------------------------------------------------------------
238
+
239
+ /** §9.2's allowlist, verbatim. `office` is deliberately excluded. */
240
+ export const SELF_SERVE_CATEGORIES = ['coworking', 'dedicated'];
241
+
242
+ /**
243
+ * §2.4 step 10 / §9.2's eligibility gate, replicated field for field:
244
+ * `active`, `billable`, category in the allowlist, billing_interval 'month',
245
+ * and either a stored stripe_price_id or a valid ad-hoc price_cents.
246
+ */
247
+ export function isPlanEligible(plan: MembershipPlanRow | null): boolean {
248
+ const usesAdHocPrice =
249
+ !plan?.stripe_price_id &&
250
+ !!plan?.billing_interval &&
251
+ typeof plan?.price_cents === 'number' &&
252
+ plan.price_cents > 0;
253
+
254
+ return (
255
+ !!plan &&
256
+ plan.active === true &&
257
+ plan.billable === true &&
258
+ SELF_SERVE_CATEGORIES.includes(plan.category as string) &&
259
+ plan.billing_interval === 'month' &&
260
+ (!!plan.stripe_price_id || usesAdHocPrice)
261
+ );
262
+ }
263
+
264
+ /**
265
+ * §9.2's lineItem, replicated: `price_data` and `quantity` as SIBLINGS, with
266
+ * every field Stripe requires nested inside `price_data` (round-6 S7-1 — an
267
+ * earlier plan revision flattened currency/product_data/unit_amount/recurring
268
+ * onto the line item and omitted `quantity`, which Stripe rejects outright).
269
+ */
270
+ export function buildLineItem(plan: MembershipPlanRow): Stripe.Checkout.SessionCreateParams.LineItem {
271
+ return plan.stripe_price_id
272
+ ? { price: plan.stripe_price_id, quantity: 1 }
273
+ : {
274
+ price_data: {
275
+ currency: 'usd',
276
+ product_data: { name: plan.name },
277
+ unit_amount: plan.price_cents as number,
278
+ recurring: {
279
+ interval: plan.billing_interval as Stripe.Checkout.SessionCreateParams.LineItem.PriceData.Recurring.Interval,
280
+ },
281
+ },
282
+ quantity: 1,
283
+ };
284
+ }
285
+
286
+ /**
287
+ * §2.4 step 14 / §9.2's search-then-list-then-create customer logic,
288
+ * replicated unchanged — including the eventual-consistency fallback from
289
+ * `customers.search` to `customers.list`, the >1-match error log, and the
290
+ * best-effort name update on a reused customer.
291
+ *
292
+ * `name` comes from migration_checkout_state.customer_name (§2.4 step 14).
293
+ */
294
+ export async function resolveStripeCustomer(
295
+ stripe: StripeLike,
296
+ emailKey: string,
297
+ name: string,
298
+ ): Promise<string> {
299
+ let customerId: string | null = null;
300
+ let matchCount = 0;
301
+ try {
302
+ const found = await stripe.customers.search({
303
+ query: `email:'${emailKey.replace(/'/g, "\\'")}'`,
304
+ limit: 2,
305
+ });
306
+ matchCount = found.data.length;
307
+ if (found.data.length > 0) customerId = found.data[0].id;
308
+ } catch (e) {
309
+ console.warn('[migration-checkout-redirect] customers.search failed', e);
310
+ }
311
+ // Search is eventually consistent (~1 min). Always fall back to list for freshly-created customers.
312
+ if (!customerId) {
313
+ try {
314
+ const listed = await stripe.customers.list({ email: emailKey, limit: 2 });
315
+ matchCount = listed.data.length;
316
+ if (listed.data.length > 0) customerId = listed.data[0].id;
317
+ } catch (e2) {
318
+ console.warn('[migration-checkout-redirect] customers.list failed', e2);
319
+ }
320
+ }
321
+ // Stripe does NOT enforce Customer email uniqueness. With >1 Customer per
322
+ // email the reused id is arbitrary, which makes any stripe_customer_id
323
+ // predicate downstream nondeterministic. Assert exactly one; flag otherwise.
324
+ if (matchCount > 1) {
325
+ console.error('[migration-checkout-redirect] multiple Stripe Customers for one email',
326
+ { email: emailKey, match_count: matchCount, chosen: customerId });
327
+ }
328
+ if (customerId) {
329
+ // Best-effort: keep the reused customer's name current. Never block checkout.
330
+ try {
331
+ await stripe.customers.update(customerId, { name });
332
+ } catch (e3) {
333
+ console.warn('[migration-checkout-redirect] customers.update name failed', e3);
334
+ }
335
+ } else {
336
+ const created = await stripe.customers.create({ email: emailKey, name });
337
+ customerId = created.id;
338
+ }
339
+ return customerId;
340
+ }
341
+
342
+ /**
343
+ * Clears the pending-claim marker. §2.2 is explicit that EVERY branch
344
+ * reachable after a `proceed` verdict must clear it at the point that branch
345
+ * resolves; the 60-second TTL is a backstop, not the primary mechanism.
346
+ *
347
+ * Best-effort by contract: a failure to clear must never turn into a 500 for a
348
+ * member who has otherwise been served correctly — the TTL covers it.
349
+ */
350
+ export async function releaseClaim(
351
+ deps: MigrationCheckoutDeps,
352
+ email: string,
353
+ lastRedirectError?: string | null,
354
+ ): Promise<void> {
355
+ try {
356
+ await deps.supabase
357
+ .from('migration_checkout_state')
358
+ .update({
359
+ session_creation_started_at: null,
360
+ ...(lastRedirectError === undefined ? {} : { last_redirect_error: lastRedirectError }),
361
+ })
362
+ .eq('email', email);
363
+ } catch (e) {
364
+ console.error('[migration-checkout-redirect] failed to release claim marker', { email, error: String(e) });
365
+ }
366
+ }
@@ -32,3 +32,57 @@ export function addDaysStr(dateStr: string, days: number): string {
32
32
  const [y, m, d] = dateStr.split('-').map(Number);
33
33
  return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
34
34
  }
35
+
36
+ // pacificMidnightUtc/laOffsetMinutes added here in Phase 8, copied verbatim
37
+ // from gc-connect's _shared/agreementActivation.ts (that file stays in
38
+ // gc-connect -- it also owns BoldSign-specific activation logic this module
39
+ // has nothing to do with). ./membershipWelcome.ts needs the same start-date
40
+ // instant for its private-office billing card. create-subscription-checkout.ts
41
+ // still carries its own private inline copy from an earlier phase; collapsing
42
+ // that one into this module is a separate, unrelated change.
43
+ const LA_TZ = 'America/Los_Angeles';
44
+
45
+ /**
46
+ * Resolve the UTC instant of midnight (00:00) on a Pacific calendar date,
47
+ * handling PST/PDT correctly. Returns null for a missing/invalid date string.
48
+ */
49
+ export function pacificMidnightUtc(dateStr: string | null | undefined): Date | null {
50
+ if (!dateStr) return null;
51
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(dateStr));
52
+ if (!m) return null;
53
+ const [, y, mo, d] = m;
54
+ // Start from the UTC-midnight guess, then correct by the zone offset that
55
+ // actually applies at that instant (two passes settles DST boundaries).
56
+ let ts = Date.UTC(Number(y), Number(mo) - 1, Number(d), 0, 0, 0);
57
+ for (let i = 0; i < 2; i++) {
58
+ const offsetMinutes = laOffsetMinutes(new Date(ts));
59
+ ts = Date.UTC(Number(y), Number(mo) - 1, Number(d), 0, 0, 0) - offsetMinutes * 60_000;
60
+ }
61
+ return new Date(ts);
62
+ }
63
+
64
+ /** Offset of America/Los_Angeles from UTC, in minutes, at the given instant. */
65
+ function laOffsetMinutes(at: Date): number {
66
+ const fmt = new Intl.DateTimeFormat('en-US', {
67
+ timeZone: LA_TZ,
68
+ hour12: false,
69
+ year: 'numeric',
70
+ month: '2-digit',
71
+ day: '2-digit',
72
+ hour: '2-digit',
73
+ minute: '2-digit',
74
+ second: '2-digit',
75
+ });
76
+ const parts = Object.fromEntries(
77
+ fmt.formatToParts(at).filter((p) => p.type !== 'literal').map((p) => [p.type, p.value]),
78
+ ) as Record<string, string>;
79
+ const asUtc = Date.UTC(
80
+ Number(parts.year),
81
+ Number(parts.month) - 1,
82
+ Number(parts.day),
83
+ Number(parts.hour) % 24,
84
+ Number(parts.minute),
85
+ Number(parts.second),
86
+ );
87
+ return (asUtc - at.getTime()) / 60_000;
88
+ }
@@ -0,0 +1,123 @@
1
+ // Payment-link email for a completed private office agreement.
2
+ //
3
+ // Mirrors the GHL request shape, headers, timeouts, escaping and error
4
+ // classification of sendMembershipWelcome in ./membershipWelcome.ts.
5
+
6
+ import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
7
+ import { logOps } from './ops.ts';
8
+
9
+ type SupabaseLike = SupabaseClient<any, 'public', any>;
10
+
11
+ export type PaymentLinkEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
12
+
13
+ /** Escape untrusted values interpolated into outbound HTML. */
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
+ /** Classify a caught error as transient (worth another event) or hopeless. */
24
+ function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
25
+ const name = e instanceof Error ? e.name : '';
26
+ if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
27
+ const msg = e instanceof Error ? e.message : String(e);
28
+ const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
29
+ if (m) {
30
+ const code = Number(m[1]);
31
+ if (code === 429 || code >= 500) return 'failed_retryable';
32
+ }
33
+ return 'failed_permanent';
34
+ }
35
+
36
+ export async function sendPaymentLinkEmail(
37
+ supabase: SupabaseLike,
38
+ { email, name, checkoutUrl, officeNumber }: {
39
+ email: string;
40
+ name?: string | null;
41
+ checkoutUrl: string;
42
+ officeNumber?: string | null;
43
+ },
44
+ operator: { name: string; shortName: string; domain: string; supportEmail: string },
45
+ ): Promise<PaymentLinkEmailResult> {
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, 'payment_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
+ // Greeting is display-only. The CRM name is OMITTED when we have no name —
65
+ // never defaulted, or we would overwrite a real contact with "there".
66
+ const greetingName = parts[0] || 'there';
67
+ const crmName: { firstName?: string; lastName?: string } = {};
68
+ if (parts[0]) crmName.firstName = parts[0];
69
+ if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
70
+
71
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
72
+ method: 'POST', headers,
73
+ signal: AbortSignal.timeout(8000),
74
+ body: JSON.stringify({
75
+ locationId, ...crmName, email,
76
+ source: `${operator.shortName} Website — Office Agreement`,
77
+ tags: ['Office Agreement', operator.domain],
78
+ }),
79
+ });
80
+ if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
81
+ const upJson = await upRes.json();
82
+ const contactId = upJson.contact?.id || upJson.id || null;
83
+ if (!contactId) throw new Error('ghl_upsert_no_contact_id');
84
+
85
+ const p = (t: string) =>
86
+ `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
87
+
88
+ const office = (officeNumber || '').trim();
89
+ const officeClause = office ? ` for office ${esc(office)}` : '';
90
+
91
+ 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">
92
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your ${operator.shortName} office agreement is signed — set up payment</h2>
93
+ ${p(`Hi ${esc(greetingName)},`)}
94
+ ${p(`Thanks for signing your ${operator.name} office agreement${officeClause} — you're one step from locked in.`)}
95
+ ${p('The last step is setting up your monthly payment. Use the link below to add a payment method and start your subscription:')}
96
+ ${p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Set up payment →</a>`)}
97
+ ${p('This link is unique to your agreement, so please don\'t forward it. Once checkout is complete, we\'ll follow up with move-in details and everything else you need to get started.')}
98
+ ${p(`Questions in the meantime? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
99
+ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
100
+ </td></tr></table></td></tr></table></div>`;
101
+
102
+ const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
103
+ method: 'POST', headers,
104
+ signal: AbortSignal.timeout(8000),
105
+ body: JSON.stringify({
106
+ type: 'Email',
107
+ contactId,
108
+ subject: `Your ${operator.shortName} office agreement is signed — set up payment`,
109
+ html,
110
+ }),
111
+ });
112
+ if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
113
+
114
+ await logOps(supabase, 'payment_link_email_sent', { email }, { severity: 'info' }).catch(() => {});
115
+ return 'sent';
116
+ } catch (e) {
117
+ const classification = classifyError(e);
118
+ await logOps(supabase, 'payment_link_email_failed',
119
+ { email, message: e instanceof Error ? e.message : String(e) },
120
+ { severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
121
+ return classification;
122
+ }
123
+ }