@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
@@ -73,16 +73,16 @@ export async function sendAgreementPortalEmail(supabase, { email, name, portalUr
73
73
  const office = (officeNumber || '').trim();
74
74
  const officeClause = office ? ` for office ${esc(office)}` : '';
75
75
  const subject = `Your ${operator.shortName} private office agreement is ready — review and pay your retainer`;
76
- 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">
77
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your ${operator.shortName} private office agreement is ready</h2>
78
- ${p(`Hi ${esc(greetingName)},`)}
79
- ${p(`Your ${operator.name} private office agreement${officeClause} is ready to review. There are two quick steps to get you moved in.`)}
80
- ${p('<strong>1. Review your terms and pay your service retainer.</strong> Open your secure agreement portal:')}
81
- ${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Review and pay your retainer →</a>`)}
82
- ${p('<strong>2. Sign your agreement.</strong> BoldSign is sending you a separate email with the signing link — watch for it in your inbox (check spam if you don\'t see it shortly).')}
83
- ${p('Your monthly billing starts only after both steps are complete. This portal link is unique to your agreement, so please don\'t forward it.')}
84
- ${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>.`)}
85
- ${p(`Welcome aboard,<br />The ${operator.name} team`)}
76
+ 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">
77
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your ${operator.shortName} private office agreement is ready</h2>
78
+ ${p(`Hi ${esc(greetingName)},`)}
79
+ ${p(`Your ${operator.name} private office agreement${officeClause} is ready to review. There are two quick steps to get you moved in.`)}
80
+ ${p('<strong>1. Review your terms and pay your service retainer.</strong> Open your secure agreement portal:')}
81
+ ${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Review and pay your retainer →</a>`)}
82
+ ${p('<strong>2. Sign your agreement.</strong> BoldSign is sending you a separate email with the signing link — watch for it in your inbox (check spam if you don\'t see it shortly).')}
83
+ ${p('Your monthly billing starts only after both steps are complete. This portal link is unique to your agreement, so please don\'t forward it.')}
84
+ ${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>.`)}
85
+ ${p(`Welcome aboard,<br />The ${operator.name} team`)}
86
86
  </td></tr></table></td></tr></table></div>`;
87
87
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
88
88
  method: 'POST', headers,
@@ -66,14 +66,14 @@ export async function sendBillingPortalLinkEmail(supabase, { email, name, portal
66
66
  if (!contactId)
67
67
  throw new Error('ghl_upsert_no_contact_id');
68
68
  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>`;
69
- 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">
70
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Update your ${operator.shortName} billing details</h2>
71
- ${p(`Hi ${esc(greetingName)},`)}
72
- ${p(`Our team wanted to make it easy for you to update the payment method on your ${operator.name} membership. Use the secure link below:`)}
73
- ${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Update payment method →</a>`)}
74
- ${p("This link is unique to your account and takes you straight to our payment processor, Stripe, where you can update your card, view invoices, and manage your subscription. Please don't forward it.")}
75
- ${p(`Questions? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
76
- ${p(`Thanks,<br />The ${operator.name} team`)}
69
+ 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">
70
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Update your ${operator.shortName} billing details</h2>
71
+ ${p(`Hi ${esc(greetingName)},`)}
72
+ ${p(`Our team wanted to make it easy for you to update the payment method on your ${operator.name} membership. Use the secure link below:`)}
73
+ ${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Update payment method →</a>`)}
74
+ ${p("This link is unique to your account and takes you straight to our payment processor, Stripe, where you can update your card, view invoices, and manage your subscription. Please don't forward it.")}
75
+ ${p(`Questions? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
76
+ ${p(`Thanks,<br />The ${operator.name} team`)}
77
77
  </td></tr></table></td></tr></table></div>`;
78
78
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
79
79
  method: 'POST', headers,
@@ -57,9 +57,9 @@ async function sendViaGhl(supabase, opts) {
57
57
  const contactId = upJson.contact?.id || upJson.id || null;
58
58
  if (!contactId)
59
59
  throw new Error('ghl_upsert_no_contact_id');
60
- 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">
61
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
62
- ${opts.body(esc(greetingName))}
60
+ 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">
61
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
62
+ ${opts.body(esc(greetingName))}
63
63
  </td></tr></table></td></tr></table></div>`;
64
64
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
65
65
  method: 'POST', headers,
@@ -1,4 +1,13 @@
1
1
  import type Stripe from 'stripe';
2
+ /**
3
+ * Application fee in whole cents for a `feePercent` share of `baseCents`.
4
+ *
5
+ * A `feePercent` of 0, null or undefined means "no fee" and returns 0, so a
6
+ * caller can feed the result straight into a truthiness check to decide
7
+ * whether to emit the Connect fields at all. Stripe only accepts an integer
8
+ * cents amount, so the product is rounded half-up.
9
+ */
10
+ export declare function computeApplicationFeeCents(baseCents: number, feePercent: number | null | undefined): number;
2
11
  export declare function buildSubscriptionSessionParams(input: {
3
12
  customerId: string;
4
13
  lineItem: Stripe.Checkout.SessionCreateParams.LineItem;
@@ -7,6 +16,8 @@ export declare function buildSubscriptionSessionParams(input: {
7
16
  successUrl: string;
8
17
  cancelUrl: string;
9
18
  stripeCouponId: string | null;
19
+ applicationFeePercent?: number | null;
20
+ connectedAccountId?: string | null;
10
21
  }): Stripe.Checkout.SessionCreateParams;
11
22
  export declare function buildDayPassSessionParams(input: {
12
23
  customerId: string;
@@ -16,4 +27,6 @@ export declare function buildDayPassSessionParams(input: {
16
27
  successUrl: string;
17
28
  cancelUrl: string;
18
29
  stripeCouponId: string | null;
30
+ applicationFeeCents?: number | null;
31
+ connectedAccountId?: string | null;
19
32
  }): Stripe.Checkout.SessionCreateParams;
@@ -6,7 +6,35 @@
6
6
  // `discounts` and `allow_promotion_codes`. With no internal coupon we keep the
7
7
  // pre-existing `allow_promotion_codes: true` and emit no `discounts` key at
8
8
  // all; with one we do the exact opposite.
9
+ //
10
+ // The Stripe Connect fee split follows the same shape: the fee fields appear
11
+ // ONLY when a tenant supplies both a connected account and a non-zero fee. The
12
+ // platform account's own checkouts pass neither, so they take the untouched
13
+ // pre-Connect path -- an account is never charged an application fee on itself.
14
+ /**
15
+ * Application fee in whole cents for a `feePercent` share of `baseCents`.
16
+ *
17
+ * A `feePercent` of 0, null or undefined means "no fee" and returns 0, so a
18
+ * caller can feed the result straight into a truthiness check to decide
19
+ * whether to emit the Connect fields at all. Stripe only accepts an integer
20
+ * cents amount, so the product is rounded half-up.
21
+ */
22
+ export function computeApplicationFeeCents(baseCents, feePercent) {
23
+ if (!feePercent || !Number.isFinite(feePercent))
24
+ return 0;
25
+ if (!Number.isFinite(baseCents))
26
+ return 0;
27
+ return Math.round((baseCents * feePercent) / 100);
28
+ }
9
29
  export function buildSubscriptionSessionParams(input) {
30
+ const { applicationFeePercent, connectedAccountId } = input;
31
+ const subscriptionData = applicationFeePercent && connectedAccountId
32
+ ? {
33
+ ...input.subscriptionData,
34
+ application_fee_percent: applicationFeePercent,
35
+ transfer_data: { destination: connectedAccountId },
36
+ }
37
+ : input.subscriptionData;
10
38
  return {
11
39
  mode: 'subscription',
12
40
  customer: input.customerId,
@@ -15,12 +43,20 @@ export function buildSubscriptionSessionParams(input) {
15
43
  ? { discounts: [{ coupon: input.stripeCouponId }] }
16
44
  : { allow_promotion_codes: true }),
17
45
  metadata: input.metadata,
18
- subscription_data: input.subscriptionData,
46
+ subscription_data: subscriptionData,
19
47
  success_url: input.successUrl,
20
48
  cancel_url: input.cancelUrl,
21
49
  };
22
50
  }
23
51
  export function buildDayPassSessionParams(input) {
52
+ const { applicationFeeCents, connectedAccountId } = input;
53
+ const paymentIntentData = applicationFeeCents && connectedAccountId
54
+ ? {
55
+ receipt_email: input.receiptEmail,
56
+ application_fee_amount: applicationFeeCents,
57
+ transfer_data: { destination: connectedAccountId },
58
+ }
59
+ : { receipt_email: input.receiptEmail };
24
60
  return {
25
61
  mode: 'payment',
26
62
  customer: input.customerId,
@@ -29,7 +65,7 @@ export function buildDayPassSessionParams(input) {
29
65
  ? { discounts: [{ coupon: input.stripeCouponId }] }
30
66
  : { allow_promotion_codes: true }),
31
67
  metadata: input.metadata,
32
- payment_intent_data: { receipt_email: input.receiptEmail },
68
+ payment_intent_data: paymentIntentData,
33
69
  success_url: input.successUrl,
34
70
  cancel_url: input.cancelUrl,
35
71
  };
@@ -128,9 +128,9 @@ async function sendViaGhl(supabase, opts) {
128
128
  const contactId = upJson.contact?.id || upJson.id || null;
129
129
  if (!contactId)
130
130
  throw new Error('ghl_upsert_no_contact_id');
131
- 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">
132
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
133
- ${opts.body(esc(greetingName))}
131
+ 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">
132
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
133
+ ${opts.body(esc(greetingName))}
134
134
  </td></tr></table></td></tr></table></div>`;
135
135
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
136
136
  method: 'POST', headers,
@@ -153,13 +153,13 @@ export async function sendDayPassConfirmation(supabase, purchase, operator) {
153
153
  p(wifiLine),
154
154
  p(`Hosts are on site ${esc(hostHours)} Pacific — outside those hours, check in whenever the front desk is staffed.`),
155
155
  ].join(''));
156
- 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">
157
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your day pass is confirmed</h2>
158
- ${p(`Hi ${esc(greetingName)},`)}
159
- ${p(`Thanks for booking a day pass at ${esc(operator.name)}.`)}
160
- <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${detailsCard}${checkinCard}</table>
161
- ${p(`Questions before you come in? Reply to this email or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
162
- <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
156
+ 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">
157
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Your day pass is confirmed</h2>
158
+ ${p(`Hi ${esc(greetingName)},`)}
159
+ ${p(`Thanks for booking a day pass at ${esc(operator.name)}.`)}
160
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${detailsCard}${checkinCard}</table>
161
+ ${p(`Questions before you come in? Reply to this email or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
162
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
163
163
  </td></tr></table></td></tr></table></div>`;
164
164
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
165
165
  method: 'POST', headers,
@@ -150,11 +150,11 @@ export async function sendDunningEmail(supabase, email, membershipId, stage, gra
150
150
  })
151
151
  : 'the end of your grace period';
152
152
  const { subject, bodyLines } = stageCopy(stage, endLabel, p);
153
- 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">
154
- <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
155
- ${bodyLines.join('')}
156
- ${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>.`)}
157
- <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
153
+ 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">
154
+ <h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
155
+ ${bodyLines.join('')}
156
+ ${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>.`)}
157
+ <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
158
158
  </td></tr></table></td></tr></table></div>`;
159
159
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
160
160
  method: 'POST', headers,
@@ -0,0 +1,17 @@
1
+ export type FeatureKey = 'membership' | 'day_pass' | 'access_control' | 'events' | 'office_assignment' | 'guest_print' | 'voice_ai';
2
+ /**
3
+ * Every existing deployment of this platform (there is exactly one in
4
+ * production today, Granite City Workspaces) predates this entitlements
5
+ * concept and must keep 100% of its current behavior with zero configuration
6
+ * changes. 'legacy-full' carries every feature key, and resolvePlanId()
7
+ * falls back to it whenever an operator's planId is absent, empty, or not a
8
+ * recognized key in PLANS -- an entitlement check must NEVER silently lock
9
+ * out an existing deployment because of a missing or unrecognized planId.
10
+ */
11
+ export declare const DEFAULT_PLAN_ID = "legacy-full";
12
+ export declare const PLANS: Record<string, readonly FeatureKey[]>;
13
+ export interface OperatorEntitlements {
14
+ planId?: string | null;
15
+ }
16
+ export declare function resolvePlanId(operator: OperatorEntitlements): string;
17
+ export declare function hasEntitlement(operator: OperatorEntitlements, feature: FeatureKey): boolean;
@@ -0,0 +1,33 @@
1
+ // D33 Phase E.1: product-bundling / entitlements foundation.
2
+ //
3
+ // The platform's baseline -- room booking and payment processing -- is
4
+ // always on for every tenant and is NOT represented here. Everything below
5
+ // is an optional feature family a tenant's plan may or may not include.
6
+ /**
7
+ * Every existing deployment of this platform (there is exactly one in
8
+ * production today, Granite City Workspaces) predates this entitlements
9
+ * concept and must keep 100% of its current behavior with zero configuration
10
+ * changes. 'legacy-full' carries every feature key, and resolvePlanId()
11
+ * falls back to it whenever an operator's planId is absent, empty, or not a
12
+ * recognized key in PLANS -- an entitlement check must NEVER silently lock
13
+ * out an existing deployment because of a missing or unrecognized planId.
14
+ */
15
+ export const DEFAULT_PLAN_ID = 'legacy-full';
16
+ export const PLANS = {
17
+ 'legacy-full': [
18
+ 'membership', 'day_pass', 'access_control', 'events',
19
+ 'office_assignment', 'guest_print', 'voice_ai',
20
+ ],
21
+ // First named scoped-down plan: sized for a small single-purpose customer
22
+ // (e.g. a podcast studio) that wants booking + memberships and nothing
23
+ // else the platform offers.
24
+ 'studio-core': ['membership'],
25
+ };
26
+ export function resolvePlanId(operator) {
27
+ const id = operator.planId;
28
+ return id && PLANS[id] ? id : DEFAULT_PLAN_ID;
29
+ }
30
+ export function hasEntitlement(operator, feature) {
31
+ const planId = resolvePlanId(operator);
32
+ return PLANS[planId].includes(feature);
33
+ }
@@ -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>;
@@ -3,6 +3,7 @@ import Stripe from 'stripe';
3
3
  import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
+ import { hasEntitlement } from '../entitlements.js';
6
7
  const corsHeaders = {
7
8
  'Access-Control-Allow-Origin': '*',
8
9
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -37,7 +38,11 @@ function json(status, body) {
37
38
  });
38
39
  }
39
40
  const CANCELLABLE = new Set(['active', 'trialing', 'past_due']);
40
- export async function handle(req) {
41
+ // D33 Phase E.1: no per-deployment operator object was wired into this
42
+ // function before now. Optional and defaulted so every existing caller --
43
+ // whether or not it passes a second argument -- is unaffected: an absent
44
+ // planId resolves to the full-featured legacy plan.
45
+ export async function handle(req, operator = {}) {
41
46
  if (req.method === 'OPTIONS')
42
47
  return new Response('ok', { headers: corsHeaders });
43
48
  if (req.method !== 'POST')
@@ -68,6 +73,9 @@ export async function handle(req) {
68
73
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
69
74
  if (!allow)
70
75
  return json(403, { ok: false, error: 'not_authorized' });
76
+ if (!hasEntitlement(operator, 'membership')) {
77
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'membership' });
78
+ }
71
79
  let body;
72
80
  try {
73
81
  body = await req.json();
@@ -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>;
@@ -3,6 +3,7 @@ import Stripe from 'stripe';
3
3
  import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
+ import { hasEntitlement } from '../entitlements.js';
6
7
  const corsHeaders = {
7
8
  'Access-Control-Allow-Origin': '*',
8
9
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -41,7 +42,11 @@ function json(status, body) {
41
42
  // before a plan change is attempted, to avoid stacking a proration on top
42
43
  // of an already-failing payment method.
43
44
  const CHANGEABLE = new Set(['active', 'trialing']);
44
- export async function handle(req) {
45
+ // D33 Phase E.1: no per-deployment operator object was wired into this
46
+ // function before now. Optional and defaulted so every existing caller --
47
+ // whether or not it passes a second argument -- is unaffected: an absent
48
+ // planId resolves to the full-featured legacy plan.
49
+ export async function handle(req, operator = {}) {
45
50
  if (req.method === 'OPTIONS')
46
51
  return new Response('ok', { headers: corsHeaders });
47
52
  if (req.method !== 'POST')
@@ -72,6 +77,9 @@ export async function handle(req) {
72
77
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
73
78
  if (!allow)
74
79
  return json(403, { ok: false, error: 'not_authorized' });
80
+ if (!hasEntitlement(operator, 'membership')) {
81
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'membership' });
82
+ }
75
83
  let body;
76
84
  try {
77
85
  body = await req.json();
@@ -151,20 +151,48 @@ export async function handle(req, operator, deps) {
151
151
  const net = Math.max(0, price_cents - dynamic_discount_cents);
152
152
  // Reclaim stale holds overlapping the range (same as create-booking).
153
153
  await reclaimStaleHoldsExceptCompletedTier3(admin, room_id, rangeLiteral);
154
- let creditEligible = false;
155
- if (membership) {
156
- let tier = null;
154
+ // Contract tier lookup: needed both for member-credit eligibility (Tier 3
155
+ // rooms never draw member credit - they always go through the Commons
156
+ // contract/deposit flow) and, new here, for the contract-skip audit trail
157
+ // below. Root cause + rationale: claude/admin-create-booking-agreement-gap-scope.md
158
+ // (this function never runs create-booking.js's tiered agreement gate or
159
+ // the audited admin-skip-commons-contract path - every booking it settles
160
+ // to 'paid' does so with no agreement, previously with no audit trail
161
+ // either).
162
+ let contractTier = null;
163
+ try {
164
+ contractTier = await resolveRoomContractTier(admin, room_id);
165
+ }
166
+ catch (e) {
167
+ console.warn('[admin-create-booking] contract tier lookup failed', String(e));
157
168
  try {
158
- tier = await resolveRoomContractTier(admin, room_id);
159
- }
160
- catch (e) {
161
- console.warn('[admin-create-booking] contract tier lookup failed', String(e));
169
+ await logOps(admin, 'admin_create_booking_tier_lookup_failed', { message: String(e), room_id }, { severity: 'warning' });
162
170
  }
163
- creditEligible = room.booking_mode !== 'quote' && tier !== null && tier !== 3;
171
+ catch { /* ignore */ }
172
+ }
173
+ let creditEligible = false;
174
+ if (membership) {
175
+ creditEligible = room.booking_mode !== 'quote' && contractTier !== null && contractTier !== 3;
164
176
  }
165
177
  const useCredit = !!membership && creditEligible;
166
178
  const nowIso = new Date().toISOString();
167
179
  const isOffline = mode === 'offline';
180
+ // Audit-only contract-skip marking (landed 2026-09-18, see scope doc
181
+ // above): every booking this function settles straight to 'paid' bypasses
182
+ // the tiered agreement gate self-serve bookings go through. This does NOT
183
+ // block or gate the booking - it only makes the skip self-documenting via
184
+ // the same contract_skipped_* columns admin-skip-commons-contract uses for
185
+ // an explicit staff skip. NOTE: private.on_booking_paid_transition() still
186
+ // fires and still inserts its own booking_contract_violations row on this
187
+ // same write -- this stamp is in ADDITION to that row, not a replacement
188
+ // for it; the violations table keeps growing exactly as before.
189
+ const CONTRACT_SKIP_REASON = `admin-create-booking: no agreement flow in this function (tier ${contractTier ?? 'unmapped'}; ` +
190
+ 'known gap, audit-only fix landed 2026-09-18 - see admin-create-booking-agreement-gap-scope.md)';
191
+ const contractSkipFields = {
192
+ contract_skipped_at: nowIso,
193
+ contract_skipped_by_email: callerEmail,
194
+ contract_skip_reason: CONTRACT_SKIP_REASON,
195
+ };
168
196
  const insertRow = {
169
197
  room_id,
170
198
  during: rangeLiteral,
@@ -190,6 +218,7 @@ export async function handle(req, operator, deps) {
190
218
  insertRow.charged_amount_cents = net;
191
219
  insertRow.credit_applied_cents = 0;
192
220
  insertRow.hold_expires_at = null;
221
+ Object.assign(insertRow, contractSkipFields);
193
222
  }
194
223
  else {
195
224
  insertRow.status = 'pending';
@@ -300,6 +329,7 @@ export async function handle(req, operator, deps) {
300
329
  credit_applied_cents: credit_applied,
301
330
  discount_applied_cents: discount_applied,
302
331
  hold_expires_at: null,
332
+ ...contractSkipFields,
303
333
  })
304
334
  .eq('id', booking_id);
305
335
  await runPaidSideEffects();
@@ -0,0 +1,47 @@
1
+ export interface OnboardStripeAccount {
2
+ id: string;
3
+ }
4
+ export interface OnboardStripeAccountLink {
5
+ url: string;
6
+ expires_at: number;
7
+ }
8
+ export interface OnboardStripeLike {
9
+ accounts: {
10
+ create(params: Record<string, unknown>): Promise<OnboardStripeAccount>;
11
+ };
12
+ accountLinks: {
13
+ create(params: Record<string, unknown>): Promise<OnboardStripeAccountLink>;
14
+ };
15
+ }
16
+ export interface OnboardDeps {
17
+ stripe: OnboardStripeLike;
18
+ log(kind: string, detail: Record<string, unknown>, severity: 'info' | 'warning' | 'error'): Promise<unknown>;
19
+ }
20
+ export interface OnboardInput {
21
+ tenantLabel: string;
22
+ email: string;
23
+ country: string;
24
+ businessType?: 'individual' | 'company';
25
+ }
26
+ export interface OnboardResult {
27
+ status: number;
28
+ body: Record<string, unknown>;
29
+ }
30
+ /** Basic shape/sanity checks only -- Stripe does its own real validation. */
31
+ export declare function validateOnboardInput(raw: unknown): {
32
+ ok: true;
33
+ value: OnboardInput;
34
+ } | {
35
+ ok: false;
36
+ error: string;
37
+ };
38
+ /** accounts.create params, built conditionally so `business_type` is never
39
+ * passed as `undefined` -- the Stripe SDK rejects that key outright. */
40
+ export declare function buildStripeAccountCreateParams(input: OnboardInput): Record<string, unknown>;
41
+ export declare function handleOnboardConnectAccount(rawBody: unknown, actorEmail: string, domain: string, deps: OnboardDeps): Promise<OnboardResult>;
42
+ export declare function handle(req: Request, operator: {
43
+ operatorName: string;
44
+ operatorShortName: string;
45
+ domain: string;
46
+ supportEmail: string;
47
+ }): Promise<Response>;