@simplelayer/graniteer-core 0.0.2 → 0.1.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.
- package/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// supabase/functions/admin-charge-guest-print/index.ts
|
|
2
|
+
//
|
|
3
|
+
// Staff-facing: charge a guest's saved card once their print job's actual
|
|
4
|
+
// usage/cost is known. Same auth shape as admin-issue-day-pass/
|
|
5
|
+
// admin-create-booking: JWKS-verified caller JWT, aal2 required,
|
|
6
|
+
// admin_users allowlist re-checked server-side, rate limited.
|
|
7
|
+
//
|
|
8
|
+
// Automatic ezeep-webhook correlation (looking the cost up from print_jobs
|
|
9
|
+
// by guest_billing_code, rather than a staff member typing it in) is
|
|
10
|
+
// deliberately NOT built in this pass -- see the D5 build report for why.
|
|
11
|
+
// This function's `amount_cents` input is staff-entered.
|
|
12
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
13
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
14
|
+
import { z } from 'npm:zod@3.23.8';
|
|
15
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
16
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
17
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
18
|
+
import {
|
|
19
|
+
chargeGuestPrintJob,
|
|
20
|
+
CLAIMABLE_CHARGE_STATUSES,
|
|
21
|
+
type GuestPrintDbLike,
|
|
22
|
+
type GuestPrintStripeLike,
|
|
23
|
+
type SubmissionRow,
|
|
24
|
+
} from 'npm:@simplelayer/graniteer-core/guestPrintCapture';
|
|
25
|
+
|
|
26
|
+
const corsHeaders = {
|
|
27
|
+
'Access-Control-Allow-Origin': '*',
|
|
28
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
29
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
33
|
+
|
|
34
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
35
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
36
|
+
function getJwks(supabaseUrl: string) {
|
|
37
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
38
|
+
return jwksCache;
|
|
39
|
+
}
|
|
40
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
41
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
42
|
+
const token = authHeader.slice(7).trim();
|
|
43
|
+
try {
|
|
44
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
45
|
+
const claims = payload as unknown as CallerClaims;
|
|
46
|
+
if (!claims.sub) return null;
|
|
47
|
+
return claims;
|
|
48
|
+
} catch { return null; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function json(status: number, body: unknown) {
|
|
52
|
+
return new Response(JSON.stringify(body), {
|
|
53
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const Body = z.object({
|
|
58
|
+
submission_id: z.string().uuid(),
|
|
59
|
+
amount_cents: z.number().int().positive().max(500_00), // sanity ceiling: $500
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export async function handle(req: Request): Promise<Response> {
|
|
63
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
64
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
65
|
+
|
|
66
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
67
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
68
|
+
|
|
69
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
70
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
71
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
72
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
73
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
74
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
75
|
+
|
|
76
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
77
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
81
|
+
checkRateLimit(admin, 'admin-charge-guest-print-ip', clientIp(req), 30, 300),
|
|
82
|
+
checkRateLimit(admin, 'admin-charge-guest-print-email', callerEmail, 20, 300),
|
|
83
|
+
]);
|
|
84
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
85
|
+
|
|
86
|
+
const { data: allow, error: allowErr } = await admin
|
|
87
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
88
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
89
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
90
|
+
|
|
91
|
+
let raw: unknown;
|
|
92
|
+
try { raw = await req.json(); } catch { return json(400, { ok: false, error: 'invalid_json' }); }
|
|
93
|
+
const parsed = Body.safeParse(raw);
|
|
94
|
+
if (!parsed.success) return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
|
|
95
|
+
const { submission_id, amount_cents } = parsed.data;
|
|
96
|
+
|
|
97
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
98
|
+
if (!stripeKey) return json(500, { ok: false, error: 'stripe_not_configured' });
|
|
99
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
100
|
+
|
|
101
|
+
const stripeLike: GuestPrintStripeLike = {
|
|
102
|
+
customers: {
|
|
103
|
+
search: (p) => stripe.customers.search(p),
|
|
104
|
+
list: (p) => stripe.customers.list(p),
|
|
105
|
+
create: (p) => stripe.customers.create(p),
|
|
106
|
+
},
|
|
107
|
+
setupIntents: {
|
|
108
|
+
create: (p, o) => stripe.setupIntents.create(p, o),
|
|
109
|
+
retrieve: (id, p) => stripe.setupIntents.retrieve(id, p),
|
|
110
|
+
},
|
|
111
|
+
paymentIntents: {
|
|
112
|
+
// See guest-print-submit/index.ts for why this cast is needed.
|
|
113
|
+
create: (p, o) => stripe.paymentIntents.create(p as never, o),
|
|
114
|
+
// B4 (round 2 review): chargeGuestPrintJob must be able to check the
|
|
115
|
+
// status of a PRIOR PaymentIntent on this row before ever creating a
|
|
116
|
+
// second one -- see that function's own comment.
|
|
117
|
+
retrieve: (id) => stripe.paymentIntents.retrieve(id),
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const dbLike: GuestPrintDbLike = {
|
|
122
|
+
async insertPending() { throw new Error('not used by charge'); },
|
|
123
|
+
async attachStripeIds() { throw new Error('not used by charge'); },
|
|
124
|
+
async markCardSaved() { throw new Error('not used by charge'); },
|
|
125
|
+
async markFailed() { throw new Error('not used by charge'); },
|
|
126
|
+
async getById(id) {
|
|
127
|
+
const { data, error } = await admin
|
|
128
|
+
.from('print_guest_submissions')
|
|
129
|
+
.select('id,email,status,stripe_customer_id,stripe_setup_intent_id,stripe_payment_method_id,stripe_payment_intent_id,guest_billing_code')
|
|
130
|
+
.eq('id', id)
|
|
131
|
+
.maybeSingle();
|
|
132
|
+
if (error) throw error;
|
|
133
|
+
return (data as SubmissionRow) ?? null;
|
|
134
|
+
},
|
|
135
|
+
async claimForCharge(id) {
|
|
136
|
+
// Atomic compare-and-swap: this UPDATE's WHERE clause can only ever
|
|
137
|
+
// match the row while it is in CLAIMABLE_CHARGE_STATUSES (currently
|
|
138
|
+
// 'card_saved' or 'charge_failed' -- a previously-failed charge
|
|
139
|
+
// attempt is a legitimate retry source, D5 adversarial review round
|
|
140
|
+
// 1, B3). Imported from guestPrintCapture.ts rather than hardcoded
|
|
141
|
+
// here so this filter and the module's own documentation of it can
|
|
142
|
+
// never silently drift apart -- see round 2 review's test-vacuity
|
|
143
|
+
// finding on the original hardcoded pair. Two concurrent calls for
|
|
144
|
+
// the same id: Postgres serializes them on the row lock, and the
|
|
145
|
+
// second re-evaluates WHERE against the already-advanced row and
|
|
146
|
+
// matches zero rows. That -- not application code -- is the guard.
|
|
147
|
+
const { data, error } = await admin
|
|
148
|
+
.from('print_guest_submissions')
|
|
149
|
+
.update({ status: 'charging' })
|
|
150
|
+
.eq('id', id)
|
|
151
|
+
.in('status', CLAIMABLE_CHARGE_STATUSES)
|
|
152
|
+
.select('id');
|
|
153
|
+
if (error) throw error;
|
|
154
|
+
return (data ?? []).length === 1;
|
|
155
|
+
},
|
|
156
|
+
async writebackCharged(id, amountCents, paymentIntentId) {
|
|
157
|
+
const { error } = await admin
|
|
158
|
+
.from('print_guest_submissions')
|
|
159
|
+
.update({
|
|
160
|
+
status: 'charged',
|
|
161
|
+
charge_cents: amountCents,
|
|
162
|
+
stripe_payment_intent_id: paymentIntentId,
|
|
163
|
+
charged_at: new Date().toISOString(),
|
|
164
|
+
})
|
|
165
|
+
.eq('id', id);
|
|
166
|
+
if (error) throw error;
|
|
167
|
+
},
|
|
168
|
+
async writebackChargeFailed(id, reason, paymentIntentId) {
|
|
169
|
+
// status = 'charge_failed' (NOT the pre-card 'failed') -- this row IS
|
|
170
|
+
// retryable via claimForCharge above. Persist paymentIntentId whenever
|
|
171
|
+
// Stripe returned one (even non-succeeded), so a live-but-stuck PI is
|
|
172
|
+
// always findable from this row afterward. See D5 adversarial review
|
|
173
|
+
// round 1, B2/B3.
|
|
174
|
+
const update: Record<string, unknown> = { status: 'charge_failed', last_error: reason.slice(0, 2000) };
|
|
175
|
+
if (paymentIntentId) update.stripe_payment_intent_id = paymentIntentId;
|
|
176
|
+
const { error } = await admin
|
|
177
|
+
.from('print_guest_submissions')
|
|
178
|
+
.update(update)
|
|
179
|
+
.eq('id', id);
|
|
180
|
+
if (error) throw error;
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
try {
|
|
185
|
+
const outcome = await chargeGuestPrintJob(stripeLike, dbLike, submission_id, amount_cents);
|
|
186
|
+
// Only 'charged' is a real success. In particular, 'not_claimed' comes
|
|
187
|
+
// back with outcome.ok === true (it's "not an error" at the decision-core
|
|
188
|
+
// level -- see chargeGuestPrintJob's own comment) but MUST NOT be
|
|
189
|
+
// reported to staff/UI as HTTP 200/ok:true: that would silently hide a
|
|
190
|
+
// concurrent duplicate-charge attempt, or a not-yet-chargeable row, as a
|
|
191
|
+
// success with no logOps trail. See D5 adversarial review round 1, B1.
|
|
192
|
+
if (outcome.status !== 'charged') {
|
|
193
|
+
await logOps(admin, 'admin_charge_guest_print_failed',
|
|
194
|
+
{
|
|
195
|
+
submission_id, status: outcome.status, detail: outcome.detail, actor: callerEmail,
|
|
196
|
+
payment_intent_id: outcome.paymentIntentId,
|
|
197
|
+
},
|
|
198
|
+
{ severity: 'error' });
|
|
199
|
+
return json(409, {
|
|
200
|
+
ok: false, error: outcome.status, detail: outcome.detail, payment_intent_id: outcome.paymentIntentId,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
// S9: a 'charged' outcome from the already-succeeded-prior-PaymentIntent
|
|
204
|
+
// recovery branch can legitimately record a DIFFERENT amount than what
|
|
205
|
+
// staff typed here (outcome.amountCents is the TRUE, ledger-recorded
|
|
206
|
+
// amount -- see that branch's comment in guestPrintCapture.ts). The
|
|
207
|
+
// ledger itself is correct either way, but staff must never be silently
|
|
208
|
+
// left believing amount_cents (what they typed) is what was actually
|
|
209
|
+
// charged -- log it as its own event even though the charge succeeded.
|
|
210
|
+
if (outcome.amountCents !== undefined && outcome.amountCents !== amount_cents) {
|
|
211
|
+
await logOps(admin, 'admin_charge_guest_print_amount_mismatch',
|
|
212
|
+
{
|
|
213
|
+
submission_id, actor: callerEmail, payment_intent_id: outcome.paymentIntentId,
|
|
214
|
+
requested_amount_cents: amount_cents, charged_amount_cents: outcome.amountCents,
|
|
215
|
+
},
|
|
216
|
+
{ severity: 'error' });
|
|
217
|
+
}
|
|
218
|
+
return json(200, {
|
|
219
|
+
ok: true, status: outcome.status, payment_intent_id: outcome.paymentIntentId,
|
|
220
|
+
amount_cents: outcome.amountCents,
|
|
221
|
+
});
|
|
222
|
+
} catch (e) {
|
|
223
|
+
console.error('admin-charge-guest-print error', e);
|
|
224
|
+
await logOps(admin, 'admin_charge_guest_print_error',
|
|
225
|
+
{ submission_id, message: e instanceof Error ? e.message : String(e), actor: callerEmail },
|
|
226
|
+
{ severity: 'error' });
|
|
227
|
+
return json(500, { ok: false, error: 'unexpected_error' });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// supabase/functions/admin-correct-booking/index.ts
|
|
2
|
+
//
|
|
3
|
+
// Undo path for the two manual admin actions that have none: "skip contract"
|
|
4
|
+
// (admin-skip-commons-contract) and "mark fully paid"
|
|
5
|
+
// (admin-mark-booking-paid). Both of those actions log a full "before"
|
|
6
|
+
// snapshot of every column they mutate -- AND every column
|
|
7
|
+
// bookings_amount_math_check depends on -- into ops_events at the moment
|
|
8
|
+
// they run, tagged with an exact event timestamp (mark_event_at /
|
|
9
|
+
// skip_event_at) that matches the row's own paid_marked_at /
|
|
10
|
+
// contract_skipped_at column exactly. This function's only job is to look
|
|
11
|
+
// up that EXACT snapshot (never "the most recent one of this kind" -- a
|
|
12
|
+
// swallowed logOps insert or a second mark/undo cycle can leave a stale
|
|
13
|
+
// older row sitting there) and write it back verbatim, refusing outright
|
|
14
|
+
// whenever anything needed is missing, drifted, or ambiguous.
|
|
15
|
+
//
|
|
16
|
+
// This is a bookkeeping correction only. It never talks to Stripe and never
|
|
17
|
+
// reverses a real payment -- if money actually needs to move, that is a
|
|
18
|
+
// separate, explicit action (a Stripe refund, an outgoing Mercury transfer),
|
|
19
|
+
// not something this function does as a side effect.
|
|
20
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
21
|
+
import { z } from 'npm:zod@3.23.8';
|
|
22
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
23
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
24
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
25
|
+
|
|
26
|
+
const corsHeaders = {
|
|
27
|
+
'Access-Control-Allow-Origin': '*',
|
|
28
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
29
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
33
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
34
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
35
|
+
function getJwks(supabaseUrl: string) {
|
|
36
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
37
|
+
return jwksCache;
|
|
38
|
+
}
|
|
39
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
40
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
41
|
+
const token = authHeader.slice(7).trim();
|
|
42
|
+
try {
|
|
43
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
44
|
+
const claims = payload as unknown as CallerClaims;
|
|
45
|
+
if (!claims.sub) return null;
|
|
46
|
+
return claims;
|
|
47
|
+
} catch { return null; }
|
|
48
|
+
}
|
|
49
|
+
function json(status: number, body: unknown) {
|
|
50
|
+
return new Response(JSON.stringify(body), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } });
|
|
51
|
+
}
|
|
52
|
+
function fail(status: number, code: string, error: string, extra?: Record<string, unknown>) {
|
|
53
|
+
return json(status, { ok: false, status, code, error, ...(extra ?? {}) });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const ACTIONS = ['undo_mark_paid', 'undo_skip_contract'] as const;
|
|
57
|
+
const Body = z.object({
|
|
58
|
+
booking_id: z.string().uuid(),
|
|
59
|
+
action: z.enum(ACTIONS),
|
|
60
|
+
reason: z.string().trim().min(1).max(500),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// A hold restored to a moment already in the past would leave the booking
|
|
64
|
+
// exposed to the 5-minute expire-stale-booking-holds cron with no real
|
|
65
|
+
// window for staff to act -- Commons (tier-3) holds are routinely extended
|
|
66
|
+
// out to 7 days (see _shared/bookingHoldReclaim.ts), so "already lapsed" is
|
|
67
|
+
// an expected state to land in here, not an edge case. Give a real working
|
|
68
|
+
// day, not a fuse shorter than the cron interval.
|
|
69
|
+
const REVERT_HOLD_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
70
|
+
type HoldRestore = { ok: true; value: string | null; extended: boolean } | { ok: false };
|
|
71
|
+
function restoreHold(prior: unknown): HoldRestore {
|
|
72
|
+
if (prior === null) return { ok: true, value: null, extended: false };
|
|
73
|
+
if (typeof prior !== 'string') return { ok: false }; // absent/wrong-typed snapshot -- refuse, never guess
|
|
74
|
+
const ms = Date.parse(prior);
|
|
75
|
+
if (!Number.isFinite(ms)) return { ok: false };
|
|
76
|
+
if (ms > Date.now() + REVERT_HOLD_GRACE_MS) return { ok: true, value: prior, extended: false };
|
|
77
|
+
return { ok: true, value: new Date(Date.now() + REVERT_HOLD_GRACE_MS).toISOString(), extended: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isSafeNonNegInt(v: unknown): v is number {
|
|
81
|
+
return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
|
|
85
|
+
const PAYMENT_SOURCES = new Set(['stripe', 'offline']);
|
|
86
|
+
|
|
87
|
+
export async function handle(req: Request): Promise<Response> {
|
|
88
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
89
|
+
if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
|
|
90
|
+
|
|
91
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
92
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
93
|
+
|
|
94
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
95
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
96
|
+
if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
|
|
97
|
+
if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
|
|
98
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
99
|
+
if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
|
|
100
|
+
|
|
101
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
|
|
102
|
+
|
|
103
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
104
|
+
checkRateLimit(admin, 'admin-correct-booking-ip', clientIp(req), 15, 300),
|
|
105
|
+
checkRateLimit(admin, 'admin-correct-booking-email', callerEmail, 15, 300),
|
|
106
|
+
]);
|
|
107
|
+
if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
|
|
108
|
+
|
|
109
|
+
const { data: allow, error: allowErr } = await admin.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
110
|
+
if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
|
|
111
|
+
if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
|
|
112
|
+
|
|
113
|
+
let raw: unknown;
|
|
114
|
+
try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
|
|
115
|
+
const parsed = Body.safeParse(raw);
|
|
116
|
+
if (!parsed.success) return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
|
|
117
|
+
const { booking_id, action, reason } = parsed.data;
|
|
118
|
+
|
|
119
|
+
if (action === 'undo_mark_paid') {
|
|
120
|
+
const { data: booking, error: bErr } = await admin
|
|
121
|
+
.from('bookings')
|
|
122
|
+
.select('id,status,paid_method,payment_source,paid_marked_at,paid_marked_by_email,charged_amount_cents,discount_applied_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents')
|
|
123
|
+
.eq('id', booking_id)
|
|
124
|
+
.maybeSingle();
|
|
125
|
+
if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
|
|
126
|
+
if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
|
|
127
|
+
if (booking.status !== 'paid') {
|
|
128
|
+
return fail(409, 'not_paid', `Booking status is "${booking.status}"; nothing to undo — it isn't currently marked paid.`);
|
|
129
|
+
}
|
|
130
|
+
if (!booking.paid_marked_at) {
|
|
131
|
+
const isOfflineCreated = booking.payment_source === 'offline';
|
|
132
|
+
return fail(409, 'not_manually_marked',
|
|
133
|
+
isOfflineCreated
|
|
134
|
+
? 'This booking was recorded paid at creation time (an offline/manually-created booking), not through this action -- there is nothing here for this action to undo. Correct it by hand if it was created wrong.'
|
|
135
|
+
: 'This booking was paid through the live Stripe flow, not this manual action -- there is no manual mark-paid to undo. ' +
|
|
136
|
+
'If money needs to be returned, issue a Stripe refund; if the booking itself needs to change, use a different action.');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Match the EXACT event this row's current paid_marked_at describes --
|
|
140
|
+
// never "the most recent row of this kind" for this booking, which a
|
|
141
|
+
// swallowed logOps insert error, or a second mark/undo/mark cycle, could
|
|
142
|
+
// leave pointing at a stale snapshot that no longer matches this row.
|
|
143
|
+
// booking.paid_marked_at comes back from PostgREST as "...+00:00"; the
|
|
144
|
+
// logged detail.mark_event_at was written with JS's toISOString(),
|
|
145
|
+
// which always produces "...Z". Same instant, different text -- and
|
|
146
|
+
// detail->>'x' forces a text comparison with no implicit cast, so they
|
|
147
|
+
// must be normalized to the same format before comparing.
|
|
148
|
+
const paidMarkedAtIso = new Date(booking.paid_marked_at).toISOString();
|
|
149
|
+
const { data: event, error: evErr } = await admin
|
|
150
|
+
.from('ops_events')
|
|
151
|
+
.select('id,detail')
|
|
152
|
+
.eq('booking_id', booking_id)
|
|
153
|
+
.eq('kind', 'booking_marked_fully_paid')
|
|
154
|
+
.eq('detail->>mark_event_at', paidMarkedAtIso)
|
|
155
|
+
.order('created_at', { ascending: false })
|
|
156
|
+
.limit(1)
|
|
157
|
+
.maybeSingle();
|
|
158
|
+
if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
|
|
159
|
+
if (!event) {
|
|
160
|
+
return fail(409, 'no_audit_snapshot',
|
|
161
|
+
'No recorded snapshot exactly matching this booking\'s current paid_marked_at was found, so there is nothing safe to revert to automatically. ' +
|
|
162
|
+
'Correct it by hand and log an ops_events row before relying on this action for it again.');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const d = (event.detail ?? {}) as Record<string, unknown>;
|
|
166
|
+
const priorStatus = typeof d.prior_status === 'string' ? d.prior_status : null;
|
|
167
|
+
const priorDiscountCents = d.prior_discount_applied_cents;
|
|
168
|
+
const priorChargedRaw = d.prior_charged_amount_cents;
|
|
169
|
+
const priorPaymentSource = d.prior_payment_source;
|
|
170
|
+
|
|
171
|
+
if (
|
|
172
|
+
!priorStatus || !PAYABLE_STATUSES.has(priorStatus)
|
|
173
|
+
|| !isSafeNonNegInt(priorDiscountCents)
|
|
174
|
+
|| !(priorChargedRaw === null || isSafeNonNegInt(priorChargedRaw))
|
|
175
|
+
|| typeof priorPaymentSource !== 'string' || !PAYMENT_SOURCES.has(priorPaymentSource)
|
|
176
|
+
) {
|
|
177
|
+
return fail(409, 'incomplete_audit_snapshot',
|
|
178
|
+
'The recorded snapshot for this booking is missing or has invalid values for fields this action needs to revert it safely. Correct it by hand instead.');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Drift check: bookings_amount_math_check depends on list/dynamic/
|
|
182
|
+
// credit too, and nothing else guards those against having changed
|
|
183
|
+
// (e.g. a reschedule or a credit adjustment) between the mark-paid and
|
|
184
|
+
// this undo. If any of them moved, the snapshot no longer describes a
|
|
185
|
+
// state that's safe to restore -- refuse rather than either violate the
|
|
186
|
+
// CHECK (a raw Postgres error surfaced to staff) or silently restore a
|
|
187
|
+
// stale discount against new inputs.
|
|
188
|
+
const driftChecks: Array<[string, unknown, number]> = [
|
|
189
|
+
['list_amount_cents', d.prior_list_amount_cents, Number(booking.list_amount_cents)],
|
|
190
|
+
['dynamic_discount_cents', d.prior_dynamic_discount_cents, Number(booking.dynamic_discount_cents ?? 0)],
|
|
191
|
+
['credit_applied_cents', d.prior_credit_applied_cents, Number(booking.credit_applied_cents ?? 0)],
|
|
192
|
+
];
|
|
193
|
+
for (const [label, snapshot, live] of driftChecks) {
|
|
194
|
+
if (!isSafeNonNegInt(snapshot) || snapshot !== live) {
|
|
195
|
+
return fail(409, 'booking_drifted',
|
|
196
|
+
`This booking's ${label} changed since it was marked paid (or the snapshot doesn't record it), so the recorded snapshot no longer describes a state it's safe to restore. Correct it by hand.`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const priorChargedCents = priorChargedRaw === null ? null : (priorChargedRaw as number);
|
|
201
|
+
const priorPaidNotes = typeof d.prior_paid_notes === 'string' ? d.prior_paid_notes : null;
|
|
202
|
+
const priorDepositPaidAt = typeof d.prior_deposit_paid_at === 'string' ? d.prior_deposit_paid_at : null;
|
|
203
|
+
const holdRestore = restoreHold(d.prior_hold_expires_at);
|
|
204
|
+
if (!holdRestore.ok) {
|
|
205
|
+
return fail(409, 'unrestorable_hold',
|
|
206
|
+
'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand, then undo the rest separately if needed.');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const { data: updated, error: updErr } = await admin
|
|
210
|
+
.from('bookings')
|
|
211
|
+
.update({
|
|
212
|
+
status: priorStatus,
|
|
213
|
+
charged_amount_cents: priorChargedCents,
|
|
214
|
+
discount_applied_cents: priorDiscountCents,
|
|
215
|
+
payment_source: priorPaymentSource,
|
|
216
|
+
paid_notes: priorPaidNotes,
|
|
217
|
+
paid_method: null,
|
|
218
|
+
paid_marked_by_email: null,
|
|
219
|
+
paid_marked_at: null,
|
|
220
|
+
deposit_paid_at: priorDepositPaidAt,
|
|
221
|
+
hold_expires_at: holdRestore.value,
|
|
222
|
+
})
|
|
223
|
+
.eq('id', booking_id)
|
|
224
|
+
.eq('status', 'paid')
|
|
225
|
+
.eq('paid_marked_at', booking.paid_marked_at) // CAS
|
|
226
|
+
.eq('charged_amount_cents', booking.charged_amount_cents) // CAS -- catch a concurrent money-column write the timestamp CAS alone wouldn't
|
|
227
|
+
.eq('discount_applied_cents', booking.discount_applied_cents) // CAS, same reason
|
|
228
|
+
.select('id')
|
|
229
|
+
.maybeSingle();
|
|
230
|
+
if (updErr) return fail(500, 'update_failed', updErr.message);
|
|
231
|
+
if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
|
|
232
|
+
|
|
233
|
+
// 'sponsored' is the only paid_method that genuinely moved zero dollars.
|
|
234
|
+
// Every other value -- including 'other', the catch-all for real money
|
|
235
|
+
// that isn't cash/stripe/mercury -- means this warning must fire.
|
|
236
|
+
const involvesRealMoney = booking.paid_method !== 'sponsored';
|
|
237
|
+
|
|
238
|
+
await logOps(admin, 'booking_paid_mark_undone', {
|
|
239
|
+
booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
|
|
240
|
+
undone_event_id: event.id, reverted_to_status: priorStatus,
|
|
241
|
+
prior_paid_method: booking.paid_method ?? null,
|
|
242
|
+
prior_paid_marked_by_email: booking.paid_marked_by_email ?? null,
|
|
243
|
+
prior_paid_marked_at: booking.paid_marked_at ?? null,
|
|
244
|
+
prior_charged_amount_cents_before_undo: booking.charged_amount_cents ?? null,
|
|
245
|
+
hold_extended: holdRestore.extended,
|
|
246
|
+
}, { severity: 'warning', bookingId: booking_id }).catch(() => {});
|
|
247
|
+
|
|
248
|
+
const notes: string[] = [];
|
|
249
|
+
if (involvesRealMoney) {
|
|
250
|
+
notes.push('This only corrected the booking record. It did NOT reverse any real payment -- if money needs to be returned, handle that separately (Stripe refund / outgoing transfer).');
|
|
251
|
+
}
|
|
252
|
+
if (holdRestore.extended) {
|
|
253
|
+
notes.push(`The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff act.`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return json(200, {
|
|
257
|
+
ok: true, booking_id, status: priorStatus, hold_expires_at: holdRestore.value, hold_extended: holdRestore.extended,
|
|
258
|
+
warning: notes.length ? notes.join(' ') : undefined,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// action === 'undo_skip_contract'
|
|
263
|
+
const { data: booking, error: bErr } = await admin
|
|
264
|
+
.from('bookings')
|
|
265
|
+
.select('id,status,contract_skipped_at,contract_skipped_by_email,contract_skip_reason')
|
|
266
|
+
.eq('id', booking_id)
|
|
267
|
+
.maybeSingle();
|
|
268
|
+
if (bErr) return fail(500, 'booking_lookup_failed', bErr.message);
|
|
269
|
+
if (!booking) return fail(404, 'booking_not_found', 'Booking not found.');
|
|
270
|
+
if (!booking.contract_skipped_at) {
|
|
271
|
+
return fail(409, 'not_skipped', "This booking's contract was not marked skipped; nothing to undo.");
|
|
272
|
+
}
|
|
273
|
+
if (booking.status !== 'pending') {
|
|
274
|
+
return fail(409, 'not_pending',
|
|
275
|
+
`Booking status is "${booking.status}"; only a still-pending booking's skip can be undone. If it's already been marked paid, undo that first.`);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Same normalization as undo_mark_paid -- see the comment there.
|
|
279
|
+
const contractSkippedAtIso = new Date(booking.contract_skipped_at).toISOString();
|
|
280
|
+
const { data: event, error: evErr } = await admin
|
|
281
|
+
.from('ops_events')
|
|
282
|
+
.select('id,detail')
|
|
283
|
+
.eq('booking_id', booking_id)
|
|
284
|
+
.eq('kind', 'commons_contract_skipped')
|
|
285
|
+
.eq('detail->>skip_event_at', contractSkippedAtIso)
|
|
286
|
+
.order('created_at', { ascending: false })
|
|
287
|
+
.limit(1)
|
|
288
|
+
.maybeSingle();
|
|
289
|
+
if (evErr) return fail(500, 'audit_lookup_failed', evErr.message);
|
|
290
|
+
if (!event) {
|
|
291
|
+
return fail(409, 'no_audit_snapshot',
|
|
292
|
+
'No recorded snapshot exactly matching this booking\'s current contract_skipped_at was found, so there is nothing safe to revert to automatically. ' +
|
|
293
|
+
'Correct it by hand and log an ops_events row before relying on this action for it again.');
|
|
294
|
+
}
|
|
295
|
+
const d = (event.detail ?? {}) as Record<string, unknown>;
|
|
296
|
+
const holdRestore = restoreHold(d.prior_hold_expires_at);
|
|
297
|
+
if (!holdRestore.ok) {
|
|
298
|
+
return fail(409, 'unrestorable_hold',
|
|
299
|
+
'The recorded snapshot has no usable prior hold expiry, so restoring it could either strand this booking on an indefinite hold or leave it about to be auto-expired with no real window to act. Fix hold_expires_at by hand instead.');
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const { data: updated, error: updErr } = await admin
|
|
303
|
+
.from('bookings')
|
|
304
|
+
.update({
|
|
305
|
+
contract_skipped_at: null,
|
|
306
|
+
contract_skipped_by_email: null,
|
|
307
|
+
contract_skip_reason: null,
|
|
308
|
+
hold_expires_at: holdRestore.value,
|
|
309
|
+
})
|
|
310
|
+
.eq('id', booking_id)
|
|
311
|
+
.eq('status', 'pending')
|
|
312
|
+
.eq('contract_skipped_at', booking.contract_skipped_at) // CAS
|
|
313
|
+
.select('id')
|
|
314
|
+
.maybeSingle();
|
|
315
|
+
if (updErr) return fail(500, 'update_failed', updErr.message);
|
|
316
|
+
if (!updated) return fail(409, 'status_changed', "This booking changed before the update landed — reload and try again.");
|
|
317
|
+
|
|
318
|
+
await logOps(admin, 'commons_contract_skip_undone', {
|
|
319
|
+
booking_id, actor: callerEmail, actor_user_id: caller.sub, reason,
|
|
320
|
+
undone_event_id: event.id,
|
|
321
|
+
prior_skip_reason: booking.contract_skip_reason ?? null,
|
|
322
|
+
prior_skipped_by_email: booking.contract_skipped_by_email ?? null,
|
|
323
|
+
hold_extended: holdRestore.extended,
|
|
324
|
+
}, { severity: 'warning', bookingId: booking_id }).catch(() => {});
|
|
325
|
+
|
|
326
|
+
return json(200, {
|
|
327
|
+
ok: true, booking_id, status: 'pending', contract_skip_cleared: true,
|
|
328
|
+
hold_expires_at: holdRestore.value,
|
|
329
|
+
warning: holdRestore.extended
|
|
330
|
+
? `The original hold had already lapsed, so this booking now holds its slot only until ${holdRestore.value} and will auto-expire after that unless staff send a contract or otherwise act.`
|
|
331
|
+
: undefined,
|
|
332
|
+
});
|
|
333
|
+
}
|