@simplelayer/graniteer-core 0.0.1 → 0.1.2
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/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Monthly meeting-room credit for STAFF-created bookings (admin-create-booking).
|
|
2
|
+
//
|
|
3
|
+
// This is the same period-based credit pattern the member self-serve path uses
|
|
4
|
+
// (create-booking/index.ts): credit_get_or_create_period -> Math.min(net, avail)
|
|
5
|
+
// -> credit_hold, with credit_consume only once the booking is actually paid.
|
|
6
|
+
// It lives here rather than inline so the money math is covered by
|
|
7
|
+
// adminBookingCredit.test.ts with a fake Stripe + fake Supabase — the same
|
|
8
|
+
// no-network approach checkoutCoupon.test.ts uses.
|
|
9
|
+
//
|
|
10
|
+
// The staff path only ever reaches this module when the operator explicitly
|
|
11
|
+
// attached a membership. A staff booking with no membership attached keeps its
|
|
12
|
+
// original free-form behavior and never touches any of this.
|
|
13
|
+
|
|
14
|
+
// These clients are typed STRUCTURALLY rather than as
|
|
15
|
+
// `ReturnType<typeof createClient>`. A real `createClient(url, key, opts)` call
|
|
16
|
+
// infers `SupabaseClient<any, "public", "public", any, any>`, which is not
|
|
17
|
+
// assignable to the un-inferred `ReturnType<...>` default — that mismatch is
|
|
18
|
+
// the source of the SupabaseClient variance errors the older shared modules
|
|
19
|
+
// still produce under `deno check`. Structural types sidestep it, and they let
|
|
20
|
+
// a test hand in a plain object with no client library at all.
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Minimal RPC surface these helpers need.
|
|
24
|
+
* `PromiseLike`, not `Promise`: supabase-js returns a thenable query builder
|
|
25
|
+
* from .rpc(), which is awaitable but is not a Promise instance.
|
|
26
|
+
*/
|
|
27
|
+
export interface CreditRpcClient {
|
|
28
|
+
// deno-lint-ignore no-explicit-any
|
|
29
|
+
rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: any; error: any }>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Minimal single-row read surface: .from(t).select(c).eq(c, v).maybeSingle().
|
|
34
|
+
* The builder is deliberately `any` — spelling the chain out structurally makes
|
|
35
|
+
* TypeScript try to unify it with PostgREST's recursive generic builder and it
|
|
36
|
+
* gives up with TS2589 ("type instantiation is excessively deep").
|
|
37
|
+
*/
|
|
38
|
+
export interface RowReadClient {
|
|
39
|
+
// deno-lint-ignore no-explicit-any
|
|
40
|
+
from(table: string): any;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Stripe rejects charges under $0.50. */
|
|
44
|
+
export const STRIPE_MIN_CHARGE_CENTS = 50;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Spendable balance on a credit_periods row:
|
|
48
|
+
* granted - consumed - held - expired, floored at 0.
|
|
49
|
+
*/
|
|
50
|
+
export function availableCredit(period: unknown): number {
|
|
51
|
+
// deno-lint-ignore no-explicit-any
|
|
52
|
+
const pr = period as any;
|
|
53
|
+
return Math.max(
|
|
54
|
+
0,
|
|
55
|
+
(pr?.granted_cents ?? 0) - (pr?.consumed_cents ?? 0)
|
|
56
|
+
- (pr?.held_cents ?? 0) - (pr?.expired_cents ?? 0),
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Places a credit hold for at most `net` cents against `membershipId`.
|
|
62
|
+
*
|
|
63
|
+
* Returns the cents actually held (0 when the member has no balance, or when
|
|
64
|
+
* any RPC failed). Never throws and never fails the booking — an unavailable
|
|
65
|
+
* credit ledger means the member simply pays full price, exactly as in
|
|
66
|
+
* create-booking.
|
|
67
|
+
*/
|
|
68
|
+
export async function holdMemberCredit(
|
|
69
|
+
supabase: CreditRpcClient,
|
|
70
|
+
opts: { membershipId: string; bookingId: string; net: number },
|
|
71
|
+
): Promise<number> {
|
|
72
|
+
const { membershipId, bookingId, net } = opts;
|
|
73
|
+
try {
|
|
74
|
+
const { data: period, error: perErr } = await supabase.rpc(
|
|
75
|
+
'credit_get_or_create_period', { p_membership_id: membershipId },
|
|
76
|
+
);
|
|
77
|
+
if (perErr) throw perErr;
|
|
78
|
+
const want = Math.min(net, availableCredit(period));
|
|
79
|
+
if (want <= 0) return 0;
|
|
80
|
+
const { error: holdErr } = await supabase.rpc('credit_hold', {
|
|
81
|
+
p_membership_id: membershipId,
|
|
82
|
+
p_booking_id: bookingId,
|
|
83
|
+
p_amount_cents: want,
|
|
84
|
+
p_idempotency_key: `hold:${bookingId}`,
|
|
85
|
+
});
|
|
86
|
+
if (holdErr) throw holdErr;
|
|
87
|
+
return want;
|
|
88
|
+
} catch (e) {
|
|
89
|
+
console.warn('[admin-create-booking] credit hold skipped', String(e));
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Finalizes an open hold. Returns an error message, or null on success. */
|
|
95
|
+
export async function consumeMemberCredit(
|
|
96
|
+
supabase: CreditRpcClient,
|
|
97
|
+
bookingId: string,
|
|
98
|
+
): Promise<string | null> {
|
|
99
|
+
const { error } = await supabase.rpc('credit_consume', {
|
|
100
|
+
p_booking_id: bookingId,
|
|
101
|
+
p_idempotency_key: `consume:${bookingId}`,
|
|
102
|
+
});
|
|
103
|
+
if (!error) return null;
|
|
104
|
+
return typeof error === 'object' && error && 'message' in error
|
|
105
|
+
// deno-lint-ignore no-explicit-any
|
|
106
|
+
? String((error as any).message)
|
|
107
|
+
: String(error);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Unwinds an open hold when the booking never got as far as payment (Stripe
|
|
112
|
+
* misconfigured, session creation failed). Returns an error message, or null.
|
|
113
|
+
*/
|
|
114
|
+
export async function releaseMemberCredit(
|
|
115
|
+
supabase: CreditRpcClient,
|
|
116
|
+
bookingId: string,
|
|
117
|
+
reason: string,
|
|
118
|
+
): Promise<string | null> {
|
|
119
|
+
const { error } = await supabase.rpc('credit_release', {
|
|
120
|
+
p_booking_id: bookingId,
|
|
121
|
+
p_reason: reason,
|
|
122
|
+
p_idempotency_key: `release:${bookingId}`,
|
|
123
|
+
});
|
|
124
|
+
if (!error) return null;
|
|
125
|
+
return typeof error === 'object' && error && 'message' in error
|
|
126
|
+
// deno-lint-ignore no-explicit-any
|
|
127
|
+
? String((error as any).message)
|
|
128
|
+
: String(error);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Splits the net price into what credit covers and what still has to be
|
|
133
|
+
* charged. A sub-$0.50 remainder is absorbed into `discount_applied_cents`
|
|
134
|
+
* rather than sent to Stripe, so that
|
|
135
|
+
* `(list - dynamic) - credit - discount = charged` (bookings_amount_math_check)
|
|
136
|
+
* stays exactly true. Same rule as create-booking.
|
|
137
|
+
*/
|
|
138
|
+
export function splitCharge(net: number, creditApplied: number): {
|
|
139
|
+
charged: number;
|
|
140
|
+
discount_applied: number;
|
|
141
|
+
} {
|
|
142
|
+
let charged = Math.max(0, net - creditApplied);
|
|
143
|
+
let discount_applied = 0;
|
|
144
|
+
if (charged > 0 && charged < STRIPE_MIN_CHARGE_CENTS) {
|
|
145
|
+
discount_applied = charged;
|
|
146
|
+
charged = 0;
|
|
147
|
+
}
|
|
148
|
+
return { charged, discount_applied };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface AdminCheckoutSessionInput {
|
|
152
|
+
roomName: string;
|
|
153
|
+
roomSlug: string | null;
|
|
154
|
+
/** Human-readable time range, from formatHumanTime(). */
|
|
155
|
+
human: string;
|
|
156
|
+
customerEmail: string;
|
|
157
|
+
bookingId: string;
|
|
158
|
+
amountCents: number;
|
|
159
|
+
/** Origin of the admin console, or the production fallback. */
|
|
160
|
+
base: string;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Checkout Session params for a staff-created booking.
|
|
165
|
+
*
|
|
166
|
+
* Byte-identical to the params admin-create-booking built inline before member
|
|
167
|
+
* attachment existed — the only thing that varies is `amountCents`, which is
|
|
168
|
+
* the full net for a free-form booking and the credit-uncovered remainder for
|
|
169
|
+
* a member booking. `metadata.booking_id` is what stripe-webhook keys on to
|
|
170
|
+
* credit_consume the open hold when the member pays.
|
|
171
|
+
*/
|
|
172
|
+
export function buildAdminCheckoutSessionParams(
|
|
173
|
+
input: AdminCheckoutSessionInput,
|
|
174
|
+
): Record<string, unknown> {
|
|
175
|
+
return {
|
|
176
|
+
mode: 'payment',
|
|
177
|
+
customer_email: input.customerEmail,
|
|
178
|
+
line_items: [{
|
|
179
|
+
quantity: 1,
|
|
180
|
+
price_data: {
|
|
181
|
+
currency: 'usd',
|
|
182
|
+
unit_amount: input.amountCents,
|
|
183
|
+
product_data: { name: `${input.roomName} — ${input.human}` },
|
|
184
|
+
},
|
|
185
|
+
}],
|
|
186
|
+
metadata: { booking_id: input.bookingId },
|
|
187
|
+
success_url: `${input.base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
|
|
188
|
+
cancel_url: `${input.base}/meeting-rooms/${input.roomSlug ?? ''}?canceled=1`,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Commons Booking Contract tier for a room, or null when the room isn't
|
|
194
|
+
* mapped. Same RPC as _shared/tier1Agreement.ts's resolveContractTier; it is
|
|
195
|
+
* re-declared against `CreditRpcClient` here so this module stays dependency-
|
|
196
|
+
* free (importing tier1Agreement.ts drags its whole agreement-hashing graph
|
|
197
|
+
* into every caller) and so a test can drive it with a plain object.
|
|
198
|
+
*
|
|
199
|
+
* Unlike the create-booking gate, this one is advisory: staff booking is not
|
|
200
|
+
* blocked by an unmapped room, the booking just doesn't draw credit.
|
|
201
|
+
*/
|
|
202
|
+
export async function resolveRoomContractTier(
|
|
203
|
+
supabase: CreditRpcClient,
|
|
204
|
+
roomId: string,
|
|
205
|
+
): Promise<number | null> {
|
|
206
|
+
const { data, error } = await supabase.rpc('resolve_room_contract_tier', { p_room_id: roomId });
|
|
207
|
+
if (error) throw error;
|
|
208
|
+
return data === null || data === undefined ? null : Number(data);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export type MembershipEntitlementRow = {
|
|
212
|
+
id: string;
|
|
213
|
+
email: string | null;
|
|
214
|
+
customer_name: string | null;
|
|
215
|
+
status: string;
|
|
216
|
+
pricing_grace_ends_at: string | null;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Loads the membership the operator attached, by id.
|
|
221
|
+
*
|
|
222
|
+
* Server-authoritative: the client sends only an id, and everything that
|
|
223
|
+
* matters (does it exist, is it entitled to member pricing) is read here.
|
|
224
|
+
* Returns null when the id doesn't resolve, in which case the caller must
|
|
225
|
+
* reject rather than silently booking it as free-form — staff picked a member
|
|
226
|
+
* and the booking must not quietly stop drawing on their credit.
|
|
227
|
+
*/
|
|
228
|
+
export async function loadMembershipById(
|
|
229
|
+
supabase: RowReadClient,
|
|
230
|
+
membershipId: string,
|
|
231
|
+
): Promise<MembershipEntitlementRow | null> {
|
|
232
|
+
const { data, error } = await supabase
|
|
233
|
+
.from('memberships')
|
|
234
|
+
.select('id,email,customer_name,status,pricing_grace_ends_at')
|
|
235
|
+
.eq('id', membershipId)
|
|
236
|
+
.maybeSingle();
|
|
237
|
+
if (error) throw error;
|
|
238
|
+
return (data as MembershipEntitlementRow | null) ?? null;
|
|
239
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
|
|
2
|
+
import { parsePgRange } from './availability.ts';
|
|
3
|
+
|
|
4
|
+
const START = Date.UTC(2026, 6, 21, 15, 30, 0);
|
|
5
|
+
const END = Date.UTC(2026, 6, 21, 16, 30, 0);
|
|
6
|
+
|
|
7
|
+
Deno.test('parsePgRange handles bare +00 with space separator', () => {
|
|
8
|
+
assertEquals(
|
|
9
|
+
parsePgRange('["2026-07-21 15:30:00+00","2026-07-21 16:30:00+00")'),
|
|
10
|
+
[START, END],
|
|
11
|
+
);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
Deno.test('parsePgRange handles ISO form', () => {
|
|
15
|
+
assertEquals(
|
|
16
|
+
parsePgRange('["2026-07-21T15:30:00+00:00","2026-07-21T16:30:00+00:00")'),
|
|
17
|
+
[START, END],
|
|
18
|
+
);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
Deno.test('parsePgRange returns null for malformed input', () => {
|
|
22
|
+
assertEquals(parsePgRange('[,)'), null);
|
|
23
|
+
assertEquals(parsePgRange('garbage'), null);
|
|
24
|
+
assertEquals(parsePgRange(''), null);
|
|
25
|
+
});
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Shared availability primitives for room booking surfaces.
|
|
2
|
+
//
|
|
3
|
+
// Extracted verbatim (behaviour-identical) from booking-availability so that
|
|
4
|
+
// every consumer answers "is this room busy?" the same way. Do NOT fork these
|
|
5
|
+
// helpers — add a caller instead.
|
|
6
|
+
|
|
7
|
+
// Structural client type: the concrete SupabaseClient generics differ between
|
|
8
|
+
// call sites, so we only describe the query surface these helpers use.
|
|
9
|
+
interface QueryResult {
|
|
10
|
+
data: unknown[] | null;
|
|
11
|
+
error: { message: string } | null;
|
|
12
|
+
}
|
|
13
|
+
interface FilterBuilder extends PromiseLike<QueryResult> {
|
|
14
|
+
eq(column: string, value: unknown): FilterBuilder;
|
|
15
|
+
in(column: string, values: unknown[]): FilterBuilder;
|
|
16
|
+
or(filters: string): FilterBuilder;
|
|
17
|
+
filter(column: string, operator: string, value: unknown): FilterBuilder;
|
|
18
|
+
}
|
|
19
|
+
interface QueryClient {
|
|
20
|
+
from(table: string): { select(columns: string): FilterBuilder };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Minimal accepted shape. Kept deliberately loose: the concrete
|
|
24
|
+
* SupabaseClient generics vary per call site and matching the full builder
|
|
25
|
+
* type structurally is prohibitively expensive for the type checker.
|
|
26
|
+
*/
|
|
27
|
+
export interface SupabaseLike {
|
|
28
|
+
from(table: string): unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** LA offset in hours (integer: -7 DST, -8 STD) for a given UTC instant. */
|
|
32
|
+
export function laOffsetHours(atUtc: Date): number {
|
|
33
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
34
|
+
timeZone: 'America/Los_Angeles',
|
|
35
|
+
timeZoneName: 'longOffset',
|
|
36
|
+
}).formatToParts(atUtc);
|
|
37
|
+
const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
|
|
38
|
+
const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
|
|
39
|
+
if (!m) return -8;
|
|
40
|
+
const sign = m[1] === '+' ? 1 : -1;
|
|
41
|
+
return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Convert an LA wall-clock (YYYY-MM-DD + HH:MM) to a real UTC Date. */
|
|
45
|
+
export function laWallToUtc(dateStr: string, hh: number, mm: number): Date {
|
|
46
|
+
const [y, mo, d] = dateStr.split('-').map(Number);
|
|
47
|
+
// Use noon-UTC that day to pick a stable offset (no DST edge case at noon).
|
|
48
|
+
const guess = new Date(Date.UTC(y, mo - 1, d, 12));
|
|
49
|
+
const off = laOffsetHours(guess); // negative integer
|
|
50
|
+
return new Date(Date.UTC(y, mo - 1, d, hh - Math.trunc(off), mm));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function laWeekday(dateStr: string): number {
|
|
54
|
+
const [y, mo, d] = dateStr.split('-').map(Number);
|
|
55
|
+
const guess = new Date(Date.UTC(y, mo - 1, d, 12));
|
|
56
|
+
const s = new Intl.DateTimeFormat('en-US', {
|
|
57
|
+
timeZone: 'America/Los_Angeles',
|
|
58
|
+
weekday: 'short',
|
|
59
|
+
}).format(guess);
|
|
60
|
+
return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(s);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The America/Los_Angeles calendar date (YYYY-MM-DD) for a UTC instant.
|
|
65
|
+
* Added so callers never hand-roll a second timezone conversion.
|
|
66
|
+
*/
|
|
67
|
+
export function laDateStr(atUtc: Date): string {
|
|
68
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
69
|
+
timeZone: 'America/Los_Angeles',
|
|
70
|
+
year: 'numeric',
|
|
71
|
+
month: '2-digit',
|
|
72
|
+
day: '2-digit',
|
|
73
|
+
}).formatToParts(atUtc);
|
|
74
|
+
const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';
|
|
75
|
+
return `${get('year')}-${get('month')}-${get('day')}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Normalise a Postgres timestamptz text value into something V8 parses
|
|
80
|
+
* unambiguously: space separator -> "T", bare "+00"/"-00" -> "+00:00"/"-00:00".
|
|
81
|
+
* Defensive only — current data already parses.
|
|
82
|
+
*/
|
|
83
|
+
function normalizeTimestamp(s: string): string {
|
|
84
|
+
return s
|
|
85
|
+
.trim()
|
|
86
|
+
.replace(' ', 'T')
|
|
87
|
+
.replace(/([+-]\d{2})$/, '$1:00');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Parse a Postgres tstzrange text literal `[start,end)` into epoch ms bounds. */
|
|
91
|
+
export function parsePgRange(r: string): [number, number] | null {
|
|
92
|
+
if (typeof r !== 'string' || r.length < 2) return null;
|
|
93
|
+
const inner = r.slice(1, -1);
|
|
94
|
+
const parts = inner.split(',').map((s) => s.replace(/^"|"$/g, ''));
|
|
95
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
|
|
96
|
+
const a = new Date(normalizeTimestamp(parts[0])).getTime();
|
|
97
|
+
const b = new Date(normalizeTimestamp(parts[1])).getTime();
|
|
98
|
+
if (Number.isNaN(a) || Number.isNaN(b)) return null;
|
|
99
|
+
return [a, b];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* business_hours row for a room + weekday. A room-specific row wins over the
|
|
104
|
+
* global (room_id IS NULL) row. Returns null/undefined when closed.
|
|
105
|
+
*/
|
|
106
|
+
export interface BusinessHoursRow {
|
|
107
|
+
room_id: string | null;
|
|
108
|
+
open_time: string;
|
|
109
|
+
close_time: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function getBusinessHoursRow(
|
|
113
|
+
supabase: SupabaseLike,
|
|
114
|
+
roomId: string,
|
|
115
|
+
weekday: number,
|
|
116
|
+
): Promise<BusinessHoursRow | undefined> {
|
|
117
|
+
const db = supabase as unknown as QueryClient;
|
|
118
|
+
const { data, error } = await db
|
|
119
|
+
.from('business_hours')
|
|
120
|
+
.select('*')
|
|
121
|
+
.eq('weekday', weekday)
|
|
122
|
+
.or(`room_id.eq.${roomId},room_id.is.null`);
|
|
123
|
+
if (error) throw error;
|
|
124
|
+
const rows = (data ?? []) as BusinessHoursRow[];
|
|
125
|
+
// Room-specific row wins over the global (room_id IS NULL) row.
|
|
126
|
+
return rows.sort((a, b) => (a.room_id ? -1 : 1))[0];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Busy intervals (epoch ms pairs) for a room overlapping `rangeLiteral`:
|
|
131
|
+
* pending/paid bookings (pending only while its hold is still valid) plus
|
|
132
|
+
* blackouts.
|
|
133
|
+
*/
|
|
134
|
+
export async function getBusyRanges(
|
|
135
|
+
supabase: SupabaseLike,
|
|
136
|
+
roomId: string,
|
|
137
|
+
rangeLiteral: string,
|
|
138
|
+
): Promise<[number, number][]> {
|
|
139
|
+
return (await getBusyRangesDetailed(supabase, roomId, rangeLiteral)).busy;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Same query and same busy computation as `getBusyRanges`, but also reports
|
|
144
|
+
* how many rows had a `during` value that could not be parsed.
|
|
145
|
+
*
|
|
146
|
+
* `getBusyRanges` silently skips those rows (a skipped row reads as *free*).
|
|
147
|
+
* That is fine for the booking flow, where the DB exclusion constraint is the
|
|
148
|
+
* real gate, but a read-only "what's open right now?" surface must fail the
|
|
149
|
+
* other way — an unparseable row has to be treated as busy. Callers that need
|
|
150
|
+
* that safety use this function; the historical behaviour of `getBusyRanges`
|
|
151
|
+
* is unchanged (it simply delegates here and drops the count).
|
|
152
|
+
*/
|
|
153
|
+
export async function getBusyRangesDetailed(
|
|
154
|
+
supabase: SupabaseLike,
|
|
155
|
+
roomId: string,
|
|
156
|
+
rangeLiteral: string,
|
|
157
|
+
): Promise<{ busy: [number, number][]; unparsed: number }> {
|
|
158
|
+
const db = supabase as unknown as QueryClient;
|
|
159
|
+
const [bRes, blRes] = await Promise.all([
|
|
160
|
+
db
|
|
161
|
+
.from('bookings')
|
|
162
|
+
.select('during,status,hold_expires_at')
|
|
163
|
+
.eq('room_id', roomId)
|
|
164
|
+
.in('status', ['pending', 'paid'])
|
|
165
|
+
.filter('during', 'ov', rangeLiteral),
|
|
166
|
+
db
|
|
167
|
+
.from('blackouts')
|
|
168
|
+
.select('during')
|
|
169
|
+
.eq('room_id', roomId)
|
|
170
|
+
.filter('during', 'ov', rangeLiteral),
|
|
171
|
+
]);
|
|
172
|
+
if (bRes.error) throw bRes.error;
|
|
173
|
+
if (blRes.error) throw blRes.error;
|
|
174
|
+
|
|
175
|
+
const bookingRows = (bRes.data ?? []) as Array<{
|
|
176
|
+
during: string;
|
|
177
|
+
status: string;
|
|
178
|
+
hold_expires_at: string | null;
|
|
179
|
+
}>;
|
|
180
|
+
const blackoutRows = (blRes.data ?? []) as Array<{ during: string }>;
|
|
181
|
+
|
|
182
|
+
const busy: [number, number][] = [];
|
|
183
|
+
let unparsed = 0;
|
|
184
|
+
const nowMs = Date.now();
|
|
185
|
+
for (const row of bookingRows) {
|
|
186
|
+
// Paid bookings always block; pending only blocks while the hold is still valid.
|
|
187
|
+
if (row.status === 'pending') {
|
|
188
|
+
const holdMs = row.hold_expires_at ? new Date(row.hold_expires_at).getTime() : null;
|
|
189
|
+
if (holdMs !== null && holdMs < nowMs) continue;
|
|
190
|
+
}
|
|
191
|
+
const p = parsePgRange(row.during);
|
|
192
|
+
if (p) busy.push(p);
|
|
193
|
+
else unparsed += 1;
|
|
194
|
+
}
|
|
195
|
+
for (const row of blackoutRows) {
|
|
196
|
+
const p = parsePgRange(row.during);
|
|
197
|
+
if (p) busy.push(p);
|
|
198
|
+
else unparsed += 1;
|
|
199
|
+
}
|
|
200
|
+
return { busy, unparsed };
|
|
201
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { logOps } from './ops.ts';
|
|
3
|
+
|
|
4
|
+
// Loose generics, matching _shared/ops.ts. A real createClient(url, key, opts)
|
|
5
|
+
// call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
|
|
6
|
+
// assignable to the un-inferred ReturnType<typeof createClient> default — that
|
|
7
|
+
// mismatch is what made every call site here fail deno check.
|
|
8
|
+
// deno-lint-ignore no-explicit-any
|
|
9
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
10
|
+
|
|
11
|
+
const HOLD_EXTENSION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Reclaims stale ('pending', hold expired) bookings overlapping `rangeLiteral`
|
|
15
|
+
* in `room_id` — same candidate set the inline reclaim block used to select —
|
|
16
|
+
* EXCEPT a booking backed by a completed Tier 3 (Commons) booking_agreements
|
|
17
|
+
* row is never expired here: signing that agreement is a real commitment, and
|
|
18
|
+
* the lazy 15-minute-hold-style reclaim was never meant to unwind it. Instead
|
|
19
|
+
* its hold is pushed out 7 days and an ops event is raised so staff can follow
|
|
20
|
+
* up (this should be rare — Commons deposits move the booking to
|
|
21
|
+
* 'deposit_paid' well before the hold would ever go stale).
|
|
22
|
+
*
|
|
23
|
+
* Every other candidate is expired exactly as before.
|
|
24
|
+
*/
|
|
25
|
+
export async function reclaimStaleHoldsExceptCompletedTier3(
|
|
26
|
+
supabase: SupabaseLike,
|
|
27
|
+
room_id: string,
|
|
28
|
+
rangeLiteral: string,
|
|
29
|
+
): Promise<void> {
|
|
30
|
+
const { data: candidates, error: selErr } = await supabase
|
|
31
|
+
.from('bookings')
|
|
32
|
+
.select('id,hold_expires_at')
|
|
33
|
+
.eq('room_id', room_id)
|
|
34
|
+
.eq('status', 'pending')
|
|
35
|
+
.lt('hold_expires_at', new Date().toISOString())
|
|
36
|
+
.filter('during', 'ov', rangeLiteral);
|
|
37
|
+
if (selErr) {
|
|
38
|
+
await logOps(supabase, 'booking_hold_reclaim_select_failed',
|
|
39
|
+
{ room_id, range: rangeLiteral, detail: selErr.message }, { severity: 'error' });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (!candidates || candidates.length === 0) return;
|
|
43
|
+
|
|
44
|
+
for (const candidate of candidates as { id: string; hold_expires_at: string | null }[]) {
|
|
45
|
+
try {
|
|
46
|
+
const { data: agreement, error: agErr } = await supabase
|
|
47
|
+
.from('booking_agreements')
|
|
48
|
+
.select('status')
|
|
49
|
+
.eq('booking_id', candidate.id)
|
|
50
|
+
.eq('tier', 3)
|
|
51
|
+
.order('created_at', { ascending: false })
|
|
52
|
+
.limit(1)
|
|
53
|
+
.maybeSingle();
|
|
54
|
+
if (agErr) {
|
|
55
|
+
await logOps(supabase, 'booking_hold_reclaim_agreement_lookup_failed',
|
|
56
|
+
{ room_id, booking_id: candidate.id, detail: agErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (agreement && (agreement as { status: string }).status === 'completed') {
|
|
61
|
+
const oldHoldExpiresAt = candidate.hold_expires_at;
|
|
62
|
+
const newHoldExpiresAt = new Date(Date.now() + HOLD_EXTENSION_MS).toISOString();
|
|
63
|
+
const { error: extendErr } = await supabase
|
|
64
|
+
.from('bookings')
|
|
65
|
+
.update({ hold_expires_at: newHoldExpiresAt })
|
|
66
|
+
.eq('id', candidate.id);
|
|
67
|
+
if (extendErr) {
|
|
68
|
+
await logOps(supabase, 'booking_hold_reclaim_extend_failed',
|
|
69
|
+
{ room_id, booking_id: candidate.id, detail: extendErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
await logOps(supabase, 'commons_completed_hold_would_have_expired', {
|
|
73
|
+
room_id,
|
|
74
|
+
booking_id: candidate.id,
|
|
75
|
+
old_hold_expires_at: oldHoldExpiresAt,
|
|
76
|
+
new_hold_expires_at: newHoldExpiresAt,
|
|
77
|
+
}, { severity: 'error', bookingId: candidate.id });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const { error: expireErr } = await supabase
|
|
82
|
+
.from('bookings')
|
|
83
|
+
.update({ status: 'expired' })
|
|
84
|
+
.eq('id', candidate.id);
|
|
85
|
+
if (expireErr) {
|
|
86
|
+
await logOps(supabase, 'booking_hold_reclaim_expire_failed',
|
|
87
|
+
{ room_id, booking_id: candidate.id, detail: expireErr.message }, { severity: 'error', bookingId: candidate.id });
|
|
88
|
+
}
|
|
89
|
+
} catch (e) {
|
|
90
|
+
await logOps(supabase, 'booking_hold_reclaim_row_error',
|
|
91
|
+
{ room_id, booking_id: candidate.id, detail: String(e) }, { severity: 'error', bookingId: candidate.id });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Stripe Checkout Session parameter construction for the two public
|
|
2
|
+
// self-serve paths, lifted out of the edge functions so it can be asserted on
|
|
3
|
+
// without a network call.
|
|
4
|
+
//
|
|
5
|
+
// The one rule these encode: Stripe REJECTS a session that sets both
|
|
6
|
+
// `discounts` and `allow_promotion_codes`. With no internal coupon we keep the
|
|
7
|
+
// pre-existing `allow_promotion_codes: true` and emit no `discounts` key at
|
|
8
|
+
// all; with one we do the exact opposite.
|
|
9
|
+
|
|
10
|
+
import type Stripe from 'npm:stripe@17.5.0';
|
|
11
|
+
|
|
12
|
+
export function buildSubscriptionSessionParams(input: {
|
|
13
|
+
customerId: string;
|
|
14
|
+
lineItem: Stripe.Checkout.SessionCreateParams.LineItem;
|
|
15
|
+
metadata: Record<string, string>;
|
|
16
|
+
subscriptionData: Stripe.Checkout.SessionCreateParams.SubscriptionData;
|
|
17
|
+
successUrl: string;
|
|
18
|
+
cancelUrl: string;
|
|
19
|
+
stripeCouponId: string | null;
|
|
20
|
+
}): Stripe.Checkout.SessionCreateParams {
|
|
21
|
+
return {
|
|
22
|
+
mode: 'subscription',
|
|
23
|
+
customer: input.customerId,
|
|
24
|
+
line_items: [input.lineItem],
|
|
25
|
+
...(input.stripeCouponId
|
|
26
|
+
? { discounts: [{ coupon: input.stripeCouponId }] }
|
|
27
|
+
: { allow_promotion_codes: true }),
|
|
28
|
+
metadata: input.metadata,
|
|
29
|
+
subscription_data: input.subscriptionData,
|
|
30
|
+
success_url: input.successUrl,
|
|
31
|
+
cancel_url: input.cancelUrl,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function buildDayPassSessionParams(input: {
|
|
36
|
+
customerId: string;
|
|
37
|
+
priceId: string;
|
|
38
|
+
metadata: Record<string, string>;
|
|
39
|
+
receiptEmail: string;
|
|
40
|
+
successUrl: string;
|
|
41
|
+
cancelUrl: string;
|
|
42
|
+
stripeCouponId: string | null;
|
|
43
|
+
}): Stripe.Checkout.SessionCreateParams {
|
|
44
|
+
return {
|
|
45
|
+
mode: 'payment',
|
|
46
|
+
customer: input.customerId,
|
|
47
|
+
line_items: [{ price: input.priceId, quantity: 1 }],
|
|
48
|
+
...(input.stripeCouponId
|
|
49
|
+
? { discounts: [{ coupon: input.stripeCouponId }] }
|
|
50
|
+
: { allow_promotion_codes: true }),
|
|
51
|
+
metadata: input.metadata,
|
|
52
|
+
payment_intent_data: { receipt_email: input.receiptEmail },
|
|
53
|
+
success_url: input.successUrl,
|
|
54
|
+
cancel_url: input.cancelUrl,
|
|
55
|
+
};
|
|
56
|
+
}
|