@simplelayer/graniteer-core 0.3.27 → 0.3.28
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/dist/agentBooking.d.ts +172 -0
- package/dist/agentBooking.js +601 -0
- package/dist/agentPolicy.d.ts +29 -0
- package/dist/agentPolicy.js +23 -0
- package/dist/connectBookingCharge.d.ts +5 -2
- package/dist/connectBookingCharge.js +7 -3
- package/dist/createBookingCore.d.ts +84 -0
- package/dist/createBookingCore.js +334 -0
- package/dist/functions/admin-create-booking.js +62 -332
- package/dist/functions/agent-create-booking.d.ts +19 -0
- package/dist/functions/agent-create-booking.js +26 -0
- package/dist/functions/stripe-webhook.js +106 -26
- package/dist/functions/voice-booking.js +59 -7
- package/dist/humanPolicy.d.ts +13 -0
- package/dist/humanPolicy.js +13 -0
- package/dist/paymentLinkEmail.d.ts +8 -1
- package/dist/paymentLinkEmail.js +33 -9
- package/dist/pricing.js +2 -1
- package/dist/rateLimit.d.ts +7 -0
- package/dist/rateLimit.js +28 -0
- package/dist/supabaseTestFakes.d.ts +60 -0
- package/dist/supabaseTestFakes.js +68 -1
- package/dist/tier1Agreement.d.ts +9 -1
- package/dist/tier1Agreement.js +25 -0
- package/package.json +17 -1
|
@@ -16,12 +16,9 @@ import { z } from 'zod';
|
|
|
16
16
|
import { jwtVerify, createRemoteJWKSet } from 'jose';
|
|
17
17
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
18
18
|
import { logOps } from '../ops.js';
|
|
19
|
-
import { reclaimStaleHoldsExceptCompletedTier3 } from '../bookingHoldReclaim.js';
|
|
20
|
-
import { validateAndPriceForRoom, formatHumanTime, } from '../pricing.js';
|
|
21
|
-
import { resolveIsMember, computeEntitlement } from '../membership.js';
|
|
22
19
|
import { writebackBookingCreated } from '../gcalBookingEvents.js';
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
20
|
+
import { createBookingCore } from '../createBookingCore.js';
|
|
21
|
+
import { HUMAN_POLICY } from '../humanPolicy.js';
|
|
25
22
|
const corsHeaders = {
|
|
26
23
|
'Access-Control-Allow-Origin': '*',
|
|
27
24
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
@@ -115,339 +112,72 @@ export async function handle(req, operator, deps) {
|
|
|
115
112
|
if (!parsed.success)
|
|
116
113
|
return json(400, { ok: false, error: 'invalid_body', detail: parsed.error.flatten() });
|
|
117
114
|
const { room_id, contact, mode, skip_dynamic_discount } = parsed.data;
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
.from('rooms')
|
|
121
|
-
.select('id,name,slug,hourly_cents,day_cents,half_day_cents,min_booking_minutes,booking_mode,active,address,google_calendar_id,dynamic_pricing_eligible,half_day_am_start,half_day_am_end,half_day_pm_start,half_day_pm_end,half_day_days_of_week')
|
|
122
|
-
.eq('id', room_id)
|
|
123
|
-
.eq('active', true)
|
|
124
|
-
.maybeSingle();
|
|
125
|
-
if (rErr)
|
|
126
|
-
return json(500, { ok: false, error: 'load_room_failed', detail: rErr.message });
|
|
127
|
-
if (!room)
|
|
128
|
-
return json(404, { ok: false, error: 'room_not_found' });
|
|
129
|
-
// === Optional member attachment ===
|
|
130
|
-
const membershipId = parsed.data.membership_id ?? parsed.data.membershipId ?? null;
|
|
131
|
-
let membership = null;
|
|
132
|
-
if (membershipId) {
|
|
133
|
-
try {
|
|
134
|
-
membership = await loadMembershipById(admin, membershipId);
|
|
135
|
-
}
|
|
136
|
-
catch (e) {
|
|
137
|
-
return json(500, { ok: false, error: 'membership_lookup_failed', detail: String(e) });
|
|
138
|
-
}
|
|
139
|
-
if (!membership)
|
|
140
|
-
return json(404, { ok: false, error: 'membership_not_found' });
|
|
141
|
-
}
|
|
142
|
-
// Server-authoritative membership lookup on the CUSTOMER's email (not the admin's).
|
|
143
|
-
const custEmailKey = contact.email.toLowerCase();
|
|
144
|
-
const emailIsMember = await resolveIsMember(admin, custEmailKey);
|
|
145
|
-
const isMember = emailIsMember || (membership ? computeEntitlement(membership) : false);
|
|
146
|
-
const priced = await validateAndPriceForRoom(admin, room, parsed.data, Date.now(), {
|
|
147
|
-
isMember,
|
|
148
|
-
allowDynamic: !skip_dynamic_discount,
|
|
149
|
-
});
|
|
150
|
-
if (!priced.ok)
|
|
151
|
-
return json(priced.status, { ok: false, error: priced.error });
|
|
152
|
-
const { startUtc, endUtc, price_cents, rangeLiteral, dynamic_discount_cents, dynamic_discount_rule_type, list_rule_type, } = priced;
|
|
153
|
-
const net = Math.max(0, price_cents - dynamic_discount_cents);
|
|
154
|
-
// Reclaim stale holds overlapping the range (same as create-booking).
|
|
155
|
-
await reclaimStaleHoldsExceptCompletedTier3(admin, room_id, rangeLiteral);
|
|
156
|
-
// Contract tier lookup: needed both for member-credit eligibility (Tier 3
|
|
157
|
-
// rooms never draw member credit - they always go through the Commons
|
|
158
|
-
// contract/deposit flow) and, new here, for the contract-skip audit trail
|
|
159
|
-
// below. Root cause + rationale: claude/admin-create-booking-agreement-gap-scope.md
|
|
160
|
-
// (this function never runs create-booking.js's tiered agreement gate or
|
|
161
|
-
// the audited admin-skip-commons-contract path - every booking it settles
|
|
162
|
-
// to 'paid' does so with no agreement, previously with no audit trail
|
|
163
|
-
// either).
|
|
164
|
-
let contractTier = null;
|
|
165
|
-
try {
|
|
166
|
-
contractTier = await resolveRoomContractTier(admin, room_id);
|
|
167
|
-
}
|
|
168
|
-
catch (e) {
|
|
169
|
-
console.warn('[admin-create-booking] contract tier lookup failed', String(e));
|
|
170
|
-
try {
|
|
171
|
-
await logOps(admin, 'admin_create_booking_tier_lookup_failed', { message: String(e), room_id }, { severity: 'warning' });
|
|
172
|
-
}
|
|
173
|
-
catch { /* ignore */ }
|
|
174
|
-
}
|
|
175
|
-
let creditEligible = false;
|
|
176
|
-
if (membership) {
|
|
177
|
-
creditEligible = room.booking_mode !== 'quote' && contractTier !== null && contractTier !== 3;
|
|
178
|
-
}
|
|
179
|
-
const useCredit = !!membership && creditEligible;
|
|
180
|
-
const nowIso = new Date().toISOString();
|
|
181
|
-
const isOffline = mode === 'offline';
|
|
182
|
-
// Audit-only contract-skip marking (landed 2026-09-18, see scope doc
|
|
183
|
-
// above): every booking this function settles straight to 'paid' bypasses
|
|
184
|
-
// the tiered agreement gate self-serve bookings go through. This does NOT
|
|
185
|
-
// block or gate the booking - it only makes the skip self-documenting via
|
|
186
|
-
// the same contract_skipped_* columns admin-skip-commons-contract uses for
|
|
187
|
-
// an explicit staff skip. NOTE: private.on_booking_paid_transition() still
|
|
188
|
-
// fires and still inserts its own booking_contract_violations row on this
|
|
189
|
-
// same write -- this stamp is in ADDITION to that row, not a replacement
|
|
190
|
-
// for it; the violations table keeps growing exactly as before.
|
|
191
|
-
const CONTRACT_SKIP_REASON = `admin-create-booking: no agreement flow in this function (tier ${contractTier ?? 'unmapped'}; ` +
|
|
192
|
-
'known gap, audit-only fix landed 2026-09-18 - see admin-create-booking-agreement-gap-scope.md)';
|
|
193
|
-
const contractSkipFields = {
|
|
194
|
-
contract_skipped_at: nowIso,
|
|
195
|
-
contract_skipped_by_email: callerEmail,
|
|
196
|
-
contract_skip_reason: CONTRACT_SKIP_REASON,
|
|
197
|
-
};
|
|
198
|
-
const insertRow = {
|
|
199
|
-
room_id,
|
|
200
|
-
during: rangeLiteral,
|
|
201
|
-
list_amount_cents: price_cents,
|
|
202
|
-
dynamic_discount_cents,
|
|
203
|
-
dynamic_discount_rule_type,
|
|
204
|
-
list_rule_type,
|
|
205
|
-
contact_email: contact.email,
|
|
206
|
-
contact_name: contact.name,
|
|
207
|
-
contact_phone: contact.phone ?? null,
|
|
208
|
-
is_member: isMember,
|
|
209
|
-
policy_accepted_at: nowIso,
|
|
210
|
-
created_by: callerEmail,
|
|
211
|
-
};
|
|
212
|
-
if (useCredit) {
|
|
213
|
-
insertRow.status = 'pending';
|
|
214
|
-
insertRow.payment_source = isOffline ? 'offline' : 'stripe';
|
|
215
|
-
insertRow.hold_expires_at = new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString();
|
|
216
|
-
}
|
|
217
|
-
else if (isOffline) {
|
|
218
|
-
insertRow.status = 'paid';
|
|
219
|
-
insertRow.payment_source = 'offline';
|
|
220
|
-
insertRow.charged_amount_cents = net;
|
|
221
|
-
insertRow.credit_applied_cents = 0;
|
|
222
|
-
insertRow.hold_expires_at = null;
|
|
223
|
-
Object.assign(insertRow, contractSkipFields);
|
|
224
|
-
}
|
|
225
|
-
else {
|
|
226
|
-
insertRow.status = 'pending';
|
|
227
|
-
insertRow.payment_source = 'stripe';
|
|
228
|
-
insertRow.hold_expires_at = new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString();
|
|
229
|
-
}
|
|
230
|
-
const { data: inserted, error: iErr } = await admin
|
|
231
|
-
.from('bookings')
|
|
232
|
-
.insert(insertRow)
|
|
233
|
-
.select('id')
|
|
234
|
-
.single();
|
|
235
|
-
if (iErr) {
|
|
236
|
-
// deno-lint-ignore no-explicit-any
|
|
237
|
-
const code = iErr.code;
|
|
238
|
-
if (code === '23P01')
|
|
239
|
-
return json(409, { ok: false, error: 'slot_taken' });
|
|
240
|
-
return json(500, { ok: false, error: 'insert_failed', detail: iErr.message });
|
|
241
|
-
}
|
|
242
|
-
const booking_id = inserted.id;
|
|
243
|
-
const human = formatHumanTime(startUtc, endUtc);
|
|
244
|
-
// === Member credit (member-attached bookings only) ===
|
|
245
|
-
let credit_applied = 0;
|
|
246
|
-
let discount_applied = 0;
|
|
247
|
-
let charged = net;
|
|
248
|
-
if (useCredit && membership) {
|
|
249
|
-
credit_applied = await holdMemberCredit(admin, {
|
|
250
|
-
membershipId: membership.id,
|
|
251
|
-
bookingId: booking_id,
|
|
252
|
-
net,
|
|
253
|
-
});
|
|
254
|
-
const split = splitCharge(net, credit_applied);
|
|
255
|
-
charged = split.charged;
|
|
256
|
-
discount_applied = split.discount_applied;
|
|
257
|
-
}
|
|
258
|
-
const creditSummary = membership
|
|
259
|
-
? {
|
|
260
|
-
membership_id: membership.id,
|
|
261
|
-
credit_applied_cents: credit_applied,
|
|
262
|
-
discount_applied_cents: discount_applied,
|
|
263
|
-
charged_amount_cents: charged,
|
|
264
|
-
}
|
|
265
|
-
: {};
|
|
115
|
+
const origin = req.headers.get('origin');
|
|
116
|
+
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
266
117
|
// Post-paid side effects (door provisioning, GHL, calendar). Best-effort -
|
|
267
118
|
// never fail the booking on one of these.
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
119
|
+
const paidEffects = {
|
|
120
|
+
runPaidSideEffects: async (booking_id) => {
|
|
121
|
+
const { data: full } = await admin
|
|
122
|
+
.from('bookings')
|
|
123
|
+
.select('id,contact_name,contact_email,contact_phone,during,charged_amount_cents,list_amount_cents,google_event_id,ghl_contact_id,rooms(id,name,address,google_calendar_id,slug,usage_instructions)')
|
|
124
|
+
.eq('id', booking_id)
|
|
125
|
+
.maybeSingle();
|
|
126
|
+
if (!full)
|
|
127
|
+
return;
|
|
128
|
+
const eff = full;
|
|
129
|
+
let busResp = null;
|
|
130
|
+
try {
|
|
131
|
+
const range = deps.parseTstzRange(eff.during);
|
|
132
|
+
const slug = eff.rooms?.slug ?? null;
|
|
133
|
+
if (range && slug) {
|
|
134
|
+
busResp = await deps.busProvision({
|
|
135
|
+
bookingId: eff.id,
|
|
136
|
+
roomKey: slug,
|
|
137
|
+
startUtc: range.startISO,
|
|
138
|
+
endUtc: range.endISO,
|
|
139
|
+
customer: {
|
|
140
|
+
name: eff.contact_name ?? undefined,
|
|
141
|
+
email: eff.contact_email,
|
|
142
|
+
phone: eff.contact_phone ?? undefined,
|
|
143
|
+
},
|
|
144
|
+
}, admin);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
console.log('[admin-create-booking] busProvision skipped (missing slug/range)', booking_id);
|
|
148
|
+
}
|
|
293
149
|
}
|
|
294
|
-
|
|
295
|
-
|
|
150
|
+
catch { /* never break the caller */ }
|
|
151
|
+
try {
|
|
152
|
+
await deps.notifyGhl(admin, eff, deps.extractDoorAccess(busResp));
|
|
296
153
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
try {
|
|
300
|
-
await deps.notifyGhl(admin, eff, deps.extractDoorAccess(busResp));
|
|
301
|
-
}
|
|
302
|
-
catch (e) {
|
|
303
|
-
console.warn('[admin-create-booking] ghl failed', e);
|
|
304
|
-
}
|
|
305
|
-
try {
|
|
306
|
-
await deps.createCalendarEvent(admin, eff);
|
|
307
|
-
}
|
|
308
|
-
catch (e) {
|
|
309
|
-
console.warn('[admin-create-booking] gcal failed', e);
|
|
310
|
-
}
|
|
311
|
-
await writebackBookingCreated(operator, eff);
|
|
312
|
-
};
|
|
313
|
-
// Finalizes a booking that needs no Stripe payment: consume the held credit,
|
|
314
|
-
// flip the row to paid, then run the paid side effects.
|
|
315
|
-
const settleAsPaid = async (paymentSource) => {
|
|
316
|
-
if (credit_applied > 0) {
|
|
317
|
-
const consumeErr = await consumeMemberCredit(admin, booking_id);
|
|
318
|
-
if (consumeErr) {
|
|
319
|
-
console.error('[admin-create-booking] credit_consume failed', consumeErr);
|
|
320
|
-
try {
|
|
321
|
-
await logOps(admin, 'credit_consume_failed', { message: consumeErr }, { severity: 'error', bookingId: booking_id });
|
|
322
|
-
}
|
|
323
|
-
catch { /* ignore */ }
|
|
154
|
+
catch (e) {
|
|
155
|
+
console.warn('[admin-create-booking] ghl failed', e);
|
|
324
156
|
}
|
|
325
|
-
}
|
|
326
|
-
await admin
|
|
327
|
-
.from('bookings')
|
|
328
|
-
.update({
|
|
329
|
-
status: 'paid',
|
|
330
|
-
payment_source: paymentSource,
|
|
331
|
-
charged_amount_cents: charged,
|
|
332
|
-
credit_applied_cents: credit_applied,
|
|
333
|
-
discount_applied_cents: discount_applied,
|
|
334
|
-
hold_expires_at: null,
|
|
335
|
-
...contractSkipFields,
|
|
336
|
-
})
|
|
337
|
-
.eq('id', booking_id);
|
|
338
|
-
await runPaidSideEffects();
|
|
339
|
-
};
|
|
340
|
-
// Abandon path: give the member their balance back.
|
|
341
|
-
const releaseHeldCredit = async (reason) => {
|
|
342
|
-
if (credit_applied <= 0)
|
|
343
|
-
return;
|
|
344
|
-
const relErr = await releaseMemberCredit(admin, booking_id, reason);
|
|
345
|
-
if (relErr) {
|
|
346
157
|
try {
|
|
347
|
-
await
|
|
158
|
+
await deps.createCalendarEvent(admin, eff);
|
|
348
159
|
}
|
|
349
|
-
catch {
|
|
350
|
-
|
|
160
|
+
catch (e) {
|
|
161
|
+
console.warn('[admin-create-booking] gcal failed', e);
|
|
162
|
+
}
|
|
163
|
+
await writebackBookingCreated(operator, eff);
|
|
164
|
+
},
|
|
351
165
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
when: human,
|
|
370
|
-
...creditSummary,
|
|
371
|
-
});
|
|
372
|
-
}
|
|
373
|
-
if (useCredit && charged === 0) {
|
|
374
|
-
await settleAsPaid('stripe');
|
|
375
|
-
try {
|
|
376
|
-
await logOps(admin, 'admin_booking_credit_covered', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
|
|
377
|
-
membership_id: membership?.id, credit_applied_cents: credit_applied }, { severity: 'info', bookingId: booking_id });
|
|
378
|
-
}
|
|
379
|
-
catch { /* ignore */ }
|
|
380
|
-
return json(200, {
|
|
381
|
-
ok: true,
|
|
382
|
-
mode: 'payment_link',
|
|
383
|
-
fully_covered: true,
|
|
384
|
-
booking_id,
|
|
385
|
-
amount_cents: net,
|
|
386
|
-
when: human,
|
|
387
|
-
...creditSummary,
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
if (useCredit && (credit_applied > 0 || discount_applied > 0)) {
|
|
391
|
-
await admin
|
|
392
|
-
.from('bookings')
|
|
393
|
-
.update({
|
|
394
|
-
credit_applied_cents: credit_applied,
|
|
395
|
-
discount_applied_cents: discount_applied,
|
|
396
|
-
})
|
|
397
|
-
.eq('id', booking_id);
|
|
398
|
-
}
|
|
399
|
-
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
400
|
-
if (!stripeKey) {
|
|
401
|
-
await releaseHeldCredit('payments_not_configured');
|
|
402
|
-
await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
|
|
403
|
-
return json(500, { ok: false, error: 'stripe_not_configured' });
|
|
404
|
-
}
|
|
405
|
-
const chargePlan = planBookingCharge(operator, charged);
|
|
406
|
-
if ('error' in chargePlan) {
|
|
407
|
-
await releaseHeldCredit('payments_misconfigured');
|
|
408
|
-
await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
|
|
409
|
-
try {
|
|
410
|
-
await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'admin-create-booking', booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
|
|
411
|
-
}
|
|
412
|
-
catch { /* ignore */ }
|
|
413
|
-
return json(500, { ok: false, error: 'payments_misconfigured' });
|
|
414
|
-
}
|
|
415
|
-
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
416
|
-
const origin = req.headers.get('origin');
|
|
417
|
-
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
418
|
-
try {
|
|
419
|
-
const session = await createBookingCheckoutSession(stripe, buildAdminCheckoutSessionParams({
|
|
420
|
-
roomName: room.name,
|
|
421
|
-
roomSlug: room.slug ?? null,
|
|
422
|
-
human,
|
|
423
|
-
customerEmail: contact.email,
|
|
424
|
-
bookingId: booking_id,
|
|
425
|
-
amountCents: charged,
|
|
426
|
-
base,
|
|
427
|
-
}), chargePlan);
|
|
428
|
-
await admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', booking_id);
|
|
429
|
-
try {
|
|
430
|
-
await logOps(admin, 'admin_payment_link_created', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
|
|
431
|
-
...(membership ? { membership_id: membership.id, credit_applied_cents: credit_applied, charged_amount_cents: charged } : {}) }, { severity: 'info', bookingId: booking_id });
|
|
432
|
-
}
|
|
433
|
-
catch { /* ignore */ }
|
|
434
|
-
return json(200, {
|
|
435
|
-
ok: true,
|
|
436
|
-
mode: 'payment_link',
|
|
437
|
-
booking_id,
|
|
438
|
-
amount_cents: net,
|
|
439
|
-
url: session.url,
|
|
440
|
-
when: human,
|
|
441
|
-
...creditSummary,
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
catch (e) {
|
|
445
|
-
await releaseHeldCredit('stripe_create_failed');
|
|
446
|
-
await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
|
|
447
|
-
try {
|
|
448
|
-
await logOps(admin, 'admin_stripe_create_failed', { message: String(e), booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
|
|
449
|
-
}
|
|
450
|
-
catch { /* ignore */ }
|
|
451
|
-
return json(502, { ok: false, error: 'payment_start_failed' });
|
|
452
|
-
}
|
|
166
|
+
const out = await createBookingCore({
|
|
167
|
+
admin,
|
|
168
|
+
operator,
|
|
169
|
+
stripeFactory: () => {
|
|
170
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
171
|
+
if (!stripeKey)
|
|
172
|
+
return null;
|
|
173
|
+
return () => new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
174
|
+
},
|
|
175
|
+
logOps,
|
|
176
|
+
input: parsed.data,
|
|
177
|
+
policy: HUMAN_POLICY,
|
|
178
|
+
base,
|
|
179
|
+
actor: callerEmail,
|
|
180
|
+
paidEffects,
|
|
181
|
+
});
|
|
182
|
+
return json(out.status, out.body);
|
|
453
183
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
import { type BookingLogOps, type CreateBookingOperator, type CreateBookingResult, type BookingStripe } from '../createBookingCore.js';
|
|
3
|
+
import type { AgentBrand, AgentClaims, AgentIdentity, AgentRuntime } from '../agentBooking.js';
|
|
4
|
+
export { voidAgentBooking } from '../agentBooking.js';
|
|
5
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
6
|
+
export interface AgentCreateBookingDeps {
|
|
7
|
+
readonly admin: SupabaseLike;
|
|
8
|
+
readonly operator: CreateBookingOperator;
|
|
9
|
+
readonly stripeFactory: () => (() => BookingStripe) | null;
|
|
10
|
+
readonly logOps: BookingLogOps;
|
|
11
|
+
readonly agent: AgentIdentity;
|
|
12
|
+
readonly claims: AgentClaims;
|
|
13
|
+
readonly brand: AgentBrand;
|
|
14
|
+
readonly nowMs?: () => number;
|
|
15
|
+
readonly sendLinkEmail?: AgentRuntime['sendLinkEmail'];
|
|
16
|
+
readonly loadTerms?: AgentRuntime['loadTerms'];
|
|
17
|
+
readonly termsUrl?: AgentRuntime['termsUrl'];
|
|
18
|
+
}
|
|
19
|
+
export declare function createAgentBooking(deps: AgentCreateBookingDeps, rawInput: unknown): Promise<CreateBookingResult>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createBookingCore } from '../createBookingCore.js';
|
|
2
|
+
import { AGENT_POLICY } from '../agentPolicy.js';
|
|
3
|
+
export { voidAgentBooking } from '../agentBooking.js';
|
|
4
|
+
export async function createAgentBooking(deps, rawInput) {
|
|
5
|
+
if (!Object.isFrozen(deps))
|
|
6
|
+
return { ok: false, status: 500, body: { ok: false, error: 'deps_not_frozen' } };
|
|
7
|
+
return await createBookingCore({
|
|
8
|
+
admin: deps.admin,
|
|
9
|
+
operator: deps.operator,
|
|
10
|
+
stripeFactory: deps.stripeFactory,
|
|
11
|
+
logOps: deps.logOps,
|
|
12
|
+
input: rawInput,
|
|
13
|
+
policy: AGENT_POLICY,
|
|
14
|
+
base: `https://${deps.operator.domain}`,
|
|
15
|
+
actor: `service:${deps.agent.label}`,
|
|
16
|
+
agentRuntime: {
|
|
17
|
+
agent: deps.agent,
|
|
18
|
+
claims: deps.claims,
|
|
19
|
+
brand: deps.brand,
|
|
20
|
+
nowMs: deps.nowMs,
|
|
21
|
+
sendLinkEmail: deps.sendLinkEmail,
|
|
22
|
+
loadTerms: deps.loadTerms,
|
|
23
|
+
termsUrl: deps.termsUrl,
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
}
|
|
@@ -13,6 +13,7 @@ import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpa
|
|
|
13
13
|
import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
|
|
14
14
|
import { errorNameFromUnknown, revokeBookingOrganizerAccessGrants, shouldRevokeOrganizerGrantsOnStripeChargeRefunded, } from './booking-access-revoke.js';
|
|
15
15
|
import { isValidConnectedAccountId } from '../connectBookingCharge.js';
|
|
16
|
+
import { insertTier1Agreement, loadTier1TermsVersion } from '../tier1Agreement.js';
|
|
16
17
|
import { connectAcceptedOpsKind, gateConnectBookingEvent } from '../stripeConnectEvents.js';
|
|
17
18
|
export function createStripeWebhookHandler(config) {
|
|
18
19
|
return buildStripeWebhookHandler(config, null);
|
|
@@ -101,6 +102,73 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
101
102
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
102
103
|
return data;
|
|
103
104
|
}
|
|
105
|
+
// Agent bookings: verified Checkout consent + Tier-1 agreement row, or no flip.
|
|
106
|
+
async function agentConsentGate(bookingId, session) {
|
|
107
|
+
class TransientGateError extends Error {
|
|
108
|
+
}
|
|
109
|
+
// transient=true: alarm then THROW so the outer catch removes the
|
|
110
|
+
// stripe_events ledger row and returns 500 (Stripe retries).
|
|
111
|
+
const block = async (reason, detail = {}, transient = false) => {
|
|
112
|
+
const r = await logOps(supabase, 'agent_booking_consent_missing', { session_id: session.id, reason, ...detail }, {
|
|
113
|
+
severity: 'error',
|
|
114
|
+
bookingId,
|
|
115
|
+
dedupeKey: `agent_booking_consent_missing:${bookingId}:${session.id}`,
|
|
116
|
+
});
|
|
117
|
+
if (!r.ok) {
|
|
118
|
+
console.error('[stripe-webhook] agent consent alarm failed to persist', { bookingId, sessionId: session.id, error: r.error });
|
|
119
|
+
}
|
|
120
|
+
// ANY block on a PAID session pins the hold: Stripe retries (transient) can
|
|
121
|
+
// outlive the 2h grace, and a permanent block needs staff time.
|
|
122
|
+
const pin = await supabase.from('bookings')
|
|
123
|
+
.update({ hold_expires_at: new Date(Date.now() + 30 * 24 * 3600 * 1000).toISOString() })
|
|
124
|
+
.eq('id', bookingId)
|
|
125
|
+
.eq('status', 'pending');
|
|
126
|
+
if (transient)
|
|
127
|
+
throw new TransientGateError(`agent_consent_gate_transient:${reason}`);
|
|
128
|
+
if (pin?.error)
|
|
129
|
+
throw new TransientGateError(`agent_consent_gate_pin_failed:${pin.error.message}`);
|
|
130
|
+
return { ok: false };
|
|
131
|
+
};
|
|
132
|
+
try {
|
|
133
|
+
if (session.consent?.terms_of_service !== 'accepted')
|
|
134
|
+
return await block('consent_not_accepted');
|
|
135
|
+
const metaVersion = session.metadata?.terms_version;
|
|
136
|
+
const metaSha = session.metadata?.terms_sha256;
|
|
137
|
+
if (!metaVersion || !metaSha)
|
|
138
|
+
return await block('terms_metadata_missing');
|
|
139
|
+
// Verify the exact version the customer saw (not the CURRENT manifest):
|
|
140
|
+
// its published bytes must still hash to what the session recorded.
|
|
141
|
+
const loaded = await loadTier1TermsVersion(supabase, metaVersion);
|
|
142
|
+
if (!loaded.ok) {
|
|
143
|
+
return await block(loaded.error, {}, loaded.error === 'terms_unavailable');
|
|
144
|
+
}
|
|
145
|
+
if (loaded.terms.content_sha256 !== metaSha) {
|
|
146
|
+
return await block('terms_hash_mismatch');
|
|
147
|
+
}
|
|
148
|
+
const { data: bk } = await supabase
|
|
149
|
+
.from('bookings').select('id,rooms(slug)').eq('id', bookingId).maybeSingle();
|
|
150
|
+
const rooms = bk?.rooms;
|
|
151
|
+
const ag = await insertTier1Agreement(supabase, {
|
|
152
|
+
bookingId,
|
|
153
|
+
roomSlug: rooms?.slug ?? null,
|
|
154
|
+
terms: loaded.terms,
|
|
155
|
+
method: 'stripe_checkout_tos',
|
|
156
|
+
signerName: session.customer_details?.name ?? null,
|
|
157
|
+
signerEmail: session.customer_details?.email ?? session.customer_email ?? null,
|
|
158
|
+
signerIp: null,
|
|
159
|
+
signerUserAgent: null,
|
|
160
|
+
});
|
|
161
|
+
// insertTier1Agreement already tolerates 23505 (agreement already recorded).
|
|
162
|
+
if (ag.error)
|
|
163
|
+
return await block('agreement_insert_failed', { message: ag.error }, true);
|
|
164
|
+
return { ok: true, stamp: { policy_accepted_at: new Date().toISOString() } };
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
if (e instanceof TransientGateError)
|
|
168
|
+
throw e;
|
|
169
|
+
return await block('consent_gate_error', { message: String(e) }, true);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
104
172
|
let bookingLookupErrored = false;
|
|
105
173
|
async function findBookingIdByPaymentIntent(paymentIntentId) {
|
|
106
174
|
bookingLookupErrored = false;
|
|
@@ -1854,32 +1922,41 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
1854
1922
|
const paymentIntent = typeof session.payment_intent === 'string'
|
|
1855
1923
|
? session.payment_intent
|
|
1856
1924
|
: session.payment_intent?.id ?? null;
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
}
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1925
|
+
// Agent-created bookings (keyed on the SESSION metadata, never on
|
|
1926
|
+
// bookings.source) may only flip to paid after the customer accepted
|
|
1927
|
+
// the Tier-1 terms on Checkout. Human sessions skip this entirely.
|
|
1928
|
+
const agentGate = session.metadata?.source === 'agent'
|
|
1929
|
+
? await agentConsentGate(booking.id, session)
|
|
1930
|
+
: { ok: true, stamp: {} };
|
|
1931
|
+
const { data: flipped, error: flipErr } = !agentGate.ok
|
|
1932
|
+
? { data: null, error: null }
|
|
1933
|
+
: await supabase
|
|
1934
|
+
.from('bookings')
|
|
1935
|
+
.update({
|
|
1936
|
+
status: 'paid',
|
|
1937
|
+
charged_amount_cents: session.amount_total ?? null,
|
|
1938
|
+
stripe_payment_intent: paymentIntent,
|
|
1939
|
+
...agentGate.stamp,
|
|
1940
|
+
})
|
|
1941
|
+
.eq('id', booking.id)
|
|
1942
|
+
.neq('status', 'paid')
|
|
1943
|
+
// A Commons deposit capture is a PARTIAL payment: flipping it to
|
|
1944
|
+
// 'paid' here would both overstate the money collected and violate
|
|
1945
|
+
// bookings_amount_math_check. Excluded rather than tightening to
|
|
1946
|
+
// status='pending', because this generic path legitimately serves
|
|
1947
|
+
// other non-pending recoveries (e.g. a re-paid expired hold).
|
|
1948
|
+
.neq('status', 'deposit_paid')
|
|
1949
|
+
// Never resurrect an already-cancelled booking on a replayed/
|
|
1950
|
+
// out-of-order webhook (all 3 terminal cancelled_* states --
|
|
1951
|
+
// see stripe-db-reconcile.ts's BOOKING_POST_PAID_OK). Explicit
|
|
1952
|
+
// .neq() chain to match this file's existing idiom, rather than
|
|
1953
|
+
// a LIKE pattern -- this file elsewhere notes '_' is a live SQL
|
|
1954
|
+
// wildcard, not just a literal underscore, so an unescaped
|
|
1955
|
+
// 'cancelled_%' LIKE could match unintended values.
|
|
1956
|
+
.neq('status', 'cancelled_credited')
|
|
1957
|
+
.neq('status', 'cancelled_forfeited')
|
|
1958
|
+
.neq('status', 'cancelled_refunded')
|
|
1959
|
+
.select('id');
|
|
1883
1960
|
if (!flipErr && flipped && flipped.length > 0) {
|
|
1884
1961
|
// Post-payment side effects — MUST NOT break the webhook.
|
|
1885
1962
|
// FIRST: consume the period credit hold placed by create-booking
|
|
@@ -2002,6 +2079,9 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2002
2079
|
console.error('[stripe-webhook] booking-paid-flip-failed alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: persisted.error });
|
|
2003
2080
|
}
|
|
2004
2081
|
}
|
|
2082
|
+
else if (!agentGate.ok) {
|
|
2083
|
+
// Consent gate already alarmed and pinned the hold; no second alarm.
|
|
2084
|
+
}
|
|
2005
2085
|
else {
|
|
2006
2086
|
// Guard blocked the flip even though the JS-level read saw this
|
|
2007
2087
|
// booking as flippable (not paid/deposit_paid/cancelled_*) --
|