@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -1,308 +1,312 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import Stripe from 'npm:stripe@17.5.0';
3
- import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
- import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
-
7
- const corsHeaders = {
8
- 'Access-Control-Allow-Origin': '*',
9
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
- 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
- };
12
-
13
- interface CallerClaims {
14
- sub: string;
15
- email?: string;
16
- aal?: string;
17
- }
18
-
19
- const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
20
- let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
21
- function getJwks(supabaseUrl: string) {
22
- if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
23
- return jwksCache;
24
- }
25
-
26
- async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
27
- if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
28
- const token = authHeader.slice(7).trim();
29
- try {
30
- const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
31
- const claims = payload as unknown as CallerClaims;
32
- if (!claims.sub) return null;
33
- return claims;
34
- } catch {
35
- return null;
36
- }
37
- }
38
-
39
- function json(status: number, body: unknown) {
40
- return new Response(JSON.stringify(body), {
41
- status,
42
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
- });
44
- }
45
-
46
- // Only these statuses may have their plan changed. past_due is excluded
47
- // deliberately — dunning must resolve (or the member must be cancelled)
48
- // before a plan change is attempted, to avoid stacking a proration on top
49
- // of an already-failing payment method.
50
- const CHANGEABLE = new Set(['active', 'trialing']);
51
-
52
- type PlanRow = {
53
- id: string;
54
- slug: string;
55
- name: string;
56
- category: string;
57
- active: boolean;
58
- billable: boolean;
59
- billing_interval: string | null;
60
- price_cents: number | null;
61
- stripe_price_id: string | null;
62
- stripe_product_id: string | null;
63
- };
64
-
65
- export async function handle(req: Request): Promise<Response> {
66
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
67
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
68
-
69
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
70
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
71
-
72
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
73
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
74
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
75
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
76
- const callerEmail = (caller.email ?? '').toLowerCase();
77
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
78
-
79
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
80
- auth: { persistSession: false, autoRefreshToken: false },
81
- });
82
-
83
- const [ipOk, emailOk] = await Promise.all([
84
- checkRateLimit(admin, 'admin-change-membership-plan-ip', clientIp(req), 30, 300),
85
- checkRateLimit(admin, 'admin-change-membership-plan-email', callerEmail, 20, 300),
86
- ]);
87
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
88
-
89
- const { data: allow, error: allowErr } = await admin
90
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
91
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
92
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
93
-
94
- let body: {
95
- membership_id?: string;
96
- new_plan_id?: string;
97
- reason?: string;
98
- idempotency_key?: string;
99
- dry_run?: boolean;
100
- };
101
- try {
102
- body = await req.json();
103
- } catch {
104
- return json(400, { ok: false, error: 'invalid_json' });
105
- }
106
-
107
- const membershipId = (body.membership_id ?? '').trim();
108
- if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
109
- return json(400, { ok: false, error: 'invalid_membership_id' });
110
- }
111
- const newPlanId = (body.new_plan_id ?? '').trim();
112
- if (!/^[0-9a-f-]{36}$/i.test(newPlanId)) {
113
- return json(400, { ok: false, error: 'invalid_new_plan_id' });
114
- }
115
- const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
116
- const idempotencyKey = (body.idempotency_key ?? '').trim();
117
- if (!idempotencyKey || idempotencyKey.length > 100) {
118
- return json(400, { ok: false, error: 'invalid_idempotency_key' });
119
- }
120
- const dryRun = !!body.dry_run;
121
-
122
- // 1. Live membership state.
123
- const { data: membership, error: mErr } = await admin
124
- .from('memberships')
125
- .select('id,email,status,stripe_subscription_id,plan_id,cancel_at')
126
- .eq('id', membershipId)
127
- .maybeSingle();
128
- if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
129
- if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
130
- if (membership.cancel_at) return json(400, { ok: false, error: 'pending_cancellation' });
131
- if (!CHANGEABLE.has(membership.status)) {
132
- return json(400, { ok: false, error: 'not_changeable', detail: `status is ${membership.status}` });
133
- }
134
- const subscriptionId = membership.stripe_subscription_id;
135
- if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
136
- if (newPlanId === membership.plan_id) return json(400, { ok: false, error: 'same_plan' });
137
-
138
- // 2. Load both plan rows in one query.
139
- const { data: planRows, error: planErr } = await admin
140
- .from('membership_plans')
141
- .select('id,slug,name,category,active,billable,billing_interval,price_cents,stripe_price_id,stripe_product_id')
142
- .in('id', [membership.plan_id, newPlanId]);
143
- if (planErr) return json(500, { ok: false, error: 'load_plans_failed', detail: planErr.message });
144
- const currentPlan = (planRows ?? []).find((p) => p.id === membership.plan_id) as PlanRow | undefined;
145
- const newPlan = (planRows ?? []).find((p) => p.id === newPlanId) as PlanRow | undefined;
146
- if (!currentPlan) return json(500, { ok: false, error: 'current_plan_not_found' });
147
- if (!newPlan) return json(400, { ok: false, error: 'plan_not_found' });
148
-
149
- // 3. Plan-change eligibility guards. Office-category plans are sign-before-pay
150
- // (BoldSign agreement precedes any charge) and must never be reachable from
151
- // this self-serve-adjacent admin path, as either the source or destination.
152
- if (currentPlan.category === 'office' || newPlan.category === 'office') {
153
- return json(400, { ok: false, error: 'office_plan_blocked' });
154
- }
155
- if (!newPlan.active) return json(400, { ok: false, error: 'plan_inactive' });
156
- if (!newPlan.billable) return json(400, { ok: false, error: 'plan_not_billable' });
157
- // Scope limited to monthly plans for now, matching the site's own
158
- // `subscribable` definition (build-pricing-bootstrap.mjs) — annual plans
159
- // are out of scope for this feature.
160
- if ((newPlan.billing_interval ?? '').toLowerCase() !== 'month') {
161
- return json(400, { ok: false, error: 'unsupported_billing_interval' });
162
- }
163
-
164
- // 4. Resolve what to actually send Stripe for the new price. Mirrors the
165
- // ad-hoc checkout path: a stored stripe_price_id is preferred, but a plan
166
- // with only price_cents + a Stripe product can still be priced inline.
167
- let priceUpdate: { price: string } | { price_data: Record<string, unknown> };
168
- if (newPlan.stripe_price_id) {
169
- priceUpdate = { price: newPlan.stripe_price_id };
170
- } else if (newPlan.stripe_product_id && typeof newPlan.price_cents === 'number' && newPlan.price_cents > 0) {
171
- priceUpdate = {
172
- price_data: {
173
- currency: 'usd',
174
- unit_amount: newPlan.price_cents,
175
- recurring: { interval: 'month' },
176
- product: newPlan.stripe_product_id,
177
- },
178
- };
179
- } else {
180
- return json(400, { ok: false, error: 'plan_not_chargeable' });
181
- }
182
-
183
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
184
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
185
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
186
-
187
- // 5. Retrieve subscription (read-only) for the item id + current period bounds.
188
- let sub: Stripe.Subscription;
189
- try {
190
- sub = await stripe.subscriptions.retrieve(subscriptionId);
191
- } catch (e) {
192
- const msg = e instanceof Error ? e.message : String(e);
193
- return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
194
- }
195
- if (sub.items.data.length !== 1) {
196
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
197
- }
198
- const item = sub.items.data[0] as unknown as {
199
- id: string;
200
- current_period_start: number;
201
- current_period_end: number;
202
- };
203
- const periodStart = item.current_period_start;
204
- const periodEnd = item.current_period_end;
205
- const nowUnix = Math.floor(Date.now() / 1000);
206
-
207
- // 6. Estimate-only proration math (same time-remaining-fraction approach as
208
- // admin-cancel-membership's refund estimate) — a heads-up for the admin.
209
- // The REAL amount is always read back from the invoice Stripe actually
210
- // creates in step 8, never trusted from this estimate.
211
- const span = periodEnd - periodStart;
212
- const remaining = Math.max(0, periodEnd - nowUnix);
213
- const fraction = span > 0 ? remaining / span : 0;
214
- const creditForOldPlan = Math.round((currentPlan.price_cents ?? 0) * fraction);
215
- const chargeForNewPlan = Math.round((newPlan.price_cents ?? 0) * fraction);
216
- const estimatedNetCents = chargeForNewPlan - creditForOldPlan;
217
-
218
- if (dryRun) {
219
- return json(200, {
220
- ok: true,
221
- estimated_net_cents: estimatedNetCents,
222
- current_plan_name: currentPlan.name,
223
- new_plan_name: newPlan.name,
224
- });
225
- }
226
-
227
- // 7. Idempotent audit insert — claims the idempotency key immediately
228
- // before the Stripe mutation, same discipline as admin-cancel-membership.
229
- const { error: insErr } = await admin.from('membership_admin_actions').insert({
230
- membership_id: membershipId,
231
- action: 'plan_changed',
232
- old_plan_id: membership.plan_id,
233
- new_plan_id: newPlanId,
234
- actor_email: callerEmail,
235
- idempotency_key: idempotencyKey,
236
- reason: reasonInput,
237
- effective_at: new Date().toISOString(),
238
- });
239
- if (insErr) {
240
- if ((insErr as { code?: string }).code === '23505') {
241
- return json(200, { ok: true, duplicate: true });
242
- }
243
- return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
244
- }
245
-
246
- // 8. Apply the plan change in Stripe. proration_behavior: 'always_invoice'
247
- // bills/credits the difference immediately rather than deferring it to the
248
- // next regular invoice, matching the "settle now, not later" precedent set
249
- // by admin-cancel-membership's immediate scheduled-cancellation refunds.
250
- let updatedSub: Stripe.Subscription;
251
- try {
252
- updatedSub = await stripe.subscriptions.update(
253
- subscriptionId,
254
- {
255
- items: [{ id: item.id, ...priceUpdate } as any],
256
- proration_behavior: 'always_invoice',
257
- metadata: { plan_id: newPlanId, plan_slug: newPlan.slug },
258
- },
259
- { idempotencyKey },
260
- );
261
- } catch (e) {
262
- const msg = e instanceof Error ? e.message : String(e);
263
- return json(500, { ok: false, error: 'stripe_update_failed', detail: msg });
264
- }
265
-
266
- // 9. Read back the real invoice 'always_invoice' just created — this is
267
- // the authoritative amount/status, never the pre-update estimate.
268
- let invoiceId: string | null = null;
269
- let invoiceAmountCents: number | null = null;
270
- let invoiceStatus: string | null = null;
271
- try {
272
- const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
273
- const latest = invoices.data[0];
274
- if (latest) {
275
- invoiceId = latest.id ?? null;
276
- invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
277
- invoiceStatus = latest.status ?? null;
278
- }
279
- } catch (e) {
280
- const msg = e instanceof Error ? e.message : String(e);
281
- await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
282
- message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
283
- }, { severity: 'warning' });
284
- }
285
-
286
- // 10. Authoritative membership write, done immediately after the Stripe
287
- // mutation that produced it.
288
- const { error: updErr } = await admin
289
- .from('memberships')
290
- .update({ plan_id: newPlanId, status: updatedSub.status })
291
- .eq('id', membershipId);
292
- if (updErr) {
293
- await logOps(admin, 'membership_plan_change_db_write_failed', {
294
- message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
295
- }, { severity: 'error' });
296
- return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
297
- }
298
-
299
- return json(200, {
300
- ok: true,
301
- status: updatedSub.status,
302
- new_plan_id: newPlanId,
303
- invoice_id: invoiceId,
304
- invoice_amount_cents: invoiceAmountCents,
305
- invoice_status: invoiceStatus,
306
- estimated_net_cents: estimatedNetCents,
307
- });
308
- }
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import Stripe from 'npm:stripe@17.5.0';
3
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
6
+
7
+ const corsHeaders = {
8
+ 'Access-Control-Allow-Origin': '*',
9
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
+ };
12
+
13
+ interface CallerClaims {
14
+ sub: string;
15
+ email?: string;
16
+ aal?: string;
17
+ }
18
+
19
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
20
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
21
+ function getJwks(supabaseUrl: string) {
22
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
23
+ return jwksCache;
24
+ }
25
+
26
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
27
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
28
+ const token = authHeader.slice(7).trim();
29
+ try {
30
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
31
+ const claims = payload as unknown as CallerClaims;
32
+ if (!claims.sub) return null;
33
+ return claims;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function json(status: number, body: unknown) {
40
+ return new Response(JSON.stringify(body), {
41
+ status,
42
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
43
+ });
44
+ }
45
+
46
+ // Only these statuses may have their plan changed. past_due is excluded
47
+ // deliberately — dunning must resolve (or the member must be cancelled)
48
+ // before a plan change is attempted, to avoid stacking a proration on top
49
+ // of an already-failing payment method.
50
+ const CHANGEABLE = new Set(['active', 'trialing']);
51
+
52
+ type PlanRow = {
53
+ id: string;
54
+ slug: string;
55
+ name: string;
56
+ category: string;
57
+ is_private_office: boolean;
58
+ active: boolean;
59
+ billable: boolean;
60
+ billing_interval: string | null;
61
+ price_cents: number | null;
62
+ stripe_price_id: string | null;
63
+ stripe_product_id: string | null;
64
+ };
65
+
66
+ export async function handle(req: Request): Promise<Response> {
67
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
68
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
69
+
70
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
71
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
72
+
73
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
74
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
75
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
76
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
77
+ const callerEmail = (caller.email ?? '').toLowerCase();
78
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
79
+
80
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
81
+ auth: { persistSession: false, autoRefreshToken: false },
82
+ });
83
+
84
+ const [ipOk, emailOk] = await Promise.all([
85
+ checkRateLimit(admin, 'admin-change-membership-plan-ip', clientIp(req), 30, 300),
86
+ checkRateLimit(admin, 'admin-change-membership-plan-email', callerEmail, 20, 300),
87
+ ]);
88
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
89
+
90
+ const { data: allow, error: allowErr } = await admin
91
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
92
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
93
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
94
+
95
+ let body: {
96
+ membership_id?: string;
97
+ new_plan_id?: string;
98
+ reason?: string;
99
+ idempotency_key?: string;
100
+ dry_run?: boolean;
101
+ };
102
+ try {
103
+ body = await req.json();
104
+ } catch {
105
+ return json(400, { ok: false, error: 'invalid_json' });
106
+ }
107
+
108
+ const membershipId = (body.membership_id ?? '').trim();
109
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
110
+ return json(400, { ok: false, error: 'invalid_membership_id' });
111
+ }
112
+ const newPlanId = (body.new_plan_id ?? '').trim();
113
+ if (!/^[0-9a-f-]{36}$/i.test(newPlanId)) {
114
+ return json(400, { ok: false, error: 'invalid_new_plan_id' });
115
+ }
116
+ const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
117
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
118
+ if (!idempotencyKey || idempotencyKey.length > 100) {
119
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
120
+ }
121
+ const dryRun = !!body.dry_run;
122
+
123
+ // 1. Live membership state.
124
+ const { data: membership, error: mErr } = await admin
125
+ .from('memberships')
126
+ .select('id,email,status,stripe_subscription_id,plan_id,cancel_at')
127
+ .eq('id', membershipId)
128
+ .maybeSingle();
129
+ if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
130
+ if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
131
+ if (membership.cancel_at) return json(400, { ok: false, error: 'pending_cancellation' });
132
+ if (!CHANGEABLE.has(membership.status)) {
133
+ return json(400, { ok: false, error: 'not_changeable', detail: `status is ${membership.status}` });
134
+ }
135
+ const subscriptionId = membership.stripe_subscription_id;
136
+ if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
137
+ if (newPlanId === membership.plan_id) return json(400, { ok: false, error: 'same_plan' });
138
+
139
+ // 2. Load both plan rows in one query.
140
+ const { data: planRows, error: planErr } = await admin
141
+ .from('membership_plans')
142
+ .select('id,slug,name,category,is_private_office,active,billable,billing_interval,price_cents,stripe_price_id,stripe_product_id')
143
+ .in('id', [membership.plan_id, newPlanId]);
144
+ if (planErr) return json(500, { ok: false, error: 'load_plans_failed', detail: planErr.message });
145
+ const currentPlan = (planRows ?? []).find((p) => p.id === membership.plan_id) as PlanRow | undefined;
146
+ const newPlan = (planRows ?? []).find((p) => p.id === newPlanId) as PlanRow | undefined;
147
+ if (!currentPlan) return json(500, { ok: false, error: 'current_plan_not_found' });
148
+ if (!newPlan) return json(400, { ok: false, error: 'plan_not_found' });
149
+
150
+ // 3. Plan-change eligibility guards. Private-office plans are sign-before-pay
151
+ // (BoldSign agreement precedes any charge) and must never be reachable from
152
+ // this self-serve-adjacent admin path, as either the source or destination.
153
+ // is_private_office is a capability flag (D33 Phase 0.5 Phase 7), not the
154
+ // catalog 'category' column — a resale operator's own category taxonomy
155
+ // need not include 'office' at all for this guard to still apply correctly.
156
+ if (currentPlan.is_private_office || newPlan.is_private_office) {
157
+ return json(400, { ok: false, error: 'office_plan_blocked' });
158
+ }
159
+ if (!newPlan.active) return json(400, { ok: false, error: 'plan_inactive' });
160
+ if (!newPlan.billable) return json(400, { ok: false, error: 'plan_not_billable' });
161
+ // Scope limited to monthly plans for now, matching the site's own
162
+ // `subscribable` definition (build-pricing-bootstrap.mjs) — annual plans
163
+ // are out of scope for this feature.
164
+ if ((newPlan.billing_interval ?? '').toLowerCase() !== 'month') {
165
+ return json(400, { ok: false, error: 'unsupported_billing_interval' });
166
+ }
167
+
168
+ // 4. Resolve what to actually send Stripe for the new price. Mirrors the
169
+ // ad-hoc checkout path: a stored stripe_price_id is preferred, but a plan
170
+ // with only price_cents + a Stripe product can still be priced inline.
171
+ let priceUpdate: { price: string } | { price_data: Record<string, unknown> };
172
+ if (newPlan.stripe_price_id) {
173
+ priceUpdate = { price: newPlan.stripe_price_id };
174
+ } else if (newPlan.stripe_product_id && typeof newPlan.price_cents === 'number' && newPlan.price_cents > 0) {
175
+ priceUpdate = {
176
+ price_data: {
177
+ currency: 'usd',
178
+ unit_amount: newPlan.price_cents,
179
+ recurring: { interval: 'month' },
180
+ product: newPlan.stripe_product_id,
181
+ },
182
+ };
183
+ } else {
184
+ return json(400, { ok: false, error: 'plan_not_chargeable' });
185
+ }
186
+
187
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
188
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
189
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
190
+
191
+ // 5. Retrieve subscription (read-only) for the item id + current period bounds.
192
+ let sub: Stripe.Subscription;
193
+ try {
194
+ sub = await stripe.subscriptions.retrieve(subscriptionId);
195
+ } catch (e) {
196
+ const msg = e instanceof Error ? e.message : String(e);
197
+ return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
198
+ }
199
+ if (sub.items.data.length !== 1) {
200
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
201
+ }
202
+ const item = sub.items.data[0] as unknown as {
203
+ id: string;
204
+ current_period_start: number;
205
+ current_period_end: number;
206
+ };
207
+ const periodStart = item.current_period_start;
208
+ const periodEnd = item.current_period_end;
209
+ const nowUnix = Math.floor(Date.now() / 1000);
210
+
211
+ // 6. Estimate-only proration math (same time-remaining-fraction approach as
212
+ // admin-cancel-membership's refund estimate) — a heads-up for the admin.
213
+ // The REAL amount is always read back from the invoice Stripe actually
214
+ // creates in step 8, never trusted from this estimate.
215
+ const span = periodEnd - periodStart;
216
+ const remaining = Math.max(0, periodEnd - nowUnix);
217
+ const fraction = span > 0 ? remaining / span : 0;
218
+ const creditForOldPlan = Math.round((currentPlan.price_cents ?? 0) * fraction);
219
+ const chargeForNewPlan = Math.round((newPlan.price_cents ?? 0) * fraction);
220
+ const estimatedNetCents = chargeForNewPlan - creditForOldPlan;
221
+
222
+ if (dryRun) {
223
+ return json(200, {
224
+ ok: true,
225
+ estimated_net_cents: estimatedNetCents,
226
+ current_plan_name: currentPlan.name,
227
+ new_plan_name: newPlan.name,
228
+ });
229
+ }
230
+
231
+ // 7. Idempotent audit insert — claims the idempotency key immediately
232
+ // before the Stripe mutation, same discipline as admin-cancel-membership.
233
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
234
+ membership_id: membershipId,
235
+ action: 'plan_changed',
236
+ old_plan_id: membership.plan_id,
237
+ new_plan_id: newPlanId,
238
+ actor_email: callerEmail,
239
+ idempotency_key: idempotencyKey,
240
+ reason: reasonInput,
241
+ effective_at: new Date().toISOString(),
242
+ });
243
+ if (insErr) {
244
+ if ((insErr as { code?: string }).code === '23505') {
245
+ return json(200, { ok: true, duplicate: true });
246
+ }
247
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
248
+ }
249
+
250
+ // 8. Apply the plan change in Stripe. proration_behavior: 'always_invoice'
251
+ // bills/credits the difference immediately rather than deferring it to the
252
+ // next regular invoice, matching the "settle now, not later" precedent set
253
+ // by admin-cancel-membership's immediate scheduled-cancellation refunds.
254
+ let updatedSub: Stripe.Subscription;
255
+ try {
256
+ updatedSub = await stripe.subscriptions.update(
257
+ subscriptionId,
258
+ {
259
+ items: [{ id: item.id, ...priceUpdate } as any],
260
+ proration_behavior: 'always_invoice',
261
+ metadata: { plan_id: newPlanId, plan_slug: newPlan.slug },
262
+ },
263
+ { idempotencyKey },
264
+ );
265
+ } catch (e) {
266
+ const msg = e instanceof Error ? e.message : String(e);
267
+ return json(500, { ok: false, error: 'stripe_update_failed', detail: msg });
268
+ }
269
+
270
+ // 9. Read back the real invoice 'always_invoice' just created — this is
271
+ // the authoritative amount/status, never the pre-update estimate.
272
+ let invoiceId: string | null = null;
273
+ let invoiceAmountCents: number | null = null;
274
+ let invoiceStatus: string | null = null;
275
+ try {
276
+ const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
277
+ const latest = invoices.data[0];
278
+ if (latest) {
279
+ invoiceId = latest.id ?? null;
280
+ invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
281
+ invoiceStatus = latest.status ?? null;
282
+ }
283
+ } catch (e) {
284
+ const msg = e instanceof Error ? e.message : String(e);
285
+ await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
286
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
287
+ }, { severity: 'warning' });
288
+ }
289
+
290
+ // 10. Authoritative membership write, done immediately after the Stripe
291
+ // mutation that produced it.
292
+ const { error: updErr } = await admin
293
+ .from('memberships')
294
+ .update({ plan_id: newPlanId, status: updatedSub.status })
295
+ .eq('id', membershipId);
296
+ if (updErr) {
297
+ await logOps(admin, 'membership_plan_change_db_write_failed', {
298
+ message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
299
+ }, { severity: 'error' });
300
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
301
+ }
302
+
303
+ return json(200, {
304
+ ok: true,
305
+ status: updatedSub.status,
306
+ new_plan_id: newPlanId,
307
+ invoice_id: invoiceId,
308
+ invoice_amount_cents: invoiceAmountCents,
309
+ invoice_status: invoiceStatus,
310
+ estimated_net_cents: estimatedNetCents,
311
+ });
312
+ }