@simplelayer/graniteer-core 0.3.16 → 0.3.18
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/bookingSource.d.ts +2 -0
- package/dist/bookingSource.js +11 -0
- package/dist/businessHours.d.ts +11 -0
- package/dist/businessHours.js +55 -0
- package/dist/connectBookingCharge.d.ts +49 -0
- package/dist/connectBookingCharge.js +68 -0
- package/dist/functions/admin-create-booking.d.ts +3 -0
- package/dist/functions/admin-create-booking.js +15 -2
- package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
- package/dist/functions/admin-mark-booking-paid.js +27 -3
- package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
- package/dist/functions/booking-access-revoke-backstop.js +121 -0
- package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
- package/dist/functions/booking-access-revoke-door-state.js +61 -0
- package/dist/functions/booking-access-revoke.d.ts +35 -0
- package/dist/functions/booking-access-revoke.js +279 -0
- package/dist/functions/booking-availability.d.ts +2 -1
- package/dist/functions/booking-availability.js +14 -5
- package/dist/functions/create-booking.d.ts +5 -0
- package/dist/functions/create-booking.js +22 -4
- package/dist/functions/manage-booking.d.ts +6 -0
- package/dist/functions/manage-booking.js +29 -12
- package/dist/functions/reschedule-booking.d.ts +5 -0
- package/dist/functions/reschedule-booking.js +28 -2
- package/dist/functions/space-availability-range.d.ts +2 -1
- package/dist/functions/space-availability-range.js +8 -1
- package/dist/functions/stripe-webhook.d.ts +4 -0
- package/dist/functions/stripe-webhook.js +168 -2
- package/dist/functions/sync-gcal-blackouts.js +1 -1
- package/dist/gcalBookingEvents.d.ts +59 -0
- package/dist/gcalBookingEvents.js +182 -0
- package/dist/gcalSync.d.ts +1 -0
- package/dist/gcalSync.js +5 -0
- package/dist/pricing.d.ts +10 -2
- package/dist/pricing.js +14 -9
- package/dist/stripeConnectEvents.d.ts +11 -0
- package/dist/stripeConnectEvents.js +37 -0
- package/dist/tenant-config.d.ts +8 -0
- package/dist/tenant-config.js +24 -0
- package/package.json +26 -2
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Best-effort revoke of a booking's organizer door grants via the tenant
|
|
2
|
+
// middleware's signed /admin/event-access/revoke path (same e1 HMAC contract
|
|
3
|
+
// as event-access-admin.ts). Never throws; failures are ops-logged only.
|
|
4
|
+
import { logOps } from '../ops.js';
|
|
5
|
+
import { sha256Hex, signBusMessage } from '../busSignature.js';
|
|
6
|
+
import { getEventAccessBusBase } from '../tenant-config.js';
|
|
7
|
+
import { doorReadForOpsLog, isDoorStateCompleteForGrantRevoke, } from './booking-access-revoke-door-state.js';
|
|
8
|
+
/** @deprecated Granite City's literal default, kept for import compatibility.
|
|
9
|
+
* The actual default is resolved at call time from tenant-config.ts's
|
|
10
|
+
* getEventAccessBusBase(), which reads the EVENT_ACCESS_BUS_BASE env var. */
|
|
11
|
+
export const DEFAULT_EVENT_ACCESS_BUS_BASE = 'https://ftw.granitecity.io';
|
|
12
|
+
/** C6 code-side: revoke calls must stay at or below 8s. */
|
|
13
|
+
export const REVOKE_TIMEOUT_MS = 8_000;
|
|
14
|
+
const MAX_GRANTS_PER_BATCH = 5;
|
|
15
|
+
/** Hardening: cap in-process sweep batches (20 × 5 grants max per edge invocation). */
|
|
16
|
+
export const MAX_REVOKE_SWEEP_BATCHES = 20;
|
|
17
|
+
const REVOCABLE_STATUSES = ['active', 'pending', 'reconciling', 'revoke_failed'];
|
|
18
|
+
const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
|
|
19
|
+
export const BOOKING_GRANT_REVOKE_ENABLED_ENV = 'BOOKING_GRANT_REVOKE_ENABLED';
|
|
20
|
+
/** Tests only: next revoke call throws (W1 marker-failed + revoke throw path). */
|
|
21
|
+
let forceRevokeThrowForTest = false;
|
|
22
|
+
export function setForceRevokeThrowForTest(enabled) {
|
|
23
|
+
forceRevokeThrowForTest = enabled;
|
|
24
|
+
}
|
|
25
|
+
/** Fail-closed: only the exact string 'true' arms revoke work. */
|
|
26
|
+
export function isBookingGrantRevokeEnabled() {
|
|
27
|
+
return Deno.env.get(BOOKING_GRANT_REVOKE_ENABLED_ENV) === 'true';
|
|
28
|
+
}
|
|
29
|
+
export function errorNameFromUnknown(e) {
|
|
30
|
+
if (e instanceof Error && e.name)
|
|
31
|
+
return e.name;
|
|
32
|
+
return 'Error';
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* CS-GM product decision (O3b / PR #21): partial refunds must NOT revoke organizer door access.
|
|
36
|
+
* The guest keeps a valid paid booking; grants remain until the booking window ends.
|
|
37
|
+
*
|
|
38
|
+
* Stripe emits `charge.refunded` on every refund leg, but `charge.refunded` is only `true` once
|
|
39
|
+
* the charge is fully refunded — that is the sole gate for organizer grant revoke on refund.
|
|
40
|
+
*/
|
|
41
|
+
export function shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge) {
|
|
42
|
+
return charge.refunded === true;
|
|
43
|
+
}
|
|
44
|
+
function parseMiddlewareBody(text) {
|
|
45
|
+
if (!text)
|
|
46
|
+
return null;
|
|
47
|
+
try {
|
|
48
|
+
const parsed = JSON.parse(text);
|
|
49
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function middlewareErrorCode(parsed) {
|
|
56
|
+
const err = parsed?.error;
|
|
57
|
+
if (typeof err !== 'string' || !SAFE_ERROR_CODE.test(err))
|
|
58
|
+
return undefined;
|
|
59
|
+
return err;
|
|
60
|
+
}
|
|
61
|
+
function opsDoorReadDetail(parsed) {
|
|
62
|
+
const doorRead = doorReadForOpsLog(parsed?.door_read);
|
|
63
|
+
return doorRead ? { door_read: doorRead } : {};
|
|
64
|
+
}
|
|
65
|
+
async function signRevokeE1(secret, verb, ts, bodyHashHex) {
|
|
66
|
+
const msg = ['e1', verb, ts, bodyHashHex].join('\n');
|
|
67
|
+
return signBusMessage(msg, secret);
|
|
68
|
+
}
|
|
69
|
+
async function postRevoke(admin, opts) {
|
|
70
|
+
const outbound = { acting_user_id: opts.actingUserId, grant_id: opts.grantId };
|
|
71
|
+
const rawBody = JSON.stringify(outbound);
|
|
72
|
+
const bodyHash = await sha256Hex(rawBody);
|
|
73
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
74
|
+
const signature = await signRevokeE1(opts.secret, 'revoke', ts, bodyHash);
|
|
75
|
+
let res;
|
|
76
|
+
try {
|
|
77
|
+
res = await fetch(`${opts.busBase}/admin/event-access/revoke`, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: {
|
|
80
|
+
'Content-Type': 'application/json',
|
|
81
|
+
'X-Event-Access-Signature': signature,
|
|
82
|
+
'X-Event-Access-Timestamp': ts,
|
|
83
|
+
},
|
|
84
|
+
body: rawBody,
|
|
85
|
+
signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
await logOps(admin, 'booking_access_revoke_call_error', {
|
|
90
|
+
reason: opts.reason,
|
|
91
|
+
grant_id: opts.grantId,
|
|
92
|
+
error_name: errorNameFromUnknown(e),
|
|
93
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const text = await res.text();
|
|
97
|
+
const parsed = parseMiddlewareBody(text);
|
|
98
|
+
if (res.ok) {
|
|
99
|
+
// C5 (flag-on): waits on O3(a) middleware — HTTP 200 must satisfy the C6 ruling read.
|
|
100
|
+
if (!isDoorStateCompleteForGrantRevoke(parsed)) {
|
|
101
|
+
await logOps(admin, 'booking_access_revoke_door_not_secured', {
|
|
102
|
+
reason: opts.reason,
|
|
103
|
+
grant_id: opts.grantId,
|
|
104
|
+
status: res.status,
|
|
105
|
+
...opsDoorReadDetail(parsed),
|
|
106
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const errCode = middlewareErrorCode(parsed);
|
|
111
|
+
if (errCode === 'grant_not_found') {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (errCode === 'grant_not_revocable' || errCode === 'grant_already_revoked' || errCode === 'already_revoked') {
|
|
115
|
+
if (isDoorStateCompleteForGrantRevoke(parsed)) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
// R1: not-revocable without a secured door is an error, not a warning.
|
|
119
|
+
await logOps(admin, 'booking_access_revoke_not_revocable', {
|
|
120
|
+
reason: opts.reason,
|
|
121
|
+
grant_id: opts.grantId,
|
|
122
|
+
status: res.status,
|
|
123
|
+
error_code: errCode,
|
|
124
|
+
...opsDoorReadDetail(parsed),
|
|
125
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const detail = {
|
|
129
|
+
reason: opts.reason,
|
|
130
|
+
grant_id: opts.grantId,
|
|
131
|
+
status: res.status,
|
|
132
|
+
};
|
|
133
|
+
if (errCode)
|
|
134
|
+
detail.error_code = errCode;
|
|
135
|
+
await logOps(admin, 'booking_access_revoke_call_failed', detail, { severity: 'error', bookingId: opts.bookingId });
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Revoke every active or upcoming organizer access grant for `bookingId`.
|
|
139
|
+
* Safe to call multiple times (cancel replay, Stripe redelivery after revoke).
|
|
140
|
+
*/
|
|
141
|
+
export async function revokeBookingOrganizerAccessGrants(admin, opts) {
|
|
142
|
+
if (!isBookingGrantRevokeEnabled()) {
|
|
143
|
+
await logOps(admin, 'booking_access_revoke_skipped_disabled', {
|
|
144
|
+
reason: opts.reason,
|
|
145
|
+
}, { severity: 'info', bookingId: opts.bookingId });
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (forceRevokeThrowForTest) {
|
|
149
|
+
forceRevokeThrowForTest = false;
|
|
150
|
+
throw new Error('forced revoke throw for test');
|
|
151
|
+
}
|
|
152
|
+
const busBase = opts.busBase ?? getEventAccessBusBase();
|
|
153
|
+
const triedGrantIds = new Set();
|
|
154
|
+
try {
|
|
155
|
+
const listRevocable = async () => {
|
|
156
|
+
const { data: grants, error: listErr } = await admin
|
|
157
|
+
.from('booking_access_grants')
|
|
158
|
+
.select('id,status,access_end')
|
|
159
|
+
.eq('booking_id', opts.bookingId)
|
|
160
|
+
.in('status', [...REVOCABLE_STATUSES]);
|
|
161
|
+
if (listErr) {
|
|
162
|
+
const code = listErr.code;
|
|
163
|
+
await logOps(admin, 'booking_access_revoke_lookup_failed', {
|
|
164
|
+
reason: opts.reason,
|
|
165
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
166
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const rows = (grants ?? []);
|
|
170
|
+
// Hardening: stable ordering before batching.
|
|
171
|
+
return rows.filter((row) => row.id).sort((a, b) => a.id.localeCompare(b.id));
|
|
172
|
+
};
|
|
173
|
+
const clearAccessRevokeMarkerIfDone = async (knownNoRevocableGrants = false) => {
|
|
174
|
+
if (!knownNoRevocableGrants) {
|
|
175
|
+
const remaining = await listRevocable();
|
|
176
|
+
if (remaining === null || remaining.length > 0)
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
await admin.from('bookings')
|
|
180
|
+
.update({ access_revoke_required_at: null })
|
|
181
|
+
.eq('id', opts.bookingId)
|
|
182
|
+
.not('access_revoke_required_at', 'is', null);
|
|
183
|
+
};
|
|
184
|
+
const initial = await listRevocable();
|
|
185
|
+
if (initial === null)
|
|
186
|
+
return;
|
|
187
|
+
if (initial.length === 0) {
|
|
188
|
+
await clearAccessRevokeMarkerIfDone(true);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (initial.length > MAX_GRANTS_PER_BATCH) {
|
|
192
|
+
await logOps(admin, 'booking_access_revoke_truncated', {
|
|
193
|
+
reason: opts.reason,
|
|
194
|
+
count: initial.length,
|
|
195
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
196
|
+
}
|
|
197
|
+
const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
|
|
198
|
+
const secret = typeof secretRaw === 'string' ? secretRaw : null;
|
|
199
|
+
if (secretErr || !secret) {
|
|
200
|
+
await logOps(admin, 'booking_access_revoke_secret_missing', {
|
|
201
|
+
reason: opts.reason,
|
|
202
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
// C6 code-side: Promise.allSettled batches (≤5) until done, stalled, or hardening cap.
|
|
206
|
+
let batches = 0;
|
|
207
|
+
let truncatedSweepLogged = false;
|
|
208
|
+
while (batches < MAX_REVOKE_SWEEP_BATCHES) {
|
|
209
|
+
const rows = batches === 0 ? initial : await listRevocable();
|
|
210
|
+
if (rows === null)
|
|
211
|
+
return;
|
|
212
|
+
if (rows.length === 0) {
|
|
213
|
+
await clearAccessRevokeMarkerIfDone(true);
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
const pending = rows.filter((row) => !triedGrantIds.has(row.id));
|
|
217
|
+
if (pending.length === 0) {
|
|
218
|
+
await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
|
|
219
|
+
reason: opts.reason,
|
|
220
|
+
grant_ids: rows.map((r) => r.id),
|
|
221
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
if (batches > 0 && rows.length > MAX_GRANTS_PER_BATCH && !truncatedSweepLogged) {
|
|
225
|
+
await logOps(admin, 'booking_access_revoke_sweep_continued', {
|
|
226
|
+
reason: opts.reason,
|
|
227
|
+
count: rows.length,
|
|
228
|
+
batch: batches + 1,
|
|
229
|
+
}, { severity: 'info', bookingId: opts.bookingId });
|
|
230
|
+
truncatedSweepLogged = true;
|
|
231
|
+
}
|
|
232
|
+
const idsBefore = new Set(rows.map((r) => r.id));
|
|
233
|
+
const targets = pending.slice(0, MAX_GRANTS_PER_BATCH);
|
|
234
|
+
for (const row of targets)
|
|
235
|
+
triedGrantIds.add(row.id);
|
|
236
|
+
await Promise.allSettled(targets.map((row) => postRevoke(admin, {
|
|
237
|
+
busBase,
|
|
238
|
+
secret,
|
|
239
|
+
actingUserId: opts.actingUserId,
|
|
240
|
+
grantId: row.id,
|
|
241
|
+
bookingId: opts.bookingId,
|
|
242
|
+
reason: opts.reason,
|
|
243
|
+
})));
|
|
244
|
+
batches += 1;
|
|
245
|
+
const afterRows = await listRevocable();
|
|
246
|
+
if (afterRows === null)
|
|
247
|
+
return;
|
|
248
|
+
const idsAfter = new Set(afterRows.map((r) => r.id));
|
|
249
|
+
const removedCount = [...idsBefore].filter((id) => !idsAfter.has(id)).length;
|
|
250
|
+
if (removedCount === 0) {
|
|
251
|
+
await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
|
|
252
|
+
reason: opts.reason,
|
|
253
|
+
grant_ids: afterRows.map((r) => r.id),
|
|
254
|
+
batches_run: batches,
|
|
255
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (batches >= MAX_REVOKE_SWEEP_BATCHES) {
|
|
260
|
+
const remaining = await listRevocable();
|
|
261
|
+
if (remaining === null)
|
|
262
|
+
return;
|
|
263
|
+
if (remaining.length > 0) {
|
|
264
|
+
await logOps(admin, 'booking_access_revoke_sweep_incomplete', {
|
|
265
|
+
reason: opts.reason,
|
|
266
|
+
remaining_count: remaining.length,
|
|
267
|
+
batches_run: batches,
|
|
268
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
await clearAccessRevokeMarkerIfDone();
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
await logOps(admin, 'booking_access_revoke_unexpected', {
|
|
275
|
+
reason: opts.reason,
|
|
276
|
+
error_name: errorNameFromUnknown(e),
|
|
277
|
+
}, { severity: 'error', bookingId: opts.bookingId });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { NoticeConfig } from '../businessHours.js';
|
|
2
|
+
export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
|
|
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
|
|
4
4
|
import { getBusinessHoursRow, getBusyRanges, laWallToUtc, laWeekday, } from '../availability.js';
|
|
5
5
|
import { listFlatBlockOffers, makeDynamicPctResolver, makeListAdjustmentResolver, resolveHalfDayWindow, } from '../pricing.js';
|
|
6
6
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
7
|
+
import { earliestBookingStartMs, hasBusinessHoursNotice } from '../businessHours.js';
|
|
7
8
|
// Spells out a whole-dollar amount as words for TTS safety. Retell's TTS has
|
|
8
9
|
// been observed mispronouncing digit-form 2-3 digit dollar amounts (e.g.
|
|
9
10
|
// "$215" rendered as "two dollars and fifteen cents") — confirmed via audio
|
|
@@ -56,7 +57,7 @@ const AvailabilityBody = z.object({
|
|
|
56
57
|
});
|
|
57
58
|
const ListBody = z.object({ action: z.literal('list') });
|
|
58
59
|
const Body = z.union([AvailabilityBody, ListBody]);
|
|
59
|
-
export async function handle(req) {
|
|
60
|
+
export async function handle(req, operator) {
|
|
60
61
|
if (req.method === 'OPTIONS')
|
|
61
62
|
return new Response('ok', { headers: corsHeaders });
|
|
62
63
|
try {
|
|
@@ -181,6 +182,8 @@ export async function handle(req) {
|
|
|
181
182
|
// truth for what a customer is actually charged, so a wrong preview here
|
|
182
183
|
// can never change a charge.
|
|
183
184
|
const nowMs = Date.now();
|
|
185
|
+
// Only when the operator opts in; otherwise slot output is exactly as before.
|
|
186
|
+
const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(nowMs, operator) : null;
|
|
184
187
|
const pctFor = makeDynamicPctResolver(supabase, room, nowMs);
|
|
185
188
|
// Same contract as `pctFor`, for the list-ADJUSTING rules: a preview of a
|
|
186
189
|
// peak-hour premium so the picker can show the uplift before the customer
|
|
@@ -227,7 +230,8 @@ export async function handle(req) {
|
|
|
227
230
|
const rangeLiteral = `[${openUtc.toISOString()},${closeUtc.toISOString()})`;
|
|
228
231
|
const busy = await getBusyRanges(supabase, room_id, rangeLiteral);
|
|
229
232
|
const overlaps = (s, e) => busy.some(([bs, be]) => s < be && e > bs);
|
|
230
|
-
const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime())
|
|
233
|
+
const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime()) &&
|
|
234
|
+
(noticeFloorMs === null || openUtc.getTime() >= noticeFloorMs);
|
|
231
235
|
// Half-day windows come from the SAME resolver the charge path uses
|
|
232
236
|
// (validateAndPriceDayBlock -> resolveHalfDayWindow), reading this
|
|
233
237
|
// room's own override columns off the select('*') row above. A room
|
|
@@ -236,8 +240,10 @@ export async function handle(req) {
|
|
|
236
240
|
// never an error for the whole request. Full-day is untouched by it.
|
|
237
241
|
const amWin = resolveHalfDayWindow(room, 'half_am', wd, dStr, openUtc, closeUtc);
|
|
238
242
|
const pmWin = resolveHalfDayWindow(room, 'half_pm', wd, dStr, openUtc, closeUtc);
|
|
239
|
-
const amFree = amWin.ok && !overlaps(amWin.startUtc.getTime(), amWin.endUtc.getTime())
|
|
240
|
-
|
|
243
|
+
const amFree = amWin.ok && !overlaps(amWin.startUtc.getTime(), amWin.endUtc.getTime()) &&
|
|
244
|
+
(noticeFloorMs === null || amWin.startUtc.getTime() >= noticeFloorMs);
|
|
245
|
+
const pmFree = pmWin.ok && !overlaps(pmWin.startUtc.getTime(), pmWin.endUtc.getTime()) &&
|
|
246
|
+
(noticeFloorMs === null || pmWin.startUtc.getTime() >= noticeFloorMs);
|
|
241
247
|
// One pct per day (not per block) — a deliberate simplification for
|
|
242
248
|
// this preview; see makeDynamicPctResolver. Occupancy for this day is
|
|
243
249
|
// resolved once here, not once per block. isFullDayPrice=true: this
|
|
@@ -299,7 +305,8 @@ export async function handle(req) {
|
|
|
299
305
|
for (let t = openUtc.getTime(); t + SLOT_MS <= closeUtc.getTime(); t += SLOT_MS) {
|
|
300
306
|
const s = t;
|
|
301
307
|
const e = t + SLOT_MS;
|
|
302
|
-
const available = !busy.some(([bs, be]) => s < be && e > bs)
|
|
308
|
+
const available = !busy.some(([bs, be]) => s < be && e > bs) &&
|
|
309
|
+
(noticeFloorMs === null || s >= noticeFloorMs);
|
|
303
310
|
// Occupancy (if any occupancy rule is in play) is resolved once for
|
|
304
311
|
// this whole business day via `rangeLiteral`, not once per slot. This
|
|
305
312
|
// is the ordinary per-slot preview (isFullDayPrice=false) — it never
|
|
@@ -336,6 +343,8 @@ export async function handle(req) {
|
|
|
336
343
|
return false;
|
|
337
344
|
if (bs < openUtc.getTime() || be > closeUtc.getTime())
|
|
338
345
|
return false;
|
|
346
|
+
if (noticeFloorMs !== null && bs < noticeFloorMs)
|
|
347
|
+
return false;
|
|
339
348
|
return !busy.some(([xs, xe]) => bs < xe && be > xs);
|
|
340
349
|
});
|
|
341
350
|
// Display-only preview of what pct would apply if the customer's final
|
|
@@ -42,5 +42,10 @@ export interface CreateBookingDeps {
|
|
|
42
42
|
export declare function handle(req: Request, operator: {
|
|
43
43
|
domain: string;
|
|
44
44
|
actorEmail: string;
|
|
45
|
+
minNoticeBusinessHours?: number | null;
|
|
46
|
+
holidays?: string[] | null;
|
|
47
|
+
googleCalendarWriteback?: boolean | null;
|
|
48
|
+
stripeConnectedAccountId?: string | null;
|
|
49
|
+
stripeApplicationFeePercent?: number | null;
|
|
45
50
|
}, deps: CreateBookingDeps): Promise<Response>;
|
|
46
51
|
export {};
|
|
@@ -10,6 +10,10 @@ import { resolveMembershipContext } from '../membership.js';
|
|
|
10
10
|
import { resolveContractTier, loadTier1Terms, insertTier1Agreement, signerIpFrom, signerUserAgentFrom, } from '../tier1Agreement.js';
|
|
11
11
|
import { checkPolicyAcceptance, insertPolicyAcknowledgment, POLICY_NOT_ACCEPTED_ERROR, } from '../policyAcknowledgment.js';
|
|
12
12
|
import { createEventInquiryLead } from '../ghlEventInquiry.js';
|
|
13
|
+
import { clampCheckoutExpiresAtSeconds } from '../checkoutSessionParams.js';
|
|
14
|
+
import { sanitizeBookingSource } from '../bookingSource.js';
|
|
15
|
+
import { writebackBookingCreated } from '../gcalBookingEvents.js';
|
|
16
|
+
import { CONNECT_MISCONFIGURED_MESSAGE, createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
|
|
13
17
|
const Contact = z.object({
|
|
14
18
|
name: z.string().min(1).max(200),
|
|
15
19
|
email: z.string().email(),
|
|
@@ -31,6 +35,7 @@ const Body = z.object({
|
|
|
31
35
|
agreementAccepted: z.boolean().optional(),
|
|
32
36
|
avRequest: z.boolean().optional(),
|
|
33
37
|
avRequestNotes: z.string().max(1000).optional(),
|
|
38
|
+
source: z.unknown().optional(),
|
|
34
39
|
});
|
|
35
40
|
// Stripe rejects charges under $0.50. When credit + coupon leave a sub-minimum
|
|
36
41
|
// remainder we treat the booking as fully covered rather than failing checkout.
|
|
@@ -121,7 +126,7 @@ export async function handle(req, operator, deps) {
|
|
|
121
126
|
}
|
|
122
127
|
tier1Terms = loaded.terms;
|
|
123
128
|
}
|
|
124
|
-
const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true });
|
|
129
|
+
const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true, notice: operator });
|
|
125
130
|
if (!priced.ok) {
|
|
126
131
|
return new Response(JSON.stringify({ error: priced.error }), {
|
|
127
132
|
status: priced.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
@@ -132,6 +137,7 @@ export async function handle(req, operator, deps) {
|
|
|
132
137
|
// Reclaim stale holds overlapping the range so abandoned carts don't block it.
|
|
133
138
|
await reclaimStaleHoldsExceptCompletedTier3(supabase, room_id, rangeLiteral);
|
|
134
139
|
const usesBoldSignAgreement = contractTier === 2 || contractTier === 3;
|
|
140
|
+
const bookingSource = sanitizeBookingSource(parsed.data.source);
|
|
135
141
|
const holdExpires = new Date(Date.now() + 60 * 60 * 1000).toISOString();
|
|
136
142
|
const effectiveHoldExpires = usesBoldSignAgreement
|
|
137
143
|
? new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
|
|
@@ -152,6 +158,8 @@ export async function handle(req, operator, deps) {
|
|
|
152
158
|
contact_phone: contact.phone ?? null,
|
|
153
159
|
is_member: isMember,
|
|
154
160
|
policy_accepted_at: new Date().toISOString(),
|
|
161
|
+
// Only sent when present so an unmigrated database (no `source` column) keeps working.
|
|
162
|
+
...(bookingSource ? { source: bookingSource } : {}),
|
|
155
163
|
})
|
|
156
164
|
.select('id')
|
|
157
165
|
.single();
|
|
@@ -419,6 +427,7 @@ export async function handle(req, operator, deps) {
|
|
|
419
427
|
catch (e) {
|
|
420
428
|
await logOps(supabase, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: booking_id });
|
|
421
429
|
}
|
|
430
|
+
await writebackBookingCreated(operator, eff);
|
|
422
431
|
}
|
|
423
432
|
}
|
|
424
433
|
catch (e) {
|
|
@@ -477,12 +486,21 @@ export async function handle(req, operator, deps) {
|
|
|
477
486
|
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
478
487
|
});
|
|
479
488
|
}
|
|
489
|
+
const chargePlan = planBookingCharge(operator, charged);
|
|
490
|
+
if ('error' in chargePlan) {
|
|
491
|
+
await abandonHoldAndCoupon('payments_misconfigured');
|
|
492
|
+
await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
|
|
493
|
+
await logOps(supabase, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'create-booking' }, { severity: 'error', bookingId: booking_id });
|
|
494
|
+
return new Response(JSON.stringify({ error: 'payments_misconfigured', message: CONNECT_MISCONFIGURED_MESSAGE }), {
|
|
495
|
+
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
496
|
+
});
|
|
497
|
+
}
|
|
480
498
|
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
481
499
|
const origin = req.headers.get('origin');
|
|
482
500
|
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
483
501
|
const human = formatHumanTime(startUtc, endUtc);
|
|
484
502
|
try {
|
|
485
|
-
const session = await stripe
|
|
503
|
+
const session = await createBookingCheckoutSession(stripe, {
|
|
486
504
|
mode: 'payment',
|
|
487
505
|
customer_email: contact.email,
|
|
488
506
|
line_items: [{
|
|
@@ -494,12 +512,12 @@ export async function handle(req, operator, deps) {
|
|
|
494
512
|
},
|
|
495
513
|
}],
|
|
496
514
|
metadata: { booking_id },
|
|
497
|
-
expires_at:
|
|
515
|
+
expires_at: clampCheckoutExpiresAtSeconds(Date.now(), effectiveHoldExpires),
|
|
498
516
|
success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
|
|
499
517
|
cancel_url: `${base}/meeting-rooms/${room.slug ?? ''}?canceled=1`,
|
|
500
518
|
// TODO: enable Stripe automatic tax once tax registrations are configured.
|
|
501
519
|
// automatic_tax: { enabled: true },
|
|
502
|
-
});
|
|
520
|
+
}, chargePlan);
|
|
503
521
|
await supabase
|
|
504
522
|
.from('bookings')
|
|
505
523
|
.update({ stripe_session_id: session.id })
|
|
@@ -35,6 +35,11 @@ export interface ManageBookingDeps {
|
|
|
35
35
|
}, admin: SupabaseLike) => Promise<unknown>;
|
|
36
36
|
signBus: (verb: string, bookingId: string, roomKey: string, startUtc: string, endUtc: string, secret: string, ts: number) => Promise<string>;
|
|
37
37
|
toBusUtc: (iso: string) => string;
|
|
38
|
+
/** Override for this tenant's event-access middleware origin. Defaults to
|
|
39
|
+
* tenant-config.ts's getEventAccessBusBase() (EVENT_ACCESS_BUS_BASE env
|
|
40
|
+
* var) when omitted -- same opts-override pattern as
|
|
41
|
+
* booking-access-revoke.ts's revokeBookingOrganizerAccessGrants. */
|
|
42
|
+
busBase?: string;
|
|
38
43
|
}
|
|
39
44
|
declare function parseTstzRange(range: string): {
|
|
40
45
|
startISO: string;
|
|
@@ -68,6 +73,7 @@ declare function bookingViewForCustomer(b: BookingRow, operator: {
|
|
|
68
73
|
}>;
|
|
69
74
|
export declare function handle(req: Request, operator: {
|
|
70
75
|
operatorName: string;
|
|
76
|
+
googleCalendarWriteback?: boolean | null;
|
|
71
77
|
}, deps: ManageBookingDeps): Promise<Response>;
|
|
72
78
|
export declare const _test: {
|
|
73
79
|
bookingViewForCustomer: typeof bookingViewForCustomer;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createClient } from '@supabase/supabase-js';
|
|
2
2
|
import { JWT } from 'google-auth-library';
|
|
3
|
+
import { writebackBookingCancelled } from '../gcalBookingEvents.js';
|
|
3
4
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
4
5
|
import { verifyManageToken } from '../manageToken.js';
|
|
5
6
|
import { resolvePortalSessionEmail } from '../portalSession.js';
|
|
@@ -7,6 +8,8 @@ import { logOps } from '../ops.js';
|
|
|
7
8
|
import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
|
|
8
9
|
import { buildCancellationCreditGrants } from '../rescheduleCredit.js';
|
|
9
10
|
import { sha256Hex, signBusMessage } from '../busSignature.js';
|
|
11
|
+
import { getEventAccessBusBase } from '../tenant-config.js';
|
|
12
|
+
import { revokeBookingOrganizerAccessGrants } from './booking-access-revoke.js';
|
|
10
13
|
const corsHeaders = {
|
|
11
14
|
'Access-Control-Allow-Origin': '*',
|
|
12
15
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
@@ -28,8 +31,7 @@ async function signOrganizerLinkE1(secret, verb, ts, bodyHashHex) {
|
|
|
28
31
|
const msg = ['e1', verb, ts, bodyHashHex].join('\n');
|
|
29
32
|
return signBusMessage(msg, secret);
|
|
30
33
|
}
|
|
31
|
-
|
|
32
|
-
async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId) {
|
|
34
|
+
async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, busBase) {
|
|
33
35
|
// Every failure path logs a breadcrumb (severity 'warning', same as the
|
|
34
36
|
// sibling credential branch's manage_credential_unauthorized) so a broken
|
|
35
37
|
// contract is visible in ops_events/Slack, even though the customer-facing
|
|
@@ -48,7 +50,7 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId) {
|
|
|
48
50
|
const bodyHash = await sha256Hex(rawBody);
|
|
49
51
|
const ts = String(Math.floor(Date.now() / 1000));
|
|
50
52
|
const signature = await signOrganizerLinkE1(secret, 'organizer_link', ts, bodyHash);
|
|
51
|
-
const res = await fetch(
|
|
53
|
+
const res = await fetch(`${busBase}/admin/event-access/organizer-link`, {
|
|
52
54
|
method: 'POST',
|
|
53
55
|
headers: {
|
|
54
56
|
'Content-Type': 'application/json',
|
|
@@ -65,16 +67,23 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId) {
|
|
|
65
67
|
return await fail('invalid_response');
|
|
66
68
|
// The response isn't otherwise authenticated (no signature on the reply),
|
|
67
69
|
// so a compromised/misconfigured middleware could hand back an
|
|
68
|
-
// attacker-controlled URL. Reject anything not on the expected
|
|
69
|
-
// rather than trusting it blindly.
|
|
70
|
+
// attacker-controlled URL. Reject anything not on the expected (this
|
|
71
|
+
// tenant's own busBase) origin rather than trusting it blindly.
|
|
70
72
|
let origin;
|
|
73
|
+
let expectedOrigin;
|
|
71
74
|
try {
|
|
72
75
|
origin = new URL(j.url).origin;
|
|
73
76
|
}
|
|
74
77
|
catch {
|
|
75
78
|
origin = null;
|
|
76
79
|
}
|
|
77
|
-
|
|
80
|
+
try {
|
|
81
|
+
expectedOrigin = new URL(busBase).origin;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
expectedOrigin = null;
|
|
85
|
+
}
|
|
86
|
+
if (!expectedOrigin || origin !== expectedOrigin)
|
|
78
87
|
return await fail('origin_mismatch', { origin });
|
|
79
88
|
return j.url;
|
|
80
89
|
}
|
|
@@ -203,6 +212,7 @@ export async function handle(req, operator, deps) {
|
|
|
203
212
|
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
204
213
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
205
214
|
});
|
|
215
|
+
const busBase = deps.busBase ?? getEventAccessBusBase();
|
|
206
216
|
// Rate-limit BEFORE any DB work.
|
|
207
217
|
const ip = clientIp(req);
|
|
208
218
|
const [ipOk] = await Promise.all([
|
|
@@ -291,11 +301,7 @@ export async function handle(req, operator, deps) {
|
|
|
291
301
|
const ts = Math.floor(Date.now() / 1000);
|
|
292
302
|
const sig = await deps.signBus('credential', b.id, slug, startUtc, endUtc, busSecret, ts);
|
|
293
303
|
const qs = new URLSearchParams({ source: 'gc-connect', booking_id: b.id });
|
|
294
|
-
|
|
295
|
-
// _shared/busClient.ts's own BUS_BASE, tracked for the later "make the
|
|
296
|
-
// bus pluggable" phase of this project, not this identity-parameterization
|
|
297
|
-
// phase.
|
|
298
|
-
const res = await fetch(`https://ftw.granitecity.io/bookings/credential?${qs.toString()}`, {
|
|
304
|
+
const res = await fetch(`${busBase}/bookings/credential?${qs.toString()}`, {
|
|
299
305
|
method: 'GET',
|
|
300
306
|
headers: { 'X-GC-Signature': sig, 'X-GC-Timestamp': String(ts) },
|
|
301
307
|
signal: AbortSignal.timeout(10000),
|
|
@@ -356,7 +362,7 @@ export async function handle(req, operator, deps) {
|
|
|
356
362
|
const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
|
|
357
363
|
const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
|
|
358
364
|
if (grant.id && grantWithinWindow) {
|
|
359
|
-
organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id);
|
|
365
|
+
organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
|
|
360
366
|
}
|
|
361
367
|
return json(200, {
|
|
362
368
|
unlock_pin: grant.unlock_pin ?? null,
|
|
@@ -463,6 +469,8 @@ export async function handle(req, operator, deps) {
|
|
|
463
469
|
catch (e) {
|
|
464
470
|
await logOps(admin, 'coupon_reverse_on_cancel_failed', { message: String(e) }, { severity: 'error', bookingId: b.id });
|
|
465
471
|
}
|
|
472
|
+
// Opt-in, fail-soft: remove the write-back event (deterministic id; no stored id needed).
|
|
473
|
+
await writebackBookingCancelled(operator, b.rooms?.google_calendar_id, b.id);
|
|
466
474
|
// Best-effort: delete Google Calendar event.
|
|
467
475
|
try {
|
|
468
476
|
const cal = await deleteCalendarEvent(b);
|
|
@@ -498,6 +506,15 @@ export async function handle(req, operator, deps) {
|
|
|
498
506
|
}
|
|
499
507
|
}
|
|
500
508
|
catch { /* never break the response */ }
|
|
509
|
+
// Best-effort: revoke organizer door grants (O3b). Must not block cancel.
|
|
510
|
+
try {
|
|
511
|
+
await revokeBookingOrganizerAccessGrants(admin, {
|
|
512
|
+
bookingId: b.id,
|
|
513
|
+
actingUserId: `customer:booking:${b.id}`,
|
|
514
|
+
reason: 'booking_cancelled',
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
catch { /* revokeBookingOrganizerAccessGrants never throws; belt-and-suspenders */ }
|
|
501
518
|
const { data: fresh } = await admin
|
|
502
519
|
.from('bookings')
|
|
503
520
|
.select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
|
|
@@ -48,5 +48,10 @@ export interface RescheduleBookingDeps {
|
|
|
48
48
|
export declare function handle(req: Request, operator: {
|
|
49
49
|
domain: string;
|
|
50
50
|
actorEmail: string;
|
|
51
|
+
minNoticeBusinessHours?: number | null;
|
|
52
|
+
holidays?: string[] | null;
|
|
53
|
+
googleCalendarWriteback?: boolean | null;
|
|
54
|
+
stripeConnectedAccountId?: string | null;
|
|
55
|
+
stripeApplicationFeePercent?: number | null;
|
|
51
56
|
}, deps: RescheduleBookingDeps): Promise<Response>;
|
|
52
57
|
export {};
|