@simplelayer/graniteer-core 0.3.15 → 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/bookingAgreementEmail.d.ts +34 -3
- package/dist/bookingAgreementEmail.js +100 -1
- package/dist/bookingEffects.d.ts +2 -0
- package/dist/bookingEffects.js +4 -3
- 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/checkoutSessionParams.d.ts +33 -0
- package/dist/checkoutSessionParams.js +71 -0
- package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
- package/dist/commonsSignedUnpaidCancellation.js +650 -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 +270 -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/supabaseTestFakes.js +7 -1
- package/dist/tenant-config.d.ts +8 -0
- package/dist/tenant-config.js +24 -0
- package/package.json +30 -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 {};
|
|
@@ -8,7 +8,18 @@ import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js
|
|
|
8
8
|
import { sendDunningEmail } from '../dunningEmails.js';
|
|
9
9
|
import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.js';
|
|
10
10
|
import { findBaseItem } from '../membershipSubscriptionItems.js';
|
|
11
|
+
import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
|
|
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';
|
|
11
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) {
|
|
12
23
|
const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
|
|
13
24
|
// No CORS — this is called by Stripe, not the browser.
|
|
14
25
|
return async (req) => {
|
|
@@ -16,11 +27,16 @@ export function createStripeWebhookHandler(config) {
|
|
|
16
27
|
return new Response('Method not allowed', { status: 405 });
|
|
17
28
|
}
|
|
18
29
|
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
19
|
-
const webhookSecret =
|
|
30
|
+
const webhookSecret = connect
|
|
31
|
+
? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
|
|
32
|
+
: Deno.env.get('STRIPE_WEBHOOK_SECRET');
|
|
20
33
|
if (!stripeKey || !webhookSecret) {
|
|
21
34
|
return new Response('Webhook not configured', { status: 500 });
|
|
22
35
|
}
|
|
23
|
-
|
|
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' });
|
|
24
40
|
const signature = req.headers.get('stripe-signature');
|
|
25
41
|
if (!signature)
|
|
26
42
|
return new Response('Missing signature', { status: 400 });
|
|
@@ -34,6 +50,30 @@ export function createStripeWebhookHandler(config) {
|
|
|
34
50
|
return new Response('Invalid signature', { status: 400 });
|
|
35
51
|
}
|
|
36
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
|
+
}
|
|
37
77
|
// Idempotency ledger — dedupe Stripe redeliveries.
|
|
38
78
|
{
|
|
39
79
|
const { error: ledgerErr } = await supabase
|
|
@@ -60,6 +100,101 @@ export function createStripeWebhookHandler(config) {
|
|
|
60
100
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
61
101
|
return data;
|
|
62
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
|
+
}
|
|
63
198
|
// --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
|
|
64
199
|
// create-subscription-checkout and create-day-pass-checkout reserve a
|
|
65
200
|
// coupon_redemptions row at session-creation time and stamp its id onto the
|
|
@@ -1917,6 +2052,14 @@ export function createStripeWebhookHandler(config) {
|
|
|
1917
2052
|
console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
|
|
1918
2053
|
}
|
|
1919
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
|
+
}
|
|
1920
2063
|
break;
|
|
1921
2064
|
}
|
|
1922
2065
|
case 'charge.dispute.created': {
|
|
@@ -1926,6 +2069,31 @@ export function createStripeWebhookHandler(config) {
|
|
|
1926
2069
|
// charge.dispute.closed below, gated on status === 'lost'.
|
|
1927
2070
|
const dispute = event.data.object;
|
|
1928
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
|
+
}
|
|
1929
2097
|
break;
|
|
1930
2098
|
}
|
|
1931
2099
|
case 'charge.dispute.closed': {
|
|
@@ -1990,6 +2158,101 @@ export function createStripeWebhookHandler(config) {
|
|
|
1990
2158
|
// reschedule's new booking to 'expired' (~15-20 min) BEFORE Stripe's own
|
|
1991
2159
|
// session expiry fires, so gating on 'pending' alone skipped the unwind.
|
|
1992
2160
|
if (booking && (booking.status === 'pending' || booking.status === 'expired')) {
|
|
2161
|
+
// Commons lost-booking fix: a stale Checkout Session must not
|
|
2162
|
+
// release a tier-3 booking whose BoldSign agreement is already
|
|
2163
|
+
// `completed` unless the self-serve signed-unpaid policy says
|
|
2164
|
+
// cancel (48h after agreement SENT). Staff-sent deposit agreements
|
|
2165
|
+
// are never policy-eligible and stay protected here.
|
|
2166
|
+
let lookupFailed = false;
|
|
2167
|
+
let completedTier3Agreement = false;
|
|
2168
|
+
let tier3AgreementSentAt = null;
|
|
2169
|
+
let agreementCtx = null;
|
|
2170
|
+
try {
|
|
2171
|
+
const { data: agreementRow, error: agreementErr } = await supabase
|
|
2172
|
+
.from('booking_agreements')
|
|
2173
|
+
.select('status,created_at,sent_by_user_id,sent_by_email')
|
|
2174
|
+
.eq('booking_id', booking.id)
|
|
2175
|
+
.eq('tier', 3)
|
|
2176
|
+
.order('created_at', { ascending: false })
|
|
2177
|
+
.limit(1)
|
|
2178
|
+
.maybeSingle();
|
|
2179
|
+
if (agreementErr)
|
|
2180
|
+
throw agreementErr;
|
|
2181
|
+
const row = agreementRow;
|
|
2182
|
+
completedTier3Agreement = row?.status === 'completed';
|
|
2183
|
+
tier3AgreementSentAt = row?.created_at ?? null;
|
|
2184
|
+
agreementCtx = row
|
|
2185
|
+
? { sent_by_user_id: row.sent_by_user_id, sent_by_email: row.sent_by_email }
|
|
2186
|
+
: null;
|
|
2187
|
+
}
|
|
2188
|
+
catch (e) {
|
|
2189
|
+
console.error('[stripe-webhook] checkout-expired tier-3 agreement lookup failed', e);
|
|
2190
|
+
lookupFailed = true;
|
|
2191
|
+
}
|
|
2192
|
+
const policyEligible = isCommonsSignedUnpaidPolicyEligible(tier3AgreementSentAt, agreementCtx);
|
|
2193
|
+
const signedUnpaidCancelDue = completedTier3Agreement && policyEligible &&
|
|
2194
|
+
isSignedUnpaidCancelDue(tier3AgreementSentAt, Date.now());
|
|
2195
|
+
const completedTier3StillProtected = completedTier3Agreement &&
|
|
2196
|
+
(!policyEligible || !signedUnpaidCancelDue);
|
|
2197
|
+
if (lookupFailed) {
|
|
2198
|
+
const alarm = await logOps(supabase, 'checkout_expired_lookup_failed', {
|
|
2199
|
+
event_type: event.type,
|
|
2200
|
+
}, {
|
|
2201
|
+
severity: 'error',
|
|
2202
|
+
bookingId: booking.id,
|
|
2203
|
+
dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}`,
|
|
2204
|
+
});
|
|
2205
|
+
if (!alarm.ok) {
|
|
2206
|
+
console.error('[stripe-webhook] checkout_expired_lookup_failed ops_event failed to persist', alarm.error);
|
|
2207
|
+
}
|
|
2208
|
+
break;
|
|
2209
|
+
}
|
|
2210
|
+
if (completedTier3StillProtected) {
|
|
2211
|
+
const alarm = await logOps(supabase, 'checkout_expired_hold_live', {
|
|
2212
|
+
event_type: event.type,
|
|
2213
|
+
completed_tier3_agreement: true,
|
|
2214
|
+
}, {
|
|
2215
|
+
severity: 'warning',
|
|
2216
|
+
bookingId: booking.id,
|
|
2217
|
+
dedupeKey: `checkout_expired_hold_live:${booking.id}:${event.id}`,
|
|
2218
|
+
});
|
|
2219
|
+
if (!alarm.ok) {
|
|
2220
|
+
console.error('[stripe-webhook] checkout_expired_hold_live ops_event failed to persist', alarm.error);
|
|
2221
|
+
}
|
|
2222
|
+
break;
|
|
2223
|
+
}
|
|
2224
|
+
if (signedUnpaidCancelDue) {
|
|
2225
|
+
const dryRun = readCommonsSignedPaymentLinkDryRun();
|
|
2226
|
+
const result = await cancelUnpaidSignedBooking({ bookingId: booking.id, dryRun }, { supabase, stripe, busCancel, systemActorEmail });
|
|
2227
|
+
if (!result.ok) {
|
|
2228
|
+
console.error('[stripe-webhook] cancelUnpaidSignedBooking check failed', result.reason);
|
|
2229
|
+
await logOps(supabase, 'checkout_expired_lookup_failed', { event_type: event.type, reason: result.reason }, { severity: 'error', bookingId: booking.id,
|
|
2230
|
+
dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}` }).catch(() => { });
|
|
2231
|
+
}
|
|
2232
|
+
else if (result.action === 'cancelled' && !result.dryRun && result.contactEmail?.trim()) {
|
|
2233
|
+
try {
|
|
2234
|
+
await sendBookingCancelledUnpaidEmailOnce(supabase, {
|
|
2235
|
+
bookingId: booking.id,
|
|
2236
|
+
email: result.contactEmail.trim(),
|
|
2237
|
+
name: result.contactName,
|
|
2238
|
+
roomName: null,
|
|
2239
|
+
bookingDuring: result.bookingDuring,
|
|
2240
|
+
}, {
|
|
2241
|
+
name: siteConfig.operatorName,
|
|
2242
|
+
shortName: siteConfig.operatorShortName,
|
|
2243
|
+
supportEmail: siteConfig.supportEmail,
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
catch (e) {
|
|
2247
|
+
console.error('[stripe-webhook] sendBookingCancelledUnpaidEmailOnce threw', e);
|
|
2248
|
+
await logOps(supabase, 'booking_side_effect_failed', { step: 'sendBookingCancelledUnpaidEmailOnce', message: String(e) }, { severity: 'warning', bookingId: booking.id }).catch(() => { });
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
else if (result.action !== 'cancelled') {
|
|
2252
|
+
console.log('[stripe-webhook] cancelUnpaidSignedBooking no-op', result.action, result.reason);
|
|
2253
|
+
}
|
|
2254
|
+
break;
|
|
2255
|
+
}
|
|
1993
2256
|
if (booking.status === 'pending') {
|
|
1994
2257
|
await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking.id);
|
|
1995
2258
|
}
|
|
@@ -2033,6 +2296,11 @@ export function createStripeWebhookHandler(config) {
|
|
|
2033
2296
|
console.error('[stripe-webhook] coupon_reverse failed', e);
|
|
2034
2297
|
await logOps(supabase, 'coupon_reverse_failed', { message: String(e) }, { severity: 'warning', bookingId: booking.id });
|
|
2035
2298
|
}
|
|
2299
|
+
// Reached only when signedUnpaidCancelDue is false (handled
|
|
2300
|
+
// above, via cancelUnpaidSignedBooking, if true) -- this is
|
|
2301
|
+
// always the GENERIC release (hold genuinely passed, no
|
|
2302
|
+
// tier-3-agreement protection at all), never the signed-unpaid
|
|
2303
|
+
// Commons case.
|
|
2036
2304
|
await logOps(supabase, 'payment_failed', { event_type: event.type }, { severity: 'warning', bookingId: booking.id });
|
|
2037
2305
|
try {
|
|
2038
2306
|
const { data: cancelInfo } = await supabase
|
|
@@ -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 {};
|