@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,299 +1,299 @@
1
- // supabase/functions/ezeep-usage-reconcile/index.ts
2
- //
3
- // PERMANENT, SECRET-GATED reconciliation gate for ezeep print-usage billing.
4
- // Pulls ezeep's official Reporting API CSV for a calendar month and diffs
5
- // it job-by-job against public.print_jobs. FAILS CLOSED: any missing/extra/
6
- // mismatched job for the month blocks ALL print_usage_periods rows for that
7
- // month from being marked reconciled -- no partial credit, no silent
8
- // auto-correction (Kyle's 2026-08-21 decision). Only a clean diff stamps
9
- // reconciled_at on every pending_bill period for that month -- the gate
10
- // Phase 2's print-usage-bill (not yet built) must read instead of
11
- // pending_bill alone.
12
- //
13
- // Scheduled by pg_cron (monthly, 1st @ 09:20 UTC) via
14
- // private.trigger_ezeep_reconcile() -> net.http_post {}.
15
- //
16
- // ezeep OAuth is Authorization Code Flow. refresh_token ROTATES ON EVERY
17
- // USE (confirmed empirically 2026-08-21) and lives in
18
- // private.ezeep_oauth_state, not a static function secret. The new
19
- // refresh_token is persisted immediately after exchange, before any other
20
- // work, so a downstream failure never strands this on a dead token.
21
-
22
- import { createClient } from 'npm:@supabase/supabase-js@2';
23
-
24
- const EZEEP_TOKEN_URL = 'https://account.ezeep.com/oauth/access_token/';
25
- const EZEEP_API_BASE = 'https://api2.ezeep.com';
26
- const REPORT_POLL_ATTEMPTS = 10;
27
- const REPORT_POLL_DELAY_MS = 3000;
28
-
29
- function safeEqual(a: string, b: string): boolean {
30
- const enc = new TextEncoder();
31
- const ab = enc.encode(a), bb = enc.encode(b);
32
- if (ab.length !== bb.length) return false;
33
- let diff = 0;
34
- for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
35
- return diff === 0;
36
- }
37
-
38
- function priorMonthRange(now = new Date()): { start: string; end: string; periodMonth: string } {
39
- const y = now.getUTCFullYear();
40
- const m = now.getUTCMonth();
41
- const start = new Date(Date.UTC(y, m - 1, 1));
42
- const end = new Date(Date.UTC(y, m, 1));
43
- const iso = (d: Date) => d.toISOString().slice(0, 10);
44
- return { start: iso(start), end: iso(end), periodMonth: iso(start) };
45
- }
46
-
47
- function nextMonthIso(iso: string): string {
48
- const d = new Date(iso + 'T00:00:00Z');
49
- const next = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
50
- return next.toISOString().slice(0, 10);
51
- }
52
-
53
- // Minimal RFC4180 CSV parser: handles quoted fields, embedded commas/quotes,
54
- // and CRLF/LF/CR line endings. ezeep's export needs this -- a naive
55
- // split(',') misaligns columns on rows with commas inside a field.
56
- function parseCsv(text: string): Record<string, string>[] {
57
- const rows: string[][] = [];
58
- let row: string[] = [];
59
- let field = '';
60
- let inQuotes = false;
61
- const clean = text.replace(/^/, '');
62
- for (let i = 0; i < clean.length; i++) {
63
- const c = clean[i];
64
- if (inQuotes) {
65
- if (c === '"') {
66
- if (clean[i + 1] === '"') { field += '"'; i++; } else { inQuotes = false; }
67
- } else field += c;
68
- } else if (c === '"') inQuotes = true;
69
- else if (c === ',') { row.push(field); field = ''; }
70
- else if (c === '\n' || c === '\r') {
71
- if (c === '\r' && clean[i + 1] === '\n') i++;
72
- row.push(field); field = '';
73
- if (row.length > 1 || row[0] !== '') rows.push(row);
74
- row = [];
75
- } else field += c;
76
- }
77
- if (field !== '' || row.length > 0) { row.push(field); rows.push(row); }
78
- if (rows.length === 0) return [];
79
- const header = rows[0];
80
- return rows.slice(1).map((r) => {
81
- const obj: Record<string, string> = {};
82
- header.forEach((h, idx) => { obj[h] = r[idx] ?? ''; });
83
- return obj;
84
- });
85
- }
86
-
87
- async function getOAuthCreds(supabase: any) {
88
- const { data, error } = await supabase.rpc('get_ezeep_oauth_credentials');
89
- if (error || !data) {
90
- throw new Error('failed to load ezeep oauth credentials: ' + (error?.message ?? 'none'));
91
- }
92
- return data as { client_id: string; client_secret: string; refresh_token: string };
93
- }
94
-
95
- async function refreshEzeepToken(
96
- supabase: any,
97
- creds: { client_id: string; client_secret: string; refresh_token: string },
98
- ): Promise<string> {
99
- const basic = btoa(`${creds.client_id}:${creds.client_secret}`);
100
- const res = await fetch(EZEEP_TOKEN_URL, {
101
- method: 'POST',
102
- headers: {
103
- 'Authorization': `Basic ${basic}`,
104
- 'Content-Type': 'application/x-www-form-urlencoded',
105
- },
106
- body: new URLSearchParams({
107
- grant_type: 'refresh_token',
108
- refresh_token: creds.refresh_token,
109
- }),
110
- });
111
- if (!res.ok) {
112
- throw new Error(`ezeep token refresh failed: ${res.status} ${await res.text().catch(() => '')}`);
113
- }
114
- const json = await res.json();
115
- // Persist the rotated refresh token IMMEDIATELY -- before anything else
116
- // that could fail and strand us on a token ezeep has already invalidated.
117
- const { error: writeErr } = await supabase.rpc('set_ezeep_refresh_token', {
118
- new_token: json.refresh_token,
119
- });
120
- if (writeErr) {
121
- throw new Error('CRITICAL: got new ezeep refresh_token but failed to persist it: ' + writeErr.message);
122
- }
123
- return json.access_token as string;
124
- }
125
-
126
- export async function handle(req: Request): Promise<Response> {
127
- if (req.method !== 'POST' && req.method !== 'GET') {
128
- return new Response('Method not allowed', { status: 405 });
129
- }
130
- const provided = req.headers.get('x-reconcile-secret');
131
- if (!provided) return new Response('Unauthorized', { status: 401 });
132
-
133
- const supabase = createClient(
134
- Deno.env.get('SUPABASE_URL')!,
135
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
136
- );
137
-
138
- const { data: gate, error: gateErr } = await supabase.rpc('get_ezeep_reconcile_secret');
139
- const expected = typeof gate === 'string' ? gate : null;
140
- if (gateErr || !expected || !safeEqual(provided, expected)) {
141
- return new Response('Unauthorized', { status: 401 });
142
- }
143
-
144
- let overridePeriod: string | null = null;
145
- if (req.method === 'POST') {
146
- const body = await req.json().catch(() => ({} as any));
147
- if (typeof body?.period_month === 'string') overridePeriod = body.period_month;
148
- }
149
-
150
- try {
151
- const creds = await getOAuthCreds(supabase);
152
- const accessToken = await refreshEzeepToken(supabase, creds);
153
-
154
- const { start, end, periodMonth } = overridePeriod
155
- ? { start: overridePeriod, end: nextMonthIso(overridePeriod), periodMonth: overridePeriod }
156
- : priorMonthRange();
157
-
158
- const createRes = await fetch(`${EZEEP_API_BASE}/reporting/reports`, {
159
- method: 'POST',
160
- headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
161
- body: JSON.stringify({ start, end, csv_delimiter: ',', timestamp_offset: 0 }),
162
- });
163
- if (!createRes.ok) {
164
- throw new Error(`ezeep report create failed: ${createRes.status} ${await createRes.text().catch(() => '')}`);
165
- }
166
- const created = await createRes.json();
167
- const reportId = created.report_id as string;
168
-
169
- let status = created.status as string;
170
- for (let i = 0; i < REPORT_POLL_ATTEMPTS && status === 'pending'; i++) {
171
- await new Promise((r) => setTimeout(r, REPORT_POLL_DELAY_MS));
172
- const pollRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}`, {
173
- headers: { 'Authorization': `Bearer ${accessToken}` },
174
- });
175
- if (!pollRes.ok) throw new Error(`ezeep report poll failed: ${pollRes.status}`);
176
- const polled = await pollRes.json();
177
- status = polled.status;
178
- }
179
- if (status !== 'succeeded') {
180
- throw new Error(`ezeep report did not succeed in time (status=${status}, report_id=${reportId})`);
181
- }
182
-
183
- const dlRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}/download`, {
184
- headers: { 'Authorization': `Bearer ${accessToken}` },
185
- });
186
- if (!dlRes.ok) throw new Error(`ezeep report download failed: ${dlRes.status}`);
187
- const csvText = await dlRes.text();
188
- const rows = parseCsv(csvText);
189
-
190
- // ezeep's own official succeeded-job set for the month.
191
- const ezeepJobs = new Map<string, { pages: number; color: boolean }>();
192
- for (const r of rows) {
193
- if (r['Final status'] !== 'succeeded') continue;
194
- const id = r['Print job ID'];
195
- if (!id) continue;
196
- ezeepJobs.set(id, {
197
- pages: Number(r['Total printed pages'] || 0),
198
- color: r['Chromaticity'] === 'color',
199
- });
200
- }
201
-
202
- const { data: ourJobsRaw, error: jobsErr } = await supabase
203
- .from('print_jobs')
204
- .select('ezeep_printjob_id,total_printed_pages,color,job_created_at,topic')
205
- .eq('topic', 'printjob_succeeded')
206
- .gte('job_created_at', `${start}T00:00:00Z`)
207
- .lt('job_created_at', `${end}T00:00:00Z`);
208
- if (jobsErr) throw new Error('print_jobs read failed: ' + jobsErr.message);
209
-
210
- const ourJobs = new Map<string, { pages: number; color: boolean }>();
211
- for (const j of ourJobsRaw ?? []) {
212
- ourJobs.set(j.ezeep_printjob_id, { pages: j.total_printed_pages, color: j.color });
213
- }
214
-
215
- const missingInOurs: string[] = [];
216
- const mismatched: Array<Record<string, unknown>> = [];
217
- for (const [id, ez] of ezeepJobs) {
218
- const ours = ourJobs.get(id);
219
- if (!ours) { missingInOurs.push(id); continue; }
220
- if (ours.pages !== ez.pages || ours.color !== ez.color) {
221
- mismatched.push({ ezeep_printjob_id: id, ezeep: ez, ours });
222
- }
223
- }
224
- const extraInOurs: string[] = [];
225
- for (const id of ourJobs.keys()) {
226
- if (!ezeepJobs.has(id)) extraInOurs.push(id);
227
- }
228
-
229
- const clean = missingInOurs.length === 0 && extraInOurs.length === 0 && mismatched.length === 0;
230
-
231
- if (!clean) {
232
- await supabase.from('ops_events').insert({
233
- kind: 'ezeep_reconciliation_mismatch',
234
- severity: 'error',
235
- detail: {
236
- period_month: periodMonth,
237
- report_id: reportId,
238
- ezeep_job_count: ezeepJobs.size,
239
- our_job_count: ourJobs.size,
240
- missing_in_ours: missingInOurs.slice(0, 25),
241
- missing_in_ours_count: missingInOurs.length,
242
- extra_in_ours: extraInOurs.slice(0, 25),
243
- extra_in_ours_count: extraInOurs.length,
244
- mismatched: mismatched.slice(0, 25),
245
- mismatched_count: mismatched.length,
246
- },
247
- });
248
- return new Response(JSON.stringify({
249
- ok: true,
250
- clean: false,
251
- period_month: periodMonth,
252
- report_id: reportId,
253
- missing_in_ours_count: missingInOurs.length,
254
- extra_in_ours_count: extraInOurs.length,
255
- mismatched_count: mismatched.length,
256
- }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
257
- }
258
-
259
- const { data: stamped, error: stampErr } = await supabase
260
- .from('print_usage_periods')
261
- .update({ reconciled_at: new Date().toISOString(), reconciliation_report_id: reportId })
262
- .eq('period_month', periodMonth)
263
- .eq('status', 'pending_bill')
264
- .is('reconciled_at', null)
265
- .select('id');
266
- if (stampErr) throw new Error('failed to stamp reconciled_at: ' + stampErr.message);
267
-
268
- await supabase.from('ops_events').insert({
269
- kind: 'ezeep_reconciliation_ok',
270
- severity: 'info',
271
- detail: {
272
- period_month: periodMonth,
273
- report_id: reportId,
274
- ezeep_job_count: ezeepJobs.size,
275
- periods_reconciled: (stamped ?? []).length,
276
- },
277
- });
278
-
279
- return new Response(JSON.stringify({
280
- ok: true,
281
- clean: true,
282
- period_month: periodMonth,
283
- report_id: reportId,
284
- ezeep_job_count: ezeepJobs.size,
285
- periods_reconciled: (stamped ?? []).length,
286
- }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
287
- } catch (e) {
288
- try {
289
- await supabase.from('ops_events').insert({
290
- kind: 'ezeep_reconciliation_error',
291
- severity: 'error',
292
- detail: { error: String(e) },
293
- });
294
- } catch { /* ignore */ }
295
- return new Response(JSON.stringify({ ok: false, error: String(e) }), {
296
- headers: { 'Content-Type': 'application/json' }, status: 500,
297
- });
298
- }
299
- }
1
+ // supabase/functions/ezeep-usage-reconcile/index.ts
2
+ //
3
+ // PERMANENT, SECRET-GATED reconciliation gate for ezeep print-usage billing.
4
+ // Pulls ezeep's official Reporting API CSV for a calendar month and diffs
5
+ // it job-by-job against public.print_jobs. FAILS CLOSED: any missing/extra/
6
+ // mismatched job for the month blocks ALL print_usage_periods rows for that
7
+ // month from being marked reconciled -- no partial credit, no silent
8
+ // auto-correction (Kyle's 2026-08-21 decision). Only a clean diff stamps
9
+ // reconciled_at on every pending_bill period for that month -- the gate
10
+ // Phase 2's print-usage-bill (not yet built) must read instead of
11
+ // pending_bill alone.
12
+ //
13
+ // Scheduled by pg_cron (monthly, 1st @ 09:20 UTC) via
14
+ // private.trigger_ezeep_reconcile() -> net.http_post {}.
15
+ //
16
+ // ezeep OAuth is Authorization Code Flow. refresh_token ROTATES ON EVERY
17
+ // USE (confirmed empirically 2026-08-21) and lives in
18
+ // private.ezeep_oauth_state, not a static function secret. The new
19
+ // refresh_token is persisted immediately after exchange, before any other
20
+ // work, so a downstream failure never strands this on a dead token.
21
+
22
+ import { createClient } from 'npm:@supabase/supabase-js@2';
23
+
24
+ const EZEEP_TOKEN_URL = 'https://account.ezeep.com/oauth/access_token/';
25
+ const EZEEP_API_BASE = 'https://api2.ezeep.com';
26
+ const REPORT_POLL_ATTEMPTS = 10;
27
+ const REPORT_POLL_DELAY_MS = 3000;
28
+
29
+ function safeEqual(a: string, b: string): boolean {
30
+ const enc = new TextEncoder();
31
+ const ab = enc.encode(a), bb = enc.encode(b);
32
+ if (ab.length !== bb.length) return false;
33
+ let diff = 0;
34
+ for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
35
+ return diff === 0;
36
+ }
37
+
38
+ function priorMonthRange(now = new Date()): { start: string; end: string; periodMonth: string } {
39
+ const y = now.getUTCFullYear();
40
+ const m = now.getUTCMonth();
41
+ const start = new Date(Date.UTC(y, m - 1, 1));
42
+ const end = new Date(Date.UTC(y, m, 1));
43
+ const iso = (d: Date) => d.toISOString().slice(0, 10);
44
+ return { start: iso(start), end: iso(end), periodMonth: iso(start) };
45
+ }
46
+
47
+ function nextMonthIso(iso: string): string {
48
+ const d = new Date(iso + 'T00:00:00Z');
49
+ const next = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
50
+ return next.toISOString().slice(0, 10);
51
+ }
52
+
53
+ // Minimal RFC4180 CSV parser: handles quoted fields, embedded commas/quotes,
54
+ // and CRLF/LF/CR line endings. ezeep's export needs this -- a naive
55
+ // split(',') misaligns columns on rows with commas inside a field.
56
+ function parseCsv(text: string): Record<string, string>[] {
57
+ const rows: string[][] = [];
58
+ let row: string[] = [];
59
+ let field = '';
60
+ let inQuotes = false;
61
+ const clean = text.replace(/^/, '');
62
+ for (let i = 0; i < clean.length; i++) {
63
+ const c = clean[i];
64
+ if (inQuotes) {
65
+ if (c === '"') {
66
+ if (clean[i + 1] === '"') { field += '"'; i++; } else { inQuotes = false; }
67
+ } else field += c;
68
+ } else if (c === '"') inQuotes = true;
69
+ else if (c === ',') { row.push(field); field = ''; }
70
+ else if (c === '\n' || c === '\r') {
71
+ if (c === '\r' && clean[i + 1] === '\n') i++;
72
+ row.push(field); field = '';
73
+ if (row.length > 1 || row[0] !== '') rows.push(row);
74
+ row = [];
75
+ } else field += c;
76
+ }
77
+ if (field !== '' || row.length > 0) { row.push(field); rows.push(row); }
78
+ if (rows.length === 0) return [];
79
+ const header = rows[0];
80
+ return rows.slice(1).map((r) => {
81
+ const obj: Record<string, string> = {};
82
+ header.forEach((h, idx) => { obj[h] = r[idx] ?? ''; });
83
+ return obj;
84
+ });
85
+ }
86
+
87
+ async function getOAuthCreds(supabase: any) {
88
+ const { data, error } = await supabase.rpc('get_ezeep_oauth_credentials');
89
+ if (error || !data) {
90
+ throw new Error('failed to load ezeep oauth credentials: ' + (error?.message ?? 'none'));
91
+ }
92
+ return data as { client_id: string; client_secret: string; refresh_token: string };
93
+ }
94
+
95
+ async function refreshEzeepToken(
96
+ supabase: any,
97
+ creds: { client_id: string; client_secret: string; refresh_token: string },
98
+ ): Promise<string> {
99
+ const basic = btoa(`${creds.client_id}:${creds.client_secret}`);
100
+ const res = await fetch(EZEEP_TOKEN_URL, {
101
+ method: 'POST',
102
+ headers: {
103
+ 'Authorization': `Basic ${basic}`,
104
+ 'Content-Type': 'application/x-www-form-urlencoded',
105
+ },
106
+ body: new URLSearchParams({
107
+ grant_type: 'refresh_token',
108
+ refresh_token: creds.refresh_token,
109
+ }),
110
+ });
111
+ if (!res.ok) {
112
+ throw new Error(`ezeep token refresh failed: ${res.status} ${await res.text().catch(() => '')}`);
113
+ }
114
+ const json = await res.json();
115
+ // Persist the rotated refresh token IMMEDIATELY -- before anything else
116
+ // that could fail and strand us on a token ezeep has already invalidated.
117
+ const { error: writeErr } = await supabase.rpc('set_ezeep_refresh_token', {
118
+ new_token: json.refresh_token,
119
+ });
120
+ if (writeErr) {
121
+ throw new Error('CRITICAL: got new ezeep refresh_token but failed to persist it: ' + writeErr.message);
122
+ }
123
+ return json.access_token as string;
124
+ }
125
+
126
+ export async function handle(req: Request): Promise<Response> {
127
+ if (req.method !== 'POST' && req.method !== 'GET') {
128
+ return new Response('Method not allowed', { status: 405 });
129
+ }
130
+ const provided = req.headers.get('x-reconcile-secret');
131
+ if (!provided) return new Response('Unauthorized', { status: 401 });
132
+
133
+ const supabase = createClient(
134
+ Deno.env.get('SUPABASE_URL')!,
135
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
136
+ );
137
+
138
+ const { data: gate, error: gateErr } = await supabase.rpc('get_ezeep_reconcile_secret');
139
+ const expected = typeof gate === 'string' ? gate : null;
140
+ if (gateErr || !expected || !safeEqual(provided, expected)) {
141
+ return new Response('Unauthorized', { status: 401 });
142
+ }
143
+
144
+ let overridePeriod: string | null = null;
145
+ if (req.method === 'POST') {
146
+ const body = await req.json().catch(() => ({} as any));
147
+ if (typeof body?.period_month === 'string') overridePeriod = body.period_month;
148
+ }
149
+
150
+ try {
151
+ const creds = await getOAuthCreds(supabase);
152
+ const accessToken = await refreshEzeepToken(supabase, creds);
153
+
154
+ const { start, end, periodMonth } = overridePeriod
155
+ ? { start: overridePeriod, end: nextMonthIso(overridePeriod), periodMonth: overridePeriod }
156
+ : priorMonthRange();
157
+
158
+ const createRes = await fetch(`${EZEEP_API_BASE}/reporting/reports`, {
159
+ method: 'POST',
160
+ headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
161
+ body: JSON.stringify({ start, end, csv_delimiter: ',', timestamp_offset: 0 }),
162
+ });
163
+ if (!createRes.ok) {
164
+ throw new Error(`ezeep report create failed: ${createRes.status} ${await createRes.text().catch(() => '')}`);
165
+ }
166
+ const created = await createRes.json();
167
+ const reportId = created.report_id as string;
168
+
169
+ let status = created.status as string;
170
+ for (let i = 0; i < REPORT_POLL_ATTEMPTS && status === 'pending'; i++) {
171
+ await new Promise((r) => setTimeout(r, REPORT_POLL_DELAY_MS));
172
+ const pollRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}`, {
173
+ headers: { 'Authorization': `Bearer ${accessToken}` },
174
+ });
175
+ if (!pollRes.ok) throw new Error(`ezeep report poll failed: ${pollRes.status}`);
176
+ const polled = await pollRes.json();
177
+ status = polled.status;
178
+ }
179
+ if (status !== 'succeeded') {
180
+ throw new Error(`ezeep report did not succeed in time (status=${status}, report_id=${reportId})`);
181
+ }
182
+
183
+ const dlRes = await fetch(`${EZEEP_API_BASE}/reporting/reports/${reportId}/download`, {
184
+ headers: { 'Authorization': `Bearer ${accessToken}` },
185
+ });
186
+ if (!dlRes.ok) throw new Error(`ezeep report download failed: ${dlRes.status}`);
187
+ const csvText = await dlRes.text();
188
+ const rows = parseCsv(csvText);
189
+
190
+ // ezeep's own official succeeded-job set for the month.
191
+ const ezeepJobs = new Map<string, { pages: number; color: boolean }>();
192
+ for (const r of rows) {
193
+ if (r['Final status'] !== 'succeeded') continue;
194
+ const id = r['Print job ID'];
195
+ if (!id) continue;
196
+ ezeepJobs.set(id, {
197
+ pages: Number(r['Total printed pages'] || 0),
198
+ color: r['Chromaticity'] === 'color',
199
+ });
200
+ }
201
+
202
+ const { data: ourJobsRaw, error: jobsErr } = await supabase
203
+ .from('print_jobs')
204
+ .select('ezeep_printjob_id,total_printed_pages,color,job_created_at,topic')
205
+ .eq('topic', 'printjob_succeeded')
206
+ .gte('job_created_at', `${start}T00:00:00Z`)
207
+ .lt('job_created_at', `${end}T00:00:00Z`);
208
+ if (jobsErr) throw new Error('print_jobs read failed: ' + jobsErr.message);
209
+
210
+ const ourJobs = new Map<string, { pages: number; color: boolean }>();
211
+ for (const j of ourJobsRaw ?? []) {
212
+ ourJobs.set(j.ezeep_printjob_id, { pages: j.total_printed_pages, color: j.color });
213
+ }
214
+
215
+ const missingInOurs: string[] = [];
216
+ const mismatched: Array<Record<string, unknown>> = [];
217
+ for (const [id, ez] of ezeepJobs) {
218
+ const ours = ourJobs.get(id);
219
+ if (!ours) { missingInOurs.push(id); continue; }
220
+ if (ours.pages !== ez.pages || ours.color !== ez.color) {
221
+ mismatched.push({ ezeep_printjob_id: id, ezeep: ez, ours });
222
+ }
223
+ }
224
+ const extraInOurs: string[] = [];
225
+ for (const id of ourJobs.keys()) {
226
+ if (!ezeepJobs.has(id)) extraInOurs.push(id);
227
+ }
228
+
229
+ const clean = missingInOurs.length === 0 && extraInOurs.length === 0 && mismatched.length === 0;
230
+
231
+ if (!clean) {
232
+ await supabase.from('ops_events').insert({
233
+ kind: 'ezeep_reconciliation_mismatch',
234
+ severity: 'error',
235
+ detail: {
236
+ period_month: periodMonth,
237
+ report_id: reportId,
238
+ ezeep_job_count: ezeepJobs.size,
239
+ our_job_count: ourJobs.size,
240
+ missing_in_ours: missingInOurs.slice(0, 25),
241
+ missing_in_ours_count: missingInOurs.length,
242
+ extra_in_ours: extraInOurs.slice(0, 25),
243
+ extra_in_ours_count: extraInOurs.length,
244
+ mismatched: mismatched.slice(0, 25),
245
+ mismatched_count: mismatched.length,
246
+ },
247
+ });
248
+ return new Response(JSON.stringify({
249
+ ok: true,
250
+ clean: false,
251
+ period_month: periodMonth,
252
+ report_id: reportId,
253
+ missing_in_ours_count: missingInOurs.length,
254
+ extra_in_ours_count: extraInOurs.length,
255
+ mismatched_count: mismatched.length,
256
+ }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
257
+ }
258
+
259
+ const { data: stamped, error: stampErr } = await supabase
260
+ .from('print_usage_periods')
261
+ .update({ reconciled_at: new Date().toISOString(), reconciliation_report_id: reportId })
262
+ .eq('period_month', periodMonth)
263
+ .eq('status', 'pending_bill')
264
+ .is('reconciled_at', null)
265
+ .select('id');
266
+ if (stampErr) throw new Error('failed to stamp reconciled_at: ' + stampErr.message);
267
+
268
+ await supabase.from('ops_events').insert({
269
+ kind: 'ezeep_reconciliation_ok',
270
+ severity: 'info',
271
+ detail: {
272
+ period_month: periodMonth,
273
+ report_id: reportId,
274
+ ezeep_job_count: ezeepJobs.size,
275
+ periods_reconciled: (stamped ?? []).length,
276
+ },
277
+ });
278
+
279
+ return new Response(JSON.stringify({
280
+ ok: true,
281
+ clean: true,
282
+ period_month: periodMonth,
283
+ report_id: reportId,
284
+ ezeep_job_count: ezeepJobs.size,
285
+ periods_reconciled: (stamped ?? []).length,
286
+ }), { headers: { 'Content-Type': 'application/json' }, status: 200 });
287
+ } catch (e) {
288
+ try {
289
+ await supabase.from('ops_events').insert({
290
+ kind: 'ezeep_reconciliation_error',
291
+ severity: 'error',
292
+ detail: { error: String(e) },
293
+ });
294
+ } catch { /* ignore */ }
295
+ return new Response(JSON.stringify({ ok: false, error: String(e) }), {
296
+ headers: { 'Content-Type': 'application/json' }, status: 500,
297
+ });
298
+ }
299
+ }