@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,218 +1,218 @@
|
|
|
1
|
-
import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
|
|
2
|
-
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
3
|
-
import Stripe from 'npm:stripe@17.5.0';
|
|
4
|
-
import { z } from 'npm:zod@3.23.8';
|
|
5
|
-
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
6
|
-
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
7
|
-
import { applyCheckoutCoupon, couponFailureBody, reverseCheckoutCoupon } from 'npm:@simplelayer/graniteer-core/checkoutCoupon';
|
|
8
|
-
import { buildDayPassSessionParams } from 'npm:@simplelayer/graniteer-core/checkoutSessionParams';
|
|
9
|
-
|
|
10
|
-
const Body = z.object({
|
|
11
|
-
plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
|
|
12
|
-
email: z.string().email().max(255),
|
|
13
|
-
visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
14
|
-
arrival_time: z.string().max(20).optional(),
|
|
15
|
-
// Internal `coupons` code. An unusable code is a hard 400 -- the guest typed
|
|
16
|
-
// it expecting a discount, so charging full price silently is wrong.
|
|
17
|
-
coupon_code: z.string().trim().min(1).max(40).regex(/^[A-Za-z0-9_-]+$/).optional(),
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
function todayLA(): string {
|
|
21
|
-
return new Intl.DateTimeFormat('en-CA', {
|
|
22
|
-
timeZone: 'America/Los_Angeles',
|
|
23
|
-
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
24
|
-
}).format(new Date());
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export async function handle(req: Request, operator: { domain: string; actorEmail: string }): Promise<Response> {
|
|
28
|
-
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
29
|
-
|
|
30
|
-
// Set once a coupon reservation exists. Held at handler scope so the outer
|
|
31
|
-
// catch can release it if anything after the reservation throws.
|
|
32
|
-
let couponRedemptionId: string | null = null;
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
const raw = await req.json().catch(() => ({}));
|
|
36
|
-
const parsed = Body.safeParse(raw);
|
|
37
|
-
if (!parsed.success) {
|
|
38
|
-
return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
|
|
39
|
-
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
const { plan_slug, email, visit_date, arrival_time, coupon_code } = parsed.data;
|
|
43
|
-
const emailKey = email.toLowerCase();
|
|
44
|
-
|
|
45
|
-
if (visit_date < todayLA()) {
|
|
46
|
-
return new Response(JSON.stringify({ error: "Visit date can't be in the past." }), {
|
|
47
|
-
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const supabase = createClient(
|
|
52
|
-
Deno.env.get('SUPABASE_URL')!,
|
|
53
|
-
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
54
|
-
);
|
|
55
|
-
|
|
56
|
-
// Fail-open rate limiting (own buckets — do not share with subscriptions).
|
|
57
|
-
const ip = clientIp(req);
|
|
58
|
-
const [ipOk, emailOk] = await Promise.all([
|
|
59
|
-
checkRateLimit(supabase, 'create-day-pass', ip, 10, 600),
|
|
60
|
-
checkRateLimit(supabase, 'create-day-pass-email', emailKey, 5, 600),
|
|
61
|
-
]);
|
|
62
|
-
if (!ipOk || !emailOk) {
|
|
63
|
-
return new Response(
|
|
64
|
-
JSON.stringify({ error: 'Too many checkout attempts — please wait a few minutes and try again.' }),
|
|
65
|
-
{ status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const { data: plan, error: pErr } = await supabase
|
|
70
|
-
.from('membership_plans')
|
|
71
|
-
.select('id,slug,name,active,billable,billing_interval,stripe_price_id,stripe_product_id,price_cents')
|
|
72
|
-
.eq('slug', plan_slug)
|
|
73
|
-
.maybeSingle();
|
|
74
|
-
if (pErr) throw pErr;
|
|
75
|
-
if (
|
|
76
|
-
!plan ||
|
|
77
|
-
plan.active !== true ||
|
|
78
|
-
plan.billable !== true ||
|
|
79
|
-
!plan.stripe_price_id ||
|
|
80
|
-
plan.billing_interval === 'month'
|
|
81
|
-
) {
|
|
82
|
-
return new Response(JSON.stringify({ error: 'That plan is not available for one-time checkout.' }), {
|
|
83
|
-
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
88
|
-
if (!stripeKey) {
|
|
89
|
-
return new Response(JSON.stringify({ error: 'Payments not configured (missing STRIPE_SECRET_KEY).' }), {
|
|
90
|
-
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
94
|
-
|
|
95
|
-
// === Optional internal coupon ===
|
|
96
|
-
// Runs BEFORE any Stripe Customer or Session is created: a bad code should
|
|
97
|
-
// cost one read-only RPC, not a customer record and an abandoned session.
|
|
98
|
-
let stripeCouponId: string | null = null;
|
|
99
|
-
let couponId: string | null = null;
|
|
100
|
-
let couponAttemptId: string | null = null;
|
|
101
|
-
if (coupon_code) {
|
|
102
|
-
// Day-pass plans always bill off a stored Stripe Price (enforced by the
|
|
103
|
-
// eligibility check above), so the amount Stripe will charge has to come
|
|
104
|
-
// from Stripe -- price_cents is not authoritative here.
|
|
105
|
-
let baseAmountCents: number | null = null;
|
|
106
|
-
try {
|
|
107
|
-
const price = await stripe.prices.retrieve(plan.stripe_price_id);
|
|
108
|
-
baseAmountCents = price.unit_amount ?? null;
|
|
109
|
-
} catch (e) {
|
|
110
|
-
console.error('[create-day-pass-checkout] prices.retrieve failed', String(e));
|
|
111
|
-
}
|
|
112
|
-
if (baseAmountCents === null) {
|
|
113
|
-
return new Response(JSON.stringify(couponFailureBody({ message: "That code isn't valid." })), {
|
|
114
|
-
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const outcome = await applyCheckoutCoupon(supabase, stripe, {
|
|
119
|
-
code: coupon_code,
|
|
120
|
-
fnName: 'create-day-pass-checkout',
|
|
121
|
-
planId: plan.id,
|
|
122
|
-
planSlug: plan.slug,
|
|
123
|
-
planName: plan.name,
|
|
124
|
-
emailKey,
|
|
125
|
-
baseAmountCents,
|
|
126
|
-
appliedToType: 'day_pass',
|
|
127
|
-
oneTime: true,
|
|
128
|
-
actorEmail: operator.actorEmail,
|
|
129
|
-
});
|
|
130
|
-
if (!outcome.ok) {
|
|
131
|
-
return new Response(JSON.stringify(couponFailureBody(outcome)), {
|
|
132
|
-
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
stripeCouponId = outcome.stripeCouponId;
|
|
136
|
-
couponId = outcome.couponId;
|
|
137
|
-
couponAttemptId = outcome.attemptId;
|
|
138
|
-
couponRedemptionId = outcome.redemptionId;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Reuse-or-create a Stripe Customer by email. Prefer search; fall back to list.
|
|
142
|
-
let customerId: string | null = null;
|
|
143
|
-
try {
|
|
144
|
-
const found = await stripe.customers.search({
|
|
145
|
-
query: `email:'${emailKey.replace(/'/g, "\\'")}'`,
|
|
146
|
-
limit: 1,
|
|
147
|
-
});
|
|
148
|
-
if (found.data.length > 0) customerId = found.data[0].id;
|
|
149
|
-
} catch (e) {
|
|
150
|
-
console.warn('[create-day-pass-checkout] customers.search failed', e);
|
|
151
|
-
}
|
|
152
|
-
// Search is eventually consistent (~1 min). Always fall back to list for freshly-created customers.
|
|
153
|
-
if (!customerId) {
|
|
154
|
-
try {
|
|
155
|
-
const listed = await stripe.customers.list({ email: emailKey, limit: 1 });
|
|
156
|
-
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
157
|
-
} catch (e2) {
|
|
158
|
-
console.warn('[create-day-pass-checkout] customers.list failed', e2);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
if (!customerId) {
|
|
162
|
-
const created = await stripe.customers.create({ email: emailKey });
|
|
163
|
-
customerId = created.id;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const origin = req.headers.get('origin');
|
|
167
|
-
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
168
|
-
|
|
169
|
-
const metadata: Record<string, string> = {
|
|
170
|
-
checkout_type: 'day_pass',
|
|
171
|
-
plan_slug: plan.slug,
|
|
172
|
-
plan_id: plan.id,
|
|
173
|
-
visit_date,
|
|
174
|
-
...(arrival_time ? { arrival_time } : {}),
|
|
175
|
-
// stripe-webhook reads these back to flip the reservation to 'applied'
|
|
176
|
-
// once payment lands, or reverse it if the session expires.
|
|
177
|
-
...(couponRedemptionId ? { coupon_redemption_id: couponRedemptionId } : {}),
|
|
178
|
-
...(couponId ? { coupon_id: couponId } : {}),
|
|
179
|
-
// Opaque per-attempt uuid; it is the redemption row's applied_to_id, so
|
|
180
|
-
// this is what correlates that row back to this checkout attempt.
|
|
181
|
-
...(couponAttemptId ? { coupon_attempt_id: couponAttemptId } : {}),
|
|
182
|
-
};
|
|
183
|
-
|
|
184
|
-
const session = await stripe.checkout.sessions.create(buildDayPassSessionParams({
|
|
185
|
-
customerId,
|
|
186
|
-
priceId: plan.stripe_price_id,
|
|
187
|
-
metadata,
|
|
188
|
-
receiptEmail: emailKey,
|
|
189
|
-
successUrl: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
190
|
-
cancelUrl: `${base}/pricing`,
|
|
191
|
-
stripeCouponId,
|
|
192
|
-
}));
|
|
193
|
-
|
|
194
|
-
return new Response(JSON.stringify({ url: session.url }), {
|
|
195
|
-
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
196
|
-
});
|
|
197
|
-
} catch (e) {
|
|
198
|
-
console.error('create-day-pass-checkout error', e);
|
|
199
|
-
try {
|
|
200
|
-
const opsClient = createClient(
|
|
201
|
-
Deno.env.get('SUPABASE_URL') ?? '',
|
|
202
|
-
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
|
|
203
|
-
);
|
|
204
|
-
// Checkout died after the coupon was reserved -- hand the redemption
|
|
205
|
-
// back. Runs BEFORE logOps so a failing ops write can't skip it.
|
|
206
|
-
if (couponRedemptionId) {
|
|
207
|
-
await reverseCheckoutCoupon(opsClient, couponRedemptionId,
|
|
208
|
-
'day_pass_checkout_error', 'create-day-pass-checkout', operator.actorEmail);
|
|
209
|
-
}
|
|
210
|
-
await logOps(opsClient, 'day_pass_checkout_error',
|
|
211
|
-
{ message: e instanceof Error ? e.message : String(e) },
|
|
212
|
-
{ severity: 'error' });
|
|
213
|
-
} catch { /* ignore */ }
|
|
214
|
-
return new Response(JSON.stringify({ error: 'Something went wrong starting your checkout. Please try again.' }), {
|
|
215
|
-
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
216
|
-
});
|
|
217
|
-
}
|
|
218
|
-
}
|
|
1
|
+
import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
|
|
2
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
3
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
4
|
+
import { z } from 'npm:zod@3.23.8';
|
|
5
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
6
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
7
|
+
import { applyCheckoutCoupon, couponFailureBody, reverseCheckoutCoupon } from 'npm:@simplelayer/graniteer-core/checkoutCoupon';
|
|
8
|
+
import { buildDayPassSessionParams } from 'npm:@simplelayer/graniteer-core/checkoutSessionParams';
|
|
9
|
+
|
|
10
|
+
const Body = z.object({
|
|
11
|
+
plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
|
|
12
|
+
email: z.string().email().max(255),
|
|
13
|
+
visit_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
14
|
+
arrival_time: z.string().max(20).optional(),
|
|
15
|
+
// Internal `coupons` code. An unusable code is a hard 400 -- the guest typed
|
|
16
|
+
// it expecting a discount, so charging full price silently is wrong.
|
|
17
|
+
coupon_code: z.string().trim().min(1).max(40).regex(/^[A-Za-z0-9_-]+$/).optional(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
function todayLA(): string {
|
|
21
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
22
|
+
timeZone: 'America/Los_Angeles',
|
|
23
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
24
|
+
}).format(new Date());
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function handle(req: Request, operator: { domain: string; actorEmail: string }): Promise<Response> {
|
|
28
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
29
|
+
|
|
30
|
+
// Set once a coupon reservation exists. Held at handler scope so the outer
|
|
31
|
+
// catch can release it if anything after the reservation throws.
|
|
32
|
+
let couponRedemptionId: string | null = null;
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
const raw = await req.json().catch(() => ({}));
|
|
36
|
+
const parsed = Body.safeParse(raw);
|
|
37
|
+
if (!parsed.success) {
|
|
38
|
+
return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
|
|
39
|
+
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const { plan_slug, email, visit_date, arrival_time, coupon_code } = parsed.data;
|
|
43
|
+
const emailKey = email.toLowerCase();
|
|
44
|
+
|
|
45
|
+
if (visit_date < todayLA()) {
|
|
46
|
+
return new Response(JSON.stringify({ error: "Visit date can't be in the past." }), {
|
|
47
|
+
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const supabase = createClient(
|
|
52
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
53
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
// Fail-open rate limiting (own buckets — do not share with subscriptions).
|
|
57
|
+
const ip = clientIp(req);
|
|
58
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
59
|
+
checkRateLimit(supabase, 'create-day-pass', ip, 10, 600),
|
|
60
|
+
checkRateLimit(supabase, 'create-day-pass-email', emailKey, 5, 600),
|
|
61
|
+
]);
|
|
62
|
+
if (!ipOk || !emailOk) {
|
|
63
|
+
return new Response(
|
|
64
|
+
JSON.stringify({ error: 'Too many checkout attempts — please wait a few minutes and try again.' }),
|
|
65
|
+
{ status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const { data: plan, error: pErr } = await supabase
|
|
70
|
+
.from('membership_plans')
|
|
71
|
+
.select('id,slug,name,active,billable,billing_interval,stripe_price_id,stripe_product_id,price_cents')
|
|
72
|
+
.eq('slug', plan_slug)
|
|
73
|
+
.maybeSingle();
|
|
74
|
+
if (pErr) throw pErr;
|
|
75
|
+
if (
|
|
76
|
+
!plan ||
|
|
77
|
+
plan.active !== true ||
|
|
78
|
+
plan.billable !== true ||
|
|
79
|
+
!plan.stripe_price_id ||
|
|
80
|
+
plan.billing_interval === 'month'
|
|
81
|
+
) {
|
|
82
|
+
return new Response(JSON.stringify({ error: 'That plan is not available for one-time checkout.' }), {
|
|
83
|
+
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
88
|
+
if (!stripeKey) {
|
|
89
|
+
return new Response(JSON.stringify({ error: 'Payments not configured (missing STRIPE_SECRET_KEY).' }), {
|
|
90
|
+
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
94
|
+
|
|
95
|
+
// === Optional internal coupon ===
|
|
96
|
+
// Runs BEFORE any Stripe Customer or Session is created: a bad code should
|
|
97
|
+
// cost one read-only RPC, not a customer record and an abandoned session.
|
|
98
|
+
let stripeCouponId: string | null = null;
|
|
99
|
+
let couponId: string | null = null;
|
|
100
|
+
let couponAttemptId: string | null = null;
|
|
101
|
+
if (coupon_code) {
|
|
102
|
+
// Day-pass plans always bill off a stored Stripe Price (enforced by the
|
|
103
|
+
// eligibility check above), so the amount Stripe will charge has to come
|
|
104
|
+
// from Stripe -- price_cents is not authoritative here.
|
|
105
|
+
let baseAmountCents: number | null = null;
|
|
106
|
+
try {
|
|
107
|
+
const price = await stripe.prices.retrieve(plan.stripe_price_id);
|
|
108
|
+
baseAmountCents = price.unit_amount ?? null;
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.error('[create-day-pass-checkout] prices.retrieve failed', String(e));
|
|
111
|
+
}
|
|
112
|
+
if (baseAmountCents === null) {
|
|
113
|
+
return new Response(JSON.stringify(couponFailureBody({ message: "That code isn't valid." })), {
|
|
114
|
+
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const outcome = await applyCheckoutCoupon(supabase, stripe, {
|
|
119
|
+
code: coupon_code,
|
|
120
|
+
fnName: 'create-day-pass-checkout',
|
|
121
|
+
planId: plan.id,
|
|
122
|
+
planSlug: plan.slug,
|
|
123
|
+
planName: plan.name,
|
|
124
|
+
emailKey,
|
|
125
|
+
baseAmountCents,
|
|
126
|
+
appliedToType: 'day_pass',
|
|
127
|
+
oneTime: true,
|
|
128
|
+
actorEmail: operator.actorEmail,
|
|
129
|
+
});
|
|
130
|
+
if (!outcome.ok) {
|
|
131
|
+
return new Response(JSON.stringify(couponFailureBody(outcome)), {
|
|
132
|
+
status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
stripeCouponId = outcome.stripeCouponId;
|
|
136
|
+
couponId = outcome.couponId;
|
|
137
|
+
couponAttemptId = outcome.attemptId;
|
|
138
|
+
couponRedemptionId = outcome.redemptionId;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Reuse-or-create a Stripe Customer by email. Prefer search; fall back to list.
|
|
142
|
+
let customerId: string | null = null;
|
|
143
|
+
try {
|
|
144
|
+
const found = await stripe.customers.search({
|
|
145
|
+
query: `email:'${emailKey.replace(/'/g, "\\'")}'`,
|
|
146
|
+
limit: 1,
|
|
147
|
+
});
|
|
148
|
+
if (found.data.length > 0) customerId = found.data[0].id;
|
|
149
|
+
} catch (e) {
|
|
150
|
+
console.warn('[create-day-pass-checkout] customers.search failed', e);
|
|
151
|
+
}
|
|
152
|
+
// Search is eventually consistent (~1 min). Always fall back to list for freshly-created customers.
|
|
153
|
+
if (!customerId) {
|
|
154
|
+
try {
|
|
155
|
+
const listed = await stripe.customers.list({ email: emailKey, limit: 1 });
|
|
156
|
+
if (listed.data.length > 0) customerId = listed.data[0].id;
|
|
157
|
+
} catch (e2) {
|
|
158
|
+
console.warn('[create-day-pass-checkout] customers.list failed', e2);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!customerId) {
|
|
162
|
+
const created = await stripe.customers.create({ email: emailKey });
|
|
163
|
+
customerId = created.id;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const origin = req.headers.get('origin');
|
|
167
|
+
const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
|
|
168
|
+
|
|
169
|
+
const metadata: Record<string, string> = {
|
|
170
|
+
checkout_type: 'day_pass',
|
|
171
|
+
plan_slug: plan.slug,
|
|
172
|
+
plan_id: plan.id,
|
|
173
|
+
visit_date,
|
|
174
|
+
...(arrival_time ? { arrival_time } : {}),
|
|
175
|
+
// stripe-webhook reads these back to flip the reservation to 'applied'
|
|
176
|
+
// once payment lands, or reverse it if the session expires.
|
|
177
|
+
...(couponRedemptionId ? { coupon_redemption_id: couponRedemptionId } : {}),
|
|
178
|
+
...(couponId ? { coupon_id: couponId } : {}),
|
|
179
|
+
// Opaque per-attempt uuid; it is the redemption row's applied_to_id, so
|
|
180
|
+
// this is what correlates that row back to this checkout attempt.
|
|
181
|
+
...(couponAttemptId ? { coupon_attempt_id: couponAttemptId } : {}),
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const session = await stripe.checkout.sessions.create(buildDayPassSessionParams({
|
|
185
|
+
customerId,
|
|
186
|
+
priceId: plan.stripe_price_id,
|
|
187
|
+
metadata,
|
|
188
|
+
receiptEmail: emailKey,
|
|
189
|
+
successUrl: `${base}/day-pass/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
190
|
+
cancelUrl: `${base}/pricing`,
|
|
191
|
+
stripeCouponId,
|
|
192
|
+
}));
|
|
193
|
+
|
|
194
|
+
return new Response(JSON.stringify({ url: session.url }), {
|
|
195
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
196
|
+
});
|
|
197
|
+
} catch (e) {
|
|
198
|
+
console.error('create-day-pass-checkout error', e);
|
|
199
|
+
try {
|
|
200
|
+
const opsClient = createClient(
|
|
201
|
+
Deno.env.get('SUPABASE_URL') ?? '',
|
|
202
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
|
|
203
|
+
);
|
|
204
|
+
// Checkout died after the coupon was reserved -- hand the redemption
|
|
205
|
+
// back. Runs BEFORE logOps so a failing ops write can't skip it.
|
|
206
|
+
if (couponRedemptionId) {
|
|
207
|
+
await reverseCheckoutCoupon(opsClient, couponRedemptionId,
|
|
208
|
+
'day_pass_checkout_error', 'create-day-pass-checkout', operator.actorEmail);
|
|
209
|
+
}
|
|
210
|
+
await logOps(opsClient, 'day_pass_checkout_error',
|
|
211
|
+
{ message: e instanceof Error ? e.message : String(e) },
|
|
212
|
+
{ severity: 'error' });
|
|
213
|
+
} catch { /* ignore */ }
|
|
214
|
+
return new Response(JSON.stringify({ error: 'Something went wrong starting your checkout. Please try again.' }), {
|
|
215
|
+
status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|