@simplelayer/graniteer-core 0.4.3 → 0.5.0-rc.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 (120) hide show
  1. package/LICENSE +4 -0
  2. package/dist/bookingAgreementEmail.d.ts +34 -3
  3. package/dist/bookingAgreementEmail.js +100 -1
  4. package/dist/bookingEffects.d.ts +3 -1
  5. package/dist/bookingEffects.js +4 -3
  6. package/dist/bookingSource.d.ts +2 -0
  7. package/dist/bookingSource.js +11 -0
  8. package/dist/businessHours.d.ts +11 -0
  9. package/dist/businessHours.js +55 -0
  10. package/dist/checkoutSessionParams.d.ts +33 -0
  11. package/dist/checkoutSessionParams.js +71 -0
  12. package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
  13. package/dist/commonsSignedUnpaidCancellation.js +650 -0
  14. package/dist/connectBookingCharge.d.ts +49 -0
  15. package/dist/connectBookingCharge.js +72 -0
  16. package/dist/entitlements.d.ts +1 -1
  17. package/dist/entitlements.js +6 -1
  18. package/dist/functions/admin-acknowledge-contract-violation.d.ts +1 -0
  19. package/dist/functions/admin-acknowledge-contract-violation.js +120 -0
  20. package/dist/functions/admin-cancel-membership.js +109 -13
  21. package/dist/functions/admin-change-membership-plan.js +74 -18
  22. package/dist/functions/admin-charge-guest-print.d.ts +3 -1
  23. package/dist/functions/admin-charge-guest-print.js +8 -1
  24. package/dist/functions/admin-create-booking.d.ts +8 -3
  25. package/dist/functions/admin-create-booking.js +15 -2
  26. package/dist/functions/admin-create-commons-event.d.ts +3 -1
  27. package/dist/functions/admin-create-commons-event.js +8 -1
  28. package/dist/functions/admin-door-write.d.ts +3 -1
  29. package/dist/functions/admin-door-write.js +8 -1
  30. package/dist/functions/admin-issue-day-pass.d.ts +1 -0
  31. package/dist/functions/admin-issue-day-pass.js +8 -1
  32. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  33. package/dist/functions/admin-mark-booking-paid.js +27 -3
  34. package/dist/functions/admin-request-trial.js +22 -1
  35. package/dist/functions/auth-email-hook.js +42 -2
  36. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  37. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  38. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  39. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  40. package/dist/functions/booking-access-revoke.d.ts +35 -0
  41. package/dist/functions/booking-access-revoke.js +280 -0
  42. package/dist/functions/booking-availability.d.ts +2 -1
  43. package/dist/functions/booking-availability.js +14 -5
  44. package/dist/functions/conductor.js +39 -16
  45. package/dist/functions/create-booking.d.ts +10 -3
  46. package/dist/functions/create-booking.js +22 -4
  47. package/dist/functions/create-day-pass-checkout.d.ts +1 -0
  48. package/dist/functions/create-day-pass-checkout.js +6 -0
  49. package/dist/functions/create-subscription-checkout.js +7 -2
  50. package/dist/functions/event-access-admin.d.ts +1 -0
  51. package/dist/functions/event-access-admin.js +23 -1
  52. package/dist/functions/event-access-store.js +18 -0
  53. package/dist/functions/guest-print-setup-confirm.d.ts +3 -1
  54. package/dist/functions/guest-print-setup-confirm.js +8 -1
  55. package/dist/functions/guest-print-submit.d.ts +3 -1
  56. package/dist/functions/guest-print-submit.js +8 -1
  57. package/dist/functions/manage-booking.d.ts +24 -1
  58. package/dist/functions/manage-booking.js +151 -16
  59. package/dist/functions/mcp.d.ts +2 -2
  60. package/dist/functions/mcp.js +2 -2
  61. package/dist/functions/member-door-action.d.ts +3 -1
  62. package/dist/functions/member-door-action.js +9 -2
  63. package/dist/functions/membership-door-sync.d.ts +18 -0
  64. package/dist/functions/membership-door-sync.js +76 -6
  65. package/dist/functions/office-assignment-end.d.ts +3 -1
  66. package/dist/functions/office-assignment-end.js +8 -1
  67. package/dist/functions/portal-submit-event.d.ts +1 -0
  68. package/dist/functions/portal-submit-event.js +4 -0
  69. package/dist/functions/reschedule-booking.d.ts +11 -4
  70. package/dist/functions/reschedule-booking.js +39 -2
  71. package/dist/functions/review-ratings.js +1 -1
  72. package/dist/functions/space-availability-range.d.ts +2 -1
  73. package/dist/functions/space-availability-range.js +8 -1
  74. package/dist/functions/stripe-db-reconcile.js +8 -1
  75. package/dist/functions/stripe-webhook.d.ts +4 -0
  76. package/dist/functions/stripe-webhook.js +328 -17
  77. package/dist/functions/sync-gcal-blackouts.js +1 -1
  78. package/dist/functions/timetable-event-register.d.ts +3 -1
  79. package/dist/functions/timetable-event-register.js +8 -1
  80. package/dist/functions/touch-pass-signup.d.ts +3 -1
  81. package/dist/functions/touch-pass-signup.js +9 -2
  82. package/dist/functions/voice-booking.d.ts +1 -1
  83. package/dist/functions/voice-day-pass.d.ts +2 -1
  84. package/dist/functions/voice-day-pass.js +4 -0
  85. package/dist/functions/voice-inquiry.d.ts +3 -1
  86. package/dist/functions/voice-inquiry.js +9 -2
  87. package/dist/functions/voice-membership-signup.d.ts +2 -2
  88. package/dist/functions/voice-tour-booking.d.ts +1 -1
  89. package/dist/gcalBookingEvents.d.ts +59 -0
  90. package/dist/gcalBookingEvents.js +183 -0
  91. package/dist/gcalSync.d.ts +1 -0
  92. package/dist/gcalSync.js +5 -0
  93. package/dist/membershipSubscriptionItems.d.ts +87 -0
  94. package/dist/membershipSubscriptionItems.js +71 -0
  95. package/dist/membershipWelcome.d.ts +1 -1
  96. package/dist/ops.js +4 -3
  97. package/dist/outbox.d.ts +64 -0
  98. package/dist/outbox.js +70 -0
  99. package/dist/pricing.d.ts +10 -2
  100. package/dist/pricing.js +14 -9
  101. package/dist/referralCodeLookup.d.ts +13 -0
  102. package/dist/referralCodeLookup.js +17 -0
  103. package/dist/referralCredits.d.ts +5 -0
  104. package/dist/referralCredits.js +5 -0
  105. package/dist/referralGrant.d.ts +4 -31
  106. package/dist/referralGrant.js +14 -234
  107. package/dist/runtime/env.d.ts +7 -0
  108. package/dist/runtime/env.js +32 -0
  109. package/dist/runtime/fs.d.ts +5 -0
  110. package/dist/runtime/fs.js +16 -0
  111. package/dist/runtime/serve.d.ts +8 -0
  112. package/dist/runtime/serve.js +12 -0
  113. package/dist/stripeConnectEvents.d.ts +11 -0
  114. package/dist/stripeConnectEvents.js +37 -0
  115. package/dist/supabaseTestFakes.js +7 -1
  116. package/dist/tenant-config.d.ts +8 -0
  117. package/dist/tenant-config.js +25 -0
  118. package/dist/tenantManifest.d.ts +85 -0
  119. package/dist/tenantManifest.js +43 -0
  120. package/package.json +59 -3
@@ -0,0 +1,49 @@
1
+ import type Stripe from 'stripe';
2
+ export interface ConnectBookingOperator {
3
+ stripeConnectedAccountId?: string | null;
4
+ stripeApplicationFeePercent?: number | null;
5
+ }
6
+ export declare const CONNECTED_ACCOUNT_ID_RE: RegExp;
7
+ export type ConnectConfigError = 'connect_account_invalid' | 'connect_fee_invalid' | 'connect_charge_invalid' | 'connect_fee_exceeds_charge';
8
+ export type ConnectedAccountResolution = {
9
+ ok: true;
10
+ accountId: string | null;
11
+ } | {
12
+ ok: false;
13
+ error: 'connect_account_invalid';
14
+ };
15
+ export type BookingChargePlan = {
16
+ ok: true;
17
+ connected: false;
18
+ } | {
19
+ ok: true;
20
+ connected: true;
21
+ accountId: string;
22
+ applicationFeeCents: number;
23
+ } | {
24
+ ok: false;
25
+ error: ConnectConfigError;
26
+ };
27
+ export declare function isValidConnectedAccountId(v: unknown): v is string;
28
+ export interface ConnectTenantEnv {
29
+ connectTenant: boolean;
30
+ }
31
+ export declare function defaultConnectTenantEnv(): ConnectTenantEnv;
32
+ export declare function resolveConnectedAccount(operator: ConnectBookingOperator | null | undefined, env?: ConnectTenantEnv): ConnectedAccountResolution;
33
+ export declare function planBookingCharge(operator: ConnectBookingOperator | null | undefined, chargeCents: number, env?: ConnectTenantEnv): BookingChargePlan;
34
+ export declare function applyConnectToSessionParams(params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Stripe.Checkout.SessionCreateParams;
35
+ export declare function stripeAccountRequestOptions(accountId: string | null | undefined): {
36
+ stripeAccount: string;
37
+ } | undefined;
38
+ type SessionCreator = {
39
+ checkout: {
40
+ sessions: {
41
+ create: (params: Stripe.Checkout.SessionCreateParams, options?: {
42
+ stripeAccount: string;
43
+ }) => Promise<Stripe.Checkout.Session>;
44
+ };
45
+ };
46
+ };
47
+ export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
48
+ export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
49
+ export {};
@@ -0,0 +1,72 @@
1
+ // Stripe Connect DIRECT charges for room bookings. Opt-in per operator: with no
2
+ // `stripeConnectedAccountId` (undefined/null) every helper here is a no-op and
3
+ // the caller's Stripe request is byte-identical to the pre-Connect one.
4
+ import { computeApplicationFeeCents } from './checkoutSessionParams.js';
5
+ import { getEnv, hasEnvSource } from './runtime/env.js';
6
+ export const CONNECTED_ACCOUNT_ID_RE = /^acct_[A-Za-z0-9]+$/;
7
+ export function isValidConnectedAccountId(v) {
8
+ return typeof v === 'string' && CONNECTED_ACCOUNT_ID_RE.test(v);
9
+ }
10
+ // A project that has STRIPE_CONNECT_WEBHOOK_SECRET set is a Connect tenant:
11
+ // an omitted account id there is a wiring bug and must never fall back to the
12
+ // platform account. GC never sets that secret, so its behavior is unchanged.
13
+ export function defaultConnectTenantEnv() {
14
+ if (!hasEnvSource()) {
15
+ throw new Error('Connect tenant check needs an env source: call setEnvReader() first on runtimes without Deno.env or process.env');
16
+ }
17
+ return { connectTenant: !!getEnv('STRIPE_CONNECT_WEBHOOK_SECRET') };
18
+ }
19
+ export function resolveConnectedAccount(operator, env = defaultConnectTenantEnv()) {
20
+ const raw = operator?.stripeConnectedAccountId;
21
+ if (raw === undefined || raw === null) {
22
+ return env.connectTenant ? { ok: false, error: 'connect_account_invalid' } : { ok: true, accountId: null };
23
+ }
24
+ if (!isValidConnectedAccountId(raw))
25
+ return { ok: false, error: 'connect_account_invalid' };
26
+ return { ok: true, accountId: raw };
27
+ }
28
+ export function planBookingCharge(operator, chargeCents, env = defaultConnectTenantEnv()) {
29
+ const account = resolveConnectedAccount(operator, env);
30
+ if ('error' in account)
31
+ return { ok: false, error: account.error };
32
+ if (account.accountId === null)
33
+ return { ok: true, connected: false };
34
+ const pct = operator?.stripeApplicationFeePercent;
35
+ const hasFee = !(pct === undefined || pct === null || pct === 0);
36
+ // Exclusive upper bound: a 100% fee would leave the connected account paying
37
+ // Stripe's processing fee on every booking.
38
+ if (hasFee && (typeof pct !== 'number' || !Number.isFinite(pct) || pct <= 0 || pct >= 100)) {
39
+ return { ok: false, error: 'connect_fee_invalid' };
40
+ }
41
+ if (!Number.isSafeInteger(chargeCents) || chargeCents <= 0) {
42
+ return { ok: false, error: 'connect_charge_invalid' };
43
+ }
44
+ const fee = hasFee ? computeApplicationFeeCents(chargeCents, pct) : 0;
45
+ if (!Number.isSafeInteger(fee) || fee < 0 || fee > chargeCents) {
46
+ return { ok: false, error: 'connect_fee_exceeds_charge' };
47
+ }
48
+ return { ok: true, connected: true, accountId: account.accountId, applicationFeeCents: fee };
49
+ }
50
+ export function applyConnectToSessionParams(params, plan) {
51
+ if (!plan.ok || !plan.connected || plan.applicationFeeCents <= 0)
52
+ return params;
53
+ return {
54
+ ...params,
55
+ payment_intent_data: {
56
+ ...(params.payment_intent_data ?? {}),
57
+ application_fee_amount: plan.applicationFeeCents,
58
+ },
59
+ };
60
+ }
61
+ export function stripeAccountRequestOptions(accountId) {
62
+ return accountId ? { stripeAccount: accountId } : undefined;
63
+ }
64
+ export function createBookingCheckoutSession(stripe, params, plan) {
65
+ if ('error' in plan) {
66
+ return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
67
+ }
68
+ if (!plan.connected)
69
+ return stripe.checkout.sessions.create(params);
70
+ return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, { stripeAccount: plan.accountId });
71
+ }
72
+ export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
@@ -1,7 +1,7 @@
1
1
  export type FeatureKey = 'membership' | 'day_pass' | 'access_control' | 'events' | 'office_assignment' | 'guest_print' | 'voice_ai';
2
2
  /**
3
3
  * Every existing deployment of this platform (there is exactly one in
4
- * production today, Granite City Workspaces) predates this entitlements
4
+ * production today) predates this entitlements
5
5
  * concept and must keep 100% of its current behavior with zero configuration
6
6
  * changes. 'legacy-full' carries every feature key, and resolvePlanId()
7
7
  * falls back to it whenever an operator's planId is absent, empty, or not a
@@ -5,7 +5,7 @@
5
5
  // is an optional feature family a tenant's plan may or may not include.
6
6
  /**
7
7
  * Every existing deployment of this platform (there is exactly one in
8
- * production today, Granite City Workspaces) predates this entitlements
8
+ * production today) predates this entitlements
9
9
  * concept and must keep 100% of its current behavior with zero configuration
10
10
  * changes. 'legacy-full' carries every feature key, and resolvePlanId()
11
11
  * falls back to it whenever an operator's planId is absent, empty, or not a
@@ -22,6 +22,11 @@ export const PLANS = {
22
22
  // (e.g. a podcast studio) that wants booking + memberships and nothing
23
23
  // else the platform offers.
24
24
  'studio-core': ['membership'],
25
+ // Coworking bundle: day passes, events and office/desk assignment alongside
26
+ // door access. NOTE: access_control is listed here but is NOT YET gated at
27
+ // any call site (that's its own dedicated, adversarially-reviewed pass) --
28
+ // so this plan is not fully enforceable end-to-end until that lands.
29
+ 'coworking-standard': ['day_pass', 'access_control', 'events', 'office_assignment'],
25
30
  };
26
31
  export function resolvePlanId(operator) {
27
32
  const id = operator.planId;
@@ -0,0 +1 @@
1
+ export declare function handle(req: Request): Promise<Response>;
@@ -0,0 +1,120 @@
1
+ // supabase/functions/admin-acknowledge-contract-violation/index.ts
2
+ //
3
+ // Simple acknowledge workflow for booking_contract_violations rows (see
4
+ // claude/booking-contract-violations-ack-scope.md in the FTW Access Platform
5
+ // project). on_booking_paid_transition() inserts a row here whenever a paid
6
+ // booking settles with no proper agreement -- staff-offline bookings via
7
+ // admin-create-booking are the recurring source (see
8
+ // admin-create-booking-agreement-gap-scope.md). This does not change or gate
9
+ // anything about the booking itself; it just lets a verified admin record
10
+ // that they reviewed a violation row, mirroring the acknowledged_at /
11
+ // acknowledged_by_email columns that already exist on the table.
12
+ import { createClient } from '@supabase/supabase-js';
13
+ import { z } from 'zod';
14
+ import { jwtVerify, createRemoteJWKSet } from 'jose';
15
+ import { clientIp, checkRateLimit } from '../rateLimit.js';
16
+ import { logOps } from '../ops.js';
17
+ const corsHeaders = {
18
+ 'Access-Control-Allow-Origin': '*',
19
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
20
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
21
+ };
22
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
23
+ let jwksCache = null;
24
+ function getJwks(supabaseUrl) {
25
+ if (!jwksCache)
26
+ jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+ async function verifyCaller(authHeader, supabaseUrl) {
30
+ if (!authHeader?.toLowerCase().startsWith('bearer '))
31
+ return null;
32
+ const token = authHeader.slice(7).trim();
33
+ try {
34
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
+ const claims = payload;
36
+ if (!claims.sub)
37
+ return null;
38
+ return claims;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function json(status, body) {
45
+ return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
46
+ }
47
+ function fail(status, code, error, extra) {
48
+ return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
49
+ }
50
+ const Body = z.object({
51
+ violation_id: z.string().uuid(),
52
+ });
53
+ export async function handle(req) {
54
+ if (req.method === 'OPTIONS')
55
+ return new Response('ok', { headers: corsHeaders });
56
+ if (req.method !== 'POST')
57
+ return fail(405, 'method_not_allowed', 'Method not allowed.');
58
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL');
59
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
60
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
61
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
62
+ if (!caller)
63
+ return fail(401, 'unauthenticated', 'Not signed in.');
64
+ if (caller.aal !== 'aal2')
65
+ return fail(403, 'mfa_required', 'Two-factor authentication is required.');
66
+ const callerEmail = (caller.email ?? '').toLowerCase();
67
+ if (!callerEmail)
68
+ return fail(403, 'no_email', 'Caller has no email claim.');
69
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
70
+ const [ipOk, emailOk] = await Promise.all([
71
+ checkRateLimit(admin, 'admin-acknowledge-contract-violation-ip', clientIp(req), 30, 300),
72
+ checkRateLimit(admin, 'admin-acknowledge-contract-violation-email', callerEmail, 30, 300),
73
+ ]);
74
+ if (!ipOk || !emailOk)
75
+ return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
76
+ const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
77
+ if (allowErr)
78
+ return fail(500, 'allowlist_lookup_failed', allowErr.message);
79
+ if (!allow)
80
+ return fail(403, 'not_authorized', 'Not authorized.');
81
+ let raw;
82
+ try {
83
+ raw = await req.json();
84
+ }
85
+ catch {
86
+ return fail(400, 'invalid_json', 'Body was not valid JSON.');
87
+ }
88
+ const parsed = Body.safeParse(raw);
89
+ if (!parsed.success)
90
+ return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
91
+ const { violation_id } = parsed.data;
92
+ const { data: violation, error: vErr } = await admin
93
+ .from('booking_contract_violations')
94
+ .select('id,booking_id,acknowledged_at')
95
+ .eq('id', violation_id)
96
+ .maybeSingle();
97
+ if (vErr)
98
+ return fail(500, 'violation_lookup_failed', vErr.message);
99
+ if (!violation)
100
+ return fail(404, 'violation_not_found', 'Violation row not found.');
101
+ const ackAt = new Date().toISOString();
102
+ // CAS on acknowledged_at IS NULL -- two admins acknowledging the same row
103
+ // at once is harmless (first write wins, second gets a clean 409 instead
104
+ // of silently overwriting who actually reviewed it).
105
+ const { data: updated, error: updErr } = await admin
106
+ .from('booking_contract_violations')
107
+ .update({ acknowledged_at: ackAt, acknowledged_by_email: callerEmail })
108
+ .eq('id', violation_id)
109
+ .is('acknowledged_at', null)
110
+ .select('id')
111
+ .maybeSingle();
112
+ if (updErr)
113
+ return fail(500, 'update_failed', updErr.message);
114
+ if (!updated)
115
+ return fail(409, 'already_acknowledged', 'This violation was already acknowledged — reload and try again.');
116
+ await logOps(admin, 'contract_violation_acknowledged', {
117
+ violation_id, booking_id: violation.booking_id, actor: callerEmail, actor_user_id: caller.sub,
118
+ }, { severity: 'info', bookingId: violation.booking_id }).catch(() => { });
119
+ return json(200, { ok: true, violation_id, acknowledged_at: ackAt });
120
+ }
@@ -4,6 +4,7 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
6
  import { hasEntitlement } from '../entitlements.js';
7
+ import { findBaseItem, countBaseItems, hasAddonItems, isRenewalInvoice, invoiceCoversPeriod } from '../membershipSubscriptionItems.js';
7
8
  const corsHeaders = {
8
9
  'Access-Control-Allow-Origin': '*',
9
10
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -116,6 +117,49 @@ export async function handle(req, operator = {}) {
116
117
  return json(400, { ok: false, error: 'invalid_idempotency_key' });
117
118
  }
118
119
  const dryRun = !!body.dry_run;
120
+ // Refunds are disabled for this release (including dry-run estimates).
121
+ // Under the 2024-11-20.acacia Stripe API pinned above, subscription items
122
+ // carry no period fields, so every refund computed by this handler so far
123
+ // has silently been $0 -- the refund path has never actually moved money.
124
+ // Enabling it for real needs two fixes first: a second cancel+refund
125
+ // stacking on an already-refunded scheduled cancel over-refunds (nothing
126
+ // subtracts the prior refund from the new one), and undoing a scheduled
127
+ // cancel after its refund went out leaves the member with both the money
128
+ // and continued service. See _review-verdict-multi-item-4.md, blockers #1
129
+ // and #2. Fail closed here, before the idempotency row is claimed and
130
+ // before any Stripe call, so cancel WITHOUT refund (including with
131
+ // add-ons) is completely unaffected.
132
+ if (issueRefund) {
133
+ return json(400, {
134
+ ok: false,
135
+ error: 'refunds_disabled',
136
+ detail: 'Automatic refunds are disabled in this release; cancel without a refund and refund manually in Stripe.',
137
+ });
138
+ }
139
+ // Deletes the idempotency row claimed in step 3 below. Call this from any
140
+ // error return that happens AFTER that insert but BEFORE the Stripe
141
+ // mutation that the row is meant to record -- otherwise a client retry with
142
+ // the same idempotency_key sees { ok:true, duplicate:true } for a
143
+ // cancellation that never happened. No-op for dry runs, which never insert
144
+ // the row in the first place.
145
+ const releaseAuditRow = async () => {
146
+ if (dryRun)
147
+ return;
148
+ try {
149
+ const { error } = await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
150
+ if (error) {
151
+ await logOps(admin, 'membership_admin_action_release_failed', {
152
+ message: error.message, idempotency_key: idempotencyKey,
153
+ }, { severity: 'warning' });
154
+ }
155
+ }
156
+ catch (e) {
157
+ const msg = e instanceof Error ? e.message : String(e);
158
+ await logOps(admin, 'membership_admin_action_release_failed', {
159
+ message: msg, idempotency_key: idempotencyKey,
160
+ }, { severity: 'warning' });
161
+ }
162
+ };
119
163
  // 1. Live state re-check (concurrency guard).
120
164
  const { data: membership, error: mErr } = await admin
121
165
  .from('memberships')
@@ -156,8 +200,10 @@ export async function handle(req, operator = {}) {
156
200
  }
157
201
  }
158
202
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
159
- if (!stripeKey)
203
+ if (!stripeKey) {
204
+ await releaseAuditRow();
160
205
  return json(500, { ok: false, error: 'stripe_not_configured' });
206
+ }
161
207
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
162
208
  // 4. Retrieve subscription.
163
209
  let sub;
@@ -166,14 +212,40 @@ export async function handle(req, operator = {}) {
166
212
  }
167
213
  catch (e) {
168
214
  const msg = e instanceof Error ? e.message : String(e);
215
+ await releaseAuditRow();
169
216
  return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
170
217
  }
171
- if (sub.items.data.length !== 1) {
172
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
218
+ const subForItems = sub;
219
+ const baseItem = findBaseItem(subForItems);
220
+ if (!baseItem) {
221
+ const nonAddonCount = countBaseItems(subForItems);
222
+ await releaseAuditRow();
223
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${nonAddonCount} non-addon items` });
224
+ }
225
+ // Add-on items carry their own pricing that the base-item period-fraction
226
+ // refund math below does not account for, so an automated refund on a
227
+ // subscription with add-ons can under-refund the member. Block it (even on
228
+ // a dry run, so staff see this instead of a misleading estimate) and leave
229
+ // cancellation-without-refund untouched.
230
+ if (issueRefund && hasAddonItems(subForItems)) {
231
+ await releaseAuditRow();
232
+ return json(400, {
233
+ ok: false,
234
+ error: 'refund_blocked_with_addons',
235
+ detail: 'This subscription has add-ons; staff must refund manually in Stripe.',
236
+ });
237
+ }
238
+ const item = baseItem;
239
+ // Item-level current_period_start/end were only added to Stripe's API in
240
+ // 2025-03-31.basil; this function pins 2024-11-20.acacia, where an item may
241
+ // not carry them. Fall back to the subscription-level period (which acacia
242
+ // always returns) rather than silently computing refund math on undefined.
243
+ const periodStart = item.current_period_start ?? sub.current_period_start;
244
+ const periodEnd = item.current_period_end ?? sub.current_period_end;
245
+ if (typeof periodStart !== 'number' || typeof periodEnd !== 'number') {
246
+ await releaseAuditRow();
247
+ return json(400, { ok: false, error: 'period_unavailable' });
173
248
  }
174
- const item = sub.items.data[0];
175
- const periodStart = item.current_period_start;
176
- const periodEnd = item.current_period_end;
177
249
  // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
178
250
  // future or Stripe rejects the cancel_at update — the safety floor below is
179
251
  // the fix for the bug where "today" (midnight) or a clamp to periodStart
@@ -203,17 +275,41 @@ export async function handle(req, operator = {}) {
203
275
  }
204
276
  catch (e) {
205
277
  const msg = e instanceof Error ? e.message : String(e);
278
+ await releaseAuditRow();
206
279
  return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
207
280
  }
208
281
  if (!invoice) {
209
- if (!dryRun) {
210
- try {
211
- await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
212
- }
213
- catch { /* non-fatal */ }
214
- }
282
+ await releaseAuditRow();
215
283
  return json(400, { ok: false, error: 'no_refundable_invoice' });
216
284
  }
285
+ // The refund math below prorates this invoice's amount_paid using the
286
+ // base item's full-period bounds. That is only valid when this invoice
287
+ // IS that full-period charge -- a renewal or the original subscription
288
+ // creation. Any other latest-paid invoice (e.g. a mid-cycle add-on
289
+ // charge) would under-refund the member, so refuse rather than guess.
290
+ if (!isRenewalInvoice(invoice)) {
291
+ await releaseAuditRow();
292
+ return json(400, {
293
+ ok: false,
294
+ error: 'refund_invoice_ambiguous',
295
+ detail: `latest paid invoice billing_reason is '${invoice.billing_reason ?? 'unknown'}', not a renewal invoice`,
296
+ });
297
+ }
298
+ // isRenewalInvoice only confirms the invoice is SHAPED like a full-period
299
+ // charge -- it says nothing about WHICH period. A past_due subscription
300
+ // (CANCELLABLE allows it) or the brief draft window right after a renewal
301
+ // can leave the latest PAID invoice as last period's while the current
302
+ // period is still unpaid. Prorating that stale invoice against the
303
+ // current period's bounds would over-refund the member, so also require
304
+ // one of its lines to actually cover the current period.
305
+ if (!invoiceCoversPeriod(invoice, periodStart)) {
306
+ await releaseAuditRow();
307
+ return json(400, {
308
+ ok: false,
309
+ error: 'refund_invoice_ambiguous',
310
+ detail: 'latest paid invoice has no line covering the current billing period',
311
+ });
312
+ }
217
313
  paymentIntent = invoice.payment_intent;
218
314
  const charge = paymentIntent?.latest_charge ?? null;
219
315
  const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
@@ -265,7 +361,7 @@ export async function handle(req, operator = {}) {
265
361
  amount: refundCents,
266
362
  reason: 'requested_by_customer',
267
363
  metadata: { membership_id: membershipId, actor: callerEmail },
268
- }, { idempotencyKey });
364
+ }, { idempotencyKey: `${idempotencyKey}:refund` });
269
365
  stripeRefundId = refund.id;
270
366
  }
271
367
  catch (e) {
@@ -4,6 +4,7 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
6
  import { hasEntitlement } from '../entitlements.js';
7
+ import { findBaseItem, countBaseItems, hasAddonItems, matchesPlanPrice } from '../membershipSubscriptionItems.js';
7
8
  const corsHeaders = {
8
9
  'Access-Control-Allow-Origin': '*',
9
10
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -186,12 +187,34 @@ export async function handle(req, operator = {}) {
186
187
  const msg = e instanceof Error ? e.message : String(e);
187
188
  return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
188
189
  }
189
- if (sub.items.data.length !== 1) {
190
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
190
+ const subForItems = sub;
191
+ const baseItem = findBaseItem(subForItems);
192
+ if (!baseItem) {
193
+ const nonAddonCount = countBaseItems(subForItems);
194
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${nonAddonCount} non-addon items` });
195
+ }
196
+ // Item metadata is editable in the Stripe Dashboard (and by any future
197
+ // add-on writer), so once add-ons exist, findBaseItem's "only untagged
198
+ // item" rule is not enough on its own -- confirm the resolved item is
199
+ // actually still priced at the member's current plan before swapping its
200
+ // price. matchesPlanPrice checks price id first, falling back to product id
201
+ // (for inline price_data plans or a rotated catalog price), and fails
202
+ // closed if the plan has neither id stored. Subscriptions with no add-on
203
+ // items keep today's behavior exactly; this check only engages once a
204
+ // gc_addon-tagged item is present.
205
+ if (hasAddonItems(subForItems) && !matchesPlanPrice(baseItem, currentPlan)) {
206
+ return json(400, { ok: false, error: 'base_item_mismatch' });
207
+ }
208
+ const item = baseItem;
209
+ // Item-level current_period_start/end were only added to Stripe's API in
210
+ // 2025-03-31.basil; this function pins 2024-11-20.acacia, where an item may
211
+ // not carry them. Fall back to the subscription-level period (which acacia
212
+ // always returns) rather than silently computing estimates on undefined.
213
+ const periodStart = item.current_period_start ?? sub.current_period_start;
214
+ const periodEnd = item.current_period_end ?? sub.current_period_end;
215
+ if (typeof periodStart !== 'number' || typeof periodEnd !== 'number') {
216
+ return json(400, { ok: false, error: 'period_unavailable' });
191
217
  }
192
- const item = sub.items.data[0];
193
- const periodStart = item.current_period_start;
194
- const periodEnd = item.current_period_end;
195
218
  const nowUnix = Math.floor(Date.now() / 1000);
196
219
  // 6. Estimate-only proration math (same time-remaining-fraction approach as
197
220
  // admin-cancel-membership's refund estimate) — a heads-up for the admin.
@@ -250,21 +273,54 @@ export async function handle(req, operator = {}) {
250
273
  let invoiceId = null;
251
274
  let invoiceAmountCents = null;
252
275
  let invoiceStatus = null;
253
- try {
254
- const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
255
- const latest = invoices.data[0];
256
- if (latest) {
257
- invoiceId = latest.id ?? null;
258
- invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
259
- invoiceStatus = latest.status ?? null;
260
- }
261
- }
262
- catch (e) {
263
- const msg = e instanceof Error ? e.message : String(e);
264
- await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
265
- message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
276
+ const priorLatestInvoiceRef = sub.latest_invoice;
277
+ const priorLatestInvoiceId = priorLatestInvoiceRef
278
+ ? (typeof priorLatestInvoiceRef === 'string' ? priorLatestInvoiceRef : priorLatestInvoiceRef.id)
279
+ : null;
280
+ const latestInvoiceRef = updatedSub.latest_invoice;
281
+ const updatedLatestInvoiceId = latestInvoiceRef
282
+ ? (typeof latestInvoiceRef === 'string' ? latestInvoiceRef : latestInvoiceRef.id)
283
+ : null;
284
+ if (updatedLatestInvoiceId && updatedLatestInvoiceId === priorLatestInvoiceId) {
285
+ // always_invoice swept no pending proration into a new invoice, so
286
+ // latest_invoice still points at the pre-update (renewal) invoice. That
287
+ // invoice is not the authoritative record of this plan change -- report
288
+ // nothing rather than a misleading unrelated amount.
289
+ await logOps(admin, 'membership_plan_change_no_new_invoice', {
290
+ membership_id: membershipId, idempotency_key: idempotencyKey, invoice_id: updatedLatestInvoiceId,
266
291
  }, { severity: 'warning' });
267
292
  }
293
+ else {
294
+ try {
295
+ let latest = null;
296
+ if (updatedLatestInvoiceId) {
297
+ try {
298
+ latest = await stripe.invoices.retrieve(updatedLatestInvoiceId);
299
+ }
300
+ catch (e) {
301
+ const msg = e instanceof Error ? e.message : String(e);
302
+ await logOps(admin, 'membership_plan_change_invoice_retrieve_failed', {
303
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
304
+ }, { severity: 'warning' });
305
+ }
306
+ }
307
+ if (!latest) {
308
+ const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
309
+ latest = invoices.data[0];
310
+ }
311
+ if (latest) {
312
+ invoiceId = latest.id ?? null;
313
+ invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
314
+ invoiceStatus = latest.status ?? null;
315
+ }
316
+ }
317
+ catch (e) {
318
+ const msg = e instanceof Error ? e.message : String(e);
319
+ await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
320
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
321
+ }, { severity: 'warning' });
322
+ }
323
+ }
268
324
  // 10. Authoritative membership write, done immediately after the Stripe
269
325
  // mutation that produced it.
270
326
  const { error: updErr } = await admin
@@ -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>;
@@ -15,6 +15,7 @@ import { z } from 'zod';
15
15
  import { jwtVerify, createRemoteJWKSet } from 'jose';
16
16
  import { clientIp, checkRateLimit } from '../rateLimit.js';
17
17
  import { logOps } from '../ops.js';
18
+ import { hasEntitlement } from '../entitlements.js';
18
19
  import { chargeGuestPrintJob, CLAIMABLE_CHARGE_STATUSES, } from '../guestPrintCapture.js';
19
20
  const corsHeaders = {
20
21
  'Access-Control-Allow-Origin': '*',
@@ -52,7 +53,10 @@ const Body = z.object({
52
53
  submission_id: z.string().uuid(),
53
54
  amount_cents: z.number().int().positive().max(500_00), // sanity ceiling: $500
54
55
  });
55
- export async function handle(req) {
56
+ export async function handle(req,
57
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
58
+ // full-featured legacy plan, so every existing caller is unaffected.
59
+ operator = {}) {
56
60
  if (req.method === 'OPTIONS')
57
61
  return new Response('ok', { headers: corsHeaders });
58
62
  if (req.method !== 'POST')
@@ -83,6 +87,9 @@ export async function handle(req) {
83
87
  return json(500, { ok: false, error: 'allowlist_lookup_failed' });
84
88
  if (!allow)
85
89
  return json(403, { ok: false, error: 'not_authorized' });
90
+ if (!hasEntitlement(operator, 'guest_print')) {
91
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'guest_print' });
92
+ }
86
93
  let raw;
87
94
  try {
88
95
  raw = await req.json();
@@ -1,3 +1,4 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
1
2
  interface EffectsBookingRow {
2
3
  id: string;
3
4
  contact_name: string | null;
@@ -17,9 +18,10 @@ interface EffectsBookingRow {
17
18
  usage_instructions?: string | null;
18
19
  } | null;
19
20
  }
21
+ type SupabaseLike = SupabaseClient<any, any, any>;
20
22
  export interface AdminCreateBookingDeps {
21
- notifyGhl: (admin: unknown, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
22
- createCalendarEvent: (admin: unknown, row: EffectsBookingRow) => Promise<void>;
23
+ notifyGhl: (admin: SupabaseLike, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
24
+ createCalendarEvent: (admin: SupabaseLike, row: EffectsBookingRow) => Promise<void>;
23
25
  parseTstzRange: (range: string) => {
24
26
  startISO: string;
25
27
  endISO: string;
@@ -34,10 +36,13 @@ export interface AdminCreateBookingDeps {
34
36
  email: string;
35
37
  phone?: string;
36
38
  };
37
- }, admin: unknown) => Promise<Record<string, unknown> | null>;
39
+ }, admin: SupabaseLike) => Promise<Record<string, unknown> | null>;
38
40
  extractDoorAccess: (busResp: Record<string, unknown> | null) => unknown;
39
41
  }
40
42
  export declare function handle(req: Request, operator: {
41
43
  domain: string;
44
+ googleCalendarWriteback?: boolean | null;
45
+ stripeConnectedAccountId?: string | null;
46
+ stripeApplicationFeePercent?: number | null;
42
47
  }, deps: AdminCreateBookingDeps): Promise<Response>;
43
48
  export {};