@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
|
@@ -11,6 +11,8 @@ import { resolveIsMember } from '../membership.js';
|
|
|
11
11
|
import { buildRescheduleCreditGrants } from '../rescheduleCredit.js';
|
|
12
12
|
import { resolveContractTier, loadTier1Terms, insertTier1Agreement, signerIpFrom, signerUserAgentFrom, } from '../tier1Agreement.js';
|
|
13
13
|
import { JWT } from 'google-auth-library';
|
|
14
|
+
import { writebackBookingCancelled, writebackBookingCreated } from '../gcalBookingEvents.js';
|
|
15
|
+
import { createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
|
|
14
16
|
const corsHeaders = {
|
|
15
17
|
'Access-Control-Allow-Origin': '*',
|
|
16
18
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
@@ -134,6 +136,7 @@ export async function handle(req, operator, deps) {
|
|
|
134
136
|
isMember,
|
|
135
137
|
allowDynamic: true,
|
|
136
138
|
allowFreshDynamic: false,
|
|
139
|
+
notice: operator,
|
|
137
140
|
carryForward: {
|
|
138
141
|
list_cents: O.list_amount_cents ?? 0,
|
|
139
142
|
discount_cents: O.dynamic_discount_cents ?? 0,
|
|
@@ -189,6 +192,16 @@ export async function handle(req, operator, deps) {
|
|
|
189
192
|
return json(500, { error: 'reserve_failed' });
|
|
190
193
|
}
|
|
191
194
|
const NEW_ID = newBk.id;
|
|
195
|
+
// Validate Connect account/fee config BEFORE the original booking is
|
|
196
|
+
// cancelled and credited: a bad config must not destroy a confirmed booking.
|
|
197
|
+
// Nothing is reserved yet (credits/coupon come later), so only the new row
|
|
198
|
+
// needs cleanup.
|
|
199
|
+
const connectPreflight = planBookingCharge(operator, 1);
|
|
200
|
+
if ('error' in connectPreflight) {
|
|
201
|
+
await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
|
|
202
|
+
await logOps(admin, 'booking_connect_config_invalid', { error: connectPreflight.error, path: 'reschedule-booking', stage: 'preflight' }, { severity: 'error', bookingId: O.id });
|
|
203
|
+
return json(500, { error: 'payments_misconfigured' });
|
|
204
|
+
}
|
|
192
205
|
// 6. Guarded cancel of ORIGINAL (paid → cancelled_credited).
|
|
193
206
|
const { data: cancelled, error: cErr } = await admin
|
|
194
207
|
.from('bookings')
|
|
@@ -227,6 +240,8 @@ export async function handle(req, operator, deps) {
|
|
|
227
240
|
}
|
|
228
241
|
}
|
|
229
242
|
}
|
|
243
|
+
// Opt-in, fail-soft: remove the original booking's write-back event.
|
|
244
|
+
await writebackBookingCancelled(operator, room.google_calendar_id, O.id);
|
|
230
245
|
// Best-effort delete of ORIGINAL calendar event.
|
|
231
246
|
try {
|
|
232
247
|
await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
|
|
@@ -491,6 +506,7 @@ export async function handle(req, operator, deps) {
|
|
|
491
506
|
catch (e) {
|
|
492
507
|
await logOps(admin, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: NEW_ID });
|
|
493
508
|
}
|
|
509
|
+
await writebackBookingCreated(operator, eff);
|
|
494
510
|
}
|
|
495
511
|
}
|
|
496
512
|
catch (e) {
|
|
@@ -514,12 +530,22 @@ export async function handle(req, operator, deps) {
|
|
|
514
530
|
await unwindCarriedCoupon('reschedule_missing_stripe_key');
|
|
515
531
|
return json(500, { error: 'Payments not configured' });
|
|
516
532
|
}
|
|
533
|
+
const chargePlan = planBookingCharge(operator, charged);
|
|
534
|
+
if ('error' in chargePlan) {
|
|
535
|
+
await admin.rpc('credit_reservation_release', {
|
|
536
|
+
p_booking_id: NEW_ID,
|
|
537
|
+
p_reason: 'reschedule_payments_misconfigured',
|
|
538
|
+
});
|
|
539
|
+
await unwindCarriedCoupon('reschedule_payments_misconfigured');
|
|
540
|
+
await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'reschedule-booking' }, { severity: 'error', bookingId: NEW_ID });
|
|
541
|
+
return json(500, { error: 'payments_misconfigured' });
|
|
542
|
+
}
|
|
517
543
|
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
518
544
|
const origin = req.headers.get('origin');
|
|
519
545
|
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
520
546
|
const human = formatHumanTime(startUtc, endUtc);
|
|
521
547
|
try {
|
|
522
|
-
const session = await stripe
|
|
548
|
+
const session = await createBookingCheckoutSession(stripe, {
|
|
523
549
|
mode: 'payment',
|
|
524
550
|
customer_email: O.contact_email,
|
|
525
551
|
line_items: [{
|
|
@@ -536,7 +562,7 @@ export async function handle(req, operator, deps) {
|
|
|
536
562
|
cancel_url: token
|
|
537
563
|
? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
|
|
538
564
|
: `${base}/portal/bookings`,
|
|
539
|
-
});
|
|
565
|
+
}, chargePlan);
|
|
540
566
|
await admin
|
|
541
567
|
.from('bookings')
|
|
542
568
|
.update({ stripe_session_id: session.id })
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { NoticeConfig } from '../businessHours.js';
|
|
2
|
+
export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
|
|
@@ -28,13 +28,14 @@ import { z } from 'zod';
|
|
|
28
28
|
import { getBusyRangesDetailed, laWallToUtc } from '../availability.js';
|
|
29
29
|
import { clientIp, checkRateLimit } from '../rateLimit.js';
|
|
30
30
|
import { dateRange, nextDateStr, statusForDay } from './dayStatus.js';
|
|
31
|
+
import { earliestBookingStartMs, hasBusinessHoursNotice } from '../businessHours.js';
|
|
31
32
|
const MAX_RANGE_DAYS = 31;
|
|
32
33
|
const Body = z.object({
|
|
33
34
|
start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
34
35
|
end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
35
36
|
room_ids: z.array(z.string().uuid()).optional(),
|
|
36
37
|
});
|
|
37
|
-
export async function handle(req) {
|
|
38
|
+
export async function handle(req, operator) {
|
|
38
39
|
if (req.method === 'OPTIONS')
|
|
39
40
|
return new Response('ok', { headers: corsHeaders });
|
|
40
41
|
try {
|
|
@@ -79,12 +80,18 @@ export async function handle(req) {
|
|
|
79
80
|
throw roomsErr;
|
|
80
81
|
const rooms = (roomsData ?? []);
|
|
81
82
|
const dates = dateRange(start_date, end_date);
|
|
83
|
+
const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(Date.now(), operator) : null;
|
|
82
84
|
const results = await Promise.all(rooms.map(async (room) => {
|
|
83
85
|
const days = await Promise.all(dates.map(async (dateStr) => {
|
|
84
86
|
const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
|
|
85
87
|
const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
|
|
86
88
|
const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
|
|
87
89
|
const { busy, unparsed } = await getBusyRangesDetailed(supabase, room.id, rangeLiteral);
|
|
90
|
+
// Opt-in notice window: treat everything before the earliest bookable
|
|
91
|
+
// start as busy so the public calendar never advertises it as open.
|
|
92
|
+
if (noticeFloorMs !== null && noticeFloorMs > windowStart) {
|
|
93
|
+
busy.push([windowStart, Math.min(noticeFloorMs, windowEnd)]);
|
|
94
|
+
}
|
|
88
95
|
return {
|
|
89
96
|
date: dateStr,
|
|
90
97
|
status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
|
|
@@ -43,4 +43,8 @@ export interface StripeWebhookConfig {
|
|
|
43
43
|
}>;
|
|
44
44
|
}
|
|
45
45
|
export declare function createStripeWebhookHandler(config: StripeWebhookConfig): (req: Request) => Promise<Response>;
|
|
46
|
+
export interface StripeConnectWebhookOperator {
|
|
47
|
+
stripeConnectedAccountId: string | null | undefined;
|
|
48
|
+
}
|
|
49
|
+
export declare function createStripeConnectWebhookHandler(config: StripeWebhookConfig & StripeConnectWebhookOperator): (req: Request) => Promise<Response>;
|
|
46
50
|
export {};
|
|
@@ -10,7 +10,16 @@ import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGran
|
|
|
10
10
|
import { findBaseItem } from '../membershipSubscriptionItems.js';
|
|
11
11
|
import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
|
|
12
12
|
import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
|
|
13
|
+
import { errorNameFromUnknown, revokeBookingOrganizerAccessGrants, shouldRevokeOrganizerGrantsOnStripeChargeRefunded, } from './booking-access-revoke.js';
|
|
14
|
+
import { isValidConnectedAccountId } from '../connectBookingCharge.js';
|
|
15
|
+
import { connectAcceptedOpsKind, gateConnectBookingEvent } from '../stripeConnectEvents.js';
|
|
13
16
|
export function createStripeWebhookHandler(config) {
|
|
17
|
+
return buildStripeWebhookHandler(config, null);
|
|
18
|
+
}
|
|
19
|
+
export function createStripeConnectWebhookHandler(config) {
|
|
20
|
+
return buildStripeWebhookHandler(config, { accountId: config.stripeConnectedAccountId });
|
|
21
|
+
}
|
|
22
|
+
function buildStripeWebhookHandler(config, connect) {
|
|
14
23
|
const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
|
|
15
24
|
// No CORS — this is called by Stripe, not the browser.
|
|
16
25
|
return async (req) => {
|
|
@@ -18,11 +27,16 @@ export function createStripeWebhookHandler(config) {
|
|
|
18
27
|
return new Response('Method not allowed', { status: 405 });
|
|
19
28
|
}
|
|
20
29
|
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
21
|
-
const webhookSecret =
|
|
30
|
+
const webhookSecret = connect
|
|
31
|
+
? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
|
|
32
|
+
: Deno.env.get('STRIPE_WEBHOOK_SECRET');
|
|
22
33
|
if (!stripeKey || !webhookSecret) {
|
|
23
34
|
return new Response('Webhook not configured', { status: 500 });
|
|
24
35
|
}
|
|
25
|
-
|
|
36
|
+
if (connect && !isValidConnectedAccountId(connect.accountId)) {
|
|
37
|
+
return new Response('Connect webhook not configured', { status: 500 });
|
|
38
|
+
}
|
|
39
|
+
let stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
26
40
|
const signature = req.headers.get('stripe-signature');
|
|
27
41
|
if (!signature)
|
|
28
42
|
return new Response('Missing signature', { status: 400 });
|
|
@@ -36,6 +50,30 @@ export function createStripeWebhookHandler(config) {
|
|
|
36
50
|
return new Response('Invalid signature', { status: 400 });
|
|
37
51
|
}
|
|
38
52
|
const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'));
|
|
53
|
+
if (connect) {
|
|
54
|
+
const connectAccountId = connect.accountId;
|
|
55
|
+
const gate = gateConnectBookingEvent(event, connectAccountId);
|
|
56
|
+
const ignoredReason = 'reason' in gate ? gate.reason : null;
|
|
57
|
+
await logOps(supabase, ignoredReason ? 'stripe_connect_event_ignored' : connectAcceptedOpsKind(event.type), {
|
|
58
|
+
event_id: event.id,
|
|
59
|
+
event_type: event.type,
|
|
60
|
+
connected_account_id: event.account ?? null,
|
|
61
|
+
...(ignoredReason ? { reason: ignoredReason } : {}),
|
|
62
|
+
}, {
|
|
63
|
+
severity: ignoredReason
|
|
64
|
+
? (ignoredReason === 'account_mismatch' ? 'warning' : 'info')
|
|
65
|
+
: (event.type.startsWith('charge.') ? 'warning' : 'info'),
|
|
66
|
+
}).catch(() => { });
|
|
67
|
+
if (ignoredReason) {
|
|
68
|
+
return new Response(JSON.stringify({ received: true, connect_event: true, ignored: ignoredReason }), {
|
|
69
|
+
headers: { 'Content-Type': 'application/json' }, status: 200,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia', stripeAccount: connectAccountId });
|
|
73
|
+
// Account already verified above; clear it so the platform-only guard below lets this event reach the shared booking logic.
|
|
74
|
+
// Namespace the id so a platform-endpoint ledger row for the same evt_ can never swallow this delivery as a duplicate.
|
|
75
|
+
event = { ...event, id: `connect:${event.id}`, account: undefined };
|
|
76
|
+
}
|
|
39
77
|
// Idempotency ledger — dedupe Stripe redeliveries.
|
|
40
78
|
{
|
|
41
79
|
const { error: ledgerErr } = await supabase
|
|
@@ -62,6 +100,101 @@ export function createStripeWebhookHandler(config) {
|
|
|
62
100
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
63
101
|
return data;
|
|
64
102
|
}
|
|
103
|
+
async function findBookingIdByPaymentIntent(paymentIntentId) {
|
|
104
|
+
const { data: rows, error } = await supabase
|
|
105
|
+
.from('bookings')
|
|
106
|
+
.select('id')
|
|
107
|
+
.eq('stripe_payment_intent', paymentIntentId)
|
|
108
|
+
.limit(2);
|
|
109
|
+
if (error) {
|
|
110
|
+
const code = error.code;
|
|
111
|
+
await logOps(supabase, 'booking_access_revoke_booking_lookup_failed', {
|
|
112
|
+
payment_intent_id: paymentIntentId,
|
|
113
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
114
|
+
}, { severity: 'error', bookingId: null });
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
const list = (rows ?? []);
|
|
118
|
+
if (list.length > 1) {
|
|
119
|
+
await logOps(supabase, 'booking_access_revoke_booking_lookup_duplicate_pi', {
|
|
120
|
+
payment_intent_id: paymentIntentId,
|
|
121
|
+
match_count: list.length,
|
|
122
|
+
}, { severity: 'error', bookingId: null });
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
return list[0]?.id ?? null;
|
|
126
|
+
}
|
|
127
|
+
async function releaseStripeEventLedgerForRetry(eventId) {
|
|
128
|
+
const { error } = await supabase.from('stripe_events').delete().eq('event_id', eventId);
|
|
129
|
+
if (error) {
|
|
130
|
+
const code = error.code;
|
|
131
|
+
await logOps(supabase, 'stripe_events_ledger_release_failed', {
|
|
132
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
133
|
+
}, { severity: 'error' });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function webhookResponseMarkerFailedForRetry() {
|
|
137
|
+
return new Response(JSON.stringify({ error: 'booking_access_revoke_marker_failed' }), {
|
|
138
|
+
status: 500,
|
|
139
|
+
headers: { 'Content-Type': 'application/json' },
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
async function maybeRevokeBookingAccessForCharge(charge, reason) {
|
|
143
|
+
const piId = typeof charge.payment_intent === 'string'
|
|
144
|
+
? charge.payment_intent
|
|
145
|
+
: charge.payment_intent?.id ?? null;
|
|
146
|
+
if (!piId)
|
|
147
|
+
return 'skipped';
|
|
148
|
+
let bookingId = null;
|
|
149
|
+
let markerFailed = false;
|
|
150
|
+
try {
|
|
151
|
+
bookingId = await findBookingIdByPaymentIntent(piId);
|
|
152
|
+
if (!bookingId)
|
|
153
|
+
return 'skipped';
|
|
154
|
+
if (connect) {
|
|
155
|
+
// Connect (direct-charge) bookings are refunded outside the app, so
|
|
156
|
+
// nothing cancels the booking: status stays 'paid', the slot stays
|
|
157
|
+
// blocked and door access stays live. Page staff to cancel in admin.
|
|
158
|
+
await logOps(supabase, 'connect_booking_refund_needs_cancel', {
|
|
159
|
+
charge_id: charge.id,
|
|
160
|
+
event_type: event.type,
|
|
161
|
+
reason,
|
|
162
|
+
}, { severity: 'error', bookingId }).catch(() => { });
|
|
163
|
+
}
|
|
164
|
+
const markerAt = new Date().toISOString();
|
|
165
|
+
const { error: markerErr } = await supabase
|
|
166
|
+
.from('bookings')
|
|
167
|
+
.update({ access_revoke_required_at: markerAt })
|
|
168
|
+
.eq('id', bookingId);
|
|
169
|
+
const runInlineRevoke = async () => {
|
|
170
|
+
await revokeBookingOrganizerAccessGrants(supabase, {
|
|
171
|
+
bookingId,
|
|
172
|
+
actingUserId: `system:${systemActorEmail}`,
|
|
173
|
+
reason,
|
|
174
|
+
});
|
|
175
|
+
};
|
|
176
|
+
if (markerErr) {
|
|
177
|
+
markerFailed = true;
|
|
178
|
+
const code = markerErr.code;
|
|
179
|
+
await logOps(supabase, 'booking_access_revoke_marker_failed', {
|
|
180
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
181
|
+
}, { severity: 'error', bookingId });
|
|
182
|
+
await runInlineRevoke();
|
|
183
|
+
return 'marker_failed';
|
|
184
|
+
}
|
|
185
|
+
await runInlineRevoke();
|
|
186
|
+
return 'ok';
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
await logOps(supabase, 'booking_access_revoke_step_failed', {
|
|
190
|
+
reason,
|
|
191
|
+
error_name: errorNameFromUnknown(e),
|
|
192
|
+
}, { severity: 'error', bookingId });
|
|
193
|
+
if (markerFailed)
|
|
194
|
+
return 'marker_failed';
|
|
195
|
+
return 'skipped';
|
|
196
|
+
}
|
|
197
|
+
}
|
|
65
198
|
// --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
|
|
66
199
|
// create-subscription-checkout and create-day-pass-checkout reserve a
|
|
67
200
|
// coupon_redemptions row at session-creation time and stamp its id onto the
|
|
@@ -1919,6 +2052,14 @@ export function createStripeWebhookHandler(config) {
|
|
|
1919
2052
|
console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
|
|
1920
2053
|
}
|
|
1921
2054
|
}
|
|
2055
|
+
// O3(b): organizer grant revoke on refund — gated by CS-GM partial-refund policy.
|
|
2056
|
+
if (shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge)) {
|
|
2057
|
+
const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_refunded');
|
|
2058
|
+
if (markerOutcome === 'marker_failed') {
|
|
2059
|
+
await releaseStripeEventLedgerForRetry(event.id);
|
|
2060
|
+
return webhookResponseMarkerFailedForRetry();
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
1922
2063
|
break;
|
|
1923
2064
|
}
|
|
1924
2065
|
case 'charge.dispute.created': {
|
|
@@ -1928,6 +2069,31 @@ export function createStripeWebhookHandler(config) {
|
|
|
1928
2069
|
// charge.dispute.closed below, gated on status === 'lost'.
|
|
1929
2070
|
const dispute = event.data.object;
|
|
1930
2071
|
await logOps(supabase, 'referral_dispute_opened_no_action', { dispute_id: dispute.id, charge: typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null }, { severity: 'warning' }).catch(() => { });
|
|
2072
|
+
// O3(b): chargeback opened — revoke organizer access immediately.
|
|
2073
|
+
let bookingIdForDisputeRevoke = null;
|
|
2074
|
+
try {
|
|
2075
|
+
const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
|
|
2076
|
+
if (chargeId) {
|
|
2077
|
+
const charge = await stripe.charges.retrieve(chargeId);
|
|
2078
|
+
const piId = typeof charge.payment_intent === 'string'
|
|
2079
|
+
? charge.payment_intent
|
|
2080
|
+
: charge.payment_intent?.id ?? null;
|
|
2081
|
+
if (piId) {
|
|
2082
|
+
bookingIdForDisputeRevoke = await findBookingIdByPaymentIntent(piId);
|
|
2083
|
+
}
|
|
2084
|
+
const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_dispute_created');
|
|
2085
|
+
if (markerOutcome === 'marker_failed') {
|
|
2086
|
+
await releaseStripeEventLedgerForRetry(event.id);
|
|
2087
|
+
return webhookResponseMarkerFailedForRetry();
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
catch (e) {
|
|
2092
|
+
await logOps(supabase, 'booking_access_revoke_step_failed', {
|
|
2093
|
+
reason: 'charge_dispute_created',
|
|
2094
|
+
error_name: errorNameFromUnknown(e),
|
|
2095
|
+
}, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
|
|
2096
|
+
}
|
|
1931
2097
|
break;
|
|
1932
2098
|
}
|
|
1933
2099
|
case 'charge.dispute.closed': {
|
|
@@ -173,7 +173,7 @@ export async function handle(req) {
|
|
|
173
173
|
const keepIds = new Set();
|
|
174
174
|
for (const ev of events) {
|
|
175
175
|
if (shouldSkipEvent(ev, selfIds)) {
|
|
176
|
-
if (ev.id && (selfIds.has(ev.id) || ev.extendedProperties?.private?.gc_source === 'gc-connect')) {
|
|
176
|
+
if (ev.id && (selfIds.has(ev.id) || ev.extendedProperties?.private?.gc_source === 'gc-connect' || ev.extendedProperties?.private?.cs_booking_id)) {
|
|
177
177
|
skippedSelf++;
|
|
178
178
|
}
|
|
179
179
|
continue;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export interface BookingEventInput {
|
|
2
|
+
calendarId: string;
|
|
3
|
+
bookingId: string;
|
|
4
|
+
startIso: string;
|
|
5
|
+
endIso: string;
|
|
6
|
+
summary: string;
|
|
7
|
+
description?: string;
|
|
8
|
+
location?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface GcalWritebackDeps {
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
getAccessToken?: () => Promise<string | null>;
|
|
13
|
+
}
|
|
14
|
+
export type WritebackResult = {
|
|
15
|
+
ok: true;
|
|
16
|
+
eventId: string;
|
|
17
|
+
action: 'created' | 'updated' | 'deleted' | 'already_absent';
|
|
18
|
+
} | {
|
|
19
|
+
ok: false;
|
|
20
|
+
reason: 'no_credentials' | 'no_calendar' | 'http_error' | 'exception';
|
|
21
|
+
status?: number;
|
|
22
|
+
detail?: string;
|
|
23
|
+
};
|
|
24
|
+
export declare function eventIdForBooking(bookingId: string): string;
|
|
25
|
+
export declare function createBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
|
|
26
|
+
export declare function updateBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
|
|
27
|
+
export declare function deleteBookingEvent(calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps): Promise<WritebackResult>;
|
|
28
|
+
export interface WritebackOperator {
|
|
29
|
+
googleCalendarWriteback?: boolean | null;
|
|
30
|
+
}
|
|
31
|
+
export declare function isGcalWritebackEnabled(operator: WritebackOperator | null | undefined): boolean;
|
|
32
|
+
export interface WritebackBookingRow {
|
|
33
|
+
id: string;
|
|
34
|
+
contact_name?: string | null;
|
|
35
|
+
contact_email?: string | null;
|
|
36
|
+
contact_phone?: string | null;
|
|
37
|
+
during: string;
|
|
38
|
+
rooms?: {
|
|
39
|
+
name?: string | null;
|
|
40
|
+
address?: string | null;
|
|
41
|
+
google_calendar_id?: string | null;
|
|
42
|
+
} | null;
|
|
43
|
+
}
|
|
44
|
+
export declare function bookingRowToEventInput(row: WritebackBookingRow): BookingEventInput | null;
|
|
45
|
+
type LogFn = (msg: string, detail: unknown) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Fail-soft create for a paid booking row. Never throws; returns null when the
|
|
48
|
+
* operator flag is off (the default), so callers can invoke it unconditionally.
|
|
49
|
+
*/
|
|
50
|
+
export declare function writebackBookingCreated(operator: WritebackOperator | null | undefined, row: WritebackBookingRow, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
|
|
51
|
+
export declare function writebackBookingCancelled(operator: WritebackOperator | null | undefined, calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
|
|
52
|
+
/**
|
|
53
|
+
* Adapter matching the `createCalendarEvent` dep shape used by create-booking,
|
|
54
|
+
* admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
|
|
55
|
+
* without door hardware can pass this as that dep; it is the only way to cover
|
|
56
|
+
* stripe-webhook's paid path without editing the webhook.
|
|
57
|
+
*/
|
|
58
|
+
export declare function makeWritebackCreateCalendarEvent(operator: WritebackOperator, deps?: GcalWritebackDeps): (admin: unknown, row: WritebackBookingRow) => Promise<void>;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { JWT } from 'google-auth-library';
|
|
2
|
+
import { parsePgRange } from './availability.js';
|
|
3
|
+
import { CS_BOOKING_ID_KEY } from './gcalSync.js';
|
|
4
|
+
const EVENTS_SCOPE = 'https://www.googleapis.com/auth/calendar.events';
|
|
5
|
+
const CAL_BASE = 'https://www.googleapis.com/calendar/v3/calendars';
|
|
6
|
+
const TZ = 'America/Los_Angeles';
|
|
7
|
+
// Deterministic id (Google allows client ids of [a-v0-9], 5-1024 chars; a UUID's
|
|
8
|
+
// hex digits qualify) so create is idempotent and update/delete need no stored id.
|
|
9
|
+
export function eventIdForBooking(bookingId) {
|
|
10
|
+
return `csb${bookingId.replace(/-/g, '').toLowerCase()}`;
|
|
11
|
+
}
|
|
12
|
+
async function defaultGetAccessToken() {
|
|
13
|
+
const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
|
|
14
|
+
const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
|
|
15
|
+
if (!clientEmail || !rawKey)
|
|
16
|
+
return null;
|
|
17
|
+
const jwt = new JWT({ email: clientEmail, key: rawKey.replace(/\\n/g, '\n'), scopes: [EVENTS_SCOPE] });
|
|
18
|
+
const tok = await jwt.getAccessToken();
|
|
19
|
+
return tok?.token ?? null;
|
|
20
|
+
}
|
|
21
|
+
function eventBody(input, includeId) {
|
|
22
|
+
return {
|
|
23
|
+
...(includeId ? { id: eventIdForBooking(input.bookingId) } : {}),
|
|
24
|
+
summary: input.summary,
|
|
25
|
+
description: input.description,
|
|
26
|
+
location: input.location,
|
|
27
|
+
start: { dateTime: input.startIso, timeZone: TZ },
|
|
28
|
+
end: { dateTime: input.endIso, timeZone: TZ },
|
|
29
|
+
transparency: 'opaque',
|
|
30
|
+
extendedProperties: { private: { [CS_BOOKING_ID_KEY]: input.bookingId } },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
async function call(method, calendarId, eventId, body, deps) {
|
|
34
|
+
const token = await (deps.getAccessToken ?? defaultGetAccessToken)();
|
|
35
|
+
if (!token)
|
|
36
|
+
return { noToken: true, status: 0 };
|
|
37
|
+
const url = `${CAL_BASE}/${encodeURIComponent(calendarId)}/events${eventId ? `/${encodeURIComponent(eventId)}` : ''}`;
|
|
38
|
+
const res = await (deps.fetch ?? fetch)(url, {
|
|
39
|
+
method,
|
|
40
|
+
headers: {
|
|
41
|
+
Authorization: `Bearer ${token}`,
|
|
42
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
43
|
+
},
|
|
44
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
45
|
+
signal: AbortSignal.timeout(15000),
|
|
46
|
+
});
|
|
47
|
+
return { noToken: false, status: res.status };
|
|
48
|
+
}
|
|
49
|
+
const isOk = (s) => s >= 200 && s < 300;
|
|
50
|
+
const noCreds = { ok: false, reason: 'no_credentials' };
|
|
51
|
+
const httpFail = (status) => ({ ok: false, reason: 'http_error', status });
|
|
52
|
+
export async function createBookingEvent(input, deps = {}) {
|
|
53
|
+
if (!input.calendarId)
|
|
54
|
+
return { ok: false, reason: 'no_calendar' };
|
|
55
|
+
try {
|
|
56
|
+
const eventId = eventIdForBooking(input.bookingId);
|
|
57
|
+
const r = await call('POST', input.calendarId, null, eventBody(input, true), deps);
|
|
58
|
+
if (r.noToken)
|
|
59
|
+
return noCreds;
|
|
60
|
+
if (isOk(r.status))
|
|
61
|
+
return { ok: true, eventId, action: 'created' };
|
|
62
|
+
// Deterministic id already exists (retry / duplicate delivery): converge via update.
|
|
63
|
+
if (r.status === 409)
|
|
64
|
+
return await updateBookingEvent(input, deps);
|
|
65
|
+
return httpFail(r.status);
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export async function updateBookingEvent(input, deps = {}) {
|
|
72
|
+
if (!input.calendarId)
|
|
73
|
+
return { ok: false, reason: 'no_calendar' };
|
|
74
|
+
try {
|
|
75
|
+
const eventId = eventIdForBooking(input.bookingId);
|
|
76
|
+
const r = await call('PATCH', input.calendarId, eventId, eventBody(input, false), deps);
|
|
77
|
+
if (r.noToken)
|
|
78
|
+
return noCreds;
|
|
79
|
+
if (isOk(r.status))
|
|
80
|
+
return { ok: true, eventId, action: 'updated' };
|
|
81
|
+
if (r.status === 404) {
|
|
82
|
+
const c = await call('POST', input.calendarId, null, eventBody(input, true), deps);
|
|
83
|
+
if (c.noToken)
|
|
84
|
+
return noCreds;
|
|
85
|
+
return isOk(c.status) ? { ok: true, eventId, action: 'created' } : httpFail(c.status);
|
|
86
|
+
}
|
|
87
|
+
return httpFail(r.status);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export async function deleteBookingEvent(calendarId, bookingId, deps = {}) {
|
|
94
|
+
if (!calendarId)
|
|
95
|
+
return { ok: false, reason: 'no_calendar' };
|
|
96
|
+
try {
|
|
97
|
+
const eventId = eventIdForBooking(bookingId);
|
|
98
|
+
const r = await call('DELETE', calendarId, eventId, null, deps);
|
|
99
|
+
if (r.noToken)
|
|
100
|
+
return noCreds;
|
|
101
|
+
if (isOk(r.status))
|
|
102
|
+
return { ok: true, eventId, action: 'deleted' };
|
|
103
|
+
if (r.status === 404 || r.status === 410)
|
|
104
|
+
return { ok: true, eventId, action: 'already_absent' };
|
|
105
|
+
return httpFail(r.status);
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export function isGcalWritebackEnabled(operator) {
|
|
112
|
+
return operator?.googleCalendarWriteback === true;
|
|
113
|
+
}
|
|
114
|
+
export function bookingRowToEventInput(row) {
|
|
115
|
+
const calendarId = row.rooms?.google_calendar_id;
|
|
116
|
+
const range = parsePgRange(row.during);
|
|
117
|
+
if (!calendarId || !range)
|
|
118
|
+
return null;
|
|
119
|
+
const who = row.contact_name || row.contact_email || 'Guest';
|
|
120
|
+
const lines = [
|
|
121
|
+
row.contact_name ? `Name: ${row.contact_name}` : null,
|
|
122
|
+
row.contact_email ? `Email: ${row.contact_email}` : null,
|
|
123
|
+
row.contact_phone ? `Phone: ${row.contact_phone}` : null,
|
|
124
|
+
`Booking: ${row.id}`,
|
|
125
|
+
].filter(Boolean);
|
|
126
|
+
return {
|
|
127
|
+
calendarId,
|
|
128
|
+
bookingId: row.id,
|
|
129
|
+
startIso: new Date(range[0]).toISOString(),
|
|
130
|
+
endIso: new Date(range[1]).toISOString(),
|
|
131
|
+
summary: `${row.rooms?.name ?? 'Booking'} — ${who}`,
|
|
132
|
+
description: lines.join('\n'),
|
|
133
|
+
location: row.rooms?.address ?? undefined,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const defaultLog = (m, d) => console.warn(m, d);
|
|
137
|
+
/**
|
|
138
|
+
* Fail-soft create for a paid booking row. Never throws; returns null when the
|
|
139
|
+
* operator flag is off (the default), so callers can invoke it unconditionally.
|
|
140
|
+
*/
|
|
141
|
+
export async function writebackBookingCreated(operator, row, deps = {}, log = defaultLog) {
|
|
142
|
+
if (!isGcalWritebackEnabled(operator))
|
|
143
|
+
return null;
|
|
144
|
+
try {
|
|
145
|
+
const input = bookingRowToEventInput(row);
|
|
146
|
+
if (!input)
|
|
147
|
+
return { ok: false, reason: 'no_calendar' };
|
|
148
|
+
const res = await createBookingEvent(input, deps);
|
|
149
|
+
if (!res.ok)
|
|
150
|
+
log('[gcalBookingEvents] create failed', { bookingId: row.id, ...res });
|
|
151
|
+
return res;
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
log('[gcalBookingEvents] create threw', { bookingId: row.id, error: String(e) });
|
|
155
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
export async function writebackBookingCancelled(operator, calendarId, bookingId, deps = {}, log = defaultLog) {
|
|
159
|
+
if (!isGcalWritebackEnabled(operator))
|
|
160
|
+
return null;
|
|
161
|
+
try {
|
|
162
|
+
const res = await deleteBookingEvent(calendarId, bookingId, deps);
|
|
163
|
+
if (!res.ok)
|
|
164
|
+
log('[gcalBookingEvents] delete failed', { bookingId, ...res });
|
|
165
|
+
return res;
|
|
166
|
+
}
|
|
167
|
+
catch (e) {
|
|
168
|
+
log('[gcalBookingEvents] delete threw', { bookingId, error: String(e) });
|
|
169
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Adapter matching the `createCalendarEvent` dep shape used by create-booking,
|
|
174
|
+
* admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
|
|
175
|
+
* without door hardware can pass this as that dep; it is the only way to cover
|
|
176
|
+
* stripe-webhook's paid path without editing the webhook.
|
|
177
|
+
*/
|
|
178
|
+
export function makeWritebackCreateCalendarEvent(operator, deps = {}) {
|
|
179
|
+
return async (_admin, row) => {
|
|
180
|
+
await writebackBookingCreated(operator, row, deps);
|
|
181
|
+
};
|
|
182
|
+
}
|
package/dist/gcalSync.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export declare function allDayToUtcRange(startDate: string, endDate: string): {
|
|
|
5
5
|
endIso: string;
|
|
6
6
|
};
|
|
7
7
|
export declare function laMidnightUtc(dateStr: string): Date;
|
|
8
|
+
export declare const CS_BOOKING_ID_KEY = "cs_booking_id";
|
|
8
9
|
export interface GcalEventStartEnd {
|
|
9
10
|
dateTime?: string;
|
|
10
11
|
date?: string;
|
package/dist/gcalSync.js
CHANGED
|
@@ -62,6 +62,7 @@ export function laMidnightUtc(dateStr) {
|
|
|
62
62
|
// Fallback (should not happen for real LA dates).
|
|
63
63
|
return new Date(Date.UTC(y, mo - 1, d, 8, 0));
|
|
64
64
|
}
|
|
65
|
+
export const CS_BOOKING_ID_KEY = 'cs_booking_id';
|
|
65
66
|
// True when this event was created by our own booking system and must NOT be
|
|
66
67
|
// re-imported as a blackout (belt & braces: gc_source marker OR known booking
|
|
67
68
|
// google_event_id). Also drops cancelled and transparent (free) events.
|
|
@@ -75,6 +76,10 @@ export function shouldSkipEvent(ev, selfIds) {
|
|
|
75
76
|
const source = ev.extendedProperties?.private?.gc_source;
|
|
76
77
|
if (source === 'gc-connect')
|
|
77
78
|
return true;
|
|
79
|
+
// Events written back by gcalBookingEvents.ts carry cs_booking_id; importing
|
|
80
|
+
// them as blackouts would make every booking block its own slot.
|
|
81
|
+
if (ev.extendedProperties?.private?.[CS_BOOKING_ID_KEY])
|
|
82
|
+
return true;
|
|
78
83
|
if (selfIds.has(ev.id))
|
|
79
84
|
return true;
|
|
80
85
|
return false;
|
package/dist/pricing.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
import type { NoticeConfig } from './businessHours.js';
|
|
2
3
|
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
3
4
|
export interface RoomForPricing {
|
|
4
5
|
id: string;
|
|
@@ -95,8 +96,8 @@ export declare function resolveHalfDayWindow(room: RoomForPricing, dayMode: 'hal
|
|
|
95
96
|
ok: false;
|
|
96
97
|
error: string;
|
|
97
98
|
};
|
|
98
|
-
export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number): Promise<PricingResult>;
|
|
99
|
-
export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number): Promise<PricingResult>;
|
|
99
|
+
export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
|
|
100
|
+
export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
|
|
100
101
|
/**
|
|
101
102
|
* Entry point: dispatches to hourly or day_block based on room.booking_mode.
|
|
102
103
|
* `quote` rooms cannot be booked via checkout.
|
|
@@ -302,5 +303,12 @@ export declare function validateAndPriceForRoom(supabase: SupabaseLike, room: Ro
|
|
|
302
303
|
discount_cents: number;
|
|
303
304
|
rule_type: string | null;
|
|
304
305
|
};
|
|
306
|
+
/**
|
|
307
|
+
* Optional per-operator minimum-notice config (minNoticeBusinessHours /
|
|
308
|
+
* holidays). Public customer paths (create-booking, reschedule-booking)
|
|
309
|
+
* pass it; staff paths (admin-create-booking) omit it and keep the plain
|
|
310
|
+
* 15-minute floor. Unset => exactly the historical 15-minute floor.
|
|
311
|
+
*/
|
|
312
|
+
notice?: NoticeConfig | null;
|
|
305
313
|
}): Promise<PricingResult>;
|
|
306
314
|
export {};
|