@simplelayer/graniteer-core 0.3.27 → 0.3.29

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.
@@ -65,13 +65,17 @@ export function stripeAccountRequestOptions(accountId) {
65
65
  * relies on. Connect sessions additionally go to the connected account with
66
66
  * the application fee.
67
67
  */
68
- export function createBookingCheckoutSession(stripe, params, plan) {
68
+ export function createBookingCheckoutSession(stripe, params, plan,
69
+ /** Optional Stripe idempotency key. Omitted (every human caller) => request is unchanged. */
70
+ idempotencyKey) {
69
71
  if ('error' in plan) {
70
72
  return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
71
73
  }
72
74
  if (!plan.connected) {
73
- return stripe.checkout.sessions.create({ ...params, payment_method_types: ['card'] });
75
+ return idempotencyKey
76
+ ? stripe.checkout.sessions.create({ ...params, payment_method_types: ['card'] }, { idempotencyKey })
77
+ : stripe.checkout.sessions.create({ ...params, payment_method_types: ['card'] });
74
78
  }
75
- return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, { stripeAccount: plan.accountId });
79
+ return stripe.checkout.sessions.create({ ...applyConnectToSessionParams(params, plan), payment_method_types: ['card'] }, idempotencyKey ? { stripeAccount: plan.accountId, idempotencyKey } : { stripeAccount: plan.accountId });
76
80
  }
77
81
  export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
@@ -0,0 +1,84 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ import { createBookingCheckoutSession } from './connectBookingCharge.js';
3
+ import type { NoticeConfig } from './businessHours.js';
4
+ import { type AgentRuntime } from './agentBooking.js';
5
+ type SupabaseLike = SupabaseClient<any, any, any>;
6
+ export interface BookingPolicy {
7
+ readonly allowOffline?: boolean;
8
+ readonly allowCredit?: boolean;
9
+ readonly allowMembershipAttach?: boolean;
10
+ readonly allowSkipDynamicDiscount?: boolean;
11
+ readonly settlePaid?: boolean;
12
+ readonly failClosedRateLimit?: boolean;
13
+ readonly requireIdempotencyKey?: boolean;
14
+ readonly minNetCents?: number;
15
+ readonly allowedTiers?: 'any' | readonly number[];
16
+ readonly refuseQuoteMode?: boolean;
17
+ readonly refuseAgreementText?: boolean;
18
+ readonly paymentMethodTypes?: readonly string[];
19
+ readonly startWindow?: {
20
+ readonly minLeadSeconds: number;
21
+ readonly maxLeadSeconds: number;
22
+ readonly maxSpanSeconds: number;
23
+ };
24
+ readonly perAgentCeiling?: {
25
+ readonly bookings: number;
26
+ readonly listCents: number;
27
+ };
28
+ readonly perTenantCeiling?: {
29
+ readonly bookings: number;
30
+ readonly listCents: number;
31
+ };
32
+ readonly hourlyLimit?: number;
33
+ }
34
+ export interface CreateBookingOperator extends NoticeConfig {
35
+ domain: string;
36
+ googleCalendarWriteback?: boolean | null;
37
+ stripeConnectedAccountId?: string | null;
38
+ stripeApplicationFeePercent?: number | null;
39
+ }
40
+ export interface CreateBookingInput {
41
+ room_id: string;
42
+ start?: string;
43
+ end?: string;
44
+ date?: string;
45
+ day_mode?: 'full' | 'half_am' | 'half_pm';
46
+ contact: {
47
+ name: string;
48
+ email: string;
49
+ phone?: string;
50
+ };
51
+ mode: 'payment_link' | 'offline';
52
+ skip_dynamic_discount?: boolean;
53
+ membership_id?: string;
54
+ membershipId?: string;
55
+ }
56
+ export type BookingStripe = Parameters<typeof createBookingCheckoutSession>[0];
57
+ export type BookingLogOps = (admin: SupabaseLike, kind: string, detail?: Record<string, unknown>, opts?: {
58
+ severity?: 'info' | 'warning' | 'error';
59
+ bookingId?: string | null;
60
+ dedupeKey?: string | null;
61
+ }) => Promise<unknown>;
62
+ export interface PaidEffects {
63
+ runPaidSideEffects: (bookingId: string) => Promise<void>;
64
+ }
65
+ export interface CreateBookingCoreArgs {
66
+ admin: SupabaseLike;
67
+ operator: CreateBookingOperator;
68
+ stripeFactory: () => (() => BookingStripe) | null;
69
+ logOps: BookingLogOps;
70
+ input: CreateBookingInput;
71
+ policy: BookingPolicy;
72
+ base: string;
73
+ actor: string;
74
+ paidEffects?: PaidEffects;
75
+ /** Agent flow only (policy.requireIdempotencyKey === true). Never set by the human handler. */
76
+ agentRuntime?: AgentRuntime;
77
+ }
78
+ export interface CreateBookingResult {
79
+ ok: boolean;
80
+ status: number;
81
+ body: Record<string, unknown>;
82
+ }
83
+ export declare function createBookingCore(args: CreateBookingCoreArgs): Promise<CreateBookingResult>;
84
+ export {};
@@ -0,0 +1,334 @@
1
+ import { reclaimStaleHoldsExceptCompletedTier3 } from './bookingHoldReclaim.js';
2
+ import { validateAndPriceForRoom, formatHumanTime } from './pricing.js';
3
+ import { resolveIsMember, computeEntitlement } from './membership.js';
4
+ import { buildAdminCheckoutSessionParams, consumeMemberCredit, holdMemberCredit, loadMembershipById, releaseMemberCredit, resolveRoomContractTier, splitCharge, } from './adminBookingCredit.js';
5
+ import { createBookingCheckoutSession, planBookingCharge } from './connectBookingCharge.js';
6
+ import { runAgentBooking } from './agentBooking.js';
7
+ const result = (status, body) => ({ ok: status >= 200 && status < 300, status, body });
8
+ export async function createBookingCore(args) {
9
+ // Agent mode is selected ONLY by the policy (never by input) and runs a
10
+ // separate flow that cannot reach paid settlement, credit or side effects.
11
+ if (args.policy.requireIdempotencyKey === true)
12
+ return await runAgentBooking(args);
13
+ // Fields only the agent flow implements: refuse rather than silently ignore.
14
+ if (args.policy.failClosedRateLimit === true || (args.policy.minNetCents ?? 0) !== 0 ||
15
+ (args.policy.allowedTiers ?? 'any') !== 'any' || args.policy.refuseQuoteMode === true ||
16
+ args.policy.refuseAgreementText === true) {
17
+ return result(500, { ok: false, error: 'policy_not_supported' });
18
+ }
19
+ const { admin, operator, stripeFactory, logOps, input, policy, base, actor, paidEffects } = args;
20
+ const { room_id, contact, mode } = input;
21
+ const callerEmail = actor;
22
+ const skip_dynamic_discount = policy.allowSkipDynamicDiscount === true && input.skip_dynamic_discount === true;
23
+ const requestedMembershipId = input.membership_id ?? input.membershipId ?? null;
24
+ if (mode === 'offline') {
25
+ if (policy.allowOffline !== true)
26
+ return result(400, { ok: false, error: 'offline_not_allowed' });
27
+ // An offline booking is inserted as status 'paid': it needs settlePaid too.
28
+ if (policy.settlePaid !== true)
29
+ return result(400, { ok: false, error: 'settle_paid_not_allowed' });
30
+ if (!paidEffects)
31
+ return result(500, { ok: false, error: 'paid_effects_unavailable' });
32
+ }
33
+ if (requestedMembershipId) {
34
+ if (policy.allowMembershipAttach !== true)
35
+ return result(400, { ok: false, error: 'membership_not_allowed' });
36
+ if (policy.allowCredit !== true)
37
+ return result(400, { ok: false, error: 'credit_not_allowed' });
38
+ if (policy.settlePaid !== true)
39
+ return result(400, { ok: false, error: 'settle_paid_not_allowed' });
40
+ if (!paidEffects)
41
+ return result(500, { ok: false, error: 'paid_effects_unavailable' });
42
+ }
43
+ // === Room + price (server-authoritative) ===
44
+ const { data: room, error: rErr } = await admin
45
+ .from('rooms')
46
+ .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')
47
+ .eq('id', room_id)
48
+ .eq('active', true)
49
+ .maybeSingle();
50
+ if (rErr)
51
+ return result(500, { ok: false, error: 'load_room_failed', detail: rErr.message });
52
+ if (!room)
53
+ return result(404, { ok: false, error: 'room_not_found' });
54
+ // === Optional member attachment ===
55
+ const membershipId = requestedMembershipId;
56
+ let membership = null;
57
+ if (membershipId) {
58
+ try {
59
+ membership = await loadMembershipById(admin, membershipId);
60
+ }
61
+ catch (e) {
62
+ return result(500, { ok: false, error: 'membership_lookup_failed', detail: String(e) });
63
+ }
64
+ if (!membership)
65
+ return result(404, { ok: false, error: 'membership_not_found' });
66
+ }
67
+ // Server-authoritative membership lookup on the CUSTOMER's email (not the admin's).
68
+ const custEmailKey = contact.email.toLowerCase();
69
+ const emailIsMember = await resolveIsMember(admin, custEmailKey);
70
+ const isMember = emailIsMember || (membership ? computeEntitlement(membership) : false);
71
+ const priced = await validateAndPriceForRoom(admin, room, input, Date.now(), {
72
+ isMember,
73
+ allowDynamic: !skip_dynamic_discount,
74
+ });
75
+ if (!priced.ok)
76
+ return result(priced.status, { ok: false, error: priced.error });
77
+ const { startUtc, endUtc, price_cents, rangeLiteral, dynamic_discount_cents, dynamic_discount_rule_type, list_rule_type, } = priced;
78
+ const net = Math.max(0, price_cents - dynamic_discount_cents);
79
+ // Reclaim stale holds overlapping the range (same as create-booking).
80
+ await reclaimStaleHoldsExceptCompletedTier3(admin, room_id, rangeLiteral);
81
+ // Contract tier lookup: needed both for member-credit eligibility (Tier 3
82
+ // rooms never draw member credit - they always go through the Commons
83
+ // contract/deposit flow) and, new here, for the contract-skip audit trail
84
+ // below. Root cause + rationale: claude/admin-create-booking-agreement-gap-scope.md
85
+ // (this function never runs create-booking.js's tiered agreement gate or
86
+ // the audited admin-skip-commons-contract path - every booking it settles
87
+ // to 'paid' does so with no agreement, previously with no audit trail
88
+ // either).
89
+ let contractTier = null;
90
+ try {
91
+ contractTier = await resolveRoomContractTier(admin, room_id);
92
+ }
93
+ catch (e) {
94
+ console.warn('[admin-create-booking] contract tier lookup failed', String(e));
95
+ try {
96
+ await logOps(admin, 'admin_create_booking_tier_lookup_failed', { message: String(e), room_id }, { severity: 'warning' });
97
+ }
98
+ catch { /* ignore */ }
99
+ }
100
+ let creditEligible = false;
101
+ if (membership) {
102
+ creditEligible = room.booking_mode !== 'quote' && contractTier !== null && contractTier !== 3;
103
+ }
104
+ const useCredit = !!membership && creditEligible;
105
+ const nowIso = new Date().toISOString();
106
+ const isOffline = mode === 'offline';
107
+ // Audit-only contract-skip marking (landed 2026-09-18, see scope doc
108
+ // above): every booking this function settles straight to 'paid' bypasses
109
+ // the tiered agreement gate self-serve bookings go through. This does NOT
110
+ // block or gate the booking - it only makes the skip self-documenting via
111
+ // the same contract_skipped_* columns admin-skip-commons-contract uses for
112
+ // an explicit staff skip. NOTE: private.on_booking_paid_transition() still
113
+ // fires and still inserts its own booking_contract_violations row on this
114
+ // same write -- this stamp is in ADDITION to that row, not a replacement
115
+ // for it; the violations table keeps growing exactly as before.
116
+ const CONTRACT_SKIP_REASON = `admin-create-booking: no agreement flow in this function (tier ${contractTier ?? 'unmapped'}; ` +
117
+ 'known gap, audit-only fix landed 2026-09-18 - see admin-create-booking-agreement-gap-scope.md)';
118
+ const contractSkipFields = {
119
+ contract_skipped_at: nowIso,
120
+ contract_skipped_by_email: callerEmail,
121
+ contract_skip_reason: CONTRACT_SKIP_REASON,
122
+ };
123
+ const insertRow = {
124
+ room_id,
125
+ during: rangeLiteral,
126
+ list_amount_cents: price_cents,
127
+ dynamic_discount_cents,
128
+ dynamic_discount_rule_type,
129
+ list_rule_type,
130
+ contact_email: contact.email,
131
+ contact_name: contact.name,
132
+ contact_phone: contact.phone ?? null,
133
+ is_member: isMember,
134
+ policy_accepted_at: nowIso,
135
+ created_by: callerEmail,
136
+ };
137
+ if (useCredit) {
138
+ insertRow.status = 'pending';
139
+ insertRow.payment_source = isOffline ? 'offline' : 'stripe';
140
+ insertRow.hold_expires_at = new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString();
141
+ }
142
+ else if (isOffline) {
143
+ insertRow.status = 'paid';
144
+ insertRow.payment_source = 'offline';
145
+ insertRow.charged_amount_cents = net;
146
+ insertRow.credit_applied_cents = 0;
147
+ insertRow.hold_expires_at = null;
148
+ Object.assign(insertRow, contractSkipFields);
149
+ }
150
+ else {
151
+ insertRow.status = 'pending';
152
+ insertRow.payment_source = 'stripe';
153
+ insertRow.hold_expires_at = new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString();
154
+ }
155
+ const { data: inserted, error: iErr } = await admin
156
+ .from('bookings')
157
+ .insert(insertRow)
158
+ .select('id')
159
+ .single();
160
+ if (iErr) {
161
+ // deno-lint-ignore no-explicit-any
162
+ const code = iErr.code;
163
+ if (code === '23P01')
164
+ return result(409, { ok: false, error: 'slot_taken' });
165
+ return result(500, { ok: false, error: 'insert_failed', detail: iErr.message });
166
+ }
167
+ const booking_id = inserted.id;
168
+ const human = formatHumanTime(startUtc, endUtc);
169
+ // === Member credit (member-attached bookings only) ===
170
+ let credit_applied = 0;
171
+ let discount_applied = 0;
172
+ let charged = net;
173
+ if (useCredit && membership) {
174
+ credit_applied = await holdMemberCredit(admin, {
175
+ membershipId: membership.id,
176
+ bookingId: booking_id,
177
+ net,
178
+ });
179
+ const split = splitCharge(net, credit_applied);
180
+ charged = split.charged;
181
+ discount_applied = split.discount_applied;
182
+ }
183
+ const creditSummary = membership
184
+ ? {
185
+ membership_id: membership.id,
186
+ credit_applied_cents: credit_applied,
187
+ discount_applied_cents: discount_applied,
188
+ charged_amount_cents: charged,
189
+ }
190
+ : {};
191
+ // Post-paid side effects (door provisioning, GHL, calendar) are injected via
192
+ // `paidEffects` and never run by the core itself.
193
+ const runPaidSideEffects = async () => {
194
+ await paidEffects.runPaidSideEffects(booking_id);
195
+ };
196
+ // Finalizes a booking that needs no Stripe payment: consume the held credit,
197
+ // flip the row to paid, then run the paid side effects.
198
+ const settleAsPaid = async (paymentSource) => {
199
+ if (credit_applied > 0) {
200
+ const consumeErr = await consumeMemberCredit(admin, booking_id);
201
+ if (consumeErr) {
202
+ console.error('[admin-create-booking] credit_consume failed', consumeErr);
203
+ try {
204
+ await logOps(admin, 'credit_consume_failed', { message: consumeErr }, { severity: 'error', bookingId: booking_id });
205
+ }
206
+ catch { /* ignore */ }
207
+ }
208
+ }
209
+ await admin
210
+ .from('bookings')
211
+ .update({
212
+ status: 'paid',
213
+ payment_source: paymentSource,
214
+ charged_amount_cents: charged,
215
+ credit_applied_cents: credit_applied,
216
+ discount_applied_cents: discount_applied,
217
+ hold_expires_at: null,
218
+ ...contractSkipFields,
219
+ })
220
+ .eq('id', booking_id);
221
+ await runPaidSideEffects();
222
+ };
223
+ // Abandon path: give the member their balance back.
224
+ const releaseHeldCredit = async (reason) => {
225
+ if (credit_applied <= 0)
226
+ return;
227
+ const relErr = await releaseMemberCredit(admin, booking_id, reason);
228
+ if (relErr) {
229
+ try {
230
+ await logOps(admin, 'credit_release_failed', { message: relErr }, { severity: 'error', bookingId: booking_id });
231
+ }
232
+ catch { /* ignore */ }
233
+ }
234
+ };
235
+ if (isOffline) {
236
+ if (useCredit) {
237
+ await settleAsPaid('offline');
238
+ }
239
+ else {
240
+ await runPaidSideEffects();
241
+ }
242
+ try {
243
+ await logOps(admin, 'admin_offline_booking_created', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
244
+ ...(membership ? { membership_id: membership.id, credit_applied_cents: credit_applied } : {}) }, { severity: 'info', bookingId: booking_id });
245
+ }
246
+ catch { /* ignore */ }
247
+ return result(200, {
248
+ ok: true,
249
+ mode: 'offline',
250
+ booking_id,
251
+ amount_cents: net,
252
+ when: human,
253
+ ...creditSummary,
254
+ });
255
+ }
256
+ if (useCredit && charged === 0) {
257
+ await settleAsPaid('stripe');
258
+ try {
259
+ await logOps(admin, 'admin_booking_credit_covered', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
260
+ membership_id: membership?.id, credit_applied_cents: credit_applied }, { severity: 'info', bookingId: booking_id });
261
+ }
262
+ catch { /* ignore */ }
263
+ return result(200, {
264
+ ok: true,
265
+ mode: 'payment_link',
266
+ fully_covered: true,
267
+ booking_id,
268
+ amount_cents: net,
269
+ when: human,
270
+ ...creditSummary,
271
+ });
272
+ }
273
+ if (useCredit && (credit_applied > 0 || discount_applied > 0)) {
274
+ await admin
275
+ .from('bookings')
276
+ .update({
277
+ credit_applied_cents: credit_applied,
278
+ discount_applied_cents: discount_applied,
279
+ })
280
+ .eq('id', booking_id);
281
+ }
282
+ const buildStripe = stripeFactory();
283
+ if (!buildStripe) {
284
+ await releaseHeldCredit('payments_not_configured');
285
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
286
+ return result(500, { ok: false, error: 'stripe_not_configured' });
287
+ }
288
+ const chargePlan = planBookingCharge(operator, charged);
289
+ if ('error' in chargePlan) {
290
+ await releaseHeldCredit('payments_misconfigured');
291
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
292
+ try {
293
+ await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'admin-create-booking', booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
294
+ }
295
+ catch { /* ignore */ }
296
+ return result(500, { ok: false, error: 'payments_misconfigured' });
297
+ }
298
+ const stripe = buildStripe();
299
+ try {
300
+ const session = await createBookingCheckoutSession(stripe, buildAdminCheckoutSessionParams({
301
+ roomName: room.name,
302
+ roomSlug: room.slug ?? null,
303
+ human,
304
+ customerEmail: contact.email,
305
+ bookingId: booking_id,
306
+ amountCents: charged,
307
+ base,
308
+ }), chargePlan);
309
+ await admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', booking_id);
310
+ try {
311
+ await logOps(admin, 'admin_payment_link_created', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
312
+ ...(membership ? { membership_id: membership.id, credit_applied_cents: credit_applied, charged_amount_cents: charged } : {}) }, { severity: 'info', bookingId: booking_id });
313
+ }
314
+ catch { /* ignore */ }
315
+ return result(200, {
316
+ ok: true,
317
+ mode: 'payment_link',
318
+ booking_id,
319
+ amount_cents: net,
320
+ url: session.url,
321
+ when: human,
322
+ ...creditSummary,
323
+ });
324
+ }
325
+ catch (e) {
326
+ await releaseHeldCredit('stripe_create_failed');
327
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
328
+ try {
329
+ await logOps(admin, 'admin_stripe_create_failed', { message: String(e), booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
330
+ }
331
+ catch { /* ignore */ }
332
+ return result(502, { ok: false, error: 'payment_start_failed' });
333
+ }
334
+ }