@simplelayer/graniteer-core 0.3.18 → 0.3.19
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/functions/admin-create-booking.d.ts +0 -3
- package/dist/functions/admin-create-booking.js +2 -15
- package/dist/functions/admin-mark-booking-paid.d.ts +1 -6
- package/dist/functions/admin-mark-booking-paid.js +3 -27
- package/dist/functions/admin-request-trial.js +1 -1
- package/dist/functions/booking-availability.d.ts +1 -2
- package/dist/functions/booking-availability.js +5 -14
- package/dist/functions/create-booking.d.ts +0 -5
- package/dist/functions/create-booking.js +4 -22
- package/dist/functions/manage-booking.d.ts +0 -6
- package/dist/functions/manage-booking.js +12 -29
- package/dist/functions/reschedule-booking.d.ts +0 -5
- package/dist/functions/reschedule-booking.js +2 -28
- package/dist/functions/space-availability-range.d.ts +1 -2
- package/dist/functions/space-availability-range.js +1 -8
- package/dist/functions/stripe-webhook.d.ts +0 -4
- package/dist/functions/stripe-webhook.js +2 -168
- package/dist/functions/sync-gcal-blackouts.js +1 -1
- package/dist/gcalSync.d.ts +0 -1
- package/dist/gcalSync.js +0 -5
- package/dist/pricing.d.ts +2 -10
- package/dist/pricing.js +9 -14
- package/package.json +2 -26
- package/dist/bookingSource.d.ts +0 -2
- package/dist/bookingSource.js +0 -11
- package/dist/businessHours.d.ts +0 -11
- package/dist/businessHours.js +0 -55
- package/dist/connectBookingCharge.d.ts +0 -49
- package/dist/connectBookingCharge.js +0 -68
- package/dist/functions/booking-access-revoke-backstop.d.ts +0 -11
- package/dist/functions/booking-access-revoke-backstop.js +0 -121
- package/dist/functions/booking-access-revoke-door-state.d.ts +0 -22
- package/dist/functions/booking-access-revoke-door-state.js +0 -61
- package/dist/functions/booking-access-revoke.d.ts +0 -35
- package/dist/functions/booking-access-revoke.js +0 -279
- package/dist/gcalBookingEvents.d.ts +0 -59
- package/dist/gcalBookingEvents.js +0 -182
- package/dist/stripeConnectEvents.d.ts +0 -11
- package/dist/stripeConnectEvents.js +0 -37
- package/dist/tenant-config.d.ts +0 -8
- package/dist/tenant-config.js +0 -24
|
@@ -10,16 +10,7 @@ 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';
|
|
16
13
|
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) {
|
|
23
14
|
const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
|
|
24
15
|
// No CORS — this is called by Stripe, not the browser.
|
|
25
16
|
return async (req) => {
|
|
@@ -27,16 +18,11 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
27
18
|
return new Response('Method not allowed', { status: 405 });
|
|
28
19
|
}
|
|
29
20
|
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
30
|
-
const webhookSecret =
|
|
31
|
-
? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
|
|
32
|
-
: Deno.env.get('STRIPE_WEBHOOK_SECRET');
|
|
21
|
+
const webhookSecret = Deno.env.get('STRIPE_WEBHOOK_SECRET');
|
|
33
22
|
if (!stripeKey || !webhookSecret) {
|
|
34
23
|
return new Response('Webhook not configured', { status: 500 });
|
|
35
24
|
}
|
|
36
|
-
|
|
37
|
-
return new Response('Connect webhook not configured', { status: 500 });
|
|
38
|
-
}
|
|
39
|
-
let stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
25
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
|
|
40
26
|
const signature = req.headers.get('stripe-signature');
|
|
41
27
|
if (!signature)
|
|
42
28
|
return new Response('Missing signature', { status: 400 });
|
|
@@ -50,30 +36,6 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
50
36
|
return new Response('Invalid signature', { status: 400 });
|
|
51
37
|
}
|
|
52
38
|
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
|
-
}
|
|
77
39
|
// Idempotency ledger — dedupe Stripe redeliveries.
|
|
78
40
|
{
|
|
79
41
|
const { error: ledgerErr } = await supabase
|
|
@@ -100,101 +62,6 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
100
62
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
101
63
|
return data;
|
|
102
64
|
}
|
|
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
|
-
}
|
|
198
65
|
// --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
|
|
199
66
|
// create-subscription-checkout and create-day-pass-checkout reserve a
|
|
200
67
|
// coupon_redemptions row at session-creation time and stamp its id onto the
|
|
@@ -2052,14 +1919,6 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2052
1919
|
console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
|
|
2053
1920
|
}
|
|
2054
1921
|
}
|
|
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
|
-
}
|
|
2063
1922
|
break;
|
|
2064
1923
|
}
|
|
2065
1924
|
case 'charge.dispute.created': {
|
|
@@ -2069,31 +1928,6 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2069
1928
|
// charge.dispute.closed below, gated on status === 'lost'.
|
|
2070
1929
|
const dispute = event.data.object;
|
|
2071
1930
|
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
|
-
}
|
|
2097
1931
|
break;
|
|
2098
1932
|
}
|
|
2099
1933
|
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')) {
|
|
177
177
|
skippedSelf++;
|
|
178
178
|
}
|
|
179
179
|
continue;
|
package/dist/gcalSync.d.ts
CHANGED
|
@@ -5,7 +5,6 @@ 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";
|
|
9
8
|
export interface GcalEventStartEnd {
|
|
10
9
|
dateTime?: string;
|
|
11
10
|
date?: string;
|
package/dist/gcalSync.js
CHANGED
|
@@ -62,7 +62,6 @@ 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';
|
|
66
65
|
// True when this event was created by our own booking system and must NOT be
|
|
67
66
|
// re-imported as a blackout (belt & braces: gc_source marker OR known booking
|
|
68
67
|
// google_event_id). Also drops cancelled and transparent (free) events.
|
|
@@ -76,10 +75,6 @@ export function shouldSkipEvent(ev, selfIds) {
|
|
|
76
75
|
const source = ev.extendedProperties?.private?.gc_source;
|
|
77
76
|
if (source === 'gc-connect')
|
|
78
77
|
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;
|
|
83
78
|
if (selfIds.has(ev.id))
|
|
84
79
|
return true;
|
|
85
80
|
return false;
|
package/dist/pricing.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
-
import type { NoticeConfig } from './businessHours.js';
|
|
3
2
|
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
4
3
|
export interface RoomForPricing {
|
|
5
4
|
id: string;
|
|
@@ -96,8 +95,8 @@ export declare function resolveHalfDayWindow(room: RoomForPricing, dayMode: 'hal
|
|
|
96
95
|
ok: false;
|
|
97
96
|
error: string;
|
|
98
97
|
};
|
|
99
|
-
export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number
|
|
100
|
-
export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number
|
|
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>;
|
|
101
100
|
/**
|
|
102
101
|
* Entry point: dispatches to hourly or day_block based on room.booking_mode.
|
|
103
102
|
* `quote` rooms cannot be booked via checkout.
|
|
@@ -303,12 +302,5 @@ export declare function validateAndPriceForRoom(supabase: SupabaseLike, room: Ro
|
|
|
303
302
|
discount_cents: number;
|
|
304
303
|
rule_type: string | null;
|
|
305
304
|
};
|
|
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;
|
|
313
305
|
}): Promise<PricingResult>;
|
|
314
306
|
export {};
|
package/dist/pricing.js
CHANGED
|
@@ -6,16 +6,11 @@
|
|
|
6
6
|
// rangeLiteral } describing a fully-validated booking window.
|
|
7
7
|
import { getBusyRangesDetailed } from './availability.js';
|
|
8
8
|
import { logOps } from './ops.js';
|
|
9
|
-
import { DEFAULT_MIN_NOTICE_MS, earliestBookingStartMs, minNoticeErrorMessage } from './businessHours.js';
|
|
10
9
|
// Minimum lead time required between "now" and a booking's start time.
|
|
11
10
|
// Mirrors the same purpose as GHL's `allowBookingAfter` setting on the tour
|
|
12
11
|
// calendars, but for meeting rooms — previously there was no floor at all
|
|
13
12
|
// beyond "not literally in the past" (see 2026-08-25 same-day-tour review).
|
|
14
|
-
const MIN_BOOKING_NOTICE_MS =
|
|
15
|
-
// Earliest allowed start. Unset notice config => exactly now + 15 minutes.
|
|
16
|
-
function noticeFloorMs(nowMs, notice) {
|
|
17
|
-
return notice ? earliestBookingStartMs(nowMs, notice) : nowMs + MIN_BOOKING_NOTICE_MS;
|
|
18
|
-
}
|
|
13
|
+
const MIN_BOOKING_NOTICE_MS = 15 * 60 * 1000;
|
|
19
14
|
function laOffsetHours(atUtc) {
|
|
20
15
|
const parts = new Intl.DateTimeFormat('en-US', {
|
|
21
16
|
timeZone: 'America/Los_Angeles',
|
|
@@ -131,7 +126,7 @@ export function resolveHalfDayWindow(room, dayMode, wd, dateStr, openUtc, closeU
|
|
|
131
126
|
endUtc: laWallToUtc(y, mo, d, Math.floor(endMin / 60), endMin % 60),
|
|
132
127
|
};
|
|
133
128
|
}
|
|
134
|
-
export async function validateAndPriceDayBlock(supabase, room, input, nowMs
|
|
129
|
+
export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
|
|
135
130
|
const { date, day_mode } = input;
|
|
136
131
|
if (!date || !day_mode)
|
|
137
132
|
return { ok: false, status: 400, error: 'date and day_mode are required for this room' };
|
|
@@ -170,8 +165,8 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs, not
|
|
|
170
165
|
endUtc = win.endUtc;
|
|
171
166
|
price_cents = room.half_day_cents;
|
|
172
167
|
}
|
|
173
|
-
if (startUtc.getTime() <
|
|
174
|
-
return { ok: false, status: 400, error:
|
|
168
|
+
if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
|
|
169
|
+
return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
|
|
175
170
|
}
|
|
176
171
|
if (price_cents <= 0)
|
|
177
172
|
return { ok: false, status: 400, error: 'invalid price' };
|
|
@@ -184,7 +179,7 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs, not
|
|
|
184
179
|
list_rule_type: null,
|
|
185
180
|
};
|
|
186
181
|
}
|
|
187
|
-
export async function validateAndPriceHourly(supabase, room, input, nowMs
|
|
182
|
+
export async function validateAndPriceHourly(supabase, room, input, nowMs) {
|
|
188
183
|
const { start, end } = input;
|
|
189
184
|
if (!start || !end)
|
|
190
185
|
return { ok: false, status: 400, error: 'start and end are required' };
|
|
@@ -195,8 +190,8 @@ export async function validateAndPriceHourly(supabase, room, input, nowMs, notic
|
|
|
195
190
|
}
|
|
196
191
|
if (!(startUtc < endUtc))
|
|
197
192
|
return { ok: false, status: 400, error: 'end must be after start' };
|
|
198
|
-
if (startUtc.getTime() <
|
|
199
|
-
return { ok: false, status: 400, error:
|
|
193
|
+
if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
|
|
194
|
+
return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
|
|
200
195
|
}
|
|
201
196
|
if (startUtc.getUTCSeconds() !== 0 || startUtc.getUTCMilliseconds() !== 0 ||
|
|
202
197
|
endUtc.getUTCSeconds() !== 0 || endUtc.getUTCMilliseconds() !== 0 ||
|
|
@@ -704,8 +699,8 @@ export async function validateAndPriceForRoom(supabase, room, input, nowMs, opts
|
|
|
704
699
|
}
|
|
705
700
|
const isDayBlock = room.booking_mode === 'day_block';
|
|
706
701
|
const price = () => (isDayBlock
|
|
707
|
-
? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs
|
|
708
|
-
: validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs
|
|
702
|
+
? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs)
|
|
703
|
+
: validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs));
|
|
709
704
|
const baseRaw = await price();
|
|
710
705
|
if (!baseRaw.ok)
|
|
711
706
|
return baseRaw;
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplelayer/graniteer-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.19",
|
|
4
4
|
"description": "Shared platform core for Graniteer",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"test": "deno test --
|
|
8
|
+
"test": "deno test --no-check --node-modules-dir=auto --allow-env --allow-net --allow-read src",
|
|
9
9
|
"build": "node scripts/build.mjs",
|
|
10
10
|
"verify:dist": "node scripts/verify-dist.mjs",
|
|
11
11
|
"prepack": "npm run build && npm run verify:dist",
|
|
@@ -157,26 +157,6 @@
|
|
|
157
157
|
"types": "./dist/email-templates/signup.d.ts",
|
|
158
158
|
"default": "./dist/email-templates/signup.js"
|
|
159
159
|
},
|
|
160
|
-
"./bookingSource": {
|
|
161
|
-
"types": "./dist/bookingSource.d.ts",
|
|
162
|
-
"default": "./dist/bookingSource.js"
|
|
163
|
-
},
|
|
164
|
-
"./businessHours": {
|
|
165
|
-
"types": "./dist/businessHours.d.ts",
|
|
166
|
-
"default": "./dist/businessHours.js"
|
|
167
|
-
},
|
|
168
|
-
"./gcalBookingEvents": {
|
|
169
|
-
"types": "./dist/gcalBookingEvents.d.ts",
|
|
170
|
-
"default": "./dist/gcalBookingEvents.js"
|
|
171
|
-
},
|
|
172
|
-
"./connectBookingCharge": {
|
|
173
|
-
"types": "./dist/connectBookingCharge.d.ts",
|
|
174
|
-
"default": "./dist/connectBookingCharge.js"
|
|
175
|
-
},
|
|
176
|
-
"./stripeConnectEvents": {
|
|
177
|
-
"types": "./dist/stripeConnectEvents.d.ts",
|
|
178
|
-
"default": "./dist/stripeConnectEvents.js"
|
|
179
|
-
},
|
|
180
160
|
"./gcalSync": {
|
|
181
161
|
"types": "./dist/gcalSync.d.ts",
|
|
182
162
|
"default": "./dist/gcalSync.js"
|
|
@@ -417,10 +397,6 @@
|
|
|
417
397
|
"types": "./dist/functions/boldsign-sender-identity.d.ts",
|
|
418
398
|
"default": "./dist/functions/boldsign-sender-identity.js"
|
|
419
399
|
},
|
|
420
|
-
"./functions/booking-access-revoke-backstop": {
|
|
421
|
-
"types": "./dist/functions/booking-access-revoke-backstop.d.ts",
|
|
422
|
-
"default": "./dist/functions/booking-access-revoke-backstop.js"
|
|
423
|
-
},
|
|
424
400
|
"./functions/booking-availability": {
|
|
425
401
|
"types": "./dist/functions/booking-availability.d.ts",
|
|
426
402
|
"default": "./dist/functions/booking-availability.js"
|
package/dist/bookingSource.d.ts
DELETED
package/dist/bookingSource.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export const MAX_BOOKING_SOURCE_LENGTH = 40;
|
|
2
|
-
export function sanitizeBookingSource(raw) {
|
|
3
|
-
if (typeof raw !== 'string')
|
|
4
|
-
return null;
|
|
5
|
-
const v = raw.trim().toLowerCase();
|
|
6
|
-
if (v.length === 0 || v.length > MAX_BOOKING_SOURCE_LENGTH)
|
|
7
|
-
return null;
|
|
8
|
-
if (!/^[a-z0-9_-]+$/.test(v))
|
|
9
|
-
return null;
|
|
10
|
-
return v;
|
|
11
|
-
}
|
package/dist/businessHours.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export declare const DEFAULT_MIN_NOTICE_MS: number;
|
|
2
|
-
export interface NoticeConfig {
|
|
3
|
-
minNoticeBusinessHours?: number | null;
|
|
4
|
-
holidays?: string[] | null;
|
|
5
|
-
}
|
|
6
|
-
export declare function addBusinessHours(fromUtc: Date, hours: number, holidays?: readonly string[]): Date;
|
|
7
|
-
export declare function hasBusinessHoursNotice(cfg?: NoticeConfig | null): cfg is NoticeConfig & {
|
|
8
|
-
minNoticeBusinessHours: number;
|
|
9
|
-
};
|
|
10
|
-
export declare function earliestBookingStartMs(nowMs: number, cfg?: NoticeConfig | null): number;
|
|
11
|
-
export declare function minNoticeErrorMessage(nowMs: number, cfg?: NoticeConfig | null): string;
|
package/dist/businessHours.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { laMidnightUtc } from './gcalSync.js';
|
|
2
|
-
import { addDaysStr, pacificDateStr } from './pacificDate.js';
|
|
3
|
-
export const DEFAULT_MIN_NOTICE_MS = 15 * 60 * 1000;
|
|
4
|
-
const HOUR_MS = 60 * 60 * 1000;
|
|
5
|
-
const MAX_DAYS_WALKED = 3700;
|
|
6
|
-
function isBusinessDay(dateStr, holidays) {
|
|
7
|
-
if (holidays.has(dateStr))
|
|
8
|
-
return false;
|
|
9
|
-
const [y, m, d] = dateStr.split('-').map(Number);
|
|
10
|
-
const wd = new Date(Date.UTC(y, m - 1, d, 12)).getUTCDay();
|
|
11
|
-
return wd >= 1 && wd <= 5;
|
|
12
|
-
}
|
|
13
|
-
export function addBusinessHours(fromUtc, hours, holidays = []) {
|
|
14
|
-
if (!Number.isFinite(hours) || hours <= 0)
|
|
15
|
-
return new Date(fromUtc.getTime());
|
|
16
|
-
const holidaySet = new Set(holidays);
|
|
17
|
-
let remaining = hours * HOUR_MS;
|
|
18
|
-
let cursor = fromUtc.getTime();
|
|
19
|
-
let day = pacificDateStr(new Date(cursor));
|
|
20
|
-
for (let i = 0; i < MAX_DAYS_WALKED; i++) {
|
|
21
|
-
const nextDay = addDaysStr(day, 1);
|
|
22
|
-
const nextMidnight = laMidnightUtc(nextDay).getTime();
|
|
23
|
-
if (isBusinessDay(day, holidaySet)) {
|
|
24
|
-
const available = nextMidnight - cursor;
|
|
25
|
-
if (remaining <= available)
|
|
26
|
-
return new Date(cursor + remaining);
|
|
27
|
-
remaining -= available;
|
|
28
|
-
}
|
|
29
|
-
cursor = nextMidnight;
|
|
30
|
-
day = nextDay;
|
|
31
|
-
}
|
|
32
|
-
return new Date(cursor + remaining);
|
|
33
|
-
}
|
|
34
|
-
export function hasBusinessHoursNotice(cfg) {
|
|
35
|
-
return typeof cfg?.minNoticeBusinessHours === 'number' &&
|
|
36
|
-
Number.isFinite(cfg.minNoticeBusinessHours) && cfg.minNoticeBusinessHours > 0;
|
|
37
|
-
}
|
|
38
|
-
export function earliestBookingStartMs(nowMs, cfg) {
|
|
39
|
-
const floor = nowMs + DEFAULT_MIN_NOTICE_MS;
|
|
40
|
-
if (!hasBusinessHoursNotice(cfg))
|
|
41
|
-
return floor;
|
|
42
|
-
const bh = addBusinessHours(new Date(nowMs), cfg.minNoticeBusinessHours, cfg.holidays ?? []).getTime();
|
|
43
|
-
return Math.max(floor, bh);
|
|
44
|
-
}
|
|
45
|
-
export function minNoticeErrorMessage(nowMs, cfg) {
|
|
46
|
-
if (!hasBusinessHoursNotice(cfg)) {
|
|
47
|
-
return 'Bookings need at least 15 minutes notice — please choose a later start time.';
|
|
48
|
-
}
|
|
49
|
-
const earliest = new Intl.DateTimeFormat('en-US', {
|
|
50
|
-
timeZone: 'America/Los_Angeles',
|
|
51
|
-
weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
|
|
52
|
-
}).format(new Date(earliestBookingStartMs(nowMs, cfg)));
|
|
53
|
-
return `Bookings need at least ${cfg.minNoticeBusinessHours} business hours notice ` +
|
|
54
|
-
`(Monday–Friday, excluding holidays). The earliest available start is ${earliest} Pacific time.`;
|
|
55
|
-
}
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import type Stripe from 'stripe';
|
|
2
|
-
export interface ConnectBookingOperator {
|
|
3
|
-
stripeConnectedAccountId?: string | null;
|
|
4
|
-
stripeApplicationFeePercent?: number | null;
|
|
5
|
-
}
|
|
6
|
-
export declare const CONNECTED_ACCOUNT_ID_RE: RegExp;
|
|
7
|
-
export type ConnectConfigError = 'connect_account_invalid' | 'connect_fee_invalid' | 'connect_charge_invalid' | 'connect_fee_exceeds_charge';
|
|
8
|
-
export type ConnectedAccountResolution = {
|
|
9
|
-
ok: true;
|
|
10
|
-
accountId: string | null;
|
|
11
|
-
} | {
|
|
12
|
-
ok: false;
|
|
13
|
-
error: 'connect_account_invalid';
|
|
14
|
-
};
|
|
15
|
-
export type BookingChargePlan = {
|
|
16
|
-
ok: true;
|
|
17
|
-
connected: false;
|
|
18
|
-
} | {
|
|
19
|
-
ok: true;
|
|
20
|
-
connected: true;
|
|
21
|
-
accountId: string;
|
|
22
|
-
applicationFeeCents: number;
|
|
23
|
-
} | {
|
|
24
|
-
ok: false;
|
|
25
|
-
error: ConnectConfigError;
|
|
26
|
-
};
|
|
27
|
-
export declare function isValidConnectedAccountId(v: unknown): v is string;
|
|
28
|
-
export interface ConnectTenantEnv {
|
|
29
|
-
connectTenant: boolean;
|
|
30
|
-
}
|
|
31
|
-
export declare function defaultConnectTenantEnv(): ConnectTenantEnv;
|
|
32
|
-
export declare function resolveConnectedAccount(operator: ConnectBookingOperator | null | undefined, env?: ConnectTenantEnv): ConnectedAccountResolution;
|
|
33
|
-
export declare function planBookingCharge(operator: ConnectBookingOperator | null | undefined, chargeCents: number, env?: ConnectTenantEnv): BookingChargePlan;
|
|
34
|
-
export declare function applyConnectToSessionParams(params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Stripe.Checkout.SessionCreateParams;
|
|
35
|
-
export declare function stripeAccountRequestOptions(accountId: string | null | undefined): {
|
|
36
|
-
stripeAccount: string;
|
|
37
|
-
} | undefined;
|
|
38
|
-
type SessionCreator = {
|
|
39
|
-
checkout: {
|
|
40
|
-
sessions: {
|
|
41
|
-
create: (params: Stripe.Checkout.SessionCreateParams, options?: {
|
|
42
|
-
stripeAccount: string;
|
|
43
|
-
}) => Promise<Stripe.Checkout.Session>;
|
|
44
|
-
};
|
|
45
|
-
};
|
|
46
|
-
};
|
|
47
|
-
export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
|
|
48
|
-
export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
|
|
49
|
-
export {};
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
// Stripe Connect DIRECT charges for room bookings. Opt-in per operator: with no
|
|
2
|
-
// `stripeConnectedAccountId` (undefined/null) every helper here is a no-op and
|
|
3
|
-
// the caller's Stripe request is byte-identical to the pre-Connect one.
|
|
4
|
-
import { computeApplicationFeeCents } from './checkoutSessionParams.js';
|
|
5
|
-
export const CONNECTED_ACCOUNT_ID_RE = /^acct_[A-Za-z0-9]+$/;
|
|
6
|
-
export function isValidConnectedAccountId(v) {
|
|
7
|
-
return typeof v === 'string' && CONNECTED_ACCOUNT_ID_RE.test(v);
|
|
8
|
-
}
|
|
9
|
-
// A project that has STRIPE_CONNECT_WEBHOOK_SECRET set is a Connect tenant:
|
|
10
|
-
// an omitted account id there is a wiring bug and must never fall back to the
|
|
11
|
-
// platform account. GC never sets that secret, so its behavior is unchanged.
|
|
12
|
-
export function defaultConnectTenantEnv() {
|
|
13
|
-
return { connectTenant: !!Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET') };
|
|
14
|
-
}
|
|
15
|
-
export function resolveConnectedAccount(operator, env = defaultConnectTenantEnv()) {
|
|
16
|
-
const raw = operator?.stripeConnectedAccountId;
|
|
17
|
-
if (raw === undefined || raw === null) {
|
|
18
|
-
return env.connectTenant ? { ok: false, error: 'connect_account_invalid' } : { ok: true, accountId: null };
|
|
19
|
-
}
|
|
20
|
-
if (!isValidConnectedAccountId(raw))
|
|
21
|
-
return { ok: false, error: 'connect_account_invalid' };
|
|
22
|
-
return { ok: true, accountId: raw };
|
|
23
|
-
}
|
|
24
|
-
export function planBookingCharge(operator, chargeCents, env = defaultConnectTenantEnv()) {
|
|
25
|
-
const account = resolveConnectedAccount(operator, env);
|
|
26
|
-
if ('error' in account)
|
|
27
|
-
return { ok: false, error: account.error };
|
|
28
|
-
if (account.accountId === null)
|
|
29
|
-
return { ok: true, connected: false };
|
|
30
|
-
const pct = operator?.stripeApplicationFeePercent;
|
|
31
|
-
const hasFee = !(pct === undefined || pct === null || pct === 0);
|
|
32
|
-
// Exclusive upper bound: a 100% fee would leave the connected account paying
|
|
33
|
-
// Stripe's processing fee on every booking.
|
|
34
|
-
if (hasFee && (typeof pct !== 'number' || !Number.isFinite(pct) || pct <= 0 || pct >= 100)) {
|
|
35
|
-
return { ok: false, error: 'connect_fee_invalid' };
|
|
36
|
-
}
|
|
37
|
-
if (!Number.isSafeInteger(chargeCents) || chargeCents <= 0) {
|
|
38
|
-
return { ok: false, error: 'connect_charge_invalid' };
|
|
39
|
-
}
|
|
40
|
-
const fee = hasFee ? computeApplicationFeeCents(chargeCents, pct) : 0;
|
|
41
|
-
if (!Number.isSafeInteger(fee) || fee < 0 || fee > chargeCents) {
|
|
42
|
-
return { ok: false, error: 'connect_fee_exceeds_charge' };
|
|
43
|
-
}
|
|
44
|
-
return { ok: true, connected: true, accountId: account.accountId, applicationFeeCents: fee };
|
|
45
|
-
}
|
|
46
|
-
export function applyConnectToSessionParams(params, plan) {
|
|
47
|
-
if (!plan.ok || !plan.connected || plan.applicationFeeCents <= 0)
|
|
48
|
-
return params;
|
|
49
|
-
return {
|
|
50
|
-
...params,
|
|
51
|
-
payment_intent_data: {
|
|
52
|
-
...(params.payment_intent_data ?? {}),
|
|
53
|
-
application_fee_amount: plan.applicationFeeCents,
|
|
54
|
-
},
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
export function stripeAccountRequestOptions(accountId) {
|
|
58
|
-
return accountId ? { stripeAccount: accountId } : undefined;
|
|
59
|
-
}
|
|
60
|
-
export function createBookingCheckoutSession(stripe, params, plan) {
|
|
61
|
-
if ('error' in plan) {
|
|
62
|
-
return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
|
|
63
|
-
}
|
|
64
|
-
if (!plan.connected)
|
|
65
|
-
return stripe.checkout.sessions.create(params);
|
|
66
|
-
return stripe.checkout.sessions.create(applyConnectToSessionParams(params, plan), { stripeAccount: plan.accountId });
|
|
67
|
-
}
|
|
68
|
-
export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Bookings whose organizer grants the backstop may revoke via terminal booking.status.
|
|
3
|
-
* Refund/dispute paths keep status `paid`; those bookings are selected via access_revoke_required_at.
|
|
4
|
-
*/
|
|
5
|
-
export declare const BACKSTOP_BOOKING_STATUSES: readonly ["cancelled_credited", "cancelled_forfeited", "cancelled_refunded"];
|
|
6
|
-
export declare function bookingStatusRequiresBackstopRevoke(status: string): boolean;
|
|
7
|
-
export declare function bookingRowRequiresBackstopRevoke(booking: {
|
|
8
|
-
status?: string;
|
|
9
|
-
access_revoke_required_at?: string | null;
|
|
10
|
-
}): boolean;
|
|
11
|
-
export declare function handle(req: Request): Promise<Response>;
|