@simplelayer/graniteer-core 0.2.1 → 0.2.2

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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  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 -460
  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 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  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 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -334
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -217
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,319 +1,319 @@
1
- // supabase/functions/stripe-db-reconcile/index.ts
2
- //
3
- // PERMANENT, SECRET-GATED, READ-ONLY reconciler.
4
- // Independently pulls live Stripe state and compares it to the memberships +
5
- // bookings tables, reporting drift REGARDLESS OF CAUSE. Read-only: Stripe
6
- // list/retrieve + Supabase selects only; no Stripe writes, no business-table
7
- // writes. Only outbound is a best-effort Slack alert. Scheduled server-side by
8
- // pg_cron (daily) via private.trigger_reconcile() -> net.http_post {"notify":true}.
9
- // Slack webhook URL comes from the service-role RPC get_slack_webhook() (env
10
- // fallback). Uses the operator's own STRIPE_SECRET_KEY only.
11
-
12
- import { createClient } from 'npm:@supabase/supabase-js@2';
13
- import Stripe from 'npm:stripe@17.5.0';
14
-
15
- const WINDOW_DAYS = 7;
16
-
17
- const STRIPE_LIVE = new Set(['active', 'trialing', 'past_due', 'unpaid', 'incomplete']);
18
- const DB_ENTITLED = new Set(['active', 'trialing', 'past_due']);
19
- const STRIPE_NOT_LIVE = new Set(['canceled', 'incomplete_expired', 'paused']);
20
- const BOOKING_POST_PAID_OK = new Set([
21
- 'paid', 'cancelled_credited', 'cancelled_forfeited', 'cancelled_refunded',
22
- ]);
23
- const MEMBERSHIP_NOT_STUCK = new Set(['active', 'canceled', 'trialing']);
24
-
25
- async function postSlack(text: string, url: string | null): Promise<boolean> {
26
- if (!url) return false;
27
- try {
28
- const r = await fetch(url, {
29
- method: 'POST',
30
- headers: { 'Content-Type': 'application/json' },
31
- body: JSON.stringify({ text }),
32
- signal: AbortSignal.timeout(10000),
33
- });
34
- return r.ok;
35
- } catch {
36
- return false;
37
- }
38
- }
39
-
40
- function safeEqual(a: string, b: string): boolean {
41
- const enc = new TextEncoder();
42
- const ab = enc.encode(a), bb = enc.encode(b);
43
- if (ab.length !== bb.length) return false;
44
- let diff = 0;
45
- for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
46
- return diff === 0;
47
- }
48
-
49
- function subCurrentPeriodEndISO(sub: any): string | null {
50
- const top = sub.current_period_end as number | undefined;
51
- if (typeof top === 'number') return new Date(top * 1000).toISOString();
52
- const itemCpe = sub.items?.data?.[0]?.current_period_end as number | undefined;
53
- if (typeof itemCpe === 'number') return new Date(itemCpe * 1000).toISOString();
54
- return null;
55
- }
56
-
57
- function periodEndDrift(stripeISO: string | null, dbISO: string | null): boolean {
58
- if (!stripeISO && !dbISO) return false;
59
- if (!stripeISO || !dbISO) return true;
60
- return Math.abs(new Date(stripeISO).getTime() - new Date(dbISO).getTime()) > 120_000;
61
- }
62
-
63
- export async function handle(req: Request, operator: { stripeAccountLabel: string }): Promise<Response> {
64
- if (req.method !== 'POST' && req.method !== 'GET') {
65
- return new Response('Method not allowed', { status: 405 });
66
- }
67
-
68
- const provided = req.headers.get('x-reconcile-secret');
69
- if (!provided) return new Response('Unauthorized', { status: 401 });
70
-
71
- let notify = false;
72
- let ping = false;
73
- if (req.method === 'POST') {
74
- const body = await req.json().catch(() => ({} as any));
75
- notify = body?.notify === true;
76
- ping = body?.ping === true;
77
- }
78
-
79
- const supabase = createClient(
80
- Deno.env.get('SUPABASE_URL')!,
81
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
82
- );
83
-
84
- const { data: gate, error: gateErr } = await supabase.rpc('get_reconcile_secret');
85
- const expected = typeof gate === 'string' ? gate : null;
86
- if (gateErr || !expected || !safeEqual(provided, expected)) {
87
- return new Response('Unauthorized', { status: 401 });
88
- }
89
-
90
- const { data: hook } = await supabase.rpc('get_slack_webhook');
91
- const webhookUrl = (typeof hook === 'string' && hook) ? hook : (Deno.env.get('SLACK_ALERT_WEBHOOK_URL') || null);
92
-
93
- if (ping) {
94
- const pinged = await postSlack(':satellite: GC Stripe⇄DB reconciler alert path OK (ping).', webhookUrl);
95
- return new Response(JSON.stringify({ ok: true, pinged, webhook_configured: !!webhookUrl }), {
96
- headers: { 'Content-Type': 'application/json' }, status: 200,
97
- });
98
- }
99
-
100
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
101
- if (!stripeKey) return new Response('Not configured', { status: 500 });
102
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
103
-
104
- const drift: Array<Record<string, unknown>> = [];
105
- const push = (kind: string, severity: 'warning' | 'error', extra: Record<string, unknown>) =>
106
- drift.push({ kind, severity, ...extra });
107
-
108
- try {
109
- const stripeSubs: any[] = [];
110
- for await (const sub of stripe.subscriptions.list({ status: 'all', limit: 100 })) {
111
- stripeSubs.push(sub);
112
- }
113
- const subById = new Map<string, any>(stripeSubs.map((s) => [s.id, s]));
114
-
115
- const { data: memberships, error: mErr } = await supabase
116
- .from('memberships')
117
- .select('id,email,status,current_period_end,stripe_customer_id,stripe_subscription_id,updated_at');
118
- if (mErr) throw new Error('memberships read failed: ' + mErr.message);
119
- const memBySub = new Map<string, any>();
120
- for (const m of memberships ?? []) {
121
- if (m.stripe_subscription_id) memBySub.set(m.stripe_subscription_id, m);
122
- }
123
-
124
- for (const sub of stripeSubs) {
125
- const m = memBySub.get(sub.id);
126
- const stripeStatus = sub.status;
127
- const stripeCpe = subCurrentPeriodEndISO(sub);
128
- if (STRIPE_LIVE.has(stripeStatus)) {
129
- if (!m) {
130
- push('membership_missing_in_db', 'error', {
131
- subscription_id: sub.id, stripe_status: stripeStatus,
132
- customer_id: typeof sub.customer === 'string' ? sub.customer : sub.customer?.id ?? null,
133
- detail: 'Stripe has a live subscription with no memberships row.',
134
- });
135
- continue;
136
- }
137
- if (m.status !== stripeStatus) {
138
- push('membership_status_mismatch', 'error', {
139
- subscription_id: sub.id, email: m.email,
140
- stripe_status: stripeStatus, db_status: m.status,
141
- detail: 'memberships.status disagrees with live Stripe status.',
142
- });
143
- }
144
- if (periodEndDrift(stripeCpe, m.current_period_end ? new Date(m.current_period_end).toISOString() : null)) {
145
- push('membership_period_end_mismatch', 'warning', {
146
- subscription_id: sub.id, email: m.email,
147
- stripe_period_end: stripeCpe, db_period_end: m.current_period_end,
148
- detail: 'current_period_end drift between Stripe and DB.',
149
- });
150
- }
151
- }
152
- }
153
-
154
- for (const m of memberships ?? []) {
155
- if (!DB_ENTITLED.has(m.status)) continue;
156
- if (!m.stripe_subscription_id || !m.stripe_customer_id) {
157
- push('membership_missing_stripe_ids', 'error', {
158
- membership_id: m.id, email: m.email, db_status: m.status,
159
- detail: 'Entitled membership row is missing stripe_subscription_id/customer_id.',
160
- });
161
- continue;
162
- }
163
- const sub = subById.get(m.stripe_subscription_id);
164
- if (!sub) {
165
- push('membership_db_active_stripe_absent', 'error', {
166
- subscription_id: m.stripe_subscription_id, email: m.email, db_status: m.status,
167
- detail: 'DB shows entitled membership but Stripe has no such subscription.',
168
- });
169
- } else if (STRIPE_NOT_LIVE.has(sub.status)) {
170
- push('membership_db_active_stripe_dead', 'error', {
171
- subscription_id: m.stripe_subscription_id, email: m.email,
172
- db_status: m.status, stripe_status: sub.status,
173
- detail: 'DB shows entitled membership but Stripe subscription is canceled/expired/paused.',
174
- });
175
- }
176
- }
177
-
178
- for (const m of memberships ?? []) {
179
- if (MEMBERSHIP_NOT_STUCK.has(m.status)) continue;
180
- const ageMs = m.updated_at ? Date.now() - new Date(m.updated_at).getTime() : 0;
181
- if (ageMs > 3_600_000) {
182
- push('membership_stuck_nonterminal', 'error', {
183
- membership_id: m.id, email: m.email, db_status: m.status,
184
- hours_stuck: Math.round((ageMs / 3_600_000) * 10) / 10,
185
- detail: 'Membership stuck in a non-terminal status (not active/canceled/trialing) for >1h.',
186
- });
187
- }
188
- }
189
-
190
- const sinceTs = Math.floor(Date.now() / 1000) - WINDOW_DAYS * 86400;
191
- const paidSessions: any[] = [];
192
- for await (const s of stripe.checkout.sessions.list({ created: { gte: sinceTs }, limit: 100 })) {
193
- if (s.mode === 'payment' && s.payment_status === 'paid') paidSessions.push(s);
194
- }
195
-
196
- for (const s of paidSessions) {
197
- const checkoutType = s.metadata?.checkout_type ?? null;
198
-
199
- // frAIdays lunch pre-orders use a standalone Stripe Payment Link and are
200
- // tracked outside gc-io entirely (Luma/luma-receiver), not in `bookings`.
201
- // Skip them here rather than false-alarming on every lunch order.
202
- const FRAIDAYS_LUNCH_PAYMENT_LINK = 'plink_1U3fBDIRhYejQaS5rlYIQF5P';
203
- if (s.payment_link === FRAIDAYS_LUNCH_PAYMENT_LINK) continue;
204
-
205
- // Day-pass checkouts are recorded in day_pass_purchases, not bookings.
206
- if (checkoutType === 'day_pass') {
207
- const { data: dp, error: dpErr } = await supabase
208
- .from('day_pass_purchases')
209
- .select('id,refunded_at')
210
- .eq('stripe_checkout_session_id', s.id)
211
- .maybeSingle();
212
- if (dpErr) {
213
- push('reconciler_day_pass_lookup_error', 'error', {
214
- session_id: s.id,
215
- detail: 'day_pass_purchases lookup errored: ' + dpErr.message,
216
- });
217
- } else if (!dp) {
218
- push('paid_session_no_day_pass', 'error', {
219
- session_id: s.id, amount_total: s.amount_total,
220
- email: s.customer_details?.email ?? s.customer_email ?? null,
221
- detail: 'Stripe recorded a PAID day-pass checkout session with no matching day_pass_purchases row.',
222
- });
223
- } else {
224
- const piId = typeof s.payment_intent === 'string' ? s.payment_intent : s.payment_intent?.id ?? null;
225
- if (piId) {
226
- try {
227
- const pi = await stripe.paymentIntents.retrieve(piId, { expand: ['latest_charge'] });
228
- const charge = pi.latest_charge as any;
229
- const stripeRefunded = !!charge && (charge.refunded === true || (charge.amount_refunded ?? 0) > 0);
230
- if (stripeRefunded && !dp.refunded_at) {
231
- push('day_pass_refund_not_reflected', 'error', {
232
- session_id: s.id, payment_intent: piId,
233
- detail: 'Stripe shows this day-pass charge refunded but day_pass_purchases.refunded_at is not set.',
234
- });
235
- } else if (!stripeRefunded && dp.refunded_at) {
236
- push('day_pass_refund_mismatch', 'warning', {
237
- session_id: s.id, payment_intent: piId,
238
- detail: 'day_pass_purchases.refunded_at is set but Stripe shows this charge as NOT refunded.',
239
- });
240
- }
241
- } catch (e) {
242
- push('reconciler_day_pass_refund_check_error', 'warning', {
243
- session_id: s.id, payment_intent: piId,
244
- detail: 'Failed to retrieve payment intent for refund check: ' + String(e),
245
- });
246
- }
247
- }
248
- }
249
- continue;
250
- }
251
-
252
- const bid = s.metadata?.booking_id ?? null;
253
- let bk: any = null;
254
- let lookupErr: string | null = null;
255
- if (bid) {
256
- const { data, error } = await supabase.from('bookings').select('id,status').eq('id', bid).maybeSingle();
257
- if (error) lookupErr = error.message; else bk = data;
258
- }
259
- if (!bk && !lookupErr) {
260
- const { data, error } = await supabase.from('bookings').select('id,status').eq('stripe_session_id', s.id).maybeSingle();
261
- if (error) lookupErr = error.message; else bk = data;
262
- }
263
- if (lookupErr) {
264
- push('reconciler_booking_lookup_error', 'error', {
265
- session_id: s.id, booking_id: bid, detail: 'bookings lookup errored: ' + lookupErr,
266
- });
267
- } else if (!bk) {
268
- push('paid_session_no_booking', 'error', {
269
- session_id: s.id, booking_id: bid, amount_total: s.amount_total,
270
- email: s.customer_details?.email ?? s.customer_email ?? null,
271
- detail: 'Stripe recorded a PAID checkout session with no matching booking row.',
272
- });
273
- } else if (
274
- !BOOKING_POST_PAID_OK.has(bk.status) &&
275
- // Commons deposit Checkout Sessions deliberately leave the booking in
276
- // 'deposit_paid' (a partial capture, not a bug) — not a post-paid
277
- // terminal status for any other session type.
278
- !(s.metadata?.payment_type === 'commons_deposit' && bk.status === 'deposit_paid')
279
- ) {
280
- push('paid_session_booking_not_paid', 'error', {
281
- session_id: s.id, booking_id: bk.id, db_status: bk.status, amount_total: s.amount_total,
282
- detail: 'Paid checkout session maps to a booking that never reached a paid/cancelled state.',
283
- });
284
- }
285
- }
286
-
287
- let notified = false;
288
- if (notify && drift.length > 0) {
289
- const lines = drift.map((d: any) =>
290
- `• [${d.severity}] ${d.kind} — ${d.subscription_id || d.booking_id || d.membership_id || d.session_id || ''} ${d.email || ''} — ${d.detail}`.trim());
291
- const text = `:money_with_wings: *GC Stripe⇄DB reconcile — ${drift.length} drift item(s)*\n`
292
- + lines.join('\n')
293
- + `\n_Verify in Stripe (${operator.stripeAccountLabel} acct only) and reconcile the DB row to live status._`;
294
- notified = await postSlack(text, webhookUrl);
295
- }
296
-
297
- return new Response(JSON.stringify({
298
- ok: true,
299
- generated_at: new Date().toISOString(),
300
- window_days: WINDOW_DAYS,
301
- counts: {
302
- stripe_subs_total: stripeSubs.length,
303
- stripe_subs_live: stripeSubs.filter((s) => STRIPE_LIVE.has(s.status)).length,
304
- db_memberships: (memberships ?? []).length,
305
- paid_sessions_checked: paidSessions.length,
306
- },
307
- drift_count: drift.length,
308
- drift,
309
- notified,
310
- }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
311
- } catch (e) {
312
- if (notify) {
313
- await postSlack(`:rotating_light: *GC Stripe⇄DB reconcile FAILED* — ${String(e)}`, webhookUrl);
314
- }
315
- return new Response(JSON.stringify({ ok: false, error: String(e) }), {
316
- headers: { 'Content-Type': 'application/json' }, status: 500,
317
- });
318
- }
319
- }
1
+ // supabase/functions/stripe-db-reconcile/index.ts
2
+ //
3
+ // PERMANENT, SECRET-GATED, READ-ONLY reconciler.
4
+ // Independently pulls live Stripe state and compares it to the memberships +
5
+ // bookings tables, reporting drift REGARDLESS OF CAUSE. Read-only: Stripe
6
+ // list/retrieve + Supabase selects only; no Stripe writes, no business-table
7
+ // writes. Only outbound is a best-effort Slack alert. Scheduled server-side by
8
+ // pg_cron (daily) via private.trigger_reconcile() -> net.http_post {"notify":true}.
9
+ // Slack webhook URL comes from the service-role RPC get_slack_webhook() (env
10
+ // fallback). Uses the operator's own STRIPE_SECRET_KEY only.
11
+
12
+ import { createClient } from 'npm:@supabase/supabase-js@2';
13
+ import Stripe from 'npm:stripe@17.5.0';
14
+
15
+ const WINDOW_DAYS = 7;
16
+
17
+ const STRIPE_LIVE = new Set(['active', 'trialing', 'past_due', 'unpaid', 'incomplete']);
18
+ const DB_ENTITLED = new Set(['active', 'trialing', 'past_due']);
19
+ const STRIPE_NOT_LIVE = new Set(['canceled', 'incomplete_expired', 'paused']);
20
+ const BOOKING_POST_PAID_OK = new Set([
21
+ 'paid', 'cancelled_credited', 'cancelled_forfeited', 'cancelled_refunded',
22
+ ]);
23
+ const MEMBERSHIP_NOT_STUCK = new Set(['active', 'canceled', 'trialing']);
24
+
25
+ async function postSlack(text: string, url: string | null): Promise<boolean> {
26
+ if (!url) return false;
27
+ try {
28
+ const r = await fetch(url, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: JSON.stringify({ text }),
32
+ signal: AbortSignal.timeout(10000),
33
+ });
34
+ return r.ok;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ function safeEqual(a: string, b: string): boolean {
41
+ const enc = new TextEncoder();
42
+ const ab = enc.encode(a), bb = enc.encode(b);
43
+ if (ab.length !== bb.length) return false;
44
+ let diff = 0;
45
+ for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
46
+ return diff === 0;
47
+ }
48
+
49
+ function subCurrentPeriodEndISO(sub: any): string | null {
50
+ const top = sub.current_period_end as number | undefined;
51
+ if (typeof top === 'number') return new Date(top * 1000).toISOString();
52
+ const itemCpe = sub.items?.data?.[0]?.current_period_end as number | undefined;
53
+ if (typeof itemCpe === 'number') return new Date(itemCpe * 1000).toISOString();
54
+ return null;
55
+ }
56
+
57
+ function periodEndDrift(stripeISO: string | null, dbISO: string | null): boolean {
58
+ if (!stripeISO && !dbISO) return false;
59
+ if (!stripeISO || !dbISO) return true;
60
+ return Math.abs(new Date(stripeISO).getTime() - new Date(dbISO).getTime()) > 120_000;
61
+ }
62
+
63
+ export async function handle(req: Request, operator: { stripeAccountLabel: string }): Promise<Response> {
64
+ if (req.method !== 'POST' && req.method !== 'GET') {
65
+ return new Response('Method not allowed', { status: 405 });
66
+ }
67
+
68
+ const provided = req.headers.get('x-reconcile-secret');
69
+ if (!provided) return new Response('Unauthorized', { status: 401 });
70
+
71
+ let notify = false;
72
+ let ping = false;
73
+ if (req.method === 'POST') {
74
+ const body = await req.json().catch(() => ({} as any));
75
+ notify = body?.notify === true;
76
+ ping = body?.ping === true;
77
+ }
78
+
79
+ const supabase = createClient(
80
+ Deno.env.get('SUPABASE_URL')!,
81
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
82
+ );
83
+
84
+ const { data: gate, error: gateErr } = await supabase.rpc('get_reconcile_secret');
85
+ const expected = typeof gate === 'string' ? gate : null;
86
+ if (gateErr || !expected || !safeEqual(provided, expected)) {
87
+ return new Response('Unauthorized', { status: 401 });
88
+ }
89
+
90
+ const { data: hook } = await supabase.rpc('get_slack_webhook');
91
+ const webhookUrl = (typeof hook === 'string' && hook) ? hook : (Deno.env.get('SLACK_ALERT_WEBHOOK_URL') || null);
92
+
93
+ if (ping) {
94
+ const pinged = await postSlack(':satellite: GC Stripe⇄DB reconciler alert path OK (ping).', webhookUrl);
95
+ return new Response(JSON.stringify({ ok: true, pinged, webhook_configured: !!webhookUrl }), {
96
+ headers: { 'Content-Type': 'application/json' }, status: 200,
97
+ });
98
+ }
99
+
100
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
101
+ if (!stripeKey) return new Response('Not configured', { status: 500 });
102
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
103
+
104
+ const drift: Array<Record<string, unknown>> = [];
105
+ const push = (kind: string, severity: 'warning' | 'error', extra: Record<string, unknown>) =>
106
+ drift.push({ kind, severity, ...extra });
107
+
108
+ try {
109
+ const stripeSubs: any[] = [];
110
+ for await (const sub of stripe.subscriptions.list({ status: 'all', limit: 100 })) {
111
+ stripeSubs.push(sub);
112
+ }
113
+ const subById = new Map<string, any>(stripeSubs.map((s) => [s.id, s]));
114
+
115
+ const { data: memberships, error: mErr } = await supabase
116
+ .from('memberships')
117
+ .select('id,email,status,current_period_end,stripe_customer_id,stripe_subscription_id,updated_at');
118
+ if (mErr) throw new Error('memberships read failed: ' + mErr.message);
119
+ const memBySub = new Map<string, any>();
120
+ for (const m of memberships ?? []) {
121
+ if (m.stripe_subscription_id) memBySub.set(m.stripe_subscription_id, m);
122
+ }
123
+
124
+ for (const sub of stripeSubs) {
125
+ const m = memBySub.get(sub.id);
126
+ const stripeStatus = sub.status;
127
+ const stripeCpe = subCurrentPeriodEndISO(sub);
128
+ if (STRIPE_LIVE.has(stripeStatus)) {
129
+ if (!m) {
130
+ push('membership_missing_in_db', 'error', {
131
+ subscription_id: sub.id, stripe_status: stripeStatus,
132
+ customer_id: typeof sub.customer === 'string' ? sub.customer : sub.customer?.id ?? null,
133
+ detail: 'Stripe has a live subscription with no memberships row.',
134
+ });
135
+ continue;
136
+ }
137
+ if (m.status !== stripeStatus) {
138
+ push('membership_status_mismatch', 'error', {
139
+ subscription_id: sub.id, email: m.email,
140
+ stripe_status: stripeStatus, db_status: m.status,
141
+ detail: 'memberships.status disagrees with live Stripe status.',
142
+ });
143
+ }
144
+ if (periodEndDrift(stripeCpe, m.current_period_end ? new Date(m.current_period_end).toISOString() : null)) {
145
+ push('membership_period_end_mismatch', 'warning', {
146
+ subscription_id: sub.id, email: m.email,
147
+ stripe_period_end: stripeCpe, db_period_end: m.current_period_end,
148
+ detail: 'current_period_end drift between Stripe and DB.',
149
+ });
150
+ }
151
+ }
152
+ }
153
+
154
+ for (const m of memberships ?? []) {
155
+ if (!DB_ENTITLED.has(m.status)) continue;
156
+ if (!m.stripe_subscription_id || !m.stripe_customer_id) {
157
+ push('membership_missing_stripe_ids', 'error', {
158
+ membership_id: m.id, email: m.email, db_status: m.status,
159
+ detail: 'Entitled membership row is missing stripe_subscription_id/customer_id.',
160
+ });
161
+ continue;
162
+ }
163
+ const sub = subById.get(m.stripe_subscription_id);
164
+ if (!sub) {
165
+ push('membership_db_active_stripe_absent', 'error', {
166
+ subscription_id: m.stripe_subscription_id, email: m.email, db_status: m.status,
167
+ detail: 'DB shows entitled membership but Stripe has no such subscription.',
168
+ });
169
+ } else if (STRIPE_NOT_LIVE.has(sub.status)) {
170
+ push('membership_db_active_stripe_dead', 'error', {
171
+ subscription_id: m.stripe_subscription_id, email: m.email,
172
+ db_status: m.status, stripe_status: sub.status,
173
+ detail: 'DB shows entitled membership but Stripe subscription is canceled/expired/paused.',
174
+ });
175
+ }
176
+ }
177
+
178
+ for (const m of memberships ?? []) {
179
+ if (MEMBERSHIP_NOT_STUCK.has(m.status)) continue;
180
+ const ageMs = m.updated_at ? Date.now() - new Date(m.updated_at).getTime() : 0;
181
+ if (ageMs > 3_600_000) {
182
+ push('membership_stuck_nonterminal', 'error', {
183
+ membership_id: m.id, email: m.email, db_status: m.status,
184
+ hours_stuck: Math.round((ageMs / 3_600_000) * 10) / 10,
185
+ detail: 'Membership stuck in a non-terminal status (not active/canceled/trialing) for >1h.',
186
+ });
187
+ }
188
+ }
189
+
190
+ const sinceTs = Math.floor(Date.now() / 1000) - WINDOW_DAYS * 86400;
191
+ const paidSessions: any[] = [];
192
+ for await (const s of stripe.checkout.sessions.list({ created: { gte: sinceTs }, limit: 100 })) {
193
+ if (s.mode === 'payment' && s.payment_status === 'paid') paidSessions.push(s);
194
+ }
195
+
196
+ for (const s of paidSessions) {
197
+ const checkoutType = s.metadata?.checkout_type ?? null;
198
+
199
+ // frAIdays lunch pre-orders use a standalone Stripe Payment Link and are
200
+ // tracked outside gc-io entirely (Luma/luma-receiver), not in `bookings`.
201
+ // Skip them here rather than false-alarming on every lunch order.
202
+ const FRAIDAYS_LUNCH_PAYMENT_LINK = 'plink_1U3fBDIRhYejQaS5rlYIQF5P';
203
+ if (s.payment_link === FRAIDAYS_LUNCH_PAYMENT_LINK) continue;
204
+
205
+ // Day-pass checkouts are recorded in day_pass_purchases, not bookings.
206
+ if (checkoutType === 'day_pass') {
207
+ const { data: dp, error: dpErr } = await supabase
208
+ .from('day_pass_purchases')
209
+ .select('id,refunded_at')
210
+ .eq('stripe_checkout_session_id', s.id)
211
+ .maybeSingle();
212
+ if (dpErr) {
213
+ push('reconciler_day_pass_lookup_error', 'error', {
214
+ session_id: s.id,
215
+ detail: 'day_pass_purchases lookup errored: ' + dpErr.message,
216
+ });
217
+ } else if (!dp) {
218
+ push('paid_session_no_day_pass', 'error', {
219
+ session_id: s.id, amount_total: s.amount_total,
220
+ email: s.customer_details?.email ?? s.customer_email ?? null,
221
+ detail: 'Stripe recorded a PAID day-pass checkout session with no matching day_pass_purchases row.',
222
+ });
223
+ } else {
224
+ const piId = typeof s.payment_intent === 'string' ? s.payment_intent : s.payment_intent?.id ?? null;
225
+ if (piId) {
226
+ try {
227
+ const pi = await stripe.paymentIntents.retrieve(piId, { expand: ['latest_charge'] });
228
+ const charge = pi.latest_charge as any;
229
+ const stripeRefunded = !!charge && (charge.refunded === true || (charge.amount_refunded ?? 0) > 0);
230
+ if (stripeRefunded && !dp.refunded_at) {
231
+ push('day_pass_refund_not_reflected', 'error', {
232
+ session_id: s.id, payment_intent: piId,
233
+ detail: 'Stripe shows this day-pass charge refunded but day_pass_purchases.refunded_at is not set.',
234
+ });
235
+ } else if (!stripeRefunded && dp.refunded_at) {
236
+ push('day_pass_refund_mismatch', 'warning', {
237
+ session_id: s.id, payment_intent: piId,
238
+ detail: 'day_pass_purchases.refunded_at is set but Stripe shows this charge as NOT refunded.',
239
+ });
240
+ }
241
+ } catch (e) {
242
+ push('reconciler_day_pass_refund_check_error', 'warning', {
243
+ session_id: s.id, payment_intent: piId,
244
+ detail: 'Failed to retrieve payment intent for refund check: ' + String(e),
245
+ });
246
+ }
247
+ }
248
+ }
249
+ continue;
250
+ }
251
+
252
+ const bid = s.metadata?.booking_id ?? null;
253
+ let bk: any = null;
254
+ let lookupErr: string | null = null;
255
+ if (bid) {
256
+ const { data, error } = await supabase.from('bookings').select('id,status').eq('id', bid).maybeSingle();
257
+ if (error) lookupErr = error.message; else bk = data;
258
+ }
259
+ if (!bk && !lookupErr) {
260
+ const { data, error } = await supabase.from('bookings').select('id,status').eq('stripe_session_id', s.id).maybeSingle();
261
+ if (error) lookupErr = error.message; else bk = data;
262
+ }
263
+ if (lookupErr) {
264
+ push('reconciler_booking_lookup_error', 'error', {
265
+ session_id: s.id, booking_id: bid, detail: 'bookings lookup errored: ' + lookupErr,
266
+ });
267
+ } else if (!bk) {
268
+ push('paid_session_no_booking', 'error', {
269
+ session_id: s.id, booking_id: bid, amount_total: s.amount_total,
270
+ email: s.customer_details?.email ?? s.customer_email ?? null,
271
+ detail: 'Stripe recorded a PAID checkout session with no matching booking row.',
272
+ });
273
+ } else if (
274
+ !BOOKING_POST_PAID_OK.has(bk.status) &&
275
+ // Commons deposit Checkout Sessions deliberately leave the booking in
276
+ // 'deposit_paid' (a partial capture, not a bug) — not a post-paid
277
+ // terminal status for any other session type.
278
+ !(s.metadata?.payment_type === 'commons_deposit' && bk.status === 'deposit_paid')
279
+ ) {
280
+ push('paid_session_booking_not_paid', 'error', {
281
+ session_id: s.id, booking_id: bk.id, db_status: bk.status, amount_total: s.amount_total,
282
+ detail: 'Paid checkout session maps to a booking that never reached a paid/cancelled state.',
283
+ });
284
+ }
285
+ }
286
+
287
+ let notified = false;
288
+ if (notify && drift.length > 0) {
289
+ const lines = drift.map((d: any) =>
290
+ `• [${d.severity}] ${d.kind} — ${d.subscription_id || d.booking_id || d.membership_id || d.session_id || ''} ${d.email || ''} — ${d.detail}`.trim());
291
+ const text = `:money_with_wings: *GC Stripe⇄DB reconcile — ${drift.length} drift item(s)*\n`
292
+ + lines.join('\n')
293
+ + `\n_Verify in Stripe (${operator.stripeAccountLabel} acct only) and reconcile the DB row to live status._`;
294
+ notified = await postSlack(text, webhookUrl);
295
+ }
296
+
297
+ return new Response(JSON.stringify({
298
+ ok: true,
299
+ generated_at: new Date().toISOString(),
300
+ window_days: WINDOW_DAYS,
301
+ counts: {
302
+ stripe_subs_total: stripeSubs.length,
303
+ stripe_subs_live: stripeSubs.filter((s) => STRIPE_LIVE.has(s.status)).length,
304
+ db_memberships: (memberships ?? []).length,
305
+ paid_sessions_checked: paidSessions.length,
306
+ },
307
+ drift_count: drift.length,
308
+ drift,
309
+ notified,
310
+ }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
311
+ } catch (e) {
312
+ if (notify) {
313
+ await postSlack(`:rotating_light: *GC Stripe⇄DB reconcile FAILED* — ${String(e)}`, webhookUrl);
314
+ }
315
+ return new Response(JSON.stringify({ ok: false, error: String(e) }), {
316
+ headers: { 'Content-Type': 'application/json' }, status: 500,
317
+ });
318
+ }
319
+ }