@simplelayer/graniteer-core 0.2.1 → 0.2.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 +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -334
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -217
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
|
@@ -1,244 +1,244 @@
|
|
|
1
|
-
// supabase/functions/admin-create-commons-event/index.ts
|
|
2
|
-
//
|
|
3
|
-
// Stage 2 of the Commons (Tier 3) contract + deposit feature.
|
|
4
|
-
// Staff-only creation of a Commons event booking: a `pending` bookings row
|
|
5
|
-
// carrying the negotiated total (list_amount_cents) and a 50% deposit
|
|
6
|
-
// (deposit_amount_cents). NOTHING is charged here and no contract is sent —
|
|
7
|
-
// BoldSign / Stripe wiring lands in a later stage.
|
|
8
|
-
//
|
|
9
|
-
// Auth scaffold is the same shape as admin-create-booking: JWKS-verified
|
|
10
|
-
// caller JWT, aal2 required, admin_users allowlist re-checked server-side,
|
|
11
|
-
// rate limited on distinct buckets.
|
|
12
|
-
//
|
|
13
|
-
// Pricing is deliberately NOT routed through _shared/pricing.ts — Commons is
|
|
14
|
-
// a negotiated quote room, so the total is staff-entered and validated here.
|
|
15
|
-
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
16
|
-
import { z } from 'npm:zod@3.23.8';
|
|
17
|
-
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
18
|
-
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
19
|
-
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
20
|
-
|
|
21
|
-
const corsHeaders = {
|
|
22
|
-
'Access-Control-Allow-Origin': '*',
|
|
23
|
-
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
24
|
-
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
28
|
-
|
|
29
|
-
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
30
|
-
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
31
|
-
function getJwks(supabaseUrl: string) {
|
|
32
|
-
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
33
|
-
return jwksCache;
|
|
34
|
-
}
|
|
35
|
-
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
36
|
-
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
37
|
-
const token = authHeader.slice(7).trim();
|
|
38
|
-
try {
|
|
39
|
-
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
40
|
-
const claims = payload as unknown as CallerClaims;
|
|
41
|
-
if (!claims.sub) return null;
|
|
42
|
-
return claims;
|
|
43
|
-
} catch { return null; }
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function json(status: number, body: unknown) {
|
|
47
|
-
return new Response(JSON.stringify(body), {
|
|
48
|
-
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
function fail(status: number, code: string, error: string) {
|
|
52
|
-
return json(status, { ok: false, status, code, error });
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const Client = z.object({
|
|
56
|
-
legal_name: z.string().trim().min(1).max(300),
|
|
57
|
-
contact_name: z.string().trim().min(1).max(200),
|
|
58
|
-
email: z.string().trim().email().max(255),
|
|
59
|
-
phone: z.string().trim().max(40).optional(),
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
const Body = z.object({
|
|
63
|
-
room_id: z.string().uuid(),
|
|
64
|
-
start_at: z.string().datetime({ offset: true }),
|
|
65
|
-
end_at: z.string().datetime({ offset: true }),
|
|
66
|
-
total_price_cents: z.number().int(),
|
|
67
|
-
security_deposit_cents: z.number().int(),
|
|
68
|
-
client: Client,
|
|
69
|
-
event_name: z.string().trim().max(200).optional(),
|
|
70
|
-
hold_days: z.number().int().optional(),
|
|
71
|
-
notes: z.string().trim().max(2000).optional(),
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
const MAX_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
|
75
|
-
|
|
76
|
-
// Event packages are priced as a single negotiated total and are
|
|
77
|
-
// intentionally excluded from the member monthly room credit — this is a
|
|
78
|
-
// product decision, not an oversight. The credit mechanism (credit_hold /
|
|
79
|
-
// credit_consume) only ever applies to hourly/day-rate room bookings in
|
|
80
|
-
// create-booking. Never wire this up without a deliberate product call.
|
|
81
|
-
const EVENT_PACKAGE_CREDIT_APPLIED_CENTS = 0;
|
|
82
|
-
|
|
83
|
-
export async function handle(req: Request): Promise<Response> {
|
|
84
|
-
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
85
|
-
if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
|
|
86
|
-
|
|
87
|
-
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
88
|
-
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
89
|
-
|
|
90
|
-
// === Admin auth: same shape as admin-create-booking ===
|
|
91
|
-
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
92
|
-
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
93
|
-
if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
|
|
94
|
-
if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
|
|
95
|
-
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
96
|
-
if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
|
|
97
|
-
|
|
98
|
-
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
99
|
-
auth: { persistSession: false, autoRefreshToken: false },
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
const [ipOk, emailOk] = await Promise.all([
|
|
103
|
-
checkRateLimit(admin, 'admin-create-commons-event-ip', clientIp(req), 30, 300),
|
|
104
|
-
checkRateLimit(admin, 'admin-create-commons-event-email', callerEmail, 20, 300),
|
|
105
|
-
]);
|
|
106
|
-
if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
|
|
107
|
-
|
|
108
|
-
const { data: allow, error: allowErr } = await admin
|
|
109
|
-
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
110
|
-
if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
|
|
111
|
-
if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
|
|
112
|
-
|
|
113
|
-
// === Body ===
|
|
114
|
-
let raw: unknown;
|
|
115
|
-
try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
|
|
116
|
-
const parsed = Body.safeParse(raw);
|
|
117
|
-
if (!parsed.success) {
|
|
118
|
-
return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
|
|
119
|
-
}
|
|
120
|
-
const {
|
|
121
|
-
room_id, start_at, end_at, total_price_cents, security_deposit_cents,
|
|
122
|
-
client, event_name, hold_days, notes,
|
|
123
|
-
} = parsed.data;
|
|
124
|
-
|
|
125
|
-
// === Room + tier ===
|
|
126
|
-
const { data: room, error: rErr } = await admin
|
|
127
|
-
.from('rooms')
|
|
128
|
-
.select('id,name,slug,booking_mode,active')
|
|
129
|
-
.eq('id', room_id)
|
|
130
|
-
.maybeSingle();
|
|
131
|
-
if (rErr) return fail(500, 'load_room_failed', rErr.message);
|
|
132
|
-
if (!room) return fail(404, 'room_not_found', 'Room not found.');
|
|
133
|
-
|
|
134
|
-
const { data: tier, error: tErr } = await admin
|
|
135
|
-
.rpc('resolve_room_contract_tier', { p_room_id: room_id });
|
|
136
|
-
if (tErr) return fail(500, 'tier_lookup_failed', tErr.message);
|
|
137
|
-
if (Number(tier) !== 3) {
|
|
138
|
-
return fail(409, 'not_tier3', 'This room is not a tier-3 (contract + deposit) room.');
|
|
139
|
-
}
|
|
140
|
-
// Commons moved from `quote` to self-serve `day_block`; this gate would
|
|
141
|
-
// otherwise 409 every staff-created Commons event. This function prices from
|
|
142
|
-
// the staff-supplied total and reads neither business_hours nor any dynamic
|
|
143
|
-
// rule, so widening the accepted modes is the whole change needed here.
|
|
144
|
-
if (!['quote', 'day_block'].includes(room.booking_mode) || room.active !== true) {
|
|
145
|
-
return fail(409, 'room_inactive', 'Room must be an active quote-mode or day-block room.');
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// === Window ===
|
|
149
|
-
const startMs = Date.parse(start_at);
|
|
150
|
-
const endMs = Date.parse(end_at);
|
|
151
|
-
const nowMs = Date.now();
|
|
152
|
-
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
|
|
153
|
-
return fail(400, 'invalid_window', 'Arrival and checkout must be valid timestamps.');
|
|
154
|
-
}
|
|
155
|
-
if (startMs >= endMs) return fail(400, 'invalid_window', 'Checkout must be after arrival.');
|
|
156
|
-
if (startMs <= nowMs) return fail(400, 'invalid_window', 'Arrival must be in the future.');
|
|
157
|
-
if (endMs - startMs > MAX_WINDOW_MS) {
|
|
158
|
-
return fail(400, 'invalid_window', 'Event window cannot exceed 14 days.');
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// === Price ===
|
|
162
|
-
if (total_price_cents % 100 !== 0) {
|
|
163
|
-
return fail(400, 'invalid_price', 'Total must be a whole-dollar amount (no cents) so the 50% split is exact.');
|
|
164
|
-
}
|
|
165
|
-
if (total_price_cents < 10000 || total_price_cents > 10000000) {
|
|
166
|
-
return fail(400, 'invalid_price', 'Total must be between $100 and $100,000.');
|
|
167
|
-
}
|
|
168
|
-
if (security_deposit_cents < 0 || security_deposit_cents > total_price_cents) {
|
|
169
|
-
return fail(400, 'invalid_price', 'Security deposit must be between $0 and the event total.');
|
|
170
|
-
}
|
|
171
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(client.email)) {
|
|
172
|
-
return fail(400, 'invalid_client', 'Client email is not valid.');
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const depositCents = total_price_cents / 2;
|
|
176
|
-
|
|
177
|
-
// Hold: min(now + hold_days, arrival). Default 14 days, clamped to 60.
|
|
178
|
-
const holdDays = Math.min(Math.max(hold_days ?? 14, 1), 60);
|
|
179
|
-
const holdMs = Math.min(nowMs + holdDays * 24 * 60 * 60 * 1000, startMs);
|
|
180
|
-
const holdExpiresAt = new Date(holdMs).toISOString();
|
|
181
|
-
|
|
182
|
-
const rangeLiteral = `[${new Date(startMs).toISOString()},${new Date(endMs).toISOString()})`;
|
|
183
|
-
|
|
184
|
-
// NOTE: `charged_amount_cents` is left NULL, not 0. The existing
|
|
185
|
-
// `bookings_amount_math_check` constraint requires
|
|
186
|
-
// list - dynamic_discount - credit - discount = charged whenever charged is
|
|
187
|
-
// NOT NULL, so a literal 0 alongside a non-zero list would be rejected.
|
|
188
|
-
// NULL is the schema's existing "nothing captured yet" state.
|
|
189
|
-
const insertRow: Record<string, unknown> = {
|
|
190
|
-
room_id,
|
|
191
|
-
during: rangeLiteral,
|
|
192
|
-
status: 'pending',
|
|
193
|
-
list_amount_cents: total_price_cents,
|
|
194
|
-
charged_amount_cents: null,
|
|
195
|
-
deposit_amount_cents: depositCents,
|
|
196
|
-
credit_applied_cents: EVENT_PACKAGE_CREDIT_APPLIED_CENTS,
|
|
197
|
-
discount_applied_cents: 0,
|
|
198
|
-
payment_source: 'stripe',
|
|
199
|
-
contact_email: client.email.toLowerCase(),
|
|
200
|
-
contact_name: client.contact_name,
|
|
201
|
-
contact_phone: client.phone ?? null,
|
|
202
|
-
hold_expires_at: holdExpiresAt,
|
|
203
|
-
created_by: callerEmail,
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
const { data: inserted, error: iErr } = await admin
|
|
207
|
-
.from('bookings')
|
|
208
|
-
.insert(insertRow)
|
|
209
|
-
.select('id')
|
|
210
|
-
.single();
|
|
211
|
-
if (iErr) {
|
|
212
|
-
// deno-lint-ignore no-explicit-any
|
|
213
|
-
const code = (iErr as any).code;
|
|
214
|
-
if (code === '23P01') {
|
|
215
|
-
return fail(409, 'overlap', 'Another booking already holds part of that window.');
|
|
216
|
-
}
|
|
217
|
-
return fail(500, 'insert_failed', iErr.message);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const booking_id = inserted.id as string;
|
|
221
|
-
|
|
222
|
-
// `event_name`, `client.legal_name` and `notes` have no column on `bookings`
|
|
223
|
-
// today — they are recorded on the ops event for traceability only and will
|
|
224
|
-
// move onto `booking_agreements` when the tier-3 contract stage lands.
|
|
225
|
-
await logOps(admin, 'commons_event_booking_created', {
|
|
226
|
-
booking_id,
|
|
227
|
-
room_id,
|
|
228
|
-
actor: callerEmail,
|
|
229
|
-
client_legal_name: client.legal_name,
|
|
230
|
-
event_name: event_name ?? null,
|
|
231
|
-
notes: notes ?? null,
|
|
232
|
-
list_amount_cents: total_price_cents,
|
|
233
|
-
deposit_amount_cents: depositCents,
|
|
234
|
-
security_deposit_cents,
|
|
235
|
-
}, { severity: 'info', bookingId: booking_id }).catch(() => {});
|
|
236
|
-
|
|
237
|
-
return json(200, {
|
|
238
|
-
ok: true,
|
|
239
|
-
booking_id,
|
|
240
|
-
list_amount_cents: total_price_cents,
|
|
241
|
-
deposit_amount_cents: depositCents,
|
|
242
|
-
hold_expires_at: holdExpiresAt,
|
|
243
|
-
});
|
|
244
|
-
}
|
|
1
|
+
// supabase/functions/admin-create-commons-event/index.ts
|
|
2
|
+
//
|
|
3
|
+
// Stage 2 of the Commons (Tier 3) contract + deposit feature.
|
|
4
|
+
// Staff-only creation of a Commons event booking: a `pending` bookings row
|
|
5
|
+
// carrying the negotiated total (list_amount_cents) and a 50% deposit
|
|
6
|
+
// (deposit_amount_cents). NOTHING is charged here and no contract is sent —
|
|
7
|
+
// BoldSign / Stripe wiring lands in a later stage.
|
|
8
|
+
//
|
|
9
|
+
// Auth scaffold is the same shape as admin-create-booking: JWKS-verified
|
|
10
|
+
// caller JWT, aal2 required, admin_users allowlist re-checked server-side,
|
|
11
|
+
// rate limited on distinct buckets.
|
|
12
|
+
//
|
|
13
|
+
// Pricing is deliberately NOT routed through _shared/pricing.ts — Commons is
|
|
14
|
+
// a negotiated quote room, so the total is staff-entered and validated here.
|
|
15
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
16
|
+
import { z } from 'npm:zod@3.23.8';
|
|
17
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
18
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
19
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
20
|
+
|
|
21
|
+
const corsHeaders = {
|
|
22
|
+
'Access-Control-Allow-Origin': '*',
|
|
23
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
24
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
interface CallerClaims { sub: string; email?: string; aal?: string }
|
|
28
|
+
|
|
29
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
30
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
31
|
+
function getJwks(supabaseUrl: string) {
|
|
32
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
33
|
+
return jwksCache;
|
|
34
|
+
}
|
|
35
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
36
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
37
|
+
const token = authHeader.slice(7).trim();
|
|
38
|
+
try {
|
|
39
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
40
|
+
const claims = payload as unknown as CallerClaims;
|
|
41
|
+
if (!claims.sub) return null;
|
|
42
|
+
return claims;
|
|
43
|
+
} catch { return null; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function json(status: number, body: unknown) {
|
|
47
|
+
return new Response(JSON.stringify(body), {
|
|
48
|
+
status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function fail(status: number, code: string, error: string) {
|
|
52
|
+
return json(status, { ok: false, status, code, error });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const Client = z.object({
|
|
56
|
+
legal_name: z.string().trim().min(1).max(300),
|
|
57
|
+
contact_name: z.string().trim().min(1).max(200),
|
|
58
|
+
email: z.string().trim().email().max(255),
|
|
59
|
+
phone: z.string().trim().max(40).optional(),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const Body = z.object({
|
|
63
|
+
room_id: z.string().uuid(),
|
|
64
|
+
start_at: z.string().datetime({ offset: true }),
|
|
65
|
+
end_at: z.string().datetime({ offset: true }),
|
|
66
|
+
total_price_cents: z.number().int(),
|
|
67
|
+
security_deposit_cents: z.number().int(),
|
|
68
|
+
client: Client,
|
|
69
|
+
event_name: z.string().trim().max(200).optional(),
|
|
70
|
+
hold_days: z.number().int().optional(),
|
|
71
|
+
notes: z.string().trim().max(2000).optional(),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const MAX_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
|
75
|
+
|
|
76
|
+
// Event packages are priced as a single negotiated total and are
|
|
77
|
+
// intentionally excluded from the member monthly room credit — this is a
|
|
78
|
+
// product decision, not an oversight. The credit mechanism (credit_hold /
|
|
79
|
+
// credit_consume) only ever applies to hourly/day-rate room bookings in
|
|
80
|
+
// create-booking. Never wire this up without a deliberate product call.
|
|
81
|
+
const EVENT_PACKAGE_CREDIT_APPLIED_CENTS = 0;
|
|
82
|
+
|
|
83
|
+
export async function handle(req: Request): Promise<Response> {
|
|
84
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
85
|
+
if (req.method !== 'POST') return fail(405, 'method_not_allowed', 'Method not allowed.');
|
|
86
|
+
|
|
87
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
88
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
89
|
+
|
|
90
|
+
// === Admin auth: same shape as admin-create-booking ===
|
|
91
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
92
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
93
|
+
if (!caller) return fail(401, 'unauthenticated', 'Not signed in.');
|
|
94
|
+
if (caller.aal !== 'aal2') return fail(403, 'mfa_required', 'Two-factor authentication is required.');
|
|
95
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
96
|
+
if (!callerEmail) return fail(403, 'no_email', 'Caller has no email claim.');
|
|
97
|
+
|
|
98
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
99
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
103
|
+
checkRateLimit(admin, 'admin-create-commons-event-ip', clientIp(req), 30, 300),
|
|
104
|
+
checkRateLimit(admin, 'admin-create-commons-event-email', callerEmail, 20, 300),
|
|
105
|
+
]);
|
|
106
|
+
if (!ipOk || !emailOk) return fail(429, 'rate_limited', 'Too many attempts — try again shortly.');
|
|
107
|
+
|
|
108
|
+
const { data: allow, error: allowErr } = await admin
|
|
109
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
110
|
+
if (allowErr) return fail(500, 'allowlist_lookup_failed', allowErr.message);
|
|
111
|
+
if (!allow) return fail(403, 'not_authorized', 'Not authorized.');
|
|
112
|
+
|
|
113
|
+
// === Body ===
|
|
114
|
+
let raw: unknown;
|
|
115
|
+
try { raw = await req.json(); } catch { return fail(400, 'invalid_json', 'Body was not valid JSON.'); }
|
|
116
|
+
const parsed = Body.safeParse(raw);
|
|
117
|
+
if (!parsed.success) {
|
|
118
|
+
return fail(400, 'invalid_body', JSON.stringify(parsed.error.flatten().fieldErrors));
|
|
119
|
+
}
|
|
120
|
+
const {
|
|
121
|
+
room_id, start_at, end_at, total_price_cents, security_deposit_cents,
|
|
122
|
+
client, event_name, hold_days, notes,
|
|
123
|
+
} = parsed.data;
|
|
124
|
+
|
|
125
|
+
// === Room + tier ===
|
|
126
|
+
const { data: room, error: rErr } = await admin
|
|
127
|
+
.from('rooms')
|
|
128
|
+
.select('id,name,slug,booking_mode,active')
|
|
129
|
+
.eq('id', room_id)
|
|
130
|
+
.maybeSingle();
|
|
131
|
+
if (rErr) return fail(500, 'load_room_failed', rErr.message);
|
|
132
|
+
if (!room) return fail(404, 'room_not_found', 'Room not found.');
|
|
133
|
+
|
|
134
|
+
const { data: tier, error: tErr } = await admin
|
|
135
|
+
.rpc('resolve_room_contract_tier', { p_room_id: room_id });
|
|
136
|
+
if (tErr) return fail(500, 'tier_lookup_failed', tErr.message);
|
|
137
|
+
if (Number(tier) !== 3) {
|
|
138
|
+
return fail(409, 'not_tier3', 'This room is not a tier-3 (contract + deposit) room.');
|
|
139
|
+
}
|
|
140
|
+
// Commons moved from `quote` to self-serve `day_block`; this gate would
|
|
141
|
+
// otherwise 409 every staff-created Commons event. This function prices from
|
|
142
|
+
// the staff-supplied total and reads neither business_hours nor any dynamic
|
|
143
|
+
// rule, so widening the accepted modes is the whole change needed here.
|
|
144
|
+
if (!['quote', 'day_block'].includes(room.booking_mode) || room.active !== true) {
|
|
145
|
+
return fail(409, 'room_inactive', 'Room must be an active quote-mode or day-block room.');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// === Window ===
|
|
149
|
+
const startMs = Date.parse(start_at);
|
|
150
|
+
const endMs = Date.parse(end_at);
|
|
151
|
+
const nowMs = Date.now();
|
|
152
|
+
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
|
|
153
|
+
return fail(400, 'invalid_window', 'Arrival and checkout must be valid timestamps.');
|
|
154
|
+
}
|
|
155
|
+
if (startMs >= endMs) return fail(400, 'invalid_window', 'Checkout must be after arrival.');
|
|
156
|
+
if (startMs <= nowMs) return fail(400, 'invalid_window', 'Arrival must be in the future.');
|
|
157
|
+
if (endMs - startMs > MAX_WINDOW_MS) {
|
|
158
|
+
return fail(400, 'invalid_window', 'Event window cannot exceed 14 days.');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// === Price ===
|
|
162
|
+
if (total_price_cents % 100 !== 0) {
|
|
163
|
+
return fail(400, 'invalid_price', 'Total must be a whole-dollar amount (no cents) so the 50% split is exact.');
|
|
164
|
+
}
|
|
165
|
+
if (total_price_cents < 10000 || total_price_cents > 10000000) {
|
|
166
|
+
return fail(400, 'invalid_price', 'Total must be between $100 and $100,000.');
|
|
167
|
+
}
|
|
168
|
+
if (security_deposit_cents < 0 || security_deposit_cents > total_price_cents) {
|
|
169
|
+
return fail(400, 'invalid_price', 'Security deposit must be between $0 and the event total.');
|
|
170
|
+
}
|
|
171
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(client.email)) {
|
|
172
|
+
return fail(400, 'invalid_client', 'Client email is not valid.');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const depositCents = total_price_cents / 2;
|
|
176
|
+
|
|
177
|
+
// Hold: min(now + hold_days, arrival). Default 14 days, clamped to 60.
|
|
178
|
+
const holdDays = Math.min(Math.max(hold_days ?? 14, 1), 60);
|
|
179
|
+
const holdMs = Math.min(nowMs + holdDays * 24 * 60 * 60 * 1000, startMs);
|
|
180
|
+
const holdExpiresAt = new Date(holdMs).toISOString();
|
|
181
|
+
|
|
182
|
+
const rangeLiteral = `[${new Date(startMs).toISOString()},${new Date(endMs).toISOString()})`;
|
|
183
|
+
|
|
184
|
+
// NOTE: `charged_amount_cents` is left NULL, not 0. The existing
|
|
185
|
+
// `bookings_amount_math_check` constraint requires
|
|
186
|
+
// list - dynamic_discount - credit - discount = charged whenever charged is
|
|
187
|
+
// NOT NULL, so a literal 0 alongside a non-zero list would be rejected.
|
|
188
|
+
// NULL is the schema's existing "nothing captured yet" state.
|
|
189
|
+
const insertRow: Record<string, unknown> = {
|
|
190
|
+
room_id,
|
|
191
|
+
during: rangeLiteral,
|
|
192
|
+
status: 'pending',
|
|
193
|
+
list_amount_cents: total_price_cents,
|
|
194
|
+
charged_amount_cents: null,
|
|
195
|
+
deposit_amount_cents: depositCents,
|
|
196
|
+
credit_applied_cents: EVENT_PACKAGE_CREDIT_APPLIED_CENTS,
|
|
197
|
+
discount_applied_cents: 0,
|
|
198
|
+
payment_source: 'stripe',
|
|
199
|
+
contact_email: client.email.toLowerCase(),
|
|
200
|
+
contact_name: client.contact_name,
|
|
201
|
+
contact_phone: client.phone ?? null,
|
|
202
|
+
hold_expires_at: holdExpiresAt,
|
|
203
|
+
created_by: callerEmail,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const { data: inserted, error: iErr } = await admin
|
|
207
|
+
.from('bookings')
|
|
208
|
+
.insert(insertRow)
|
|
209
|
+
.select('id')
|
|
210
|
+
.single();
|
|
211
|
+
if (iErr) {
|
|
212
|
+
// deno-lint-ignore no-explicit-any
|
|
213
|
+
const code = (iErr as any).code;
|
|
214
|
+
if (code === '23P01') {
|
|
215
|
+
return fail(409, 'overlap', 'Another booking already holds part of that window.');
|
|
216
|
+
}
|
|
217
|
+
return fail(500, 'insert_failed', iErr.message);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const booking_id = inserted.id as string;
|
|
221
|
+
|
|
222
|
+
// `event_name`, `client.legal_name` and `notes` have no column on `bookings`
|
|
223
|
+
// today — they are recorded on the ops event for traceability only and will
|
|
224
|
+
// move onto `booking_agreements` when the tier-3 contract stage lands.
|
|
225
|
+
await logOps(admin, 'commons_event_booking_created', {
|
|
226
|
+
booking_id,
|
|
227
|
+
room_id,
|
|
228
|
+
actor: callerEmail,
|
|
229
|
+
client_legal_name: client.legal_name,
|
|
230
|
+
event_name: event_name ?? null,
|
|
231
|
+
notes: notes ?? null,
|
|
232
|
+
list_amount_cents: total_price_cents,
|
|
233
|
+
deposit_amount_cents: depositCents,
|
|
234
|
+
security_deposit_cents,
|
|
235
|
+
}, { severity: 'info', bookingId: booking_id }).catch(() => {});
|
|
236
|
+
|
|
237
|
+
return json(200, {
|
|
238
|
+
ok: true,
|
|
239
|
+
booking_id,
|
|
240
|
+
list_amount_cents: total_price_cents,
|
|
241
|
+
deposit_amount_cents: depositCents,
|
|
242
|
+
hold_expires_at: holdExpiresAt,
|
|
243
|
+
});
|
|
244
|
+
}
|