@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,142 +1,142 @@
1
- // Space Availability Range — read-only, public "all-rooms availability
2
- // calendar" feed. For every active, bookable room (or a caller-supplied
3
- // subset), returns one open/partial/full-style status per calendar day over
4
- // a requested range.
5
- //
6
- // PRIVACY: status only, never booking details. No contact name/email/phone,
7
- // no ghl_contact_id, no notes, no Stripe/GHL references — none of that may
8
- // ever leave this function.
9
- //
10
- // All "is this room busy" logic comes from _shared/availability.ts
11
- // (getBusyRangesDetailed unions `bookings` + `blackouts`, same as
12
- // booking-availability and timetable-spaces). Do not add a second
13
- // implementation here.
14
- //
15
- // Deliberately does NOT consult the `business_hours` table. That table is
16
- // currently empty, so `getBusinessHoursRow` (used by booking-availability
17
- // and timetable-spaces to bound a slot window) resolves to "closed" for
18
- // every room/weekday today — and this feature's status vocabulary has no
19
- // "closed" state to report that as. Gating on it here would make every
20
- // hourly/day_block day silently unrepresentable. Instead each day's status
21
- // is computed over the full America/Los_Angeles calendar day (local
22
- // midnight to local midnight), reusing the same laWallToUtc timezone
23
- // conversion booking-availability already uses, just with different wall
24
- // times (0:00) instead of a business_hours row's open/close.
25
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
26
- import { createClient } from 'npm:@supabase/supabase-js@2';
27
- import { z } from 'npm:zod@3.23.8';
28
- import { getBusyRangesDetailed, laWallToUtc } from 'npm:@simplelayer/graniteer-core/availability';
29
- import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
30
- import { dateRange, nextDateStr, statusForDay } from './dayStatus.ts';
31
-
32
- const MAX_RANGE_DAYS = 31;
33
-
34
- const Body = z.object({
35
- start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
36
- end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
37
- room_ids: z.array(z.string().uuid()).optional(),
38
- });
39
-
40
- interface RoomRow {
41
- id: string;
42
- name: string;
43
- seats: number;
44
- amenities: unknown;
45
- booking_mode: string;
46
- }
47
-
48
- export async function handle(req: Request): Promise<Response> {
49
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
-
51
- try {
52
- const raw = await req.json().catch(() => ({}));
53
- const parsed = Body.safeParse(raw);
54
- if (!parsed.success) {
55
- return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
56
- status: 400,
57
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
58
- });
59
- }
60
-
61
- const { start_date, end_date, room_ids } = parsed.data;
62
-
63
- const [sy, sm, sd] = start_date.split('-').map(Number);
64
- const [ey, em, ed] = end_date.split('-').map(Number);
65
- const spanDays = Math.round((Date.UTC(ey, em - 1, ed) - Date.UTC(sy, sm - 1, sd)) / 86400000);
66
- if (spanDays < 0) {
67
- return new Response(JSON.stringify({ error: 'end_date must not be before start_date' }), {
68
- status: 400,
69
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
70
- });
71
- }
72
- if (spanDays > MAX_RANGE_DAYS - 1) {
73
- return new Response(
74
- JSON.stringify({ error: `Date range too large (max ${MAX_RANGE_DAYS} days).` }),
75
- { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
76
- );
77
- }
78
-
79
- const supabase = createClient(
80
- Deno.env.get('SUPABASE_URL')!,
81
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
82
- );
83
-
84
- // Read-only, public, browsed like booking-availability's own widget —
85
- // same generous per-IP limit, not the tighter write-path limits.
86
- const availOk = await checkRateLimit(supabase, 'space-availability-range-ip', clientIp(req), 60, 60);
87
- if (!availOk) {
88
- return new Response(
89
- JSON.stringify({ error: 'Too many requests - please wait a moment and try again.' }),
90
- { status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
91
- );
92
- }
93
-
94
- let roomQuery = supabase
95
- .from('rooms')
96
- .select('id,name,seats,amenities,booking_mode')
97
- .eq('active', true)
98
- .eq('room_type', 'bookable');
99
- if (room_ids && room_ids.length > 0) {
100
- roomQuery = roomQuery.in('id', room_ids);
101
- }
102
- const { data: roomsData, error: roomsErr } = await roomQuery.order('name');
103
- if (roomsErr) throw roomsErr;
104
- const rooms = (roomsData ?? []) as RoomRow[];
105
-
106
- const dates = dateRange(start_date, end_date);
107
-
108
- const results = await Promise.all(
109
- rooms.map(async (room) => {
110
- const days = await Promise.all(
111
- dates.map(async (dateStr) => {
112
- const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
113
- const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
114
- const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
115
- const { busy, unparsed } = await getBusyRangesDetailed(supabase, room.id, rangeLiteral);
116
- return {
117
- date: dateStr,
118
- status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
119
- };
120
- }),
121
- );
122
- return {
123
- id: room.id,
124
- name: room.name,
125
- seats: room.seats,
126
- amenities: Array.isArray(room.amenities) ? room.amenities : [],
127
- booking_mode: room.booking_mode,
128
- days,
129
- };
130
- }),
131
- );
132
-
133
- return new Response(JSON.stringify({ rooms: results }), {
134
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
135
- });
136
- } catch (e) {
137
- return new Response(
138
- JSON.stringify({ error: e instanceof Error ? e.message : String(e) }),
139
- { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
140
- );
141
- }
142
- }
1
+ // Space Availability Range — read-only, public "all-rooms availability
2
+ // calendar" feed. For every active, bookable room (or a caller-supplied
3
+ // subset), returns one open/partial/full-style status per calendar day over
4
+ // a requested range.
5
+ //
6
+ // PRIVACY: status only, never booking details. No contact name/email/phone,
7
+ // no ghl_contact_id, no notes, no Stripe/GHL references — none of that may
8
+ // ever leave this function.
9
+ //
10
+ // All "is this room busy" logic comes from _shared/availability.ts
11
+ // (getBusyRangesDetailed unions `bookings` + `blackouts`, same as
12
+ // booking-availability and timetable-spaces). Do not add a second
13
+ // implementation here.
14
+ //
15
+ // Deliberately does NOT consult the `business_hours` table. That table is
16
+ // currently empty, so `getBusinessHoursRow` (used by booking-availability
17
+ // and timetable-spaces to bound a slot window) resolves to "closed" for
18
+ // every room/weekday today — and this feature's status vocabulary has no
19
+ // "closed" state to report that as. Gating on it here would make every
20
+ // hourly/day_block day silently unrepresentable. Instead each day's status
21
+ // is computed over the full America/Los_Angeles calendar day (local
22
+ // midnight to local midnight), reusing the same laWallToUtc timezone
23
+ // conversion booking-availability already uses, just with different wall
24
+ // times (0:00) instead of a business_hours row's open/close.
25
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
26
+ import { createClient } from 'npm:@supabase/supabase-js@2';
27
+ import { z } from 'npm:zod@3.23.8';
28
+ import { getBusyRangesDetailed, laWallToUtc } from 'npm:@simplelayer/graniteer-core/availability';
29
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
30
+ import { dateRange, nextDateStr, statusForDay } from './dayStatus.ts';
31
+
32
+ const MAX_RANGE_DAYS = 31;
33
+
34
+ const Body = z.object({
35
+ start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
36
+ end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
37
+ room_ids: z.array(z.string().uuid()).optional(),
38
+ });
39
+
40
+ interface RoomRow {
41
+ id: string;
42
+ name: string;
43
+ seats: number;
44
+ amenities: unknown;
45
+ booking_mode: string;
46
+ }
47
+
48
+ export async function handle(req: Request): Promise<Response> {
49
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
50
+
51
+ try {
52
+ const raw = await req.json().catch(() => ({}));
53
+ const parsed = Body.safeParse(raw);
54
+ if (!parsed.success) {
55
+ return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
56
+ status: 400,
57
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
58
+ });
59
+ }
60
+
61
+ const { start_date, end_date, room_ids } = parsed.data;
62
+
63
+ const [sy, sm, sd] = start_date.split('-').map(Number);
64
+ const [ey, em, ed] = end_date.split('-').map(Number);
65
+ const spanDays = Math.round((Date.UTC(ey, em - 1, ed) - Date.UTC(sy, sm - 1, sd)) / 86400000);
66
+ if (spanDays < 0) {
67
+ return new Response(JSON.stringify({ error: 'end_date must not be before start_date' }), {
68
+ status: 400,
69
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
70
+ });
71
+ }
72
+ if (spanDays > MAX_RANGE_DAYS - 1) {
73
+ return new Response(
74
+ JSON.stringify({ error: `Date range too large (max ${MAX_RANGE_DAYS} days).` }),
75
+ { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
76
+ );
77
+ }
78
+
79
+ const supabase = createClient(
80
+ Deno.env.get('SUPABASE_URL')!,
81
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
82
+ );
83
+
84
+ // Read-only, public, browsed like booking-availability's own widget —
85
+ // same generous per-IP limit, not the tighter write-path limits.
86
+ const availOk = await checkRateLimit(supabase, 'space-availability-range-ip', clientIp(req), 60, 60);
87
+ if (!availOk) {
88
+ return new Response(
89
+ JSON.stringify({ error: 'Too many requests - please wait a moment and try again.' }),
90
+ { status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
91
+ );
92
+ }
93
+
94
+ let roomQuery = supabase
95
+ .from('rooms')
96
+ .select('id,name,seats,amenities,booking_mode')
97
+ .eq('active', true)
98
+ .eq('room_type', 'bookable');
99
+ if (room_ids && room_ids.length > 0) {
100
+ roomQuery = roomQuery.in('id', room_ids);
101
+ }
102
+ const { data: roomsData, error: roomsErr } = await roomQuery.order('name');
103
+ if (roomsErr) throw roomsErr;
104
+ const rooms = (roomsData ?? []) as RoomRow[];
105
+
106
+ const dates = dateRange(start_date, end_date);
107
+
108
+ const results = await Promise.all(
109
+ rooms.map(async (room) => {
110
+ const days = await Promise.all(
111
+ dates.map(async (dateStr) => {
112
+ const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
113
+ const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
114
+ const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
115
+ const { busy, unparsed } = await getBusyRangesDetailed(supabase, room.id, rangeLiteral);
116
+ return {
117
+ date: dateStr,
118
+ status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
119
+ };
120
+ }),
121
+ );
122
+ return {
123
+ id: room.id,
124
+ name: room.name,
125
+ seats: room.seats,
126
+ amenities: Array.isArray(room.amenities) ? room.amenities : [],
127
+ booking_mode: room.booking_mode,
128
+ days,
129
+ };
130
+ }),
131
+ );
132
+
133
+ return new Response(JSON.stringify({ rooms: results }), {
134
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
135
+ });
136
+ } catch (e) {
137
+ return new Response(
138
+ JSON.stringify({ error: e instanceof Error ? e.message : String(e) }),
139
+ { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
140
+ );
141
+ }
142
+ }
@@ -0,0 +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
+ }