@simplelayer/graniteer-core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
package/src/migrationCheckout.ts
CHANGED
|
@@ -1,366 +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
|
-
}
|
|
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
|
+
}
|