@simplelayer/graniteer-core 0.0.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +169 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +312 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-request-trial.ts +366 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/booking-status.ts +149 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/fetch-avatar-original.ts +457 -0
- package/src/functions/get-provider-sign-link.ts +155 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/push-send.ts +348 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/stripe-db-reconcile.ts +319 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/touch-pass-signup.ts +478 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-booking.ts +453 -0
- package/src/functions/voice-day-pass.ts +346 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membership.ts +109 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +88 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/slackAlert.ts +38 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/supportTicketEmail.ts +119 -0
- package/src/tier1Agreement.ts +125 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -0,0 +1,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
|
+
}
|
package/src/money.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Parse a money-ish value the exact same way everywhere. Never throws. */
|
|
2
|
+
export const centsFrom = (v: unknown): number => {
|
|
3
|
+
const n = Number(v);
|
|
4
|
+
if (!Number.isFinite(n)) return 0;
|
|
5
|
+
return Math.round(n * 100);
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export type RetainerConfig =
|
|
9
|
+
| { ok: true; cents: number; waived: boolean }
|
|
10
|
+
| { ok: false; code: 'service_retainer_must_be_positive' | 'service_retainer_unparseable' | 'service_retainer_absent' };
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The ONE place that decides "is this retainer positive, or a deliberately
|
|
14
|
+
* waived zero?" Fails closed: a blank, negative, or unparseable value is
|
|
15
|
+
* NEVER treated as zero, regardless of any waiver flag. `retainer_waived`
|
|
16
|
+
* must be exactly boolean true or string "true" -- anything else means "not
|
|
17
|
+
* waived." `service_retainer_absent` is distinct from `_must_be_positive` so
|
|
18
|
+
* callers where the field is optional (legacy checkout builder) can tell
|
|
19
|
+
* "not provided" apart from "provided but invalid."
|
|
20
|
+
*/
|
|
21
|
+
export function parseRetainerConfig(v: Record<string, unknown>): RetainerConfig {
|
|
22
|
+
const raw = v.service_retainer;
|
|
23
|
+
if (raw === undefined || raw === null || String(raw).trim() === '') {
|
|
24
|
+
return { ok: false, code: 'service_retainer_absent' };
|
|
25
|
+
}
|
|
26
|
+
const n = Number(raw);
|
|
27
|
+
if (!Number.isFinite(n)) return { ok: false, code: 'service_retainer_unparseable' };
|
|
28
|
+
const cents = Math.round(n * 100);
|
|
29
|
+
if (cents < 0) return { ok: false, code: 'service_retainer_must_be_positive' };
|
|
30
|
+
if (cents === 0) {
|
|
31
|
+
const waived = v.retainer_waived === true || v.retainer_waived === 'true';
|
|
32
|
+
if (!waived) return { ok: false, code: 'service_retainer_must_be_positive' };
|
|
33
|
+
return { ok: true, cents: 0, waived: true };
|
|
34
|
+
}
|
|
35
|
+
return { ok: true, cents, waived: false };
|
|
36
|
+
}
|
package/src/ops.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
|
|
3
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
4
|
+
type Severity = 'info' | 'warning' | 'error';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* HARD CONTRACT: logOps NEVER THROWS. It returns
|
|
8
|
+
* `{ ok: true } | { ok: false, error }`; no caller may be written assuming it
|
|
9
|
+
* can throw. This is load-bearing, not stylistic: stripe-webhook's outer
|
|
10
|
+
* `catch` calls logOps BEFORE its `stripe_events` idempotency-ledger cleanup,
|
|
11
|
+
* so a throwing logOps would skip that cleanup, Stripe's retry would hit the
|
|
12
|
+
* ledger and receive `{received:true, duplicate:true}` / HTTP 200, and the
|
|
13
|
+
* event would be permanently and silently dropped on a money path.
|
|
14
|
+
*
|
|
15
|
+
* Every caller that emits a safeguard flag MUST check the returned `ok` and
|
|
16
|
+
* escalate on false — an unchecked emission is indistinguishable from
|
|
17
|
+
* "no problem found".
|
|
18
|
+
*/
|
|
19
|
+
export async function logOps(
|
|
20
|
+
supabase: SupabaseLike,
|
|
21
|
+
kind: string,
|
|
22
|
+
detail: Record<string, unknown> = {},
|
|
23
|
+
opts: { severity?: Severity; bookingId?: string | null; dedupeKey?: string | null } = {},
|
|
24
|
+
): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
25
|
+
const severity: Severity = opts.severity ?? 'error';
|
|
26
|
+
const bookingId = opts.bookingId ?? null;
|
|
27
|
+
// `||` not `??`: an empty-string dedupeKey is not a real key. Treated as one
|
|
28
|
+
// it would collide with itself under ops_events_dedupe_key_uidx and, via
|
|
29
|
+
// ON CONFLICT DO NOTHING, silently swallow every subsequent emission.
|
|
30
|
+
const dedupeKey = opts.dedupeKey || null;
|
|
31
|
+
let outcome: { ok: true } | { ok: false; error: string } = { ok: true };
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
console.error(JSON.stringify({ level: severity, kind, booking_id: bookingId, ...detail }));
|
|
35
|
+
} catch { /* ignore */ }
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
// Cast: the generated Database types are not wired into edge functions,
|
|
39
|
+
// so the insert payload widens to `never` without it.
|
|
40
|
+
// `dedupe_key` has a unique partial index (WHERE dedupe_key IS NOT NULL).
|
|
41
|
+
// A 23505 on it does NOT throw — supabase-js resolves with { error } for
|
|
42
|
+
// a Postgres error, so the try/catch below is irrelevant to it and the
|
|
43
|
+
// returned error must be inspected instead. Callers that pass a dedupeKey
|
|
44
|
+
// WANT the collision, so it is the success case (see below).
|
|
45
|
+
const { error } = await supabase.from('ops_events').insert({
|
|
46
|
+
kind,
|
|
47
|
+
severity,
|
|
48
|
+
booking_id: bookingId,
|
|
49
|
+
detail,
|
|
50
|
+
...(dedupeKey === null ? {} : { dedupe_key: dedupeKey }),
|
|
51
|
+
} as never);
|
|
52
|
+
// A dedupe_key collision under ops_events_dedupe_key_uidx is the SUCCESS
|
|
53
|
+
// case for a once-ever emission -- never report it as a failure.
|
|
54
|
+
if (error && (error as { code?: string }).code !== '23505') {
|
|
55
|
+
outcome = { ok: false, error: error.message };
|
|
56
|
+
}
|
|
57
|
+
} catch (e) { outcome = { ok: false, error: String(e) }; }
|
|
58
|
+
|
|
59
|
+
if (severity === 'error') {
|
|
60
|
+
const text = `:rotating_light: GC Connect *${kind}* — ${JSON.stringify(detail).slice(0, 500)}`;
|
|
61
|
+
|
|
62
|
+
const url = Deno.env.get('OPS_ALERT_WEBHOOK_URL');
|
|
63
|
+
if (url) {
|
|
64
|
+
try {
|
|
65
|
+
await fetch(url, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: { 'Content-Type': 'application/json' },
|
|
68
|
+
body: JSON.stringify({ text }),
|
|
69
|
+
});
|
|
70
|
+
} catch { /* ignore */ }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Slack fallback so error-severity events land somewhere staff actually
|
|
74
|
+
// look, not just an ops_events row. Same bot-token pattern the day-pass
|
|
75
|
+
// notifier already uses. No-op until OPS_ALERT_SLACK_CHANNEL_ID is set.
|
|
76
|
+
const slackToken = Deno.env.get('SLACK_BOT_TOKEN');
|
|
77
|
+
const slackChannel = Deno.env.get('OPS_ALERT_SLACK_CHANNEL_ID');
|
|
78
|
+
if (slackToken && slackChannel) {
|
|
79
|
+
try {
|
|
80
|
+
const res = await fetch('https://slack.com/api/chat.postMessage', {
|
|
81
|
+
method: 'POST',
|
|
82
|
+
headers: {
|
|
83
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
84
|
+
Authorization: `Bearer ${slackToken}`,
|
|
85
|
+
},
|
|
86
|
+
body: JSON.stringify({ channel: slackChannel, text }),
|
|
87
|
+
});
|
|
88
|
+
const body = await res.json().catch(() => null);
|
|
89
|
+
if (!body?.ok) {
|
|
90
|
+
console.warn('[ops] slack chat.postMessage failed:', body?.error ?? `http_${res.status}`);
|
|
91
|
+
}
|
|
92
|
+
} catch { /* ignore */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return outcome;
|
|
97
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Pacific-calendar date helpers, extracted from
|
|
2
|
+
// create-subscription-checkout/index.ts (plan v13 §2.4 header, round-3 S3-1).
|
|
3
|
+
//
|
|
4
|
+
// These were private, unexported functions inside that file, so the migration
|
|
5
|
+
// plan's claim of "reusing" them was impossible without either duplicating
|
|
6
|
+
// them (drift risk) or modifying that file. Resolution: extract all three —
|
|
7
|
+
// both functions AND the MAX_START_DATE_DAYS constant (round-4 S4-2) —
|
|
8
|
+
// verbatim into this module; create-subscription-checkout now imports them
|
|
9
|
+
// from here in place of its own copies. That is a PURE REFACTOR: identical
|
|
10
|
+
// bodies, identical comments, nothing that function does changes.
|
|
11
|
+
//
|
|
12
|
+
// The migration checkout functions (migration-checkout-confirm /
|
|
13
|
+
// migration-checkout-redirect, via _shared/migrationStartDate.ts) import from
|
|
14
|
+
// the same place, which is what makes §2.4's "no clamp-vs-validation conflict"
|
|
15
|
+
// property literally true rather than merely intended.
|
|
16
|
+
|
|
17
|
+
// Stripe Checkout requires subscription_data.billing_cycle_anchor to fall within
|
|
18
|
+
// one billing period from now. These plans are always billing_interval 'month',
|
|
19
|
+
// so 27 days is a safe margin under the shortest possible month.
|
|
20
|
+
export const MAX_START_DATE_DAYS = 27;
|
|
21
|
+
|
|
22
|
+
// The window check is done on Pacific CALENDAR DATE STRINGS, not on instants vs
|
|
23
|
+
// a raw millisecond offset -- zero-padded YYYY-MM-DD sorts lexicographically =
|
|
24
|
+
// chronologically, so the client (which offers the same Pacific calendar days)
|
|
25
|
+
// and the server agree by construction rather than by coincidence.
|
|
26
|
+
export function pacificDateStr(d: Date): string {
|
|
27
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
28
|
+
timeZone: 'America/Los_Angeles', year: 'numeric', month: '2-digit', day: '2-digit',
|
|
29
|
+
}).format(d); // yields "YYYY-MM-DD"
|
|
30
|
+
}
|
|
31
|
+
export function addDaysStr(dateStr: string, days: number): string {
|
|
32
|
+
const [y, m, d] = dateStr.split('-').map(Number);
|
|
33
|
+
return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
|
|
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
|
+
}
|