@simplelayer/graniteer-core 0.3.19 → 0.3.21-referral.1
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/create-subscription-checkout.js +4 -1
- package/dist/functions/manage-booking.d.ts +6 -0
- package/dist/functions/manage-booking.js +36 -13
- package/dist/functions/reschedule-booking.d.ts +5 -0
- package/dist/functions/reschedule-booking.js +39 -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 +200 -16
- 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/referralCodeLookup.d.ts +1 -0
- package/dist/referralCodeLookup.js +3 -0
- package/dist/referralCredits.d.ts +5 -0
- package/dist/referralCredits.js +5 -0
- package/dist/referralGrant.d.ts +4 -31
- package/dist/referralGrant.js +14 -234
- 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,15 +192,36 @@ 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')
|
|
195
208
|
.update({ status: 'cancelled_credited' })
|
|
196
209
|
.eq('id', O.id)
|
|
197
210
|
.eq('status', 'paid')
|
|
211
|
+
.is('access_revoke_required_at', null)
|
|
198
212
|
.select('id');
|
|
199
213
|
if (cErr || !cancelled || cancelled.length === 0) {
|
|
200
214
|
await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
|
|
215
|
+
if (!cErr) {
|
|
216
|
+
const { data: flagRow } = await admin
|
|
217
|
+
.from('bookings')
|
|
218
|
+
.select('status,access_revoke_required_at')
|
|
219
|
+
.eq('id', O.id)
|
|
220
|
+
.maybeSingle();
|
|
221
|
+
if (flagRow && flagRow.status === 'paid' && flagRow.access_revoke_required_at) {
|
|
222
|
+
return json(409, { error: 'booking_flagged_contact_support' });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
201
225
|
return json(409, { error: 'already_changed' });
|
|
202
226
|
}
|
|
203
227
|
// Issue credit for the amount originally charged, split into up to TWO
|
|
@@ -227,6 +251,8 @@ export async function handle(req, operator, deps) {
|
|
|
227
251
|
}
|
|
228
252
|
}
|
|
229
253
|
}
|
|
254
|
+
// Opt-in, fail-soft: remove the original booking's write-back event.
|
|
255
|
+
await writebackBookingCancelled(operator, room.google_calendar_id, O.id);
|
|
230
256
|
// Best-effort delete of ORIGINAL calendar event.
|
|
231
257
|
try {
|
|
232
258
|
await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
|
|
@@ -491,6 +517,7 @@ export async function handle(req, operator, deps) {
|
|
|
491
517
|
catch (e) {
|
|
492
518
|
await logOps(admin, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: NEW_ID });
|
|
493
519
|
}
|
|
520
|
+
await writebackBookingCreated(operator, eff);
|
|
494
521
|
}
|
|
495
522
|
}
|
|
496
523
|
catch (e) {
|
|
@@ -514,12 +541,22 @@ export async function handle(req, operator, deps) {
|
|
|
514
541
|
await unwindCarriedCoupon('reschedule_missing_stripe_key');
|
|
515
542
|
return json(500, { error: 'Payments not configured' });
|
|
516
543
|
}
|
|
544
|
+
const chargePlan = planBookingCharge(operator, charged);
|
|
545
|
+
if ('error' in chargePlan) {
|
|
546
|
+
await admin.rpc('credit_reservation_release', {
|
|
547
|
+
p_booking_id: NEW_ID,
|
|
548
|
+
p_reason: 'reschedule_payments_misconfigured',
|
|
549
|
+
});
|
|
550
|
+
await unwindCarriedCoupon('reschedule_payments_misconfigured');
|
|
551
|
+
await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'reschedule-booking' }, { severity: 'error', bookingId: NEW_ID });
|
|
552
|
+
return json(500, { error: 'payments_misconfigured' });
|
|
553
|
+
}
|
|
517
554
|
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
518
555
|
const origin = req.headers.get('origin');
|
|
519
556
|
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
520
557
|
const human = formatHumanTime(startUtc, endUtc);
|
|
521
558
|
try {
|
|
522
|
-
const session = await stripe
|
|
559
|
+
const session = await createBookingCheckoutSession(stripe, {
|
|
523
560
|
mode: 'payment',
|
|
524
561
|
customer_email: O.contact_email,
|
|
525
562
|
line_items: [{
|
|
@@ -536,7 +573,7 @@ export async function handle(req, operator, deps) {
|
|
|
536
573
|
cancel_url: token
|
|
537
574
|
? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
|
|
538
575
|
: `${base}/portal/bookings`,
|
|
539
|
-
});
|
|
576
|
+
}, chargePlan);
|
|
540
577
|
await admin
|
|
541
578
|
.from('bookings')
|
|
542
579
|
.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 {};
|
|
@@ -6,11 +6,21 @@ import { isDepositOnly, parseTstzRange } from '../bookingEffects.js';
|
|
|
6
6
|
import { extractDoorAccess } from '../busClient.js';
|
|
7
7
|
import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js';
|
|
8
8
|
import { sendDunningEmail } from '../dunningEmails.js';
|
|
9
|
-
import { recordReferralFailure
|
|
9
|
+
import { recordReferralFailure } from '../referralGrant.js';
|
|
10
|
+
import { escapeLikePattern } from '../referralCodeLookup.js';
|
|
10
11
|
import { findBaseItem } from '../membershipSubscriptionItems.js';
|
|
11
12
|
import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
|
|
12
13
|
import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
|
|
14
|
+
import { errorNameFromUnknown, revokeBookingOrganizerAccessGrants, shouldRevokeOrganizerGrantsOnStripeChargeRefunded, } from './booking-access-revoke.js';
|
|
15
|
+
import { isValidConnectedAccountId } from '../connectBookingCharge.js';
|
|
16
|
+
import { connectAcceptedOpsKind, gateConnectBookingEvent } from '../stripeConnectEvents.js';
|
|
13
17
|
export function createStripeWebhookHandler(config) {
|
|
18
|
+
return buildStripeWebhookHandler(config, null);
|
|
19
|
+
}
|
|
20
|
+
export function createStripeConnectWebhookHandler(config) {
|
|
21
|
+
return buildStripeWebhookHandler(config, { accountId: config.stripeConnectedAccountId });
|
|
22
|
+
}
|
|
23
|
+
function buildStripeWebhookHandler(config, connect) {
|
|
14
24
|
const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
|
|
15
25
|
// No CORS — this is called by Stripe, not the browser.
|
|
16
26
|
return async (req) => {
|
|
@@ -18,11 +28,16 @@ export function createStripeWebhookHandler(config) {
|
|
|
18
28
|
return new Response('Method not allowed', { status: 405 });
|
|
19
29
|
}
|
|
20
30
|
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
21
|
-
const webhookSecret =
|
|
31
|
+
const webhookSecret = connect
|
|
32
|
+
? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
|
|
33
|
+
: Deno.env.get('STRIPE_WEBHOOK_SECRET');
|
|
22
34
|
if (!stripeKey || !webhookSecret) {
|
|
23
35
|
return new Response('Webhook not configured', { status: 500 });
|
|
24
36
|
}
|
|
25
|
-
|
|
37
|
+
if (connect && !isValidConnectedAccountId(connect.accountId)) {
|
|
38
|
+
return new Response('Connect webhook not configured', { status: 500 });
|
|
39
|
+
}
|
|
40
|
+
let stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
26
41
|
const signature = req.headers.get('stripe-signature');
|
|
27
42
|
if (!signature)
|
|
28
43
|
return new Response('Missing signature', { status: 400 });
|
|
@@ -36,6 +51,30 @@ export function createStripeWebhookHandler(config) {
|
|
|
36
51
|
return new Response('Invalid signature', { status: 400 });
|
|
37
52
|
}
|
|
38
53
|
const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'));
|
|
54
|
+
if (connect) {
|
|
55
|
+
const connectAccountId = connect.accountId;
|
|
56
|
+
const gate = gateConnectBookingEvent(event, connectAccountId);
|
|
57
|
+
const ignoredReason = 'reason' in gate ? gate.reason : null;
|
|
58
|
+
await logOps(supabase, ignoredReason ? 'stripe_connect_event_ignored' : connectAcceptedOpsKind(event.type), {
|
|
59
|
+
event_id: event.id,
|
|
60
|
+
event_type: event.type,
|
|
61
|
+
connected_account_id: event.account ?? null,
|
|
62
|
+
...(ignoredReason ? { reason: ignoredReason } : {}),
|
|
63
|
+
}, {
|
|
64
|
+
severity: ignoredReason
|
|
65
|
+
? (ignoredReason === 'account_mismatch' ? 'warning' : 'info')
|
|
66
|
+
: (event.type.startsWith('charge.') ? 'warning' : 'info'),
|
|
67
|
+
}).catch(() => { });
|
|
68
|
+
if (ignoredReason) {
|
|
69
|
+
return new Response(JSON.stringify({ received: true, connect_event: true, ignored: ignoredReason }), {
|
|
70
|
+
headers: { 'Content-Type': 'application/json' }, status: 200,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia', stripeAccount: connectAccountId });
|
|
74
|
+
// Account already verified above; clear it so the platform-only guard below lets this event reach the shared booking logic.
|
|
75
|
+
// Namespace the id so a platform-endpoint ledger row for the same evt_ can never swallow this delivery as a duplicate.
|
|
76
|
+
event = { ...event, id: `connect:${event.id}`, account: undefined };
|
|
77
|
+
}
|
|
39
78
|
// Idempotency ledger — dedupe Stripe redeliveries.
|
|
40
79
|
{
|
|
41
80
|
const { error: ledgerErr } = await supabase
|
|
@@ -62,6 +101,101 @@ export function createStripeWebhookHandler(config) {
|
|
|
62
101
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
63
102
|
return data;
|
|
64
103
|
}
|
|
104
|
+
async function findBookingIdByPaymentIntent(paymentIntentId) {
|
|
105
|
+
const { data: rows, error } = await supabase
|
|
106
|
+
.from('bookings')
|
|
107
|
+
.select('id')
|
|
108
|
+
.eq('stripe_payment_intent', paymentIntentId)
|
|
109
|
+
.limit(2);
|
|
110
|
+
if (error) {
|
|
111
|
+
const code = error.code;
|
|
112
|
+
await logOps(supabase, 'booking_access_revoke_booking_lookup_failed', {
|
|
113
|
+
payment_intent_id: paymentIntentId,
|
|
114
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
115
|
+
}, { severity: 'error', bookingId: null });
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const list = (rows ?? []);
|
|
119
|
+
if (list.length > 1) {
|
|
120
|
+
await logOps(supabase, 'booking_access_revoke_booking_lookup_duplicate_pi', {
|
|
121
|
+
payment_intent_id: paymentIntentId,
|
|
122
|
+
match_count: list.length,
|
|
123
|
+
}, { severity: 'error', bookingId: null });
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
return list[0]?.id ?? null;
|
|
127
|
+
}
|
|
128
|
+
async function releaseStripeEventLedgerForRetry(eventId) {
|
|
129
|
+
const { error } = await supabase.from('stripe_events').delete().eq('event_id', eventId);
|
|
130
|
+
if (error) {
|
|
131
|
+
const code = error.code;
|
|
132
|
+
await logOps(supabase, 'stripe_events_ledger_release_failed', {
|
|
133
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
134
|
+
}, { severity: 'error' });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function webhookResponseMarkerFailedForRetry() {
|
|
138
|
+
return new Response(JSON.stringify({ error: 'booking_access_revoke_marker_failed' }), {
|
|
139
|
+
status: 500,
|
|
140
|
+
headers: { 'Content-Type': 'application/json' },
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
async function maybeRevokeBookingAccessForCharge(charge, reason) {
|
|
144
|
+
const piId = typeof charge.payment_intent === 'string'
|
|
145
|
+
? charge.payment_intent
|
|
146
|
+
: charge.payment_intent?.id ?? null;
|
|
147
|
+
if (!piId)
|
|
148
|
+
return 'skipped';
|
|
149
|
+
let bookingId = null;
|
|
150
|
+
let markerFailed = false;
|
|
151
|
+
try {
|
|
152
|
+
bookingId = await findBookingIdByPaymentIntent(piId);
|
|
153
|
+
if (!bookingId)
|
|
154
|
+
return 'skipped';
|
|
155
|
+
if (connect) {
|
|
156
|
+
// Connect (direct-charge) bookings are refunded outside the app, so
|
|
157
|
+
// nothing cancels the booking: status stays 'paid', the slot stays
|
|
158
|
+
// blocked and door access stays live. Page staff to cancel in admin.
|
|
159
|
+
await logOps(supabase, 'connect_booking_refund_needs_cancel', {
|
|
160
|
+
charge_id: charge.id,
|
|
161
|
+
event_type: event.type,
|
|
162
|
+
reason,
|
|
163
|
+
}, { severity: 'error', bookingId }).catch(() => { });
|
|
164
|
+
}
|
|
165
|
+
const markerAt = new Date().toISOString();
|
|
166
|
+
const { error: markerErr } = await supabase
|
|
167
|
+
.from('bookings')
|
|
168
|
+
.update({ access_revoke_required_at: markerAt })
|
|
169
|
+
.eq('id', bookingId);
|
|
170
|
+
const runInlineRevoke = async () => {
|
|
171
|
+
await revokeBookingOrganizerAccessGrants(supabase, {
|
|
172
|
+
bookingId,
|
|
173
|
+
actingUserId: `system:${systemActorEmail}`,
|
|
174
|
+
reason,
|
|
175
|
+
});
|
|
176
|
+
};
|
|
177
|
+
if (markerErr) {
|
|
178
|
+
markerFailed = true;
|
|
179
|
+
const code = markerErr.code;
|
|
180
|
+
await logOps(supabase, 'booking_access_revoke_marker_failed', {
|
|
181
|
+
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
182
|
+
}, { severity: 'error', bookingId });
|
|
183
|
+
await runInlineRevoke();
|
|
184
|
+
return 'marker_failed';
|
|
185
|
+
}
|
|
186
|
+
await runInlineRevoke();
|
|
187
|
+
return 'ok';
|
|
188
|
+
}
|
|
189
|
+
catch (e) {
|
|
190
|
+
await logOps(supabase, 'booking_access_revoke_step_failed', {
|
|
191
|
+
reason,
|
|
192
|
+
error_name: errorNameFromUnknown(e),
|
|
193
|
+
}, { severity: 'error', bookingId });
|
|
194
|
+
if (markerFailed)
|
|
195
|
+
return 'marker_failed';
|
|
196
|
+
return 'skipped';
|
|
197
|
+
}
|
|
198
|
+
}
|
|
65
199
|
// --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
|
|
66
200
|
// create-subscription-checkout and create-day-pass-checkout reserve a
|
|
67
201
|
// coupon_redemptions row at session-creation time and stamp its id onto the
|
|
@@ -454,7 +588,9 @@ export function createStripeWebhookHandler(config) {
|
|
|
454
588
|
const { data: referrer, error: referrerErr } = await supabase
|
|
455
589
|
.from('memberships')
|
|
456
590
|
.select('id')
|
|
457
|
-
.
|
|
591
|
+
.ilike('referral_code', escapeLikePattern(refCode))
|
|
592
|
+
.order('id', { ascending: true })
|
|
593
|
+
.limit(1)
|
|
458
594
|
.maybeSingle();
|
|
459
595
|
if (referrerErr || !referrer)
|
|
460
596
|
return; // unresolvable code -- silently skip, never block signup
|
|
@@ -1660,7 +1796,32 @@ export function createStripeWebhookHandler(config) {
|
|
|
1660
1796
|
// else-if branch further down -- which handles the actual
|
|
1661
1797
|
// cancelled_* case -- can reuse it without recomputing.
|
|
1662
1798
|
const bkIsCancelled = bkStatus.startsWith('cancelled_');
|
|
1799
|
+
// Connect-only: non-Connect (GC) completions keep the legacy behavior.
|
|
1800
|
+
const sessionIsPaid = !connect ||
|
|
1801
|
+
session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
|
|
1663
1802
|
if (booking &&
|
|
1803
|
+
!sessionIsPaid &&
|
|
1804
|
+
bkStatus !== 'paid' &&
|
|
1805
|
+
bkStatus !== 'deposit_paid' &&
|
|
1806
|
+
!bkIsCancelled) {
|
|
1807
|
+
// Delayed-notification payment methods complete the session with
|
|
1808
|
+
// payment_status 'unpaid'; no money has moved, so the booking must
|
|
1809
|
+
// stay pending. Never silent (project invariant).
|
|
1810
|
+
const unpaid = await logOps(supabase, 'booking_session_completed_unpaid', {
|
|
1811
|
+
session_id: session.id,
|
|
1812
|
+
payment_status: session.payment_status ?? null,
|
|
1813
|
+
booking_status: bkStatus,
|
|
1814
|
+
amount_total: session.amount_total ?? null,
|
|
1815
|
+
}, {
|
|
1816
|
+
severity: 'warning',
|
|
1817
|
+
bookingId: booking.id,
|
|
1818
|
+
dedupeKey: `booking_session_completed_unpaid:${booking.id}:${session.id}`,
|
|
1819
|
+
});
|
|
1820
|
+
if (!unpaid.ok) {
|
|
1821
|
+
console.error('[stripe-webhook] unpaid-completion alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: unpaid.error });
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
else if (booking &&
|
|
1664
1825
|
bkStatus !== 'paid' &&
|
|
1665
1826
|
bkStatus !== 'deposit_paid' &&
|
|
1666
1827
|
!bkIsCancelled) {
|
|
@@ -1919,6 +2080,14 @@ export function createStripeWebhookHandler(config) {
|
|
|
1919
2080
|
console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
|
|
1920
2081
|
}
|
|
1921
2082
|
}
|
|
2083
|
+
// O3(b): organizer grant revoke on refund — gated by CS-GM partial-refund policy.
|
|
2084
|
+
if (shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge)) {
|
|
2085
|
+
const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_refunded');
|
|
2086
|
+
if (markerOutcome === 'marker_failed') {
|
|
2087
|
+
await releaseStripeEventLedgerForRetry(event.id);
|
|
2088
|
+
return webhookResponseMarkerFailedForRetry();
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
1922
2091
|
break;
|
|
1923
2092
|
}
|
|
1924
2093
|
case 'charge.dispute.created': {
|
|
@@ -1928,6 +2097,31 @@ export function createStripeWebhookHandler(config) {
|
|
|
1928
2097
|
// charge.dispute.closed below, gated on status === 'lost'.
|
|
1929
2098
|
const dispute = event.data.object;
|
|
1930
2099
|
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(() => { });
|
|
2100
|
+
// O3(b): chargeback opened — revoke organizer access immediately.
|
|
2101
|
+
let bookingIdForDisputeRevoke = null;
|
|
2102
|
+
try {
|
|
2103
|
+
const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
|
|
2104
|
+
if (chargeId) {
|
|
2105
|
+
const charge = await stripe.charges.retrieve(chargeId);
|
|
2106
|
+
const piId = typeof charge.payment_intent === 'string'
|
|
2107
|
+
? charge.payment_intent
|
|
2108
|
+
: charge.payment_intent?.id ?? null;
|
|
2109
|
+
if (piId) {
|
|
2110
|
+
bookingIdForDisputeRevoke = await findBookingIdByPaymentIntent(piId);
|
|
2111
|
+
}
|
|
2112
|
+
const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_dispute_created');
|
|
2113
|
+
if (markerOutcome === 'marker_failed') {
|
|
2114
|
+
await releaseStripeEventLedgerForRetry(event.id);
|
|
2115
|
+
return webhookResponseMarkerFailedForRetry();
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
catch (e) {
|
|
2120
|
+
await logOps(supabase, 'booking_access_revoke_step_failed', {
|
|
2121
|
+
reason: 'charge_dispute_created',
|
|
2122
|
+
error_name: errorNameFromUnknown(e),
|
|
2123
|
+
}, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
|
|
2124
|
+
}
|
|
1931
2125
|
break;
|
|
1932
2126
|
}
|
|
1933
2127
|
case 'charge.dispute.closed': {
|
|
@@ -2339,18 +2533,8 @@ export function createStripeWebhookHandler(config) {
|
|
|
2339
2533
|
.select('id');
|
|
2340
2534
|
if (fipErr)
|
|
2341
2535
|
console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
|
|
2342
|
-
//
|
|
2343
|
-
//
|
|
2344
|
-
// 'subscription_create' -- every other billing_reason
|
|
2345
|
-
// (subscription_cycle after a 100%-off code, a $0 invoice
|
|
2346
|
-
// covered entirely by account balance, etc.) bypasses the
|
|
2347
|
-
// amount check entirely. Gate the referral grant itself on a
|
|
2348
|
-
// genuinely nonzero amount_paid, separately from
|
|
2349
|
-
// first_invoice_paid_at (which has other consumers and should
|
|
2350
|
-
// keep its existing, broader semantics).
|
|
2351
|
-
if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
|
|
2352
|
-
await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id);
|
|
2353
|
-
}
|
|
2536
|
+
// Referral crediting is NOT done here any more: gc-io's
|
|
2537
|
+
// referral-qualify-daily job pays it 30 days after signup.
|
|
2354
2538
|
}
|
|
2355
2539
|
}
|
|
2356
2540
|
break;
|
|
@@ -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 {};
|