@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.
Files changed (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -460
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -334
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -217
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,455 +1,455 @@
1
- // Internal `coupons` table -> Stripe Checkout, for the two PUBLIC self-serve
2
- // checkout paths (create-subscription-checkout, create-day-pass-checkout).
3
- //
4
- // Why this exists: both of those functions set `allow_promotion_codes: true`,
5
- // which only ever matches a real Stripe Promotion Code object. A code created
6
- // in our own `coupons` table was therefore silently rejected at Stripe's
7
- // checkout page. This module is the bridge: validate + reserve against the
8
- // internal system, then mint a ONE-OFF Stripe Coupon carrying the same
9
- // discount and hand its id to the session as `discounts`.
10
- //
11
- // The internal system stays the source of truth for eligibility, scoping and
12
- // redemption counting. Stripe only ever sees a disposable coupon object.
13
- //
14
- // Mirrors create-booking's coupon block (validate -> redeem -> mark applied at
15
- // payment, reverse on abandon); the only genuinely new part is the Stripe
16
- // Coupon object, which the booking path doesn't need because it computes its
17
- // own charge amount rather than handing a Price to Checkout.
18
-
19
- import type Stripe from 'npm:stripe@17.5.0';
20
-
21
- /**
22
- * Structural subset of the service-role Supabase client this module uses.
23
- * `rpc` is PromiseLike, not Promise: supabase-js returns a thenable
24
- * PostgrestFilterBuilder, and requiring a real Promise here makes the live
25
- * client structurally incompatible.
26
- */
27
- export interface CouponSupabaseClient {
28
- // deno-lint-ignore no-explicit-any
29
- rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: any; error: any }>;
30
- // deno-lint-ignore no-explicit-any
31
- from(table: string): any;
32
- }
33
-
34
- /** Structural subset of the Stripe client this module uses. */
35
- export interface CouponStripeClient {
36
- coupons: {
37
- create(params: Stripe.CouponCreateParams): Promise<{ id: string }>;
38
- retrieve(id: string): Promise<{ id: string }>;
39
- };
40
- }
41
-
42
- export interface CouponRow {
43
- id: string;
44
- discount_type: string;
45
- value: number;
46
- duration: string;
47
- duration_in_months: number | null;
48
- applies_to: string;
49
- }
50
-
51
- /**
52
- * Which `coupons.applies_to` values are legal for each checkout path here.
53
- *
54
- * coupon_validate checks the validity window, the redemption caps and
55
- * coupon_scopes rows -- it never looks at applies_to at all. That was harmless
56
- * while create-booking was the only caller (a 'booking' coupon could only ever
57
- * reach a booking); these two self-serve paths are the first that let a
58
- * customer-typed code reach `coupons` from the membership / day-pass modals,
59
- * so the category has to be enforced on this side.
60
- *
61
- * - membership: this checkout creates a Stripe SUBSCRIPTION, so 'subscription'
62
- * is the matching category. 'all' is the universal opt-in.
63
- * - day_pass: a one-time (mode:'payment') purchase. It is not a subscription,
64
- * not a room booking, and not an office agreement -- the admin UI offers no
65
- * day-pass-specific value -- so only the universal 'all' fits.
66
- */
67
- export const APPLIES_TO_BY_CHECKOUT: Record<'membership' | 'day_pass', readonly string[]> = {
68
- membership: ['subscription', 'all'],
69
- day_pass: ['all'],
70
- };
71
-
72
- export type CouponOutcome =
73
- | {
74
- ok: true;
75
- /** id of the disposable Stripe Coupon to put in `discounts`. */
76
- stripeCouponId: string;
77
- /** coupon_redemptions.id -- goes on session metadata for the webhook. */
78
- redemptionId: string;
79
- /** coupons.id -- goes on session metadata for the webhook. */
80
- couponId: string;
81
- /**
82
- * Opaque per-attempt uuid used as coupon_redemptions.applied_to_id.
83
- * Also stamped on session metadata so a human can correlate the
84
- * redemption row back to the checkout attempt that created it.
85
- */
86
- attemptId: string;
87
- discountCents: number;
88
- }
89
- | { ok: false; reason: string; message: string };
90
-
91
- /**
92
- * User-facing text per coupon_validate `reason`. Deliberately vague about WHY
93
- * a code is unknown -- a public endpoint must not confirm which codes exist.
94
- */
95
- export const COUPON_ERROR_MESSAGES: Record<string, string> = {
96
- COUPON_EXPIRED: 'That code has expired.',
97
- COUPON_NOT_YET_VALID: "That code isn't active yet.",
98
- COUPON_LIMIT_REACHED: 'That code has already been fully redeemed.',
99
- COUPON_OUT_OF_SCOPE: "That code isn't valid for this plan.",
100
- COUPON_ALREADY_APPLIED: "You've already used that code.",
101
- };
102
- const DEFAULT_COUPON_ERROR = "That code isn't valid.";
103
-
104
- /**
105
- * Refusal text for coupon_code + a future start_date on the same subscription
106
- * checkout. Nobody has verified which invoice Stripe attaches a `discounts`
107
- * coupon to when `subscription_data.billing_cycle_anchor` is in the future --
108
- * a duration:'once' coupon could burn on a $0/placeholder invoice at session
109
- * creation and leave the real first charge at the anchor date at full price,
110
- * while the internal redemption already reads 'applied'. Resolving that needs
111
- * a live Stripe experiment, which this account (no test mode) can't absorb, so
112
- * the combination is refused instead of guessed at.
113
- */
114
- export const COUPON_START_DATE_CONFLICT_MESSAGE =
115
- "Discount codes can't be combined with a scheduled start date right now — leave the start date blank to use this code, or remove the code to schedule a future start.";
116
-
117
- export function couponErrorMessage(reason: string | null | undefined): string {
118
- return COUPON_ERROR_MESSAGES[String(reason ?? '')] ?? DEFAULT_COUPON_ERROR;
119
- }
120
-
121
- /**
122
- * Maps a thrown coupon_redeem error onto the same reason vocabulary
123
- * coupon_validate uses. The RPC raises `COUPON_LIMIT_REACHED: per-member cap
124
- * N reached` and friends, so match on the prefix rather than equality.
125
- */
126
- export function reasonFromRedeemError(e: unknown): string {
127
- const msg = e instanceof Error ? e.message : String((e as { message?: string })?.message ?? e ?? '');
128
- if (msg.includes('COUPON_LIMIT_REACHED')) return 'COUPON_LIMIT_REACHED';
129
- if (msg.includes('COUPON_ALREADY_APPLIED')) return 'COUPON_ALREADY_APPLIED';
130
- if (msg.includes('COUPON_NOT_APPLICABLE')) return 'COUPON_NOT_APPLICABLE';
131
- return 'COUPON_NOT_APPLICABLE';
132
- }
133
-
134
- /**
135
- * Internal coupons row -> Stripe CouponCreateParams.
136
- *
137
- * `value` follows the live coupon_validate / coupon_redeem math, which is
138
- * `base * value / 100.0` for percent -- i.e. value is a plain percentage
139
- * (100 = 100% off), NOT the basis points the (stale) column COMMENT claims.
140
- * Keeping the same convention here is what makes the Stripe-side discount
141
- * equal the discount_cents the internal system just recorded.
142
- *
143
- * `forceOnce` is for one-time (mode: 'payment') checkouts, where a
144
- * repeating/forever duration is meaningless -- there is no second invoice for
145
- * it to apply to.
146
- */
147
- export function buildStripeCouponParams(
148
- row: CouponRow,
149
- opts: { id: string; name?: string; forceOnce?: boolean; metadata?: Record<string, string> },
150
- ): Stripe.CouponCreateParams {
151
- // The (stale) column COMMENT says percent is stored in basis points, so some
152
- // rows may have been authored as 1000-for-10%. coupon_validate/coupon_redeem
153
- // clamp the COMPUTED cents to the base amount and so never expose this, but
154
- // percent_off goes to Stripe raw. Refuse rather than let a mis-scaled value
155
- // reach the API, where anything in 100 < value <= 10000 might not be cleanly
156
- // rejected.
157
- if (row.discount_type === 'percent' && !(row.value <= 100)) {
158
- throw new Error(`COUPON_CONFIG_INVALID: percent value ${row.value} exceeds 100`);
159
- }
160
-
161
- const params: Stripe.CouponCreateParams = {
162
- id: opts.id,
163
- // One checkout, one coupon object. Even if the id leaked it could not be
164
- // applied a second time.
165
- max_redemptions: 1,
166
- ...(opts.name ? { name: opts.name } : {}),
167
- ...(opts.metadata ? { metadata: opts.metadata } : {}),
168
- };
169
-
170
- if (row.discount_type === 'percent') {
171
- params.percent_off = row.value;
172
- } else {
173
- params.amount_off = row.value;
174
- params.currency = 'usd';
175
- }
176
-
177
- const duration = opts.forceOnce ? 'once' : row.duration;
178
- if (duration === 'forever') {
179
- params.duration = 'forever';
180
- } else if (duration === 'once') {
181
- params.duration = 'once';
182
- } else {
183
- // Stripe requires duration_in_months for, and ONLY for, 'repeating'.
184
- // A repeating coupon with no month count is a data error we must not
185
- // paper over with a guessed 1 -- that would silently under-discount.
186
- if (!Number.isInteger(row.duration_in_months) || (row.duration_in_months as number) < 1) {
187
- throw new Error(`COUPON_CONFIG_INVALID: duration 'repeating' with duration_in_months=${row.duration_in_months}`);
188
- }
189
- params.duration = 'repeating';
190
- params.duration_in_months = row.duration_in_months as number;
191
- }
192
-
193
- return params;
194
- }
195
-
196
- /**
197
- * Deterministic id so a retried checkout for the same reservation reuses the
198
- * same Stripe Coupon object instead of littering the account with orphans.
199
- * Stripe coupon ids are free-form strings; our redemption uuid is unique.
200
- */
201
- function stripeCouponIdFor(redemptionId: string): string {
202
- return `gcc-${redemptionId}`;
203
- }
204
-
205
- async function createOrReuseStripeCoupon(
206
- stripe: CouponStripeClient,
207
- params: Stripe.CouponCreateParams,
208
- ): Promise<string> {
209
- try {
210
- const created = await stripe.coupons.create(params);
211
- return created.id;
212
- } catch (e) {
213
- const code = (e as { code?: string })?.code;
214
- if (code === 'resource_already_exists') {
215
- // Same reservation, retried checkout -- the object from the first
216
- // attempt is still exactly the discount we want.
217
- const existing = await stripe.coupons.retrieve(params.id as string);
218
- return existing.id;
219
- }
220
- throw e;
221
- }
222
- }
223
-
224
- /**
225
- * Validate -> reserve -> mint a Stripe Coupon.
226
- *
227
- * Returns `{ ok: false }` for every "this code can't be used" outcome
228
- * (invalid, expired, out of scope, limit reached, already applied, bad coupon
229
- * config) so the caller can answer 400 with a user-facing message. Only a
230
- * genuine infrastructure failure throws.
231
- *
232
- * NOTE the reservation is `status='reserved'`, not applied. stripe-webhook
233
- * flips it to 'applied' when the payment actually lands, and reverses it if
234
- * the checkout session expires.
235
- */
236
- export async function applyCheckoutCoupon(
237
- supabase: CouponSupabaseClient,
238
- stripe: CouponStripeClient,
239
- opts: {
240
- code: string;
241
- /** Log prefix, e.g. 'create-subscription-checkout'. */
242
- fnName: string;
243
- planId: string;
244
- planSlug: string;
245
- planName: string;
246
- emailKey: string;
247
- baseAmountCents: number;
248
- appliedToType: 'membership' | 'day_pass';
249
- /** true for mode:'payment' checkouts -- forces a 'once' Stripe duration. */
250
- oneTime: boolean;
251
- /** System-actor email recorded on coupon_reverse if the mint step fails. */
252
- actorEmail: string;
253
- },
254
- ): Promise<CouponOutcome> {
255
- const fail = (reason: string): CouponOutcome => ({ ok: false, reason, message: couponErrorMessage(reason) });
256
-
257
- // 1) Read-only eligibility check. p_membership_id is null on purpose: at
258
- // checkout time no membership row exists yet for a new signup, so the
259
- // per-member cap can only be enforced by coupon_redeem (which keys on
260
- // the email we're about to reserve under).
261
- let validated: { valid?: boolean; coupon_id?: string; discount_cents?: number; reason?: string } | null = null;
262
- try {
263
- const { data, error } = await supabase.rpc('coupon_validate', {
264
- p_code: opts.code,
265
- p_membership_id: null,
266
- p_scope_type: 'plan',
267
- p_scope_target_id: opts.planId,
268
- p_base_amount_cents: opts.baseAmountCents,
269
- });
270
- if (error) throw error;
271
- validated = (Array.isArray(data) ? data[0] : data) ?? null;
272
- } catch (e) {
273
- // Fail CLOSED. Silently dropping the code would charge full price to
274
- // someone who believes they're getting a discount -- worse than a retry.
275
- console.error(`[${opts.fnName}] coupon_validate failed`, String(e));
276
- return fail('COUPON_VALIDATE_FAILED');
277
- }
278
- if (!validated?.valid || !validated.coupon_id) {
279
- return fail(validated?.reason ?? 'COUPON_NOT_APPLICABLE');
280
- }
281
- const couponId = validated.coupon_id;
282
-
283
- // 2) The discount shape itself. coupon_validate returns only the computed
284
- // cents, but Stripe needs percent/amount + duration.
285
- let row: CouponRow | null = null;
286
- try {
287
- const { data, error } = await supabase
288
- .from('coupons')
289
- .select('id,discount_type,value,duration,duration_in_months,applies_to')
290
- .eq('id', couponId)
291
- .maybeSingle();
292
- if (error) throw error;
293
- row = (data as CouponRow | null) ?? null;
294
- } catch (e) {
295
- console.error(`[${opts.fnName}] coupon row lookup failed`, String(e));
296
- return fail('COUPON_VALIDATE_FAILED');
297
- }
298
- if (!row) return fail('COUPON_NOT_APPLICABLE');
299
-
300
- // 2b) Enforce coupons.applies_to. Deliberately BEFORE coupon_redeem, so a
301
- // wrong-category code costs two reads and reserves nothing. Without this,
302
- // an unscoped coupon authored as 'booking' or 'office' is redeemable
303
- // against a live subscription through this new path, carrying a `duration`
304
- // that was never vetted for recurring use (create-booking ignores
305
- // `duration` entirely -- it computes its own one-time amount).
306
- if (!APPLIES_TO_BY_CHECKOUT[opts.appliedToType].includes(row.applies_to)) {
307
- console.warn(`[${opts.fnName}] coupon applies_to does not cover this checkout`,
308
- { coupon_id: couponId, applies_to: row.applies_to, applied_to_type: opts.appliedToType });
309
- return fail('COUPON_OUT_OF_SCOPE');
310
- }
311
-
312
- // 3) Reserve. Idempotency key is deliberately DETERMINISTIC -- a user who
313
- // abandons Stripe and retries with the same code must land on the same
314
- // reservation row, not burn a second redemption.
315
- let redemptionId: string | null = null;
316
- let discountCents = validated.discount_cents ?? 0;
317
- // Opaque per-attempt id for applied_to_id. It must NOT be plan.id: a partial
318
- // unique index (applied_to_type, applied_to_id) WHERE status <> 'reversed'
319
- // enforces "one non-reversed coupon per transaction", so a plan-wide value
320
- // would let exactly one customer ever redeem any code against that plan.
321
- // The column is uuid NOT NULL with no FK, so a generated uuid is legal.
322
- const attemptId = crypto.randomUUID();
323
- const redeemArgs = {
324
- p_coupon_id: couponId,
325
- p_member_email: opts.emailKey,
326
- p_applied_to_type: opts.appliedToType,
327
- // No membership / day_pass_purchases row exists yet at checkout time --
328
- // both are created by stripe-webhook after payment. This uuid is carried
329
- // on the session metadata as coupon_attempt_id so the row stays traceable.
330
- p_applied_to_id: attemptId,
331
- p_base_amount_cents: opts.baseAmountCents,
332
- };
333
- const stableKey = `${opts.planSlug}:${opts.emailKey}:${couponId}`;
334
- try {
335
- const { data, error } = await supabase.rpc('coupon_redeem', {
336
- ...redeemArgs,
337
- p_idempotency_key: stableKey,
338
- });
339
- if (error) throw error;
340
- type RedeemRow = { id?: string; amount_applied_cents?: number; status?: string } | null;
341
- let red = (Array.isArray(data) ? data[0] : data) as RedeemRow;
342
- if (!red?.id) throw new Error('coupon_redeem returned no row');
343
-
344
- // coupon_redeem's first statement returns any row matching the idempotency
345
- // key REGARDLESS of status, and our key is stable forever -- so this can
346
- // hand back a row that is already settled.
347
- if (red.status === 'applied') {
348
- // This customer already PAID with this code on this plan. The Stripe
349
- // coupon is spent and redeemed_count still counts it; minting a fresh
350
- // discount would be a real discount the counters don't reflect.
351
- console.warn(`[${opts.fnName}] coupon_redeem returned an already-applied row`,
352
- { redemption_id: red.id });
353
- return fail('COUPON_ALREADY_APPLIED');
354
- }
355
- if (red.status === 'reversed') {
356
- // The earlier reservation was handed back -- by an expired session, or by
357
- // reverseCheckoutCoupon after a transient failure in an earlier request
358
- // (stripe.customers.search throwing, the coupon mint failing, ...).
359
- // coupon_reverse's count sync already gave the redemption back, so the
360
- // coupon is NOT exhausted; only this eternal key is pinned to a dead row.
361
- // Refusing here would lock the customer out of a still-valid code forever
362
- // on a false "fully redeemed" message. Re-issue with a freshened key so
363
- // the INSERT actually runs. That second call takes coupon_redeem's own
364
- // FOR UPDATE lock and re-checks max_redemptions AND the per-member cap
365
- // for real, so it cannot grant an over-limit redemption.
366
- console.warn(`[${opts.fnName}] coupon_redeem returned a reversed row -- retrying with a fresh key`,
367
- { redemption_id: red.id });
368
- const { data: retryData, error: retryError } = await supabase.rpc('coupon_redeem', {
369
- ...redeemArgs,
370
- p_idempotency_key: `${stableKey}:${crypto.randomUUID()}`,
371
- });
372
- if (retryError) throw retryError;
373
- red = (Array.isArray(retryData) ? retryData[0] : retryData) as RedeemRow;
374
- if (!red?.id) throw new Error('coupon_redeem returned no row');
375
- }
376
- // Fallback: anything still not 'reserved' fails closed rather than looping.
377
- if (red.status !== 'reserved') {
378
- console.warn(`[${opts.fnName}] coupon_redeem returned a non-reserved row`,
379
- { redemption_id: red.id, status: red.status });
380
- return fail('COUPON_LIMIT_REACHED');
381
- }
382
- redemptionId = red.id;
383
- discountCents = red.amount_applied_cents ?? discountCents;
384
- } catch (e) {
385
- console.warn(`[${opts.fnName}] coupon_redeem failed`, String(e));
386
- return fail(reasonFromRedeemError(e));
387
- }
388
-
389
- // 4) Mint the disposable Stripe Coupon.
390
- try {
391
- const params = buildStripeCouponParams(row, {
392
- id: stripeCouponIdFor(redemptionId),
393
- name: `${opts.planName} — ${opts.code.toUpperCase()}`,
394
- forceOnce: opts.oneTime,
395
- metadata: {
396
- coupon_redemption_id: redemptionId,
397
- coupon_id: couponId,
398
- coupon_attempt_id: attemptId,
399
- plan_slug: opts.planSlug,
400
- },
401
- });
402
- const stripeCouponId = await createOrReuseStripeCoupon(stripe, params);
403
- return { ok: true, stripeCouponId, redemptionId, couponId, attemptId, discountCents };
404
- } catch (e) {
405
- // The reservation is already on the books but no discount will reach
406
- // Stripe -- release it now rather than leaving a single-use code
407
- // permanently consumed by a checkout that never started.
408
- console.error(`[${opts.fnName}] stripe coupon create failed`, String(e));
409
- await reverseCheckoutCoupon(supabase, redemptionId, 'stripe_coupon_create_failed', opts.fnName, opts.actorEmail);
410
- return fail('COUPON_STRIPE_FAILED');
411
- }
412
- }
413
-
414
- /**
415
- * Best-effort release of a reservation. Never throws -- every caller is on a
416
- * path where the customer-visible outcome is already decided.
417
- *
418
- * Only ever touches a still-'reserved' row. coupon_reverse itself has no
419
- * status precondition and will happily flip an 'applied' redemption -- one
420
- * that funded a real payment -- to 'reversed'. Same guard stripe-webhook's
421
- * reverseCouponFromMetadata already carries.
422
- */
423
- export async function reverseCheckoutCoupon(
424
- supabase: CouponSupabaseClient,
425
- redemptionId: string,
426
- reason: string,
427
- fnName: string,
428
- actorEmail: string,
429
- ): Promise<void> {
430
- try {
431
- const { data: redRow, error: readErr } = await supabase
432
- .from('coupon_redemptions')
433
- .select('id,status')
434
- .eq('id', redemptionId)
435
- .maybeSingle();
436
- if (readErr) throw readErr;
437
- if (!redRow) throw new Error('coupon_redemptions row not found');
438
- // Already settled either way -- nothing to release.
439
- if (redRow.status !== 'reserved') return;
440
-
441
- const { error } = await supabase.rpc('coupon_reverse', {
442
- p_redemption_id: redemptionId,
443
- p_reason: reason,
444
- p_actor_email: actorEmail,
445
- });
446
- if (error) throw error;
447
- } catch (e) {
448
- console.error(`[${fnName}] coupon_reverse failed`, String(e));
449
- }
450
- }
451
-
452
- /** 400 body shape. `field` lets the modal put the message under the code input. */
453
- export function couponFailureBody(failure: { message: string }): { error: string; field: string } {
454
- return { error: failure.message, field: 'coupon_code' };
455
- }
1
+ // Internal `coupons` table -> Stripe Checkout, for the two PUBLIC self-serve
2
+ // checkout paths (create-subscription-checkout, create-day-pass-checkout).
3
+ //
4
+ // Why this exists: both of those functions set `allow_promotion_codes: true`,
5
+ // which only ever matches a real Stripe Promotion Code object. A code created
6
+ // in our own `coupons` table was therefore silently rejected at Stripe's
7
+ // checkout page. This module is the bridge: validate + reserve against the
8
+ // internal system, then mint a ONE-OFF Stripe Coupon carrying the same
9
+ // discount and hand its id to the session as `discounts`.
10
+ //
11
+ // The internal system stays the source of truth for eligibility, scoping and
12
+ // redemption counting. Stripe only ever sees a disposable coupon object.
13
+ //
14
+ // Mirrors create-booking's coupon block (validate -> redeem -> mark applied at
15
+ // payment, reverse on abandon); the only genuinely new part is the Stripe
16
+ // Coupon object, which the booking path doesn't need because it computes its
17
+ // own charge amount rather than handing a Price to Checkout.
18
+
19
+ import type Stripe from 'npm:stripe@17.5.0';
20
+
21
+ /**
22
+ * Structural subset of the service-role Supabase client this module uses.
23
+ * `rpc` is PromiseLike, not Promise: supabase-js returns a thenable
24
+ * PostgrestFilterBuilder, and requiring a real Promise here makes the live
25
+ * client structurally incompatible.
26
+ */
27
+ export interface CouponSupabaseClient {
28
+ // deno-lint-ignore no-explicit-any
29
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: any; error: any }>;
30
+ // deno-lint-ignore no-explicit-any
31
+ from(table: string): any;
32
+ }
33
+
34
+ /** Structural subset of the Stripe client this module uses. */
35
+ export interface CouponStripeClient {
36
+ coupons: {
37
+ create(params: Stripe.CouponCreateParams): Promise<{ id: string }>;
38
+ retrieve(id: string): Promise<{ id: string }>;
39
+ };
40
+ }
41
+
42
+ export interface CouponRow {
43
+ id: string;
44
+ discount_type: string;
45
+ value: number;
46
+ duration: string;
47
+ duration_in_months: number | null;
48
+ applies_to: string;
49
+ }
50
+
51
+ /**
52
+ * Which `coupons.applies_to` values are legal for each checkout path here.
53
+ *
54
+ * coupon_validate checks the validity window, the redemption caps and
55
+ * coupon_scopes rows -- it never looks at applies_to at all. That was harmless
56
+ * while create-booking was the only caller (a 'booking' coupon could only ever
57
+ * reach a booking); these two self-serve paths are the first that let a
58
+ * customer-typed code reach `coupons` from the membership / day-pass modals,
59
+ * so the category has to be enforced on this side.
60
+ *
61
+ * - membership: this checkout creates a Stripe SUBSCRIPTION, so 'subscription'
62
+ * is the matching category. 'all' is the universal opt-in.
63
+ * - day_pass: a one-time (mode:'payment') purchase. It is not a subscription,
64
+ * not a room booking, and not an office agreement -- the admin UI offers no
65
+ * day-pass-specific value -- so only the universal 'all' fits.
66
+ */
67
+ export const APPLIES_TO_BY_CHECKOUT: Record<'membership' | 'day_pass', readonly string[]> = {
68
+ membership: ['subscription', 'all'],
69
+ day_pass: ['all'],
70
+ };
71
+
72
+ export type CouponOutcome =
73
+ | {
74
+ ok: true;
75
+ /** id of the disposable Stripe Coupon to put in `discounts`. */
76
+ stripeCouponId: string;
77
+ /** coupon_redemptions.id -- goes on session metadata for the webhook. */
78
+ redemptionId: string;
79
+ /** coupons.id -- goes on session metadata for the webhook. */
80
+ couponId: string;
81
+ /**
82
+ * Opaque per-attempt uuid used as coupon_redemptions.applied_to_id.
83
+ * Also stamped on session metadata so a human can correlate the
84
+ * redemption row back to the checkout attempt that created it.
85
+ */
86
+ attemptId: string;
87
+ discountCents: number;
88
+ }
89
+ | { ok: false; reason: string; message: string };
90
+
91
+ /**
92
+ * User-facing text per coupon_validate `reason`. Deliberately vague about WHY
93
+ * a code is unknown -- a public endpoint must not confirm which codes exist.
94
+ */
95
+ export const COUPON_ERROR_MESSAGES: Record<string, string> = {
96
+ COUPON_EXPIRED: 'That code has expired.',
97
+ COUPON_NOT_YET_VALID: "That code isn't active yet.",
98
+ COUPON_LIMIT_REACHED: 'That code has already been fully redeemed.',
99
+ COUPON_OUT_OF_SCOPE: "That code isn't valid for this plan.",
100
+ COUPON_ALREADY_APPLIED: "You've already used that code.",
101
+ };
102
+ const DEFAULT_COUPON_ERROR = "That code isn't valid.";
103
+
104
+ /**
105
+ * Refusal text for coupon_code + a future start_date on the same subscription
106
+ * checkout. Nobody has verified which invoice Stripe attaches a `discounts`
107
+ * coupon to when `subscription_data.billing_cycle_anchor` is in the future --
108
+ * a duration:'once' coupon could burn on a $0/placeholder invoice at session
109
+ * creation and leave the real first charge at the anchor date at full price,
110
+ * while the internal redemption already reads 'applied'. Resolving that needs
111
+ * a live Stripe experiment, which this account (no test mode) can't absorb, so
112
+ * the combination is refused instead of guessed at.
113
+ */
114
+ export const COUPON_START_DATE_CONFLICT_MESSAGE =
115
+ "Discount codes can't be combined with a scheduled start date right now — leave the start date blank to use this code, or remove the code to schedule a future start.";
116
+
117
+ export function couponErrorMessage(reason: string | null | undefined): string {
118
+ return COUPON_ERROR_MESSAGES[String(reason ?? '')] ?? DEFAULT_COUPON_ERROR;
119
+ }
120
+
121
+ /**
122
+ * Maps a thrown coupon_redeem error onto the same reason vocabulary
123
+ * coupon_validate uses. The RPC raises `COUPON_LIMIT_REACHED: per-member cap
124
+ * N reached` and friends, so match on the prefix rather than equality.
125
+ */
126
+ export function reasonFromRedeemError(e: unknown): string {
127
+ const msg = e instanceof Error ? e.message : String((e as { message?: string })?.message ?? e ?? '');
128
+ if (msg.includes('COUPON_LIMIT_REACHED')) return 'COUPON_LIMIT_REACHED';
129
+ if (msg.includes('COUPON_ALREADY_APPLIED')) return 'COUPON_ALREADY_APPLIED';
130
+ if (msg.includes('COUPON_NOT_APPLICABLE')) return 'COUPON_NOT_APPLICABLE';
131
+ return 'COUPON_NOT_APPLICABLE';
132
+ }
133
+
134
+ /**
135
+ * Internal coupons row -> Stripe CouponCreateParams.
136
+ *
137
+ * `value` follows the live coupon_validate / coupon_redeem math, which is
138
+ * `base * value / 100.0` for percent -- i.e. value is a plain percentage
139
+ * (100 = 100% off), NOT the basis points the (stale) column COMMENT claims.
140
+ * Keeping the same convention here is what makes the Stripe-side discount
141
+ * equal the discount_cents the internal system just recorded.
142
+ *
143
+ * `forceOnce` is for one-time (mode: 'payment') checkouts, where a
144
+ * repeating/forever duration is meaningless -- there is no second invoice for
145
+ * it to apply to.
146
+ */
147
+ export function buildStripeCouponParams(
148
+ row: CouponRow,
149
+ opts: { id: string; name?: string; forceOnce?: boolean; metadata?: Record<string, string> },
150
+ ): Stripe.CouponCreateParams {
151
+ // The (stale) column COMMENT says percent is stored in basis points, so some
152
+ // rows may have been authored as 1000-for-10%. coupon_validate/coupon_redeem
153
+ // clamp the COMPUTED cents to the base amount and so never expose this, but
154
+ // percent_off goes to Stripe raw. Refuse rather than let a mis-scaled value
155
+ // reach the API, where anything in 100 < value <= 10000 might not be cleanly
156
+ // rejected.
157
+ if (row.discount_type === 'percent' && !(row.value <= 100)) {
158
+ throw new Error(`COUPON_CONFIG_INVALID: percent value ${row.value} exceeds 100`);
159
+ }
160
+
161
+ const params: Stripe.CouponCreateParams = {
162
+ id: opts.id,
163
+ // One checkout, one coupon object. Even if the id leaked it could not be
164
+ // applied a second time.
165
+ max_redemptions: 1,
166
+ ...(opts.name ? { name: opts.name } : {}),
167
+ ...(opts.metadata ? { metadata: opts.metadata } : {}),
168
+ };
169
+
170
+ if (row.discount_type === 'percent') {
171
+ params.percent_off = row.value;
172
+ } else {
173
+ params.amount_off = row.value;
174
+ params.currency = 'usd';
175
+ }
176
+
177
+ const duration = opts.forceOnce ? 'once' : row.duration;
178
+ if (duration === 'forever') {
179
+ params.duration = 'forever';
180
+ } else if (duration === 'once') {
181
+ params.duration = 'once';
182
+ } else {
183
+ // Stripe requires duration_in_months for, and ONLY for, 'repeating'.
184
+ // A repeating coupon with no month count is a data error we must not
185
+ // paper over with a guessed 1 -- that would silently under-discount.
186
+ if (!Number.isInteger(row.duration_in_months) || (row.duration_in_months as number) < 1) {
187
+ throw new Error(`COUPON_CONFIG_INVALID: duration 'repeating' with duration_in_months=${row.duration_in_months}`);
188
+ }
189
+ params.duration = 'repeating';
190
+ params.duration_in_months = row.duration_in_months as number;
191
+ }
192
+
193
+ return params;
194
+ }
195
+
196
+ /**
197
+ * Deterministic id so a retried checkout for the same reservation reuses the
198
+ * same Stripe Coupon object instead of littering the account with orphans.
199
+ * Stripe coupon ids are free-form strings; our redemption uuid is unique.
200
+ */
201
+ function stripeCouponIdFor(redemptionId: string): string {
202
+ return `gcc-${redemptionId}`;
203
+ }
204
+
205
+ async function createOrReuseStripeCoupon(
206
+ stripe: CouponStripeClient,
207
+ params: Stripe.CouponCreateParams,
208
+ ): Promise<string> {
209
+ try {
210
+ const created = await stripe.coupons.create(params);
211
+ return created.id;
212
+ } catch (e) {
213
+ const code = (e as { code?: string })?.code;
214
+ if (code === 'resource_already_exists') {
215
+ // Same reservation, retried checkout -- the object from the first
216
+ // attempt is still exactly the discount we want.
217
+ const existing = await stripe.coupons.retrieve(params.id as string);
218
+ return existing.id;
219
+ }
220
+ throw e;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Validate -> reserve -> mint a Stripe Coupon.
226
+ *
227
+ * Returns `{ ok: false }` for every "this code can't be used" outcome
228
+ * (invalid, expired, out of scope, limit reached, already applied, bad coupon
229
+ * config) so the caller can answer 400 with a user-facing message. Only a
230
+ * genuine infrastructure failure throws.
231
+ *
232
+ * NOTE the reservation is `status='reserved'`, not applied. stripe-webhook
233
+ * flips it to 'applied' when the payment actually lands, and reverses it if
234
+ * the checkout session expires.
235
+ */
236
+ export async function applyCheckoutCoupon(
237
+ supabase: CouponSupabaseClient,
238
+ stripe: CouponStripeClient,
239
+ opts: {
240
+ code: string;
241
+ /** Log prefix, e.g. 'create-subscription-checkout'. */
242
+ fnName: string;
243
+ planId: string;
244
+ planSlug: string;
245
+ planName: string;
246
+ emailKey: string;
247
+ baseAmountCents: number;
248
+ appliedToType: 'membership' | 'day_pass';
249
+ /** true for mode:'payment' checkouts -- forces a 'once' Stripe duration. */
250
+ oneTime: boolean;
251
+ /** System-actor email recorded on coupon_reverse if the mint step fails. */
252
+ actorEmail: string;
253
+ },
254
+ ): Promise<CouponOutcome> {
255
+ const fail = (reason: string): CouponOutcome => ({ ok: false, reason, message: couponErrorMessage(reason) });
256
+
257
+ // 1) Read-only eligibility check. p_membership_id is null on purpose: at
258
+ // checkout time no membership row exists yet for a new signup, so the
259
+ // per-member cap can only be enforced by coupon_redeem (which keys on
260
+ // the email we're about to reserve under).
261
+ let validated: { valid?: boolean; coupon_id?: string; discount_cents?: number; reason?: string } | null = null;
262
+ try {
263
+ const { data, error } = await supabase.rpc('coupon_validate', {
264
+ p_code: opts.code,
265
+ p_membership_id: null,
266
+ p_scope_type: 'plan',
267
+ p_scope_target_id: opts.planId,
268
+ p_base_amount_cents: opts.baseAmountCents,
269
+ });
270
+ if (error) throw error;
271
+ validated = (Array.isArray(data) ? data[0] : data) ?? null;
272
+ } catch (e) {
273
+ // Fail CLOSED. Silently dropping the code would charge full price to
274
+ // someone who believes they're getting a discount -- worse than a retry.
275
+ console.error(`[${opts.fnName}] coupon_validate failed`, String(e));
276
+ return fail('COUPON_VALIDATE_FAILED');
277
+ }
278
+ if (!validated?.valid || !validated.coupon_id) {
279
+ return fail(validated?.reason ?? 'COUPON_NOT_APPLICABLE');
280
+ }
281
+ const couponId = validated.coupon_id;
282
+
283
+ // 2) The discount shape itself. coupon_validate returns only the computed
284
+ // cents, but Stripe needs percent/amount + duration.
285
+ let row: CouponRow | null = null;
286
+ try {
287
+ const { data, error } = await supabase
288
+ .from('coupons')
289
+ .select('id,discount_type,value,duration,duration_in_months,applies_to')
290
+ .eq('id', couponId)
291
+ .maybeSingle();
292
+ if (error) throw error;
293
+ row = (data as CouponRow | null) ?? null;
294
+ } catch (e) {
295
+ console.error(`[${opts.fnName}] coupon row lookup failed`, String(e));
296
+ return fail('COUPON_VALIDATE_FAILED');
297
+ }
298
+ if (!row) return fail('COUPON_NOT_APPLICABLE');
299
+
300
+ // 2b) Enforce coupons.applies_to. Deliberately BEFORE coupon_redeem, so a
301
+ // wrong-category code costs two reads and reserves nothing. Without this,
302
+ // an unscoped coupon authored as 'booking' or 'office' is redeemable
303
+ // against a live subscription through this new path, carrying a `duration`
304
+ // that was never vetted for recurring use (create-booking ignores
305
+ // `duration` entirely -- it computes its own one-time amount).
306
+ if (!APPLIES_TO_BY_CHECKOUT[opts.appliedToType].includes(row.applies_to)) {
307
+ console.warn(`[${opts.fnName}] coupon applies_to does not cover this checkout`,
308
+ { coupon_id: couponId, applies_to: row.applies_to, applied_to_type: opts.appliedToType });
309
+ return fail('COUPON_OUT_OF_SCOPE');
310
+ }
311
+
312
+ // 3) Reserve. Idempotency key is deliberately DETERMINISTIC -- a user who
313
+ // abandons Stripe and retries with the same code must land on the same
314
+ // reservation row, not burn a second redemption.
315
+ let redemptionId: string | null = null;
316
+ let discountCents = validated.discount_cents ?? 0;
317
+ // Opaque per-attempt id for applied_to_id. It must NOT be plan.id: a partial
318
+ // unique index (applied_to_type, applied_to_id) WHERE status <> 'reversed'
319
+ // enforces "one non-reversed coupon per transaction", so a plan-wide value
320
+ // would let exactly one customer ever redeem any code against that plan.
321
+ // The column is uuid NOT NULL with no FK, so a generated uuid is legal.
322
+ const attemptId = crypto.randomUUID();
323
+ const redeemArgs = {
324
+ p_coupon_id: couponId,
325
+ p_member_email: opts.emailKey,
326
+ p_applied_to_type: opts.appliedToType,
327
+ // No membership / day_pass_purchases row exists yet at checkout time --
328
+ // both are created by stripe-webhook after payment. This uuid is carried
329
+ // on the session metadata as coupon_attempt_id so the row stays traceable.
330
+ p_applied_to_id: attemptId,
331
+ p_base_amount_cents: opts.baseAmountCents,
332
+ };
333
+ const stableKey = `${opts.planSlug}:${opts.emailKey}:${couponId}`;
334
+ try {
335
+ const { data, error } = await supabase.rpc('coupon_redeem', {
336
+ ...redeemArgs,
337
+ p_idempotency_key: stableKey,
338
+ });
339
+ if (error) throw error;
340
+ type RedeemRow = { id?: string; amount_applied_cents?: number; status?: string } | null;
341
+ let red = (Array.isArray(data) ? data[0] : data) as RedeemRow;
342
+ if (!red?.id) throw new Error('coupon_redeem returned no row');
343
+
344
+ // coupon_redeem's first statement returns any row matching the idempotency
345
+ // key REGARDLESS of status, and our key is stable forever -- so this can
346
+ // hand back a row that is already settled.
347
+ if (red.status === 'applied') {
348
+ // This customer already PAID with this code on this plan. The Stripe
349
+ // coupon is spent and redeemed_count still counts it; minting a fresh
350
+ // discount would be a real discount the counters don't reflect.
351
+ console.warn(`[${opts.fnName}] coupon_redeem returned an already-applied row`,
352
+ { redemption_id: red.id });
353
+ return fail('COUPON_ALREADY_APPLIED');
354
+ }
355
+ if (red.status === 'reversed') {
356
+ // The earlier reservation was handed back -- by an expired session, or by
357
+ // reverseCheckoutCoupon after a transient failure in an earlier request
358
+ // (stripe.customers.search throwing, the coupon mint failing, ...).
359
+ // coupon_reverse's count sync already gave the redemption back, so the
360
+ // coupon is NOT exhausted; only this eternal key is pinned to a dead row.
361
+ // Refusing here would lock the customer out of a still-valid code forever
362
+ // on a false "fully redeemed" message. Re-issue with a freshened key so
363
+ // the INSERT actually runs. That second call takes coupon_redeem's own
364
+ // FOR UPDATE lock and re-checks max_redemptions AND the per-member cap
365
+ // for real, so it cannot grant an over-limit redemption.
366
+ console.warn(`[${opts.fnName}] coupon_redeem returned a reversed row -- retrying with a fresh key`,
367
+ { redemption_id: red.id });
368
+ const { data: retryData, error: retryError } = await supabase.rpc('coupon_redeem', {
369
+ ...redeemArgs,
370
+ p_idempotency_key: `${stableKey}:${crypto.randomUUID()}`,
371
+ });
372
+ if (retryError) throw retryError;
373
+ red = (Array.isArray(retryData) ? retryData[0] : retryData) as RedeemRow;
374
+ if (!red?.id) throw new Error('coupon_redeem returned no row');
375
+ }
376
+ // Fallback: anything still not 'reserved' fails closed rather than looping.
377
+ if (red.status !== 'reserved') {
378
+ console.warn(`[${opts.fnName}] coupon_redeem returned a non-reserved row`,
379
+ { redemption_id: red.id, status: red.status });
380
+ return fail('COUPON_LIMIT_REACHED');
381
+ }
382
+ redemptionId = red.id;
383
+ discountCents = red.amount_applied_cents ?? discountCents;
384
+ } catch (e) {
385
+ console.warn(`[${opts.fnName}] coupon_redeem failed`, String(e));
386
+ return fail(reasonFromRedeemError(e));
387
+ }
388
+
389
+ // 4) Mint the disposable Stripe Coupon.
390
+ try {
391
+ const params = buildStripeCouponParams(row, {
392
+ id: stripeCouponIdFor(redemptionId),
393
+ name: `${opts.planName} — ${opts.code.toUpperCase()}`,
394
+ forceOnce: opts.oneTime,
395
+ metadata: {
396
+ coupon_redemption_id: redemptionId,
397
+ coupon_id: couponId,
398
+ coupon_attempt_id: attemptId,
399
+ plan_slug: opts.planSlug,
400
+ },
401
+ });
402
+ const stripeCouponId = await createOrReuseStripeCoupon(stripe, params);
403
+ return { ok: true, stripeCouponId, redemptionId, couponId, attemptId, discountCents };
404
+ } catch (e) {
405
+ // The reservation is already on the books but no discount will reach
406
+ // Stripe -- release it now rather than leaving a single-use code
407
+ // permanently consumed by a checkout that never started.
408
+ console.error(`[${opts.fnName}] stripe coupon create failed`, String(e));
409
+ await reverseCheckoutCoupon(supabase, redemptionId, 'stripe_coupon_create_failed', opts.fnName, opts.actorEmail);
410
+ return fail('COUPON_STRIPE_FAILED');
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Best-effort release of a reservation. Never throws -- every caller is on a
416
+ * path where the customer-visible outcome is already decided.
417
+ *
418
+ * Only ever touches a still-'reserved' row. coupon_reverse itself has no
419
+ * status precondition and will happily flip an 'applied' redemption -- one
420
+ * that funded a real payment -- to 'reversed'. Same guard stripe-webhook's
421
+ * reverseCouponFromMetadata already carries.
422
+ */
423
+ export async function reverseCheckoutCoupon(
424
+ supabase: CouponSupabaseClient,
425
+ redemptionId: string,
426
+ reason: string,
427
+ fnName: string,
428
+ actorEmail: string,
429
+ ): Promise<void> {
430
+ try {
431
+ const { data: redRow, error: readErr } = await supabase
432
+ .from('coupon_redemptions')
433
+ .select('id,status')
434
+ .eq('id', redemptionId)
435
+ .maybeSingle();
436
+ if (readErr) throw readErr;
437
+ if (!redRow) throw new Error('coupon_redemptions row not found');
438
+ // Already settled either way -- nothing to release.
439
+ if (redRow.status !== 'reserved') return;
440
+
441
+ const { error } = await supabase.rpc('coupon_reverse', {
442
+ p_redemption_id: redemptionId,
443
+ p_reason: reason,
444
+ p_actor_email: actorEmail,
445
+ });
446
+ if (error) throw error;
447
+ } catch (e) {
448
+ console.error(`[${fnName}] coupon_reverse failed`, String(e));
449
+ }
450
+ }
451
+
452
+ /** 400 body shape. `field` lets the modal put the message under the code input. */
453
+ export function couponFailureBody(failure: { message: string }): { error: string; field: string } {
454
+ return { error: failure.message, field: 'coupon_code' };
455
+ }