@simplelayer/graniteer-core 0.2.3 → 0.3.1

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 (36) hide show
  1. package/dist/agreementPortalEmail.js +10 -10
  2. package/dist/billingPortalLinkEmail.js +8 -8
  3. package/dist/bookingAgreementEmail.js +3 -3
  4. package/dist/checkoutSessionParams.d.ts +13 -0
  5. package/dist/checkoutSessionParams.js +38 -2
  6. package/dist/commonsDeposit.js +3 -3
  7. package/dist/dayPassConfirmation.js +7 -7
  8. package/dist/dunningEmails.js +5 -5
  9. package/dist/entitlements.d.ts +17 -0
  10. package/dist/entitlements.js +33 -0
  11. package/dist/functions/admin-cancel-membership.d.ts +3 -1
  12. package/dist/functions/admin-cancel-membership.js +9 -1
  13. package/dist/functions/admin-change-membership-plan.d.ts +3 -1
  14. package/dist/functions/admin-change-membership-plan.js +9 -1
  15. package/dist/functions/admin-create-booking.js +38 -8
  16. package/dist/functions/admin-onboard-connect-account.d.ts +47 -0
  17. package/dist/functions/admin-onboard-connect-account.js +197 -0
  18. package/dist/functions/admin-revoke-agreement.js +4 -4
  19. package/dist/functions/admin-undo-membership-cancel.d.ts +3 -1
  20. package/dist/functions/admin-undo-membership-cancel.js +9 -1
  21. package/dist/functions/create-day-pass-checkout.d.ts +2 -0
  22. package/dist/functions/create-day-pass-checkout.js +30 -1
  23. package/dist/functions/create-subscription-checkout.d.ts +3 -0
  24. package/dist/functions/create-subscription-checkout.js +11 -0
  25. package/dist/functions/stripe-db-reconcile.d.ts +4 -0
  26. package/dist/functions/stripe-db-reconcile.js +15 -3
  27. package/dist/functions/stripe-webhook.js +14 -0
  28. package/dist/functions/voice-membership-signup.d.ts +1 -0
  29. package/dist/functions/voice-membership-signup.js +4 -0
  30. package/dist/mailArrivalEmail.js +6 -6
  31. package/dist/membershipWelcome.js +26 -26
  32. package/dist/paymentLinkEmail.js +9 -9
  33. package/dist/printBilling.js +47 -47
  34. package/dist/signedUnpaidReminderEmail.js +9 -9
  35. package/dist/supportTicketEmail.js +7 -7
  36. package/package.json +9 -1
@@ -0,0 +1,197 @@
1
+ // Admin-triggered onboarding of a brand-new Stripe Connect account for a
2
+ // tenant: creates the Express account and immediately mints an Account Link
3
+ // for it in one request. There is no "link an existing account" flow here --
4
+ // see D33 Phase B.5.
5
+ //
6
+ // Auth/allowlist/rate-limit scaffold copied from admin-mint-billing-portal-link.
7
+ //
8
+ // IMPORTANT: this function intentionally does NOT persist the resulting
9
+ // account_id anywhere -- not in siteConfig, not in any table. It is returned
10
+ // in the JSON response only. Phase C adds a connectedAccountId field to
11
+ // siteConfig; until that lands, the caller is responsible for placing the id
12
+ // wherever it is needed. Do not "fix" this by adding a database write.
13
+ import { createClient } from '@supabase/supabase-js';
14
+ import Stripe from 'stripe';
15
+ import { jwtVerify, createRemoteJWKSet } from 'jose';
16
+ import { clientIp, checkRateLimit } from '../rateLimit.js';
17
+ import { logOps } from '../ops.js';
18
+ const corsHeaders = {
19
+ 'Access-Control-Allow-Origin': '*',
20
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
21
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
22
+ };
23
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
+ let jwksCache = null;
25
+ function getJwks(supabaseUrl) {
26
+ if (!jwksCache)
27
+ jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
28
+ return jwksCache;
29
+ }
30
+ async function verifyCaller(authHeader, supabaseUrl) {
31
+ if (!authHeader?.toLowerCase().startsWith('bearer '))
32
+ return null;
33
+ const token = authHeader.slice(7).trim();
34
+ try {
35
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
36
+ const claims = payload;
37
+ if (!claims.sub)
38
+ return null;
39
+ return claims;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ function json(status, body) {
46
+ return new Response(JSON.stringify(body), {
47
+ status,
48
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
49
+ });
50
+ }
51
+ /** Basic shape/sanity checks only -- Stripe does its own real validation. */
52
+ export function validateOnboardInput(raw) {
53
+ const body = (raw ?? {});
54
+ const tenantLabel = typeof body.tenant_label === 'string' ? body.tenant_label.trim() : '';
55
+ if (!tenantLabel || tenantLabel.length > 200) {
56
+ return { ok: false, error: 'invalid_tenant_label' };
57
+ }
58
+ const email = typeof body.email === 'string' ? body.email.trim() : '';
59
+ if (!email || !email.includes('@') || email.length > 320) {
60
+ return { ok: false, error: 'invalid_email' };
61
+ }
62
+ let country = 'US';
63
+ if (body.country !== undefined && body.country !== null) {
64
+ const rawCountry = typeof body.country === 'string' ? body.country : '';
65
+ if (!/^[A-Za-z]{2}$/.test(rawCountry)) {
66
+ return { ok: false, error: 'invalid_country' };
67
+ }
68
+ country = rawCountry.toUpperCase();
69
+ }
70
+ let businessType;
71
+ if (body.business_type !== undefined && body.business_type !== null) {
72
+ if (body.business_type !== 'individual' && body.business_type !== 'company') {
73
+ return { ok: false, error: 'invalid_business_type' };
74
+ }
75
+ businessType = body.business_type;
76
+ }
77
+ return { ok: true, value: { tenantLabel, email, country, businessType } };
78
+ }
79
+ /** accounts.create params, built conditionally so `business_type` is never
80
+ * passed as `undefined` -- the Stripe SDK rejects that key outright. */
81
+ export function buildStripeAccountCreateParams(input) {
82
+ return {
83
+ type: 'express',
84
+ country: input.country,
85
+ email: input.email,
86
+ ...(input.businessType ? { business_type: input.businessType } : {}),
87
+ capabilities: {
88
+ card_payments: { requested: true },
89
+ transfers: { requested: true },
90
+ },
91
+ };
92
+ }
93
+ export async function handleOnboardConnectAccount(rawBody, actorEmail, domain, deps) {
94
+ const validated = validateOnboardInput(rawBody);
95
+ if (!validated.ok) {
96
+ return { status: 400, body: { ok: false, error: validated.error } };
97
+ }
98
+ const input = validated.value;
99
+ let account;
100
+ try {
101
+ account = await deps.stripe.accounts.create(buildStripeAccountCreateParams(input));
102
+ }
103
+ catch (e) {
104
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
105
+ await deps.log('admin_connect_account_create_failed', {
106
+ tenant_label: input.tenantLabel, actor_email: actorEmail, message: detail,
107
+ }, 'error');
108
+ return { status: 502, body: { ok: false, error: 'account_create_failed', detail } };
109
+ }
110
+ let accountLink;
111
+ try {
112
+ accountLink = await deps.stripe.accountLinks.create({
113
+ account: account.id,
114
+ refresh_url: `https://${domain}/admin/connect-onboarding-refresh?account=${account.id}`,
115
+ return_url: `https://${domain}/admin/connect-onboarding-complete?account=${account.id}`,
116
+ type: 'account_onboarding',
117
+ });
118
+ }
119
+ catch (e) {
120
+ const detail = (e instanceof Error ? e.message : String(e)).slice(0, 500);
121
+ // The account already exists in Stripe even though the link mint failed --
122
+ // surface its id so it is not lost, rather than dropping it on the floor.
123
+ await deps.log('admin_connect_account_link_failed', {
124
+ tenant_label: input.tenantLabel, actor_email: actorEmail, account_id: account.id, message: detail,
125
+ }, 'error');
126
+ return {
127
+ status: 502,
128
+ body: { ok: false, error: 'account_link_unavailable', account_id: account.id, detail },
129
+ };
130
+ }
131
+ await deps.log('admin_connect_account_onboarded', {
132
+ tenant_label: input.tenantLabel, actor_email: actorEmail, account_id: account.id,
133
+ }, 'info');
134
+ // NOT persisted anywhere on purpose -- no siteConfig write, no table insert
135
+ // of account.id above this line. It only ever leaves this function in the
136
+ // response body; see the file header for why.
137
+ return {
138
+ status: 200,
139
+ body: {
140
+ ok: true,
141
+ account_id: account.id,
142
+ onboarding_url: accountLink.url,
143
+ expires_at: accountLink.expires_at,
144
+ },
145
+ };
146
+ }
147
+ // ---8<--- END onboard-core (mirrored verbatim in admin-onboard-connect-account.test.ts) ---8<---
148
+ export async function handle(req, operator) {
149
+ if (req.method === 'OPTIONS')
150
+ return new Response('ok', { headers: corsHeaders });
151
+ if (req.method !== 'POST')
152
+ return json(405, { ok: false, error: 'method_not_allowed' });
153
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
154
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
155
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
156
+ if (!stripeKey)
157
+ return json(500, { ok: false, error: 'stripe_not_configured' });
158
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
159
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
160
+ if (!caller)
161
+ return json(401, { ok: false, error: 'unauthenticated' });
162
+ if (caller.aal !== 'aal2')
163
+ return json(403, { ok: false, error: 'mfa_required' });
164
+ const callerEmail = (caller.email ?? '').toLowerCase();
165
+ if (!callerEmail)
166
+ return json(403, { ok: false, error: 'no_email' });
167
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
168
+ auth: { persistSession: false, autoRefreshToken: false },
169
+ });
170
+ const [ipOk, emailOk] = await Promise.all([
171
+ checkRateLimit(admin, 'admin-onboard-connect-ip', clientIp(req), 60, 300),
172
+ checkRateLimit(admin, 'admin-onboard-connect-email', callerEmail, 40, 300),
173
+ ]);
174
+ if (!ipOk || !emailOk)
175
+ return json(429, { ok: false, error: 'rate_limited' });
176
+ const { data: allow, error: allowErr } = await admin
177
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
178
+ if (allowErr)
179
+ return json(500, { ok: false, error: 'allowlist_lookup_failed' });
180
+ if (!allow)
181
+ return json(403, { ok: false, error: 'not_authorized' });
182
+ let body;
183
+ try {
184
+ body = await req.json();
185
+ }
186
+ catch {
187
+ return json(400, { ok: false, error: 'invalid_json' });
188
+ }
189
+ // Always the platform's own key: accounts.create is a platform-level call,
190
+ // never scoped to a connected account, so no `stripeAccount` request option.
191
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
192
+ const result = await handleOnboardConnectAccount(body, callerEmail, operator.domain, {
193
+ stripe: stripe,
194
+ log: (kind, detail, severity) => logOps(admin, kind, detail, { severity }).catch(() => { }),
195
+ });
196
+ return json(result.status, result.body);
197
+ }
@@ -312,10 +312,10 @@ export async function handle(req, operator) {
312
312
  try {
313
313
  const { data: row, error: rowErr } = await admin
314
314
  .from('signature_documents')
315
- .select(`id,status,boldsign_document_id,boldsign_template_id,document_type,signer_name,signer_email,field_values,flow,start_date,
316
- stripe_checkout_url,stripe_checkout_session_id,stripe_customer_id,stripe_issued_at,stripe_subscription_id,
317
- retainer_paid_at,retainer_payment_intent_id,retainer_terms_accepted_at,retainer_setup_intent_id,retainer_intent_kind,
318
- retainer_attempt_count,subscription_attempt_count,subscription_error,client_signed_at,payment_link_email_sent_at,
315
+ .select(`id,status,boldsign_document_id,boldsign_template_id,document_type,signer_name,signer_email,field_values,flow,start_date,
316
+ stripe_checkout_url,stripe_checkout_session_id,stripe_customer_id,stripe_issued_at,stripe_subscription_id,
317
+ retainer_paid_at,retainer_payment_intent_id,retainer_terms_accepted_at,retainer_setup_intent_id,retainer_intent_kind,
318
+ retainer_attempt_count,subscription_attempt_count,subscription_error,client_signed_at,payment_link_email_sent_at,
319
319
  portal_issued_at,portal_token_revoked_at,activation_started_at`)
320
320
  .eq('id', docId)
321
321
  .maybeSingle();
@@ -1 +1,3 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -2,6 +2,7 @@ import { createClient } from '@supabase/supabase-js';
2
2
  import Stripe from 'stripe';
3
3
  import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
+ import { hasEntitlement } from '../entitlements.js';
5
6
  const corsHeaders = {
6
7
  'Access-Control-Allow-Origin': '*',
7
8
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -35,7 +36,11 @@ function json(status, body) {
35
36
  headers: { ...corsHeaders, 'Content-Type': 'application/json' },
36
37
  });
37
38
  }
38
- export async function handle(req) {
39
+ // D33 Phase E.1: no per-deployment operator object was wired into this
40
+ // function before now. Optional and defaulted so every existing caller --
41
+ // whether or not it passes a second argument -- is unaffected: an absent
42
+ // planId resolves to the full-featured legacy plan.
43
+ export async function handle(req, operator = {}) {
39
44
  if (req.method === 'OPTIONS')
40
45
  return new Response('ok', { headers: corsHeaders });
41
46
  if (req.method !== 'POST')
@@ -66,6 +71,9 @@ export async function handle(req) {
66
71
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
67
72
  if (!allow)
68
73
  return json(403, { ok: false, error: 'not_authorized' });
74
+ if (!hasEntitlement(operator, 'membership')) {
75
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'membership' });
76
+ }
69
77
  let body;
70
78
  try {
71
79
  body = await req.json();
@@ -1,4 +1,6 @@
1
1
  export declare function handle(req: Request, operator: {
2
2
  domain: string;
3
3
  actorEmail: string;
4
+ stripeConnectedAccountId?: string | null;
5
+ stripeApplicationFeePercent?: number | null;
4
6
  }): Promise<Response>;
@@ -5,7 +5,7 @@ import { z } from 'zod';
5
5
  import { clientIp, checkRateLimit } from '../rateLimit.js';
6
6
  import { logOps } from '../ops.js';
7
7
  import { applyCheckoutCoupon, couponFailureBody, reverseCheckoutCoupon } from '../checkoutCoupon.js';
8
- import { buildDayPassSessionParams } from '../checkoutSessionParams.js';
8
+ import { buildDayPassSessionParams, computeApplicationFeeCents } from '../checkoutSessionParams.js';
9
9
  const Body = z.object({
10
10
  plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
11
11
  email: z.string().email().max(255),
@@ -164,6 +164,33 @@ export async function handle(req, operator) {
164
164
  // this is what correlates that row back to this checkout attempt.
165
165
  ...(couponAttemptId ? { coupon_attempt_id: couponAttemptId } : {}),
166
166
  };
167
+ // === Optional Stripe Connect fee split ===
168
+ // A one-time payment takes a FIXED cents fee, so unlike the subscription
169
+ // path this needs the amount Stripe will actually charge -- price_cents can
170
+ // be stale. Only a tenant that supplies BOTH Connect fields pays for that
171
+ // extra retrieve; the platform account skips this block entirely and its
172
+ // session params stay byte-identical to the pre-Connect shape. Deliberately
173
+ // independent of the coupon branch's retrieve above: the fee is needed
174
+ // whether or not a coupon was used, and duplicating one call on the rare
175
+ // tenant path beats restructuring the coupon logic.
176
+ let applicationFeeCents = null;
177
+ if (operator.stripeConnectedAccountId && operator.stripeApplicationFeePercent) {
178
+ try {
179
+ const feePrice = await stripe.prices.retrieve(plan.stripe_price_id);
180
+ const baseAmountCents = feePrice.unit_amount ?? null;
181
+ if (baseAmountCents === null) {
182
+ console.warn('[create-day-pass-checkout] connect fee: price has no unit_amount, omitting fee', { price_id: plan.stripe_price_id });
183
+ }
184
+ else {
185
+ applicationFeeCents = computeApplicationFeeCents(baseAmountCents, operator.stripeApplicationFeePercent);
186
+ }
187
+ }
188
+ catch (e) {
189
+ // Never block a tenant's checkout on a fee-computation hiccup -- fall
190
+ // back to no fee fields, exactly as if Connect were not configured.
191
+ console.warn('[create-day-pass-checkout] connect fee: prices.retrieve failed, omitting fee', e);
192
+ }
193
+ }
167
194
  const session = await stripe.checkout.sessions.create(buildDayPassSessionParams({
168
195
  customerId,
169
196
  priceId: plan.stripe_price_id,
@@ -172,6 +199,8 @@ export async function handle(req, operator) {
172
199
  successUrl: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
173
200
  cancelUrl: `${base}/pricing`,
174
201
  stripeCouponId,
202
+ applicationFeeCents,
203
+ connectedAccountId: operator.stripeConnectedAccountId,
175
204
  }));
176
205
  return new Response(JSON.stringify({ url: session.url }), {
177
206
  headers: { ...corsHeaders, 'Content-Type': 'application/json' },
@@ -1,4 +1,7 @@
1
1
  export declare function handle(req: Request, operator: {
2
2
  domain: string;
3
3
  actorEmail: string;
4
+ stripeConnectedAccountId?: string | null;
5
+ stripeApplicationFeePercent?: number | null;
6
+ planId?: string | null;
4
7
  }): Promise<Response>;
@@ -4,6 +4,7 @@ import Stripe from 'stripe';
4
4
  import { z } from 'zod';
5
5
  import { clientIp, checkRateLimit } from '../rateLimit.js';
6
6
  import { logOps } from '../ops.js';
7
+ import { hasEntitlement } from '../entitlements.js';
7
8
  import { applyCheckoutCoupon, couponFailureBody, reverseCheckoutCoupon, COUPON_START_DATE_CONFLICT_MESSAGE, } from '../checkoutCoupon.js';
8
9
  import { buildSubscriptionSessionParams } from '../checkoutSessionParams.js';
9
10
  // Extracted verbatim (bodies and comments) to _shared/pacificDate.ts so the
@@ -74,6 +75,11 @@ function laOffsetMinutes(at) {
74
75
  export async function handle(req, operator) {
75
76
  if (req.method === 'OPTIONS')
76
77
  return new Response('ok', { headers: corsHeaders });
78
+ if (!hasEntitlement(operator, 'membership')) {
79
+ return new Response(JSON.stringify({ ok: false, error: 'feature_not_enabled', feature: 'membership' }), {
80
+ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
81
+ });
82
+ }
77
83
  // Set once a coupon reservation exists. Held at handler scope so the outer
78
84
  // catch can release it if anything after the reservation throws -- otherwise
79
85
  // a single-use code stays consumed by a checkout that never started.
@@ -370,6 +376,11 @@ export async function handle(req, operator) {
370
376
  : `${base}/membership/success?session_id={CHECKOUT_SESSION_ID}`,
371
377
  cancelUrl: `${base}/pricing`,
372
378
  stripeCouponId,
379
+ // Stripe's application_fee_percent is already a percentage of each
380
+ // invoice, so there is nothing to compute and no extra Stripe call. The
381
+ // builder emits neither field unless both are present.
382
+ applicationFeePercent: operator.stripeApplicationFeePercent,
383
+ connectedAccountId: operator.stripeConnectedAccountId,
373
384
  }));
374
385
  return new Response(JSON.stringify({ url: session.url }), {
375
386
  headers: { ...corsHeaders, 'Content-Type': 'application/json' },
@@ -1,3 +1,7 @@
1
+ export declare function buildStripeRequestOptions(connectedAccountId: string | null | undefined): {
2
+ stripeAccount: string;
3
+ } | undefined;
1
4
  export declare function handle(req: Request, operator: {
2
5
  stripeAccountLabel: string;
6
+ connectedAccountId?: string | null;
3
7
  }): Promise<Response>;
@@ -60,6 +60,17 @@ function periodEndDrift(stripeISO, dbISO) {
60
60
  return true;
61
61
  return Math.abs(new Date(stripeISO).getTime() - new Date(dbISO).getTime()) > 120_000;
62
62
  }
63
+ // Phase B.4 scaffold: scopes this reconciler's own Stripe reads to a
64
+ // tenant's connected account when one is configured. This assumes a
65
+ // Direct-charge Connect model where the tenant's subscriptions/checkout
66
+ // sessions live on their OWN connected account -- if Phase D's actual
67
+ // implementation instead uses Destination charges (objects stay on the
68
+ // platform account, only a transfer/application_fee references the
69
+ // connected account), this scoping will need to change before it's ever
70
+ // turned on for a real tenant. Not yet exercised by any live deployment.
71
+ export function buildStripeRequestOptions(connectedAccountId) {
72
+ return connectedAccountId ? { stripeAccount: connectedAccountId } : undefined;
73
+ }
63
74
  export async function handle(req, operator) {
64
75
  if (req.method !== 'POST' && req.method !== 'GET') {
65
76
  return new Response('Method not allowed', { status: 405 });
@@ -92,11 +103,12 @@ export async function handle(req, operator) {
92
103
  if (!stripeKey)
93
104
  return new Response('Not configured', { status: 500 });
94
105
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
106
+ const stripeOpts = buildStripeRequestOptions(operator.connectedAccountId);
95
107
  const drift = [];
96
108
  const push = (kind, severity, extra) => drift.push({ kind, severity, ...extra });
97
109
  try {
98
110
  const stripeSubs = [];
99
- for await (const sub of stripe.subscriptions.list({ status: 'all', limit: 100 })) {
111
+ for await (const sub of stripe.subscriptions.list({ status: 'all', limit: 100 }, stripeOpts)) {
100
112
  stripeSubs.push(sub);
101
113
  }
102
114
  const subById = new Map(stripeSubs.map((s) => [s.id, s]));
@@ -178,7 +190,7 @@ export async function handle(req, operator) {
178
190
  }
179
191
  const sinceTs = Math.floor(Date.now() / 1000) - WINDOW_DAYS * 86400;
180
192
  const paidSessions = [];
181
- for await (const s of stripe.checkout.sessions.list({ created: { gte: sinceTs }, limit: 100 })) {
193
+ for await (const s of stripe.checkout.sessions.list({ created: { gte: sinceTs }, limit: 100 }, stripeOpts)) {
182
194
  if (s.mode === 'payment' && s.payment_status === 'paid')
183
195
  paidSessions.push(s);
184
196
  }
@@ -214,7 +226,7 @@ export async function handle(req, operator) {
214
226
  const piId = typeof s.payment_intent === 'string' ? s.payment_intent : s.payment_intent?.id ?? null;
215
227
  if (piId) {
216
228
  try {
217
- const pi = await stripe.paymentIntents.retrieve(piId, { expand: ['latest_charge'] });
229
+ const pi = await stripe.paymentIntents.retrieve(piId, { expand: ['latest_charge'] }, stripeOpts);
218
230
  const charge = pi.latest_charge;
219
231
  const stripeRefunded = !!charge && (charge.refunded === true || (charge.amount_refunded ?? 0) > 0);
220
232
  if (stripeRefunded && !dp.refunded_at) {
@@ -1369,6 +1369,20 @@ export function createStripeWebhookHandler(config) {
1369
1369
  return true;
1370
1370
  return false;
1371
1371
  }
1372
+ if (event.account) {
1373
+ // Phase B.3 scaffold: Stripe Connect events arriving from a connected
1374
+ // account (this endpoint's own "Listen to events on Connected
1375
+ // accounts" setting). No connected accounts are onboarded yet
1376
+ // (Phase C/D), and none of the platform-only business logic below
1377
+ // (memberships, referrals, day passes, bookings, touch pass, office
1378
+ // assignments) applies to a connected account's own object graph.
1379
+ // Route these additively, without touching anything else in this
1380
+ // file: log for visibility, then return 200 immediately.
1381
+ await logOps(supabase, 'stripe_connect_event_received', { event_id: event.id, event_type: event.type, connected_account_id: event.account }, { severity: 'info' }).catch(() => { });
1382
+ return new Response(JSON.stringify({ received: true, connect_event: true }), {
1383
+ headers: { 'Content-Type': 'application/json' }, status: 200,
1384
+ });
1385
+ }
1372
1386
  try {
1373
1387
  switch (event.type) {
1374
1388
  case 'checkout.session.completed': {
@@ -11,5 +11,6 @@ export type VoiceMembershipSignupConfig = {
11
11
  businessName: string;
12
12
  /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
13
13
  supportPhoneDisplay: string;
14
+ planId?: string | null;
14
15
  };
15
16
  export declare function handle(req: Request, config: VoiceMembershipSignupConfig): Promise<Response>;
@@ -11,6 +11,7 @@ import { createClient } from '@supabase/supabase-js';
11
11
  import { z } from 'zod';
12
12
  import { logOps } from '../ops.js';
13
13
  import { verifyRetellSignature } from '../retellSignature.js';
14
+ import { hasEntitlement } from '../entitlements.js';
14
15
  const Body = z.object({
15
16
  // `.trim()` matches create-subscription-checkout's own `name` schema, which
16
17
  // this is forwarded to verbatim — a whitespace-only name would otherwise
@@ -183,6 +184,9 @@ export async function handle(req, config) {
183
184
  if (!config.sellablePlanSlugs.includes(plan_slug)) {
184
185
  return json(400, { ok: false, error: 'invalid_request' });
185
186
  }
187
+ if (!hasEntitlement(config, 'membership')) {
188
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'membership' });
189
+ }
186
190
  const supabaseUrl = Deno.env.get('SUPABASE_URL');
187
191
  const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
188
192
  const supabase = createClient(supabaseUrl, serviceKey);
@@ -74,12 +74,12 @@ export async function sendMailArrivalEmail(supabase, email, mailItemId, descript
74
74
  const detailLine = trimmed
75
75
  ? p(`Staff noted: <strong>${esc(trimmed)}</strong>`)
76
76
  : '';
77
- 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">
78
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
79
- ${p(`An item arrived for you and is being held at the front desk. Stop by during staffed hours to pick it up.`)}
80
- ${detailLine}
81
- ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
82
- <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
77
+ 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">
78
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
79
+ ${p(`An item arrived for you and is being held at the front desk. Stop by during staffed hours to pick it up.`)}
80
+ ${detailLine}
81
+ ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
82
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
83
83
  </td></tr></table></td></tr></table></div>`;
84
84
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
85
85
  method: 'POST', headers,
@@ -238,18 +238,18 @@ export async function sendMembershipWelcome(supabase, email, planId, customerNam
238
238
  : '';
239
239
  // Host hours come from app_settings, never hardcoded here.
240
240
  const hostHoursCard = await buildHostHoursCard(supabase, groups, card, p, config.hostHours);
241
- 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">
242
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.shortName} — your access is being set up</h2>
243
- ${p(`Hi ${esc(greetingName)},`)}
244
- ${p(`Thanks for joining us. You're all set on <strong>${esc(planLine)}</strong>.`)}
241
+ 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">
242
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.shortName} — your access is being set up</h2>
243
+ ${p(`Hi ${esc(greetingName)},`)}
244
+ ${p(`Thanks for joining us. You're all set on <strong>${esc(planLine)}</strong>.`)}
245
245
  ${startsOnLabel
246
246
  ? p(`<strong>Your membership starts ${esc(startsOnLabel)}.</strong> Nothing is charged today, and your door and WiFi access will be set up on that date — not before.`)
247
- : p('<strong>Your door and WiFi access is being set up right now — it usually takes a few minutes.</strong> Nothing is wrong if you don\'t have access the moment you finish reading this.')}
248
- ${p('<strong>You\'ll get a separate email inviting you to an app called UniFi Endpoint. That invitation is from us — it\'s how you unlock the door with your phone.</strong> It arrives with Ubiquiti branding, so please don\'t delete it as spam.')}
249
- <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${doorCard}${wifiCard}${hostHoursCard}</table>
250
- ${p(`We're at ${esc(address)}.`)}
251
- ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
252
- <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name} · ${esc(address)}</p>
247
+ : p('<strong>Your door and WiFi access is being set up right now — it usually takes a few minutes.</strong> Nothing is wrong if you don\'t have access the moment you finish reading this.')}
248
+ ${p('<strong>You\'ll get a separate email inviting you to an app called UniFi Endpoint. That invitation is from us — it\'s how you unlock the door with your phone.</strong> It arrives with Ubiquiti branding, so please don\'t delete it as spam.')}
249
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${doorCard}${wifiCard}${hostHoursCard}</table>
250
+ ${p(`We're at ${esc(address)}.`)}
251
+ ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
252
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name} · ${esc(address)}</p>
253
253
  </td></tr></table></td></tr></table></div>`;
254
254
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
255
255
  method: 'POST', headers,
@@ -376,14 +376,14 @@ export async function sendPrivateOfficeWelcome(supabase, email, name, plan, conf
376
376
  }
377
377
  billingCard = card('Your billing', lines.join(''));
378
378
  }
379
- 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">
380
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.name} — here's what's next</h2>
381
- ${p(`Hi ${esc(greetingName)},`)}
382
- ${p(`You're all set — welcome to ${operator.name}. We're glad to have you as part of the community.`)}
383
- <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${nextCard}${billingCard}</table>
384
-
385
- ${p(`If anything's unclear or you need something before you move in, just reply here or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a> — we're happy to help.`)}
386
- ${p(`Welcome again,<br>The ${operator.name} team`)}
379
+ 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">
380
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Welcome to ${operator.name} — here's what's next</h2>
381
+ ${p(`Hi ${esc(greetingName)},`)}
382
+ ${p(`You're all set — welcome to ${operator.name}. We're glad to have you as part of the community.`)}
383
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${nextCard}${billingCard}</table>
384
+
385
+ ${p(`If anything's unclear or you need something before you move in, just reply here or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a> — we're happy to help.`)}
386
+ ${p(`Welcome again,<br>The ${operator.name} team`)}
387
387
  </td></tr></table></td></tr></table></div>`;
388
388
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
389
389
  method: 'POST', headers,
@@ -465,14 +465,14 @@ export async function sendTeamSeatWelcome(supabase, email, name, companyName, pl
465
465
  const companyLine = companyName && companyName.trim()
466
466
  ? `You've been added as a team member on <strong>${esc(companyName.trim())}</strong>'s membership at ${esc(operator.shortName)}.`
467
467
  : `You've been added as a team member on your company's membership at ${esc(operator.shortName)}.`;
468
- 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">
469
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">You've been added as a team member</h2>
470
- ${p(`Hi ${esc(greetingName)},`)}
471
- ${p(companyLine)}
472
- ${p(`<strong>Setting up your login:</strong> go to <a href="https://${operator.domain}/portal/login" style="color:#C98A5E">${operator.domain}/portal/login</a> and enter this email address (${esc(email)}). We'll email you a sign-in link — there's no password to remember.`)}
473
- ${p('<strong>Door and WiFi access:</strong> if your seat includes it, access is being set up now and can take a little while to go live. You may also receive a separate invite to an app called <strong>UniFi Endpoint</strong> — that\'s from us, and it\'s how you unlock the door with your phone.')}
474
- ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
475
- <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
468
+ 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">
469
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">You've been added as a team member</h2>
470
+ ${p(`Hi ${esc(greetingName)},`)}
471
+ ${p(companyLine)}
472
+ ${p(`<strong>Setting up your login:</strong> go to <a href="https://${operator.domain}/portal/login" style="color:#C98A5E">${operator.domain}/portal/login</a> and enter this email address (${esc(email)}). We'll email you a sign-in link — there's no password to remember.`)}
473
+ ${p('<strong>Door and WiFi access:</strong> if your seat includes it, access is being set up now and can take a little while to go live. You may also receive a separate invite to an app called <strong>UniFi Endpoint</strong> — that\'s from us, and it\'s how you unlock the door with your phone.')}
474
+ ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
475
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
476
476
  </td></tr></table></td></tr></table></div>`;
477
477
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
478
478
  method: 'POST', headers,
@@ -69,15 +69,15 @@ export async function sendPaymentLinkEmail(supabase, { email, name, checkoutUrl,
69
69
  const p = (t) => `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
70
70
  const office = (officeNumber || '').trim();
71
71
  const officeClause = office ? ` for office ${esc(office)}` : '';
72
- 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">
73
- <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>
74
- ${p(`Hi ${esc(greetingName)},`)}
75
- ${p(`Thanks for signing your ${operator.name} office agreement${officeClause} — you're one step from locked in.`)}
76
- ${p('The last step is setting up your monthly payment. Use the link below to add a payment method and start your subscription:')}
77
- ${p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Set up payment →</a>`)}
78
- ${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.')}
79
- ${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>.`)}
80
- ${p(`Welcome aboard,<br />The ${operator.name} team`)}
72
+ 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">
73
+ <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>
74
+ ${p(`Hi ${esc(greetingName)},`)}
75
+ ${p(`Thanks for signing your ${operator.name} office agreement${officeClause} — you're one step from locked in.`)}
76
+ ${p('The last step is setting up your monthly payment. Use the link below to add a payment method and start your subscription:')}
77
+ ${p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Set up payment →</a>`)}
78
+ ${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.')}
79
+ ${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>.`)}
80
+ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
81
81
  </td></tr></table></td></tr></table></div>`;
82
82
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
83
83
  method: 'POST', headers,