@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
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { reclaimStaleHoldsExceptCompletedTier3 } from './bookingHoldReclaim.js';
|
|
3
|
+
import { validateAndPriceForRoom, formatHumanTime } from './pricing.js';
|
|
4
|
+
import { resolveIsMember } from './membership.js';
|
|
5
|
+
import { createBookingCheckoutSession, planBookingCharge, resolveConnectedAccount } from './connectBookingCharge.js';
|
|
6
|
+
import { clampCheckoutExpiresAtSeconds } from './checkoutSessionParams.js';
|
|
7
|
+
import { loadTier1Terms, resolveContractTier } from './tier1Agreement.js';
|
|
8
|
+
import { checkRateLimitDetailed } from './rateLimit.js';
|
|
9
|
+
import { sendPaymentLinkEmail } from './paymentLinkEmail.js';
|
|
10
|
+
import { AGENT_HOLD_GRACE_SECONDS } from './agentPolicy.js';
|
|
11
|
+
const result = (status, body) => ({ ok: status >= 200 && status < 300, status, body });
|
|
12
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
13
|
+
const LABEL_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/;
|
|
14
|
+
const MAX_MESSAGE_CHARS = 1200;
|
|
15
|
+
const AgentContact = z.object({
|
|
16
|
+
name: z.string().trim().min(1).max(200),
|
|
17
|
+
email: z.string().trim().email().max(254),
|
|
18
|
+
phone: z.string().trim().min(5).max(40).optional(),
|
|
19
|
+
}).strict();
|
|
20
|
+
export const AgentBookingBody = z.object({
|
|
21
|
+
room_id: z.string().uuid(),
|
|
22
|
+
start: z.string().datetime(),
|
|
23
|
+
end: z.string().datetime(),
|
|
24
|
+
contact: AgentContact,
|
|
25
|
+
reason: z.string().trim().min(3).max(500),
|
|
26
|
+
idempotency_key: z.string().regex(/^[A-Za-z0-9._:-]{8,128}$/),
|
|
27
|
+
}).strict();
|
|
28
|
+
function hasForbiddenKey(v, depth = 0) {
|
|
29
|
+
if (depth > 6 || v === null || typeof v !== 'object')
|
|
30
|
+
return false;
|
|
31
|
+
if (Array.isArray(v))
|
|
32
|
+
return v.some((x) => hasForbiddenKey(x, depth + 1));
|
|
33
|
+
for (const k of Object.getOwnPropertyNames(v)) {
|
|
34
|
+
if (FORBIDDEN_KEYS.has(k))
|
|
35
|
+
return true;
|
|
36
|
+
if (hasForbiddenKey(v[k], depth + 1))
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
export function parseAgentInput(raw) {
|
|
42
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
43
|
+
return { ok: false };
|
|
44
|
+
const proto = Object.getPrototypeOf(raw);
|
|
45
|
+
if (proto !== Object.prototype && proto !== null)
|
|
46
|
+
return { ok: false };
|
|
47
|
+
if (hasForbiddenKey(raw))
|
|
48
|
+
return { ok: false };
|
|
49
|
+
const parsed = AgentBookingBody.safeParse(raw);
|
|
50
|
+
if (!parsed.success)
|
|
51
|
+
return { ok: false };
|
|
52
|
+
return { ok: true, data: parsed.data };
|
|
53
|
+
}
|
|
54
|
+
function canonicalize(v) {
|
|
55
|
+
if (Array.isArray(v))
|
|
56
|
+
return v.map(canonicalize);
|
|
57
|
+
if (v && typeof v === 'object') {
|
|
58
|
+
const out = {};
|
|
59
|
+
for (const k of Object.keys(v).sort())
|
|
60
|
+
out[k] = canonicalize(v[k]);
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
return v;
|
|
64
|
+
}
|
|
65
|
+
async function sha256Hex(text) {
|
|
66
|
+
const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
67
|
+
return Array.from(new Uint8Array(d)).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
68
|
+
}
|
|
69
|
+
export function normalizeEmail(e) { return e.trim().toLowerCase(); }
|
|
70
|
+
export function normalizePhone(p) {
|
|
71
|
+
if (p === undefined)
|
|
72
|
+
return null;
|
|
73
|
+
const n = p.replace(/[^\d+]/g, '');
|
|
74
|
+
return n.length > 0 ? n : null;
|
|
75
|
+
}
|
|
76
|
+
/** sha256 over the canonical parsed input (sorted keys, normalized email/phone, UTC ISO times). */
|
|
77
|
+
export async function computeRequestHash(i) {
|
|
78
|
+
return await sha256Hex(JSON.stringify(canonicalize({
|
|
79
|
+
room_id: i.room_id.toLowerCase(),
|
|
80
|
+
start: new Date(i.start).toISOString(),
|
|
81
|
+
end: new Date(i.end).toISOString(),
|
|
82
|
+
contact: { name: i.contact.name, email: normalizeEmail(i.contact.email), phone: normalizePhone(i.contact.phone) },
|
|
83
|
+
reason: i.reason,
|
|
84
|
+
})));
|
|
85
|
+
}
|
|
86
|
+
export function maskEmail(email) {
|
|
87
|
+
const at = email.lastIndexOf('@');
|
|
88
|
+
if (at < 1)
|
|
89
|
+
return '***';
|
|
90
|
+
return `${email[0]}***${email.slice(at)}`;
|
|
91
|
+
}
|
|
92
|
+
function isFinitePositive(n) { return typeof n === 'number' && Number.isFinite(n) && n > 0; }
|
|
93
|
+
/** The agent flow only runs under a complete, fully-restrictive policy. */
|
|
94
|
+
function policyProblem(p) {
|
|
95
|
+
if (p.requireIdempotencyKey !== true || p.failClosedRateLimit !== true)
|
|
96
|
+
return 'idempotency_or_limiter';
|
|
97
|
+
if (p.refuseQuoteMode !== true || p.refuseAgreementText !== true)
|
|
98
|
+
return 'refusals';
|
|
99
|
+
if (p.allowOffline === true || p.allowCredit === true || p.allowMembershipAttach === true ||
|
|
100
|
+
p.allowSkipDynamicDiscount === true || p.settlePaid === true)
|
|
101
|
+
return 'capabilities';
|
|
102
|
+
if (!isFinitePositive(p.minNetCents))
|
|
103
|
+
return 'minNetCents';
|
|
104
|
+
if (!Array.isArray(p.allowedTiers) || p.allowedTiers.length === 0 ||
|
|
105
|
+
!p.allowedTiers.every((t) => Number.isInteger(t)))
|
|
106
|
+
return 'allowedTiers';
|
|
107
|
+
if (!Array.isArray(p.paymentMethodTypes) || p.paymentMethodTypes.length !== 1 || p.paymentMethodTypes[0] !== 'card')
|
|
108
|
+
return 'paymentMethodTypes';
|
|
109
|
+
const w = p.startWindow;
|
|
110
|
+
if (!w || !isFinitePositive(w.minLeadSeconds) || !isFinitePositive(w.maxLeadSeconds) || !isFinitePositive(w.maxSpanSeconds))
|
|
111
|
+
return 'startWindow';
|
|
112
|
+
if (!p.perAgentCeiling || !p.perTenantCeiling)
|
|
113
|
+
return 'ceilings';
|
|
114
|
+
if (!isFinitePositive(p.hourlyLimit))
|
|
115
|
+
return 'hourlyLimit';
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
/** Only InvalidRequest/Card errors prove no session was created. Everything else is ambiguous. */
|
|
119
|
+
export function isDefinitiveStripeError(e) {
|
|
120
|
+
const o = e;
|
|
121
|
+
const t = String(o?.type ?? o?.name ?? '');
|
|
122
|
+
return t === 'StripeInvalidRequestError' || t === 'StripeCardError' ||
|
|
123
|
+
(o?.rawType === 'invalid_request_error' || o?.rawType === 'card_error');
|
|
124
|
+
}
|
|
125
|
+
async function safely(fn, logOps, admin, kind, bookingId) {
|
|
126
|
+
try {
|
|
127
|
+
await fn();
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
try {
|
|
131
|
+
await logOps(admin, kind, { message: String(e) }, { severity: 'error', bookingId });
|
|
132
|
+
}
|
|
133
|
+
catch { /* ignore */ }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function expireSessionAndRow(a) {
|
|
137
|
+
const { admin, stripe, logOps, bookingId, sessionId, agentId } = a;
|
|
138
|
+
let status;
|
|
139
|
+
try {
|
|
140
|
+
const s = await stripe.checkout.sessions.retrieve(sessionId);
|
|
141
|
+
// The session must have been minted for THIS agent, not merely share its label.
|
|
142
|
+
if (s?.metadata?.agent_id !== agentId)
|
|
143
|
+
return { ok: false, status: 404, error: 'booking_not_found' };
|
|
144
|
+
status = s?.status;
|
|
145
|
+
}
|
|
146
|
+
catch (_e) {
|
|
147
|
+
return { ok: false, status: 502, error: 'stripe_retrieve_failed' };
|
|
148
|
+
}
|
|
149
|
+
if (status === 'complete') {
|
|
150
|
+
if (logOps) {
|
|
151
|
+
try {
|
|
152
|
+
await logOps(admin, 'agent_booking_void_already_paid', { booking_id: bookingId }, { severity: 'error', bookingId, dedupeKey: `agent_booking_void_already_paid:${bookingId}` });
|
|
153
|
+
}
|
|
154
|
+
catch { /* ignore */ }
|
|
155
|
+
}
|
|
156
|
+
return { ok: false, status: 409, error: 'already_paid' };
|
|
157
|
+
}
|
|
158
|
+
if (status === 'open') {
|
|
159
|
+
try {
|
|
160
|
+
await stripe.checkout.sessions.expire(sessionId);
|
|
161
|
+
}
|
|
162
|
+
catch (_e) {
|
|
163
|
+
return { ok: false, status: 502, error: 'stripe_expire_failed' };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
else if (status !== 'expired') {
|
|
167
|
+
return { ok: false, status: 502, error: 'stripe_session_state_unknown' };
|
|
168
|
+
}
|
|
169
|
+
const { data, error } = await admin
|
|
170
|
+
.from('bookings')
|
|
171
|
+
.update({ status: 'expired' })
|
|
172
|
+
.eq('id', bookingId)
|
|
173
|
+
.eq('status', 'pending')
|
|
174
|
+
.select('id');
|
|
175
|
+
if (error)
|
|
176
|
+
return { ok: false, status: 500, error: 'expire_failed' };
|
|
177
|
+
if (!data || data.length === 0)
|
|
178
|
+
return { ok: false, status: 409, error: 'not_pending' };
|
|
179
|
+
return { ok: true };
|
|
180
|
+
}
|
|
181
|
+
/** Voids ONLY the calling agent's own still-pending booking. Never touches paid rows. */
|
|
182
|
+
export async function voidAgentBooking(a) {
|
|
183
|
+
const { admin, stripe, agent, bookingId, logOps } = a;
|
|
184
|
+
if (!LABEL_RE.test(agent?.label ?? '') || typeof bookingId !== 'string' || bookingId.length === 0) {
|
|
185
|
+
return result(400, { ok: false, error: 'invalid_request' });
|
|
186
|
+
}
|
|
187
|
+
const { data: row, error: rErr } = await admin
|
|
188
|
+
.from('bookings')
|
|
189
|
+
.select('id,status,created_by,stripe_session_id')
|
|
190
|
+
.eq('id', bookingId)
|
|
191
|
+
.eq('created_by', `service:${agent.label}`)
|
|
192
|
+
.maybeSingle();
|
|
193
|
+
if (rErr)
|
|
194
|
+
return result(500, { ok: false, error: 'load_booking_failed' });
|
|
195
|
+
const b = row;
|
|
196
|
+
if (!b || b.created_by !== `service:${agent.label}`)
|
|
197
|
+
return result(404, { ok: false, error: 'booking_not_found' });
|
|
198
|
+
if (b.status === 'expired')
|
|
199
|
+
return result(200, { ok: true, booking_id: bookingId, status: 'expired' });
|
|
200
|
+
if (b.status !== 'pending')
|
|
201
|
+
return result(409, { ok: false, error: 'not_pending' });
|
|
202
|
+
if (!b.stripe_session_id)
|
|
203
|
+
return result(409, { ok: false, error: 'session_unknown' });
|
|
204
|
+
const r = await expireSessionAndRow({ admin, stripe, logOps, bookingId, sessionId: b.stripe_session_id, agentId: agent.id });
|
|
205
|
+
if (!r.ok)
|
|
206
|
+
return result(r.status, { ok: false, error: r.error });
|
|
207
|
+
const release = a.releaseClaim ?? (async (agentId, bid) => {
|
|
208
|
+
const { error } = await admin.rpc('agent_booking_release', { p_agent_id: agentId, p_booking_id: bid });
|
|
209
|
+
if (error)
|
|
210
|
+
throw new Error(error.message);
|
|
211
|
+
});
|
|
212
|
+
if (logOps) {
|
|
213
|
+
await safely(() => release(agent.id, bookingId), logOps, admin, 'agent_booking_claim_release_failed', bookingId);
|
|
214
|
+
try {
|
|
215
|
+
await logOps(admin, 'agent_booking_voided', { booking_id: bookingId, agent_id: agent.id }, { severity: 'info', bookingId });
|
|
216
|
+
}
|
|
217
|
+
catch { /* ignore */ }
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
try {
|
|
221
|
+
await release(agent.id, bookingId);
|
|
222
|
+
}
|
|
223
|
+
catch { /* ignore */ }
|
|
224
|
+
}
|
|
225
|
+
return result(200, { ok: true, booking_id: bookingId, status: 'expired' });
|
|
226
|
+
}
|
|
227
|
+
// ---- default Supabase-backed claims ---------------------------------------
|
|
228
|
+
/** Claims backed by SQL RPCs. Only agent_booking_reserve is specified; the rest are assumed names. */
|
|
229
|
+
export function makeSupabaseAgentClaims(admin) {
|
|
230
|
+
const finish = async (p) => {
|
|
231
|
+
const { error } = await admin.rpc('agent_booking_finish', p);
|
|
232
|
+
if (error)
|
|
233
|
+
throw new Error(error.message);
|
|
234
|
+
};
|
|
235
|
+
return {
|
|
236
|
+
async reserve(a) {
|
|
237
|
+
const { data, error } = await admin.rpc('agent_booking_reserve', {
|
|
238
|
+
p_agent_id: a.agentId, p_tenant_id: a.tenantId, p_key: a.key,
|
|
239
|
+
p_request_hash: a.requestHash, p_list_cents: a.listCents,
|
|
240
|
+
p_agent_max_bookings: a.agentMaxBookings, p_agent_max_list_cents: a.agentMaxListCents,
|
|
241
|
+
p_tenant_max_bookings: a.tenantMaxBookings, p_tenant_max_list_cents: a.tenantMaxListCents,
|
|
242
|
+
p_window_seconds: a.windowSeconds, p_created_by: a.createdBy ?? null,
|
|
243
|
+
});
|
|
244
|
+
if (error)
|
|
245
|
+
throw new Error(error.message);
|
|
246
|
+
const d = (data ?? {});
|
|
247
|
+
switch (d.outcome) {
|
|
248
|
+
case 'ok': return { status: 'ok' };
|
|
249
|
+
case 'replay_succeeded': return d.booking_id ? { status: 'replay_succeeded', bookingId: d.booking_id } : (() => { throw new Error('reserve_malformed'); })();
|
|
250
|
+
case 'in_progress': return { status: 'in_progress' };
|
|
251
|
+
case 'idempotency_conflict': return { status: 'idempotency_conflict' };
|
|
252
|
+
case 'ceiling_exceeded': return { status: 'ceiling_exceeded', scope: d.scope };
|
|
253
|
+
default: throw new Error('reserve_unknown_outcome');
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
async link(a) {
|
|
257
|
+
try {
|
|
258
|
+
const { data, error } = await admin.rpc('agent_booking_link', {
|
|
259
|
+
p_agent_id: a.agentId, p_key: a.key, p_booking_id: a.bookingId,
|
|
260
|
+
});
|
|
261
|
+
if (error)
|
|
262
|
+
return { ok: false };
|
|
263
|
+
return { ok: data?.updated === 1 };
|
|
264
|
+
}
|
|
265
|
+
catch (_e) {
|
|
266
|
+
return { ok: false };
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
succeed: (a) => finish({ p_agent_id: a.agentId, p_key: a.key, p_state: 'succeeded', p_booking_id: a.bookingId, p_response: a.response }),
|
|
270
|
+
fail: (a) => finish({ p_agent_id: a.agentId, p_key: a.key, p_state: 'failed', p_booking_id: a.bookingId ?? null, p_reason: a.reason }),
|
|
271
|
+
failAmbiguous: (a) => finish({ p_agent_id: a.agentId, p_key: a.key, p_state: 'failed_ambiguous', p_booking_id: a.bookingId, p_reason: a.reason }),
|
|
272
|
+
async release(a) {
|
|
273
|
+
const { error } = await admin.rpc('agent_booking_release', { p_agent_id: a.agentId, p_booking_id: a.bookingId });
|
|
274
|
+
if (error)
|
|
275
|
+
throw new Error(error.message);
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
// ---- create ---------------------------------------------------------------
|
|
280
|
+
export async function runAgentBooking(args) {
|
|
281
|
+
const { admin, operator, stripeFactory, logOps, policy, base } = args;
|
|
282
|
+
const rt = args.agentRuntime;
|
|
283
|
+
// paidEffects, if a caller passed one, is never read on this path.
|
|
284
|
+
if (!rt || !rt.agent || !rt.claims || !rt.brand)
|
|
285
|
+
return result(500, { ok: false, error: 'agent_context_missing' });
|
|
286
|
+
const agent = rt.agent;
|
|
287
|
+
if (!LABEL_RE.test(String(agent.label)) || !agent.id || !agent.tenantId) {
|
|
288
|
+
return result(500, { ok: false, error: 'agent_identity_invalid' });
|
|
289
|
+
}
|
|
290
|
+
if (policyProblem(policy) !== null)
|
|
291
|
+
return result(500, { ok: false, error: 'policy_not_supported' });
|
|
292
|
+
const createdBy = `service:${agent.label}`;
|
|
293
|
+
const nowMs = (rt.nowMs ?? Date.now)();
|
|
294
|
+
// 1. Parse (no I/O).
|
|
295
|
+
const parsed = parseAgentInput(args.input);
|
|
296
|
+
if (!parsed.ok)
|
|
297
|
+
return result(400, { ok: false, error: 'invalid_body' });
|
|
298
|
+
const input = parsed.data;
|
|
299
|
+
const email = normalizeEmail(input.contact.email);
|
|
300
|
+
const phone = input.contact.phone?.trim() || null;
|
|
301
|
+
// v1: non-Connect operators only.
|
|
302
|
+
const connect = resolveConnectedAccount(operator);
|
|
303
|
+
if (!connect.ok || connect.accountId !== null)
|
|
304
|
+
return result(409, { ok: false, error: 'connect_not_supported' });
|
|
305
|
+
// 2. Start / span window (no I/O).
|
|
306
|
+
const startMs = Date.parse(input.start);
|
|
307
|
+
const endMs = Date.parse(input.end);
|
|
308
|
+
const w = policy.startWindow;
|
|
309
|
+
if (!(endMs > startMs))
|
|
310
|
+
return result(400, { ok: false, error: 'invalid_range' });
|
|
311
|
+
if (startMs < nowMs + w.minLeadSeconds * 1000)
|
|
312
|
+
return result(400, { ok: false, error: 'start_too_soon' });
|
|
313
|
+
if (startMs > nowMs + w.maxLeadSeconds * 1000)
|
|
314
|
+
return result(400, { ok: false, error: 'start_too_far' });
|
|
315
|
+
if (endMs - startMs > w.maxSpanSeconds * 1000)
|
|
316
|
+
return result(400, { ok: false, error: 'span_too_long' });
|
|
317
|
+
// Limiter: an unavailable limiter fails closed.
|
|
318
|
+
const rl = await checkRateLimitDetailed(admin, 'agent-create-booking', agent.id, policy.hourlyLimit, 3600);
|
|
319
|
+
if (rl === 'error')
|
|
320
|
+
return result(503, { ok: false, error: 'rate_limiter_unavailable' });
|
|
321
|
+
if (rl === 'limited')
|
|
322
|
+
return result(429, { ok: false, error: 'rate_limited' });
|
|
323
|
+
// 3. Room.
|
|
324
|
+
const { data: room, error: rErr } = await admin
|
|
325
|
+
.from('rooms')
|
|
326
|
+
.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,checkout_agreement_text')
|
|
327
|
+
.eq('id', input.room_id)
|
|
328
|
+
.eq('active', true)
|
|
329
|
+
.maybeSingle();
|
|
330
|
+
if (rErr)
|
|
331
|
+
return result(500, { ok: false, error: 'load_room_failed' });
|
|
332
|
+
if (!room)
|
|
333
|
+
return result(404, { ok: false, error: 'room_not_found' });
|
|
334
|
+
// 4. Refusals, all before any write.
|
|
335
|
+
if (policy.refuseQuoteMode === true && room.booking_mode === 'quote')
|
|
336
|
+
return result(409, { ok: false, error: 'quote_not_supported' });
|
|
337
|
+
if (room.booking_mode !== 'hourly')
|
|
338
|
+
return result(409, { ok: false, error: 'room_not_bookable_by_agent' });
|
|
339
|
+
// `=== null` only: an absent column (undefined) or any text refuses.
|
|
340
|
+
if (!(room.checkout_agreement_text === null))
|
|
341
|
+
return result(409, { ok: false, error: 'room_requires_agreement_text' });
|
|
342
|
+
let tier;
|
|
343
|
+
try {
|
|
344
|
+
tier = await resolveContractTier(admin, input.room_id);
|
|
345
|
+
}
|
|
346
|
+
catch (_e) {
|
|
347
|
+
return result(503, { ok: false, error: 'tier_lookup_failed' });
|
|
348
|
+
}
|
|
349
|
+
if (tier === null || !Number.isInteger(tier))
|
|
350
|
+
return result(409, { ok: false, error: 'tier_unmapped' });
|
|
351
|
+
if (!policy.allowedTiers.includes(tier))
|
|
352
|
+
return result(409, { ok: false, error: 'tier_not_allowed' });
|
|
353
|
+
const loadTerms = rt.loadTerms ?? ((a) => loadTier1Terms(a, null));
|
|
354
|
+
let termsRes;
|
|
355
|
+
try {
|
|
356
|
+
termsRes = await loadTerms(admin);
|
|
357
|
+
}
|
|
358
|
+
catch (_e) {
|
|
359
|
+
return result(503, { ok: false, error: 'terms_unavailable' });
|
|
360
|
+
}
|
|
361
|
+
if (!termsRes.ok)
|
|
362
|
+
return result(503, { ok: false, error: 'terms_unavailable' });
|
|
363
|
+
const terms = termsRes.terms;
|
|
364
|
+
const termsUrl = (rt.termsUrl ?? ((v) => `https://${rt.brand.domain}/terms/booking`))(terms.version);
|
|
365
|
+
const message = `I agree to the [${rt.brand.shortName} Booking Terms (${terms.version})](${termsUrl}).`;
|
|
366
|
+
if (message.length > MAX_MESSAGE_CHARS)
|
|
367
|
+
return result(503, { ok: false, error: 'terms_unavailable' });
|
|
368
|
+
// 5. Price (server-authoritative). Agents never skip the dynamic discount.
|
|
369
|
+
const isMember = await resolveIsMember(admin, email);
|
|
370
|
+
const priced = await validateAndPriceForRoom(admin, room, { start: input.start, end: input.end }, nowMs, {
|
|
371
|
+
isMember,
|
|
372
|
+
allowDynamic: true,
|
|
373
|
+
notice: operator,
|
|
374
|
+
});
|
|
375
|
+
if (!priced.ok)
|
|
376
|
+
return result(priced.status, { ok: false, error: priced.error });
|
|
377
|
+
const { startUtc, endUtc, price_cents, rangeLiteral, dynamic_discount_cents, dynamic_discount_rule_type, list_rule_type } = priced;
|
|
378
|
+
const net = Math.max(0, price_cents - dynamic_discount_cents);
|
|
379
|
+
if (!Number.isInteger(net) || net < policy.minNetCents)
|
|
380
|
+
return result(409, { ok: false, error: 'amount_below_minimum' });
|
|
381
|
+
const buildStripe = stripeFactory();
|
|
382
|
+
if (!buildStripe)
|
|
383
|
+
return result(500, { ok: false, error: 'stripe_not_configured' });
|
|
384
|
+
const chargePlan = planBookingCharge(operator, net);
|
|
385
|
+
if ('error' in chargePlan || chargePlan.connected)
|
|
386
|
+
return result(500, { ok: false, error: 'payments_misconfigured' });
|
|
387
|
+
// 6. Reserve (idempotency claim + ceilings, atomic in the database).
|
|
388
|
+
const requestHash = await computeRequestHash(input);
|
|
389
|
+
let reserved;
|
|
390
|
+
try {
|
|
391
|
+
reserved = await rt.claims.reserve({
|
|
392
|
+
agentId: agent.id, tenantId: agent.tenantId, key: input.idempotency_key, requestHash, listCents: price_cents,
|
|
393
|
+
agentMaxBookings: policy.perAgentCeiling.bookings, agentMaxListCents: policy.perAgentCeiling.listCents,
|
|
394
|
+
tenantMaxBookings: policy.perTenantCeiling.bookings, tenantMaxListCents: policy.perTenantCeiling.listCents,
|
|
395
|
+
windowSeconds: 86400,
|
|
396
|
+
createdBy,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
catch (_e) {
|
|
400
|
+
return result(503, { ok: false, error: 'reserve_failed' });
|
|
401
|
+
}
|
|
402
|
+
switch (reserved?.status) {
|
|
403
|
+
case 'ok': break;
|
|
404
|
+
case 'replay_succeeded': {
|
|
405
|
+
const { data: cur, error: cErr } = await admin
|
|
406
|
+
.from('bookings').select('id,status').eq('id', reserved.bookingId).eq('created_by', createdBy).maybeSingle();
|
|
407
|
+
const c = cur;
|
|
408
|
+
if (cErr || !c)
|
|
409
|
+
return result(409, { ok: false, error: 'replay_unavailable' });
|
|
410
|
+
return result(200, { ok: true, replay: true, booking_id: c.id, status: c.status });
|
|
411
|
+
}
|
|
412
|
+
case 'in_progress': return result(409, { ok: false, error: 'request_in_progress' });
|
|
413
|
+
case 'idempotency_conflict': return result(409, { ok: false, error: 'idempotency_conflict' });
|
|
414
|
+
case 'ceiling_exceeded': return result(429, { ok: false, error: 'ceiling_exceeded', scope: reserved.scope ?? null });
|
|
415
|
+
default: return result(503, { ok: false, error: 'reserve_failed' });
|
|
416
|
+
}
|
|
417
|
+
const key = input.idempotency_key;
|
|
418
|
+
const fail = (reason, bookingId) => safely(() => rt.claims.fail({ agentId: agent.id, key, reason, bookingId }), logOps, admin, 'agent_booking_claim_update_failed', bookingId ?? null);
|
|
419
|
+
const failAmbiguous = (reason, bookingId) => safely(() => rt.claims.failAmbiguous({ agentId: agent.id, key, reason, bookingId }), logOps, admin, 'agent_booking_claim_update_failed', bookingId);
|
|
420
|
+
// 7. Timing: session never outlives the pay window; hold outlives the session by the grace.
|
|
421
|
+
const sessionExpiresSec = clampCheckoutExpiresAtSeconds(nowMs, new Date(Math.min(nowMs + 24 * 3600 * 1000 - 60 * 1000, startMs - 30 * 60 * 1000)).toISOString());
|
|
422
|
+
const holdExpiresAt = new Date((sessionExpiresSec + AGENT_HOLD_GRACE_SECONDS) * 1000).toISOString();
|
|
423
|
+
const expiresAtIso = new Date(sessionExpiresSec * 1000).toISOString();
|
|
424
|
+
// 8. Stale-hold reclaim, then insert (pending only).
|
|
425
|
+
try {
|
|
426
|
+
await reclaimStaleHoldsExceptCompletedTier3(admin, input.room_id, rangeLiteral);
|
|
427
|
+
}
|
|
428
|
+
catch (_e) {
|
|
429
|
+
await fail('reclaim_failed');
|
|
430
|
+
return result(500, { ok: false, error: 'reclaim_failed' });
|
|
431
|
+
}
|
|
432
|
+
const { data: inserted, error: iErr } = await admin
|
|
433
|
+
.from('bookings')
|
|
434
|
+
.insert({
|
|
435
|
+
room_id: input.room_id,
|
|
436
|
+
during: rangeLiteral,
|
|
437
|
+
list_amount_cents: price_cents,
|
|
438
|
+
dynamic_discount_cents,
|
|
439
|
+
dynamic_discount_rule_type,
|
|
440
|
+
list_rule_type,
|
|
441
|
+
contact_email: email,
|
|
442
|
+
contact_name: input.contact.name,
|
|
443
|
+
contact_phone: phone,
|
|
444
|
+
is_member: isMember,
|
|
445
|
+
policy_accepted_at: null,
|
|
446
|
+
created_by: createdBy,
|
|
447
|
+
status: 'pending',
|
|
448
|
+
payment_source: 'stripe',
|
|
449
|
+
hold_expires_at: holdExpiresAt,
|
|
450
|
+
})
|
|
451
|
+
.select('id')
|
|
452
|
+
.single();
|
|
453
|
+
if (iErr || !inserted) {
|
|
454
|
+
// deno-lint-ignore no-explicit-any
|
|
455
|
+
const code = iErr?.code;
|
|
456
|
+
await fail(code === '23P01' ? 'slot_taken' : 'insert_failed');
|
|
457
|
+
if (code === '23P01')
|
|
458
|
+
return result(409, { ok: false, error: 'slot_taken' });
|
|
459
|
+
return result(500, { ok: false, error: 'insert_failed' });
|
|
460
|
+
}
|
|
461
|
+
const bookingId = inserted.id;
|
|
462
|
+
const human = formatHumanTime(startUtc, endUtc);
|
|
463
|
+
let linked = false;
|
|
464
|
+
try {
|
|
465
|
+
linked = (await rt.claims.link({ agentId: agent.id, key, bookingId })).ok === true;
|
|
466
|
+
}
|
|
467
|
+
catch (_e) {
|
|
468
|
+
linked = false;
|
|
469
|
+
}
|
|
470
|
+
if (!linked) {
|
|
471
|
+
let expired = false;
|
|
472
|
+
try {
|
|
473
|
+
const { data: exp, error: eErr } = await admin
|
|
474
|
+
.from('bookings').update({ status: 'expired' }).eq('id', bookingId).eq('status', 'pending').select('id');
|
|
475
|
+
expired = !eErr && Array.isArray(exp) && exp.length > 0;
|
|
476
|
+
}
|
|
477
|
+
catch (_e) {
|
|
478
|
+
expired = false;
|
|
479
|
+
}
|
|
480
|
+
if (!expired) {
|
|
481
|
+
await failAmbiguous('claim_link_failed_row_stuck', bookingId);
|
|
482
|
+
try {
|
|
483
|
+
await logOps(admin, 'agent_booking_claim_link_failed', { booking_id: bookingId, agent_id: agent.id, row_expired: false }, { severity: 'error', bookingId });
|
|
484
|
+
}
|
|
485
|
+
catch { /* ignore */ }
|
|
486
|
+
return result(502, { ok: false, error: 'payment_start_uncertain' });
|
|
487
|
+
}
|
|
488
|
+
await fail('claim_link_failed');
|
|
489
|
+
try {
|
|
490
|
+
await logOps(admin, 'agent_booking_claim_link_failed', { booking_id: bookingId, agent_id: agent.id, row_expired: true }, { severity: 'error', bookingId });
|
|
491
|
+
}
|
|
492
|
+
catch { /* ignore */ }
|
|
493
|
+
return result(500, { ok: false, error: 'claim_link_failed' });
|
|
494
|
+
}
|
|
495
|
+
const stripe = buildStripe();
|
|
496
|
+
const params = {
|
|
497
|
+
mode: 'payment',
|
|
498
|
+
customer_email: email,
|
|
499
|
+
line_items: [{
|
|
500
|
+
quantity: 1,
|
|
501
|
+
price_data: {
|
|
502
|
+
currency: 'usd',
|
|
503
|
+
unit_amount: net,
|
|
504
|
+
product_data: { name: `${room.name} — ${human}` },
|
|
505
|
+
},
|
|
506
|
+
}],
|
|
507
|
+
payment_method_types: [...policy.paymentMethodTypes],
|
|
508
|
+
expires_at: sessionExpiresSec,
|
|
509
|
+
consent_collection: { terms_of_service: 'required' },
|
|
510
|
+
custom_text: { terms_of_service_acceptance: { message } },
|
|
511
|
+
metadata: {
|
|
512
|
+
booking_id: bookingId,
|
|
513
|
+
source: 'agent',
|
|
514
|
+
agent_id: agent.id,
|
|
515
|
+
terms_version: terms.version,
|
|
516
|
+
terms_sha256: terms.content_sha256,
|
|
517
|
+
},
|
|
518
|
+
success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
|
|
519
|
+
cancel_url: `${base}/meeting-rooms/${room.slug ?? ''}?canceled=1`,
|
|
520
|
+
};
|
|
521
|
+
const stripeKey = `agent:${agent.id}:${key}:${bookingId}`;
|
|
522
|
+
let session = null;
|
|
523
|
+
let definitive = false;
|
|
524
|
+
let lastErr = null;
|
|
525
|
+
for (let attempt = 0; attempt < 2 && !session; attempt++) {
|
|
526
|
+
try {
|
|
527
|
+
session = await createBookingCheckoutSession(stripe, params, chargePlan, stripeKey);
|
|
528
|
+
}
|
|
529
|
+
catch (e) {
|
|
530
|
+
lastErr = e;
|
|
531
|
+
if (isDefinitiveStripeError(e)) {
|
|
532
|
+
definitive = true;
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (!session) {
|
|
538
|
+
if (definitive) {
|
|
539
|
+
const expired = await admin.from('bookings').update({ status: 'expired' }).eq('id', bookingId).eq('status', 'pending');
|
|
540
|
+
if (expired?.error)
|
|
541
|
+
await failAmbiguous('stripe_rejected_row_stuck', bookingId);
|
|
542
|
+
else
|
|
543
|
+
await fail('stripe_rejected', bookingId);
|
|
544
|
+
try {
|
|
545
|
+
await logOps(admin, 'agent_booking_stripe_create_failed', { message: String(lastErr), booking_id: bookingId, agent_id: agent.id }, { severity: 'error', bookingId });
|
|
546
|
+
}
|
|
547
|
+
catch { /* ignore */ }
|
|
548
|
+
return result(502, { ok: false, error: 'payment_start_failed' });
|
|
549
|
+
}
|
|
550
|
+
await failAmbiguous('stripe_ambiguous', bookingId);
|
|
551
|
+
try {
|
|
552
|
+
await logOps(admin, 'agent_booking_stripe_ambiguous', { message: String(lastErr), booking_id: bookingId, agent_id: agent.id }, { severity: 'error', bookingId });
|
|
553
|
+
}
|
|
554
|
+
catch { /* ignore */ }
|
|
555
|
+
return result(502, { ok: false, error: 'payment_start_uncertain' });
|
|
556
|
+
}
|
|
557
|
+
// From here a live Checkout session exists. Never return or store its URL/id.
|
|
558
|
+
const sessionId = typeof session.id === 'string' ? session.id : '';
|
|
559
|
+
const checkoutUrl = typeof session.url === 'string' ? session.url : '';
|
|
560
|
+
if (!sessionId) {
|
|
561
|
+
await failAmbiguous('stripe_session_malformed', bookingId);
|
|
562
|
+
return result(502, { ok: false, error: 'payment_start_uncertain' });
|
|
563
|
+
}
|
|
564
|
+
const abandon = async (reason, error) => {
|
|
565
|
+
const r = await expireSessionAndRow({ admin, stripe, logOps, bookingId, sessionId, agentId: agent.id });
|
|
566
|
+
if (r.ok) {
|
|
567
|
+
await fail(reason, bookingId);
|
|
568
|
+
return result(502, { ok: false, error });
|
|
569
|
+
}
|
|
570
|
+
await failAmbiguous(`${reason}_void_failed`, bookingId);
|
|
571
|
+
try {
|
|
572
|
+
await logOps(admin, 'agent_booking_abandon_failed', { booking_id: bookingId, reason, void_error: r.error }, { severity: 'error', bookingId });
|
|
573
|
+
}
|
|
574
|
+
catch { /* ignore */ }
|
|
575
|
+
return result(502, { ok: false, error: 'payment_start_uncertain' });
|
|
576
|
+
};
|
|
577
|
+
const { error: sidErr } = await admin.from('bookings').update({ stripe_session_id: sessionId }).eq('id', bookingId);
|
|
578
|
+
if (sidErr)
|
|
579
|
+
return await abandon('session_id_write_failed', 'payment_start_failed');
|
|
580
|
+
if (!checkoutUrl)
|
|
581
|
+
return await abandon('session_url_missing', 'payment_start_failed');
|
|
582
|
+
let emailResult;
|
|
583
|
+
try {
|
|
584
|
+
emailResult = await (rt.sendLinkEmail ?? sendPaymentLinkEmail)(admin, {
|
|
585
|
+
email, name: input.contact.name, checkoutUrl, variant: 'agent_booking',
|
|
586
|
+
booking: { roomName: room.name, when: human, expiresAtIso },
|
|
587
|
+
}, rt.brand);
|
|
588
|
+
}
|
|
589
|
+
catch (_e) {
|
|
590
|
+
emailResult = 'failed_permanent';
|
|
591
|
+
}
|
|
592
|
+
if (emailResult !== 'sent')
|
|
593
|
+
return await abandon('link_email_failed', 'link_email_failed');
|
|
594
|
+
const response = { ok: true, booking_id: bookingId, link_sent_to: maskEmail(email), expires_at: expiresAtIso };
|
|
595
|
+
await safely(() => rt.claims.succeed({ agentId: agent.id, key, bookingId, response }), logOps, admin, 'agent_booking_claim_update_failed', bookingId);
|
|
596
|
+
try {
|
|
597
|
+
await logOps(admin, 'agent_booking_created', { booking_id: bookingId, room: room.name, agent_id: agent.id, tenant_id: agent.tenantId, amount_cents: net, reason: input.reason }, { severity: 'info', bookingId });
|
|
598
|
+
}
|
|
599
|
+
catch { /* ignore */ }
|
|
600
|
+
return result(200, response);
|
|
601
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const AGENT_HOLD_GRACE_SECONDS = 7200;
|
|
2
|
+
export declare const AGENT_POLICY: Readonly<{
|
|
3
|
+
readonly allowOffline: false;
|
|
4
|
+
readonly allowCredit: false;
|
|
5
|
+
readonly allowMembershipAttach: false;
|
|
6
|
+
readonly allowSkipDynamicDiscount: false;
|
|
7
|
+
readonly settlePaid: false;
|
|
8
|
+
readonly failClosedRateLimit: true;
|
|
9
|
+
readonly requireIdempotencyKey: true;
|
|
10
|
+
readonly minNetCents: 50;
|
|
11
|
+
readonly allowedTiers: readonly [1];
|
|
12
|
+
readonly refuseQuoteMode: true;
|
|
13
|
+
readonly refuseAgreementText: true;
|
|
14
|
+
readonly paymentMethodTypes: readonly ["card"];
|
|
15
|
+
readonly startWindow: Readonly<{
|
|
16
|
+
minLeadSeconds: number;
|
|
17
|
+
maxLeadSeconds: number;
|
|
18
|
+
maxSpanSeconds: number;
|
|
19
|
+
}>;
|
|
20
|
+
readonly perAgentCeiling: Readonly<{
|
|
21
|
+
bookings: 5;
|
|
22
|
+
listCents: 150000;
|
|
23
|
+
}>;
|
|
24
|
+
readonly perTenantCeiling: Readonly<{
|
|
25
|
+
bookings: 15;
|
|
26
|
+
listCents: 450000;
|
|
27
|
+
}>;
|
|
28
|
+
readonly hourlyLimit: 10;
|
|
29
|
+
}>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export const AGENT_HOLD_GRACE_SECONDS = 7200;
|
|
2
|
+
export const AGENT_POLICY = Object.freeze({
|
|
3
|
+
allowOffline: false,
|
|
4
|
+
allowCredit: false,
|
|
5
|
+
allowMembershipAttach: false,
|
|
6
|
+
allowSkipDynamicDiscount: false,
|
|
7
|
+
settlePaid: false,
|
|
8
|
+
failClosedRateLimit: true,
|
|
9
|
+
requireIdempotencyKey: true,
|
|
10
|
+
minNetCents: 50,
|
|
11
|
+
allowedTiers: Object.freeze([1]),
|
|
12
|
+
refuseQuoteMode: true,
|
|
13
|
+
refuseAgreementText: true,
|
|
14
|
+
paymentMethodTypes: Object.freeze(['card']),
|
|
15
|
+
startWindow: Object.freeze({
|
|
16
|
+
minLeadSeconds: 60 * 60,
|
|
17
|
+
maxLeadSeconds: 90 * 24 * 60 * 60,
|
|
18
|
+
maxSpanSeconds: 24 * 60 * 60,
|
|
19
|
+
}),
|
|
20
|
+
perAgentCeiling: Object.freeze({ bookings: 5, listCents: 150000 }),
|
|
21
|
+
perTenantCeiling: Object.freeze({ bookings: 15, listCents: 450000 }),
|
|
22
|
+
hourlyLimit: 10,
|
|
23
|
+
});
|
|
@@ -39,7 +39,8 @@ type SessionCreator = {
|
|
|
39
39
|
checkout: {
|
|
40
40
|
sessions: {
|
|
41
41
|
create: (params: Stripe.Checkout.SessionCreateParams, options?: {
|
|
42
|
-
stripeAccount
|
|
42
|
+
stripeAccount?: string;
|
|
43
|
+
idempotencyKey?: string;
|
|
43
44
|
}) => Promise<Stripe.Checkout.Session>;
|
|
44
45
|
};
|
|
45
46
|
};
|
|
@@ -52,6 +53,8 @@ type SessionCreator = {
|
|
|
52
53
|
* relies on. Connect sessions additionally go to the connected account with
|
|
53
54
|
* the application fee.
|
|
54
55
|
*/
|
|
55
|
-
export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan
|
|
56
|
+
export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan,
|
|
57
|
+
/** Optional Stripe idempotency key. Omitted (every human caller) => request is unchanged. */
|
|
58
|
+
idempotencyKey?: string): Promise<Stripe.Checkout.Session>;
|
|
56
59
|
export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
|
|
57
60
|
export {};
|