@simplelayer/graniteer-core 0.1.2 → 0.2.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 (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 +334 -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 +217 -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,311 +1,311 @@
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
- const CANCELLABLE = new Set(['active', 'trialing', 'past_due']);
47
-
48
- export async function handle(req: Request): Promise<Response> {
49
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
- if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
-
52
- const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
- const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
-
55
- const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
56
- const caller = await verifyCaller(authHeader, SUPABASE_URL);
57
- if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
58
- if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
59
- const callerEmail = (caller.email ?? '').toLowerCase();
60
- if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
61
-
62
- const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
63
- auth: { persistSession: false, autoRefreshToken: false },
64
- });
65
-
66
- const [ipOk, emailOk] = await Promise.all([
67
- checkRateLimit(admin, 'admin-cancel-membership-ip', clientIp(req), 30, 300),
68
- checkRateLimit(admin, 'admin-cancel-membership-email', callerEmail, 20, 300),
69
- ]);
70
- if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
71
-
72
- const { data: allow, error: allowErr } = await admin
73
- .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
74
- if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
75
- if (!allow) return json(403, { ok: false, error: 'not_authorized' });
76
-
77
- let body: {
78
- membership_id?: string;
79
- effective?: string;
80
- effective_date?: string;
81
- issue_refund?: boolean;
82
- reason?: string;
83
- idempotency_key?: string;
84
- dry_run?: boolean;
85
- };
86
- try {
87
- body = await req.json();
88
- } catch {
89
- return json(400, { ok: false, error: 'invalid_json' });
90
- }
91
-
92
- const membershipId = (body.membership_id ?? '').trim();
93
- if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
94
- return json(400, { ok: false, error: 'invalid_membership_id' });
95
- }
96
- const effective = body.effective;
97
- if (effective !== 'now' && effective !== 'date') {
98
- return json(400, { ok: false, error: 'invalid_effective' });
99
- }
100
- let effectiveDate: Date | null = null;
101
- if (effective === 'date') {
102
- const raw = (body.effective_date ?? '').trim();
103
- const parsedDate = raw ? new Date(raw) : null;
104
- if (!parsedDate || isNaN(parsedDate.getTime())) {
105
- return json(400, { ok: false, error: 'invalid_effective_date' });
106
- }
107
- const startOfToday = new Date();
108
- startOfToday.setHours(0, 0, 0, 0);
109
- if (parsedDate.getTime() < startOfToday.getTime()) {
110
- return json(400, { ok: false, error: 'effective_date_in_past' });
111
- }
112
- // Use end-of-day (UTC) for the picked date so "today" still resolves to a
113
- // genuinely future instant rather than midnight, which is almost always
114
- // already past by the time this request executes.
115
- parsedDate.setUTCHours(23, 59, 59, 0);
116
- effectiveDate = parsedDate;
117
- }
118
- const issueRefund = !!body.issue_refund;
119
- const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
120
- const idempotencyKey = (body.idempotency_key ?? '').trim();
121
- if (!idempotencyKey || idempotencyKey.length > 100) {
122
- return json(400, { ok: false, error: 'invalid_idempotency_key' });
123
- }
124
- const dryRun = !!body.dry_run;
125
-
126
- // 1. Live state re-check (concurrency guard).
127
- const { data: membership, error: mErr } = await admin
128
- .from('memberships')
129
- .select('id,email,status,stripe_subscription_id,plan_id')
130
- .eq('id', membershipId)
131
- .maybeSingle();
132
- if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
133
- if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
134
- if (membership.status === 'canceled') return json(400, { ok: false, error: 'already_canceled' });
135
- if (!CANCELLABLE.has(membership.status)) {
136
- return json(400, { ok: false, error: 'not_cancellable', detail: `status is ${membership.status}` });
137
- }
138
- const subscriptionId = membership.stripe_subscription_id;
139
- if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
140
-
141
- // 2. Audit action string.
142
- const action = effective === 'now'
143
- ? (issueRefund ? 'cancel_immediate_refunded' : 'cancel_immediate_no_refund')
144
- : (issueRefund ? 'cancel_scheduled_refunded' : 'cancel_scheduled_no_refund');
145
-
146
- // 3. Idempotent audit insert (skipped for dry runs).
147
- if (!dryRun) {
148
- const { error: insErr } = await admin.from('membership_admin_actions').insert({
149
- membership_id: membershipId,
150
- action,
151
- actor_email: callerEmail,
152
- idempotency_key: idempotencyKey,
153
- reason: reasonInput,
154
- effective_at: effective === 'now' ? new Date().toISOString() : effectiveDate!.toISOString(),
155
- });
156
- if (insErr) {
157
- if ((insErr as { code?: string }).code === '23505') {
158
- return json(200, { ok: true, duplicate: true });
159
- }
160
- return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
161
- }
162
- }
163
-
164
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
165
- if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
166
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
167
-
168
- // 4. Retrieve subscription.
169
- let sub: Stripe.Subscription;
170
- try {
171
- sub = await stripe.subscriptions.retrieve(subscriptionId);
172
- } catch (e) {
173
- const msg = e instanceof Error ? e.message : String(e);
174
- return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
175
- }
176
- if (sub.items.data.length !== 1) {
177
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
178
- }
179
- const item = sub.items.data[0] as unknown as { current_period_start: number; current_period_end: number };
180
- const periodStart = item.current_period_start;
181
- const periodEnd = item.current_period_end;
182
-
183
- // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
184
- // future or Stripe rejects the cancel_at update — the safety floor below is
185
- // the fix for the bug where "today" (midnight) or a clamp to periodStart
186
- // could resolve to a past instant by call time. Refund math further below
187
- // uses a SEPARATE, period-clamped value derived from this one, so the floor
188
- // never distorts the proration amount.
189
- let cancelAtUnix = effective === 'now'
190
- ? Math.floor(Date.now() / 1000)
191
- : Math.floor(effectiveDate!.getTime() / 1000);
192
- const nowUnix = Math.floor(Date.now() / 1000);
193
- cancelAtUnix = Math.max(cancelAtUnix, nowUnix + 60);
194
-
195
- // 6. Refund estimate (read-only; computed for both dry-run and real runs,
196
- // but no money moves and nothing is mutated in Stripe yet).
197
- let refundCents: number | null = null;
198
- let stripeRefundId: string | null = null;
199
- let invoice: Stripe.Invoice | undefined;
200
- let paymentIntent: { id: string; latest_charge?: { amount_refunded?: number } | null } | null = null;
201
- if (issueRefund) {
202
- try {
203
- const list = await stripe.invoices.list({
204
- subscription: subscriptionId,
205
- status: 'paid',
206
- limit: 1,
207
- expand: ['data.payment_intent.latest_charge'],
208
- });
209
- invoice = list.data[0];
210
- } catch (e) {
211
- const msg = e instanceof Error ? e.message : String(e);
212
- return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
213
- }
214
- if (!invoice) {
215
- if (!dryRun) {
216
- try {
217
- await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
218
- } catch { /* non-fatal */ }
219
- }
220
- return json(400, { ok: false, error: 'no_refundable_invoice' });
221
- }
222
- paymentIntent = invoice.payment_intent as unknown as
223
- { id: string; latest_charge?: { amount_refunded?: number } | null } | null;
224
- const charge = paymentIntent?.latest_charge ?? null;
225
- const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
226
-
227
- const cancelAtForRefund = Math.min(Math.max(cancelAtUnix, periodStart), periodEnd);
228
- const span = periodEnd - periodStart;
229
- const prorated = span > 0
230
- ? Math.round((invoice.amount_paid ?? 0) * (periodEnd - cancelAtForRefund) / span)
231
- : 0;
232
- refundCents = Math.max(0, Math.min(prorated, refundableCents));
233
- }
234
-
235
- if (dryRun) {
236
- return json(200, { ok: true, refund_amount_cents: refundCents ?? 0 });
237
- }
238
-
239
- // 7. Apply cancellation in Stripe FIRST. If this fails, the function returns
240
- // here and no refund is ever created — money never moves ahead of the
241
- // actual cancellation taking effect.
242
- let updatedSub: Stripe.Subscription;
243
- try {
244
- updatedSub = effective === 'now'
245
- ? await stripe.subscriptions.cancel(subscriptionId, {}, { idempotencyKey })
246
- : await stripe.subscriptions.update(
247
- subscriptionId,
248
- { cancel_at: cancelAtUnix, proration_behavior: 'none' },
249
- { idempotencyKey },
250
- );
251
- } catch (e) {
252
- const msg = e instanceof Error ? e.message : String(e);
253
- return json(500, { ok: false, error: 'stripe_cancel_failed', detail: msg });
254
- }
255
-
256
- const cancelAtIso = updatedSub.cancel_at ? new Date(updatedSub.cancel_at * 1000).toISOString() : null;
257
-
258
- // 8. Authoritative membership write, done immediately after the Stripe
259
- // mutation that produced it — so even if the refund step below fails, our
260
- // DB already correctly reflects the real cancellation state.
261
- const { error: updErr } = await admin
262
- .from('memberships')
263
- .update({ status: updatedSub.status, cancel_at: cancelAtIso })
264
- .eq('id', membershipId);
265
- if (updErr) {
266
- await logOps(admin, 'membership_cancel_db_write_failed', {
267
- message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
268
- }, { severity: 'error' });
269
- return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
270
- }
271
-
272
- // 9. Issue the refund only after cancellation succeeded and was persisted.
273
- if (issueRefund && refundCents && refundCents > 0) {
274
- if (!paymentIntent?.id) {
275
- return json(400, { ok: false, error: 'no_payment_intent' });
276
- }
277
- try {
278
- const refund = await stripe.refunds.create({
279
- payment_intent: paymentIntent.id,
280
- amount: refundCents,
281
- reason: 'requested_by_customer',
282
- metadata: { membership_id: membershipId, actor: callerEmail },
283
- }, { idempotencyKey });
284
- stripeRefundId = refund.id;
285
- } catch (e) {
286
- const msg = e instanceof Error ? e.message : String(e);
287
- return json(500, { ok: false, error: 'stripe_refund_failed', detail: msg });
288
- }
289
- }
290
-
291
- // 10. Backfill audit row with refund outcome.
292
- const { error: auditUpdErr } = await admin
293
- .from('membership_admin_actions')
294
- .update({ refund_amount_cents: refundCents ?? null, stripe_refund_id: stripeRefundId })
295
- .eq('idempotency_key', idempotencyKey);
296
- if (auditUpdErr) {
297
- await logOps(admin, 'membership_cancel_audit_update_failed', {
298
- message: auditUpdErr.message, idempotency_key: idempotencyKey,
299
- }, { severity: 'warning' });
300
- }
301
-
302
- // 11. GHL note skipped: `memberships` has no ghl_contact_id-equivalent column.
303
-
304
- return json(200, {
305
- ok: true,
306
- status: updatedSub.status,
307
- refund_amount_cents: refundCents ?? null,
308
- stripe_refund_id: stripeRefundId ?? null,
309
- cancel_at: cancelAtIso,
310
- });
311
- }
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
+ const CANCELLABLE = new Set(['active', 'trialing', 'past_due']);
47
+
48
+ export async function handle(req: Request): Promise<Response> {
49
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
51
+
52
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
53
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
54
+
55
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
56
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
57
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
58
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
59
+ const callerEmail = (caller.email ?? '').toLowerCase();
60
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
61
+
62
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
63
+ auth: { persistSession: false, autoRefreshToken: false },
64
+ });
65
+
66
+ const [ipOk, emailOk] = await Promise.all([
67
+ checkRateLimit(admin, 'admin-cancel-membership-ip', clientIp(req), 30, 300),
68
+ checkRateLimit(admin, 'admin-cancel-membership-email', callerEmail, 20, 300),
69
+ ]);
70
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
71
+
72
+ const { data: allow, error: allowErr } = await admin
73
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
74
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
75
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
76
+
77
+ let body: {
78
+ membership_id?: string;
79
+ effective?: string;
80
+ effective_date?: string;
81
+ issue_refund?: boolean;
82
+ reason?: string;
83
+ idempotency_key?: string;
84
+ dry_run?: boolean;
85
+ };
86
+ try {
87
+ body = await req.json();
88
+ } catch {
89
+ return json(400, { ok: false, error: 'invalid_json' });
90
+ }
91
+
92
+ const membershipId = (body.membership_id ?? '').trim();
93
+ if (!/^[0-9a-f-]{36}$/i.test(membershipId)) {
94
+ return json(400, { ok: false, error: 'invalid_membership_id' });
95
+ }
96
+ const effective = body.effective;
97
+ if (effective !== 'now' && effective !== 'date') {
98
+ return json(400, { ok: false, error: 'invalid_effective' });
99
+ }
100
+ let effectiveDate: Date | null = null;
101
+ if (effective === 'date') {
102
+ const raw = (body.effective_date ?? '').trim();
103
+ const parsedDate = raw ? new Date(raw) : null;
104
+ if (!parsedDate || isNaN(parsedDate.getTime())) {
105
+ return json(400, { ok: false, error: 'invalid_effective_date' });
106
+ }
107
+ const startOfToday = new Date();
108
+ startOfToday.setHours(0, 0, 0, 0);
109
+ if (parsedDate.getTime() < startOfToday.getTime()) {
110
+ return json(400, { ok: false, error: 'effective_date_in_past' });
111
+ }
112
+ // Use end-of-day (UTC) for the picked date so "today" still resolves to a
113
+ // genuinely future instant rather than midnight, which is almost always
114
+ // already past by the time this request executes.
115
+ parsedDate.setUTCHours(23, 59, 59, 0);
116
+ effectiveDate = parsedDate;
117
+ }
118
+ const issueRefund = !!body.issue_refund;
119
+ const reasonInput = (body.reason ?? '').trim().slice(0, 500) || null;
120
+ const idempotencyKey = (body.idempotency_key ?? '').trim();
121
+ if (!idempotencyKey || idempotencyKey.length > 100) {
122
+ return json(400, { ok: false, error: 'invalid_idempotency_key' });
123
+ }
124
+ const dryRun = !!body.dry_run;
125
+
126
+ // 1. Live state re-check (concurrency guard).
127
+ const { data: membership, error: mErr } = await admin
128
+ .from('memberships')
129
+ .select('id,email,status,stripe_subscription_id,plan_id')
130
+ .eq('id', membershipId)
131
+ .maybeSingle();
132
+ if (mErr) return json(500, { ok: false, error: 'load_membership_failed', detail: mErr.message });
133
+ if (!membership) return json(404, { ok: false, error: 'membership_not_found' });
134
+ if (membership.status === 'canceled') return json(400, { ok: false, error: 'already_canceled' });
135
+ if (!CANCELLABLE.has(membership.status)) {
136
+ return json(400, { ok: false, error: 'not_cancellable', detail: `status is ${membership.status}` });
137
+ }
138
+ const subscriptionId = membership.stripe_subscription_id;
139
+ if (!subscriptionId) return json(400, { ok: false, error: 'no_subscription' });
140
+
141
+ // 2. Audit action string.
142
+ const action = effective === 'now'
143
+ ? (issueRefund ? 'cancel_immediate_refunded' : 'cancel_immediate_no_refund')
144
+ : (issueRefund ? 'cancel_scheduled_refunded' : 'cancel_scheduled_no_refund');
145
+
146
+ // 3. Idempotent audit insert (skipped for dry runs).
147
+ if (!dryRun) {
148
+ const { error: insErr } = await admin.from('membership_admin_actions').insert({
149
+ membership_id: membershipId,
150
+ action,
151
+ actor_email: callerEmail,
152
+ idempotency_key: idempotencyKey,
153
+ reason: reasonInput,
154
+ effective_at: effective === 'now' ? new Date().toISOString() : effectiveDate!.toISOString(),
155
+ });
156
+ if (insErr) {
157
+ if ((insErr as { code?: string }).code === '23505') {
158
+ return json(200, { ok: true, duplicate: true });
159
+ }
160
+ return json(500, { ok: false, error: 'audit_insert_failed', detail: insErr.message });
161
+ }
162
+ }
163
+
164
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
165
+ if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
166
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
167
+
168
+ // 4. Retrieve subscription.
169
+ let sub: Stripe.Subscription;
170
+ try {
171
+ sub = await stripe.subscriptions.retrieve(subscriptionId);
172
+ } catch (e) {
173
+ const msg = e instanceof Error ? e.message : String(e);
174
+ return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
175
+ }
176
+ if (sub.items.data.length !== 1) {
177
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
178
+ }
179
+ const item = sub.items.data[0] as unknown as { current_period_start: number; current_period_end: number };
180
+ const periodStart = item.current_period_start;
181
+ const periodEnd = item.current_period_end;
182
+
183
+ // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
184
+ // future or Stripe rejects the cancel_at update — the safety floor below is
185
+ // the fix for the bug where "today" (midnight) or a clamp to periodStart
186
+ // could resolve to a past instant by call time. Refund math further below
187
+ // uses a SEPARATE, period-clamped value derived from this one, so the floor
188
+ // never distorts the proration amount.
189
+ let cancelAtUnix = effective === 'now'
190
+ ? Math.floor(Date.now() / 1000)
191
+ : Math.floor(effectiveDate!.getTime() / 1000);
192
+ const nowUnix = Math.floor(Date.now() / 1000);
193
+ cancelAtUnix = Math.max(cancelAtUnix, nowUnix + 60);
194
+
195
+ // 6. Refund estimate (read-only; computed for both dry-run and real runs,
196
+ // but no money moves and nothing is mutated in Stripe yet).
197
+ let refundCents: number | null = null;
198
+ let stripeRefundId: string | null = null;
199
+ let invoice: Stripe.Invoice | undefined;
200
+ let paymentIntent: { id: string; latest_charge?: { amount_refunded?: number } | null } | null = null;
201
+ if (issueRefund) {
202
+ try {
203
+ const list = await stripe.invoices.list({
204
+ subscription: subscriptionId,
205
+ status: 'paid',
206
+ limit: 1,
207
+ expand: ['data.payment_intent.latest_charge'],
208
+ });
209
+ invoice = list.data[0];
210
+ } catch (e) {
211
+ const msg = e instanceof Error ? e.message : String(e);
212
+ return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
213
+ }
214
+ if (!invoice) {
215
+ if (!dryRun) {
216
+ try {
217
+ await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
218
+ } catch { /* non-fatal */ }
219
+ }
220
+ return json(400, { ok: false, error: 'no_refundable_invoice' });
221
+ }
222
+ paymentIntent = invoice.payment_intent as unknown as
223
+ { id: string; latest_charge?: { amount_refunded?: number } | null } | null;
224
+ const charge = paymentIntent?.latest_charge ?? null;
225
+ const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
226
+
227
+ const cancelAtForRefund = Math.min(Math.max(cancelAtUnix, periodStart), periodEnd);
228
+ const span = periodEnd - periodStart;
229
+ const prorated = span > 0
230
+ ? Math.round((invoice.amount_paid ?? 0) * (periodEnd - cancelAtForRefund) / span)
231
+ : 0;
232
+ refundCents = Math.max(0, Math.min(prorated, refundableCents));
233
+ }
234
+
235
+ if (dryRun) {
236
+ return json(200, { ok: true, refund_amount_cents: refundCents ?? 0 });
237
+ }
238
+
239
+ // 7. Apply cancellation in Stripe FIRST. If this fails, the function returns
240
+ // here and no refund is ever created — money never moves ahead of the
241
+ // actual cancellation taking effect.
242
+ let updatedSub: Stripe.Subscription;
243
+ try {
244
+ updatedSub = effective === 'now'
245
+ ? await stripe.subscriptions.cancel(subscriptionId, {}, { idempotencyKey })
246
+ : await stripe.subscriptions.update(
247
+ subscriptionId,
248
+ { cancel_at: cancelAtUnix, proration_behavior: 'none' },
249
+ { idempotencyKey },
250
+ );
251
+ } catch (e) {
252
+ const msg = e instanceof Error ? e.message : String(e);
253
+ return json(500, { ok: false, error: 'stripe_cancel_failed', detail: msg });
254
+ }
255
+
256
+ const cancelAtIso = updatedSub.cancel_at ? new Date(updatedSub.cancel_at * 1000).toISOString() : null;
257
+
258
+ // 8. Authoritative membership write, done immediately after the Stripe
259
+ // mutation that produced it — so even if the refund step below fails, our
260
+ // DB already correctly reflects the real cancellation state.
261
+ const { error: updErr } = await admin
262
+ .from('memberships')
263
+ .update({ status: updatedSub.status, cancel_at: cancelAtIso })
264
+ .eq('id', membershipId);
265
+ if (updErr) {
266
+ await logOps(admin, 'membership_cancel_db_write_failed', {
267
+ message: updErr.message, membership_id: membershipId, idempotency_key: idempotencyKey,
268
+ }, { severity: 'error' });
269
+ return json(500, { ok: false, error: 'update_membership_failed', detail: updErr.message });
270
+ }
271
+
272
+ // 9. Issue the refund only after cancellation succeeded and was persisted.
273
+ if (issueRefund && refundCents && refundCents > 0) {
274
+ if (!paymentIntent?.id) {
275
+ return json(400, { ok: false, error: 'no_payment_intent' });
276
+ }
277
+ try {
278
+ const refund = await stripe.refunds.create({
279
+ payment_intent: paymentIntent.id,
280
+ amount: refundCents,
281
+ reason: 'requested_by_customer',
282
+ metadata: { membership_id: membershipId, actor: callerEmail },
283
+ }, { idempotencyKey });
284
+ stripeRefundId = refund.id;
285
+ } catch (e) {
286
+ const msg = e instanceof Error ? e.message : String(e);
287
+ return json(500, { ok: false, error: 'stripe_refund_failed', detail: msg });
288
+ }
289
+ }
290
+
291
+ // 10. Backfill audit row with refund outcome.
292
+ const { error: auditUpdErr } = await admin
293
+ .from('membership_admin_actions')
294
+ .update({ refund_amount_cents: refundCents ?? null, stripe_refund_id: stripeRefundId })
295
+ .eq('idempotency_key', idempotencyKey);
296
+ if (auditUpdErr) {
297
+ await logOps(admin, 'membership_cancel_audit_update_failed', {
298
+ message: auditUpdErr.message, idempotency_key: idempotencyKey,
299
+ }, { severity: 'warning' });
300
+ }
301
+
302
+ // 11. GHL note skipped: `memberships` has no ghl_contact_id-equivalent column.
303
+
304
+ return json(200, {
305
+ ok: true,
306
+ status: updatedSub.status,
307
+ refund_amount_cents: refundCents ?? null,
308
+ stripe_refund_id: stripeRefundId ?? null,
309
+ cancel_at: cancelAtIso,
310
+ });
311
+ }