@simplelayer/graniteer-core 0.3.20 → 0.3.21-referral.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/dist/businessHours.js +1 -1
- package/dist/functions/create-subscription-checkout.js +7 -2
- package/dist/functions/manage-booking.js +2 -0
- package/dist/functions/stripe-webhook.js +26 -16
- package/dist/referralCodeLookup.d.ts +13 -0
- package/dist/referralCodeLookup.js +17 -0
- package/dist/referralCredits.d.ts +5 -0
- package/dist/referralCredits.js +5 -0
- package/dist/referralGrant.d.ts +4 -31
- package/dist/referralGrant.js +14 -234
- package/package.json +1 -1
package/dist/businessHours.js
CHANGED
|
@@ -49,7 +49,7 @@ export function minNoticeErrorMessage(nowMs, cfg) {
|
|
|
49
49
|
const earliest = new Intl.DateTimeFormat('en-US', {
|
|
50
50
|
timeZone: 'America/Los_Angeles',
|
|
51
51
|
weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
|
|
52
|
-
}).format(new Date(earliestBookingStartMs(nowMs, cfg)));
|
|
52
|
+
}).format(new Date(earliestBookingStartMs(nowMs, cfg))).replace(/[ ]/g, ' ');
|
|
53
53
|
return `Bookings need at least ${cfg.minNoticeBusinessHours} business hours notice ` +
|
|
54
54
|
`(Monday–Friday, excluding holidays). The earliest available start is ${earliest} Pacific time.`;
|
|
55
55
|
}
|
|
@@ -11,6 +11,7 @@ import { buildSubscriptionSessionParams } from '../checkoutSessionParams.js';
|
|
|
11
11
|
// migration-checkout functions can reuse the exact same clamp/validation
|
|
12
12
|
// arithmetic instead of duplicating it. Pure refactor: no behavior change.
|
|
13
13
|
import { MAX_START_DATE_DAYS, pacificDateStr, addDaysStr } from '../pacificDate.js';
|
|
14
|
+
import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
|
|
14
15
|
const Body = z.object({
|
|
15
16
|
plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
|
|
16
17
|
email: z.string().email().max(255),
|
|
@@ -205,12 +206,16 @@ export async function handle(req, operator) {
|
|
|
205
206
|
// code, malicious input) is NOT an error -- it just means no referral
|
|
206
207
|
// metadata gets attached, same as if the field had been omitted.
|
|
207
208
|
let referralCode;
|
|
208
|
-
|
|
209
|
+
// Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a '*'
|
|
210
|
+
// wildcard) is treated exactly like an omitted/unknown code -- no lookup.
|
|
211
|
+
if (referral_code && isValidReferralCode(referral_code)) {
|
|
209
212
|
try {
|
|
210
213
|
const { data: referrer, error: refErr } = await supabase
|
|
211
214
|
.from('memberships')
|
|
212
215
|
.select('id')
|
|
213
|
-
.
|
|
216
|
+
.ilike('referral_code', escapeLikePattern(referral_code))
|
|
217
|
+
.order('id', { ascending: true })
|
|
218
|
+
.limit(1)
|
|
214
219
|
.maybeSingle();
|
|
215
220
|
if (!refErr && referrer)
|
|
216
221
|
referralCode = referral_code;
|
|
@@ -424,6 +424,8 @@ export async function handle(req, operator, deps) {
|
|
|
424
424
|
outcome: fresh.status,
|
|
425
425
|
});
|
|
426
426
|
}
|
|
427
|
+
// Re-read failed: fail closed, never fall through to the credit grant.
|
|
428
|
+
return json(409, { error: 'already_changed' });
|
|
427
429
|
}
|
|
428
430
|
// Credit ledger row(s): split cash-funded (1yr) vs credit-funded (capped at
|
|
429
431
|
// the ORIGINAL credit's own expiry) so a cancellation can never launder a
|
|
@@ -6,7 +6,8 @@ import { isDepositOnly, parseTstzRange } from '../bookingEffects.js';
|
|
|
6
6
|
import { extractDoorAccess } from '../busClient.js';
|
|
7
7
|
import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js';
|
|
8
8
|
import { sendDunningEmail } from '../dunningEmails.js';
|
|
9
|
-
import { recordReferralFailure
|
|
9
|
+
import { recordReferralFailure } from '../referralGrant.js';
|
|
10
|
+
import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
|
|
10
11
|
import { findBaseItem } from '../membershipSubscriptionItems.js';
|
|
11
12
|
import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
|
|
12
13
|
import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
|
|
@@ -100,7 +101,9 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
100
101
|
.from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
|
|
101
102
|
return data;
|
|
102
103
|
}
|
|
104
|
+
let bookingLookupErrored = false;
|
|
103
105
|
async function findBookingIdByPaymentIntent(paymentIntentId) {
|
|
106
|
+
bookingLookupErrored = false;
|
|
104
107
|
const { data: rows, error } = await supabase
|
|
105
108
|
.from('bookings')
|
|
106
109
|
.select('id')
|
|
@@ -112,6 +115,7 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
112
115
|
payment_intent_id: paymentIntentId,
|
|
113
116
|
...(typeof code === 'string' ? { error_code: code } : {}),
|
|
114
117
|
}, { severity: 'error', bookingId: null });
|
|
118
|
+
bookingLookupErrored = true;
|
|
115
119
|
return null;
|
|
116
120
|
}
|
|
117
121
|
const list = (rows ?? []);
|
|
@@ -149,8 +153,11 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
149
153
|
let markerFailed = false;
|
|
150
154
|
try {
|
|
151
155
|
bookingId = await findBookingIdByPaymentIntent(piId);
|
|
152
|
-
if (!bookingId)
|
|
153
|
-
|
|
156
|
+
if (!bookingId) {
|
|
157
|
+
// Connect: the marker is the only thing blocking self-service credit,
|
|
158
|
+
// so a lookup DB error must be retried by Stripe, not silently acked.
|
|
159
|
+
return connect && bookingLookupErrored ? 'marker_failed' : 'skipped';
|
|
160
|
+
}
|
|
154
161
|
if (connect) {
|
|
155
162
|
// Connect (direct-charge) bookings are refunded outside the app, so
|
|
156
163
|
// nothing cancels the booking: status stays 'paid', the slot stays
|
|
@@ -584,10 +591,16 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
584
591
|
const refCode = sub.metadata?.referral_code;
|
|
585
592
|
if (!refCode)
|
|
586
593
|
return; // no referral on this signup -- normal case
|
|
594
|
+
// Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a
|
|
595
|
+
// '*' wildcard) is treated exactly like no referral code at all.
|
|
596
|
+
if (!isValidReferralCode(refCode))
|
|
597
|
+
return;
|
|
587
598
|
const { data: referrer, error: referrerErr } = await supabase
|
|
588
599
|
.from('memberships')
|
|
589
600
|
.select('id')
|
|
590
|
-
.
|
|
601
|
+
.ilike('referral_code', escapeLikePattern(refCode))
|
|
602
|
+
.order('id', { ascending: true })
|
|
603
|
+
.limit(1)
|
|
591
604
|
.maybeSingle();
|
|
592
605
|
if (referrerErr || !referrer)
|
|
593
606
|
return; // unresolvable code -- silently skip, never block signup
|
|
@@ -2114,10 +2127,17 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2114
2127
|
}
|
|
2115
2128
|
}
|
|
2116
2129
|
catch (e) {
|
|
2130
|
+
const permanentStripeError = e?.type === 'StripeInvalidRequestError' && !isRetryableStripeError(e);
|
|
2117
2131
|
await logOps(supabase, 'booking_access_revoke_step_failed', {
|
|
2118
2132
|
reason: 'charge_dispute_created',
|
|
2119
2133
|
error_name: errorNameFromUnknown(e),
|
|
2134
|
+
permanent_stripe_error: permanentStripeError,
|
|
2120
2135
|
}, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
|
|
2136
|
+
if (connect && !permanentStripeError) {
|
|
2137
|
+
// Marker is the only thing blocking self-service credit on Connect; let Stripe retry.
|
|
2138
|
+
await releaseStripeEventLedgerForRetry(event.id);
|
|
2139
|
+
return webhookResponseMarkerFailedForRetry();
|
|
2140
|
+
}
|
|
2121
2141
|
}
|
|
2122
2142
|
break;
|
|
2123
2143
|
}
|
|
@@ -2530,18 +2550,8 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2530
2550
|
.select('id');
|
|
2531
2551
|
if (fipErr)
|
|
2532
2552
|
console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
|
|
2533
|
-
//
|
|
2534
|
-
//
|
|
2535
|
-
// 'subscription_create' -- every other billing_reason
|
|
2536
|
-
// (subscription_cycle after a 100%-off code, a $0 invoice
|
|
2537
|
-
// covered entirely by account balance, etc.) bypasses the
|
|
2538
|
-
// amount check entirely. Gate the referral grant itself on a
|
|
2539
|
-
// genuinely nonzero amount_paid, separately from
|
|
2540
|
-
// first_invoice_paid_at (which has other consumers and should
|
|
2541
|
-
// keep its existing, broader semantics).
|
|
2542
|
-
if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
|
|
2543
|
-
await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id);
|
|
2544
|
-
}
|
|
2553
|
+
// Referral crediting is NOT done here any more: gc-io's
|
|
2554
|
+
// referral-qualify-daily job pays it 30 days after signup.
|
|
2545
2555
|
}
|
|
2546
2556
|
}
|
|
2547
2557
|
break;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare function escapeLikePattern(input: string): string;
|
|
2
|
+
/**
|
|
3
|
+
* Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
|
|
4
|
+
* the 1..32 range matches the zod bound on the checkout input and tolerates
|
|
5
|
+
* lowercase typos, which ilike matches case-insensitively).
|
|
6
|
+
*
|
|
7
|
+
* Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
|
|
8
|
+
* ilike value as a wildcard alias for '%', and escapeLikePattern does not
|
|
9
|
+
* escape it, so '*' would match the first membership's code. Anything outside
|
|
10
|
+
* [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
|
|
11
|
+
* lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isValidReferralCode(input: unknown): input is string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function escapeLikePattern(input) {
|
|
2
|
+
return input.replace(/[\\%_]/g, (ch) => '\\' + ch);
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
|
|
6
|
+
* the 1..32 range matches the zod bound on the checkout input and tolerates
|
|
7
|
+
* lowercase typos, which ilike matches case-insensitively).
|
|
8
|
+
*
|
|
9
|
+
* Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
|
|
10
|
+
* ilike value as a wildcard alias for '%', and escapeLikePattern does not
|
|
11
|
+
* escape it, so '*' would match the first membership's code. Anything outside
|
|
12
|
+
* [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
|
|
13
|
+
* lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
|
|
14
|
+
*/
|
|
15
|
+
export function isValidReferralCode(input) {
|
|
16
|
+
return typeof input === 'string' && /^[A-Za-z0-9]{1,32}$/.test(input);
|
|
17
|
+
}
|
|
@@ -2,4 +2,9 @@ export interface ReferralCredits {
|
|
|
2
2
|
referrerCents: number;
|
|
3
3
|
referredCents: number;
|
|
4
4
|
}
|
|
5
|
+
/**
|
|
6
|
+
* @deprecated gc-io's referralQualify owns the referral credit formula now
|
|
7
|
+
* (50% of the referred member's first-month price, floored). Retained
|
|
8
|
+
* unchanged for published-package compatibility.
|
|
9
|
+
*/
|
|
5
10
|
export declare function computeReferralCredits(planPriceCents: number, isPrivateOffice: boolean): ReferralCredits;
|
package/dist/referralCredits.js
CHANGED
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
// price + a private-office flag into two credit amounts.
|
|
14
14
|
const PRIVATE_OFFICE_REFERRER_CENTS = 30000; // flat $300
|
|
15
15
|
const MIN_CREDIT_CENTS = 2500; // $25 floor on both sides
|
|
16
|
+
/**
|
|
17
|
+
* @deprecated gc-io's referralQualify owns the referral credit formula now
|
|
18
|
+
* (50% of the referred member's first-month price, floored). Retained
|
|
19
|
+
* unchanged for published-package compatibility.
|
|
20
|
+
*/
|
|
16
21
|
export function computeReferralCredits(planPriceCents, isPrivateOffice) {
|
|
17
22
|
const referrerCents = isPrivateOffice
|
|
18
23
|
? PRIVATE_OFFICE_REFERRER_CENTS
|
package/dist/referralGrant.d.ts
CHANGED
|
@@ -14,36 +14,9 @@ type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
|
14
14
|
*/
|
|
15
15
|
export declare function recordReferralFailure(supabase: SupabaseLike, referralId: string, fromStatus: 'signed_up' | 'grant_failed' | 'credited', toStatus: 'grant_failed' | 'clawback_failed', error: unknown): Promise<void>;
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* swap in the invoice.paid handler actually affected a row (genuinely the
|
|
21
|
-
* first real paid invoice for this membership) -- that call passes no
|
|
22
|
-
* `fromStatuses` override, so it only ever matches a 'signed_up' row.
|
|
23
|
-
*
|
|
24
|
-
* admin-referral-retry calls this SAME function with
|
|
25
|
-
* `fromStatuses: ['grant_failed']` to retry a previously-failed grant --
|
|
26
|
-
* see that function's own header comment for why it gates on the referred
|
|
27
|
-
* membership's live status first, and why it does NOT reset the row to
|
|
28
|
-
* 'signed_up' before calling this (that reset-then-call shape was tried and
|
|
29
|
-
* reverted after a second-model review found it opened a stranded-row
|
|
30
|
-
* window and a same-row race between two concurrent retries).
|
|
31
|
-
*
|
|
32
|
-
* Computes real credit amounts, grants a NEGATIVE Stripe Customer Balance
|
|
33
|
-
* Transaction (a credit) on each of the two Stripe customers, and marks the
|
|
34
|
-
* referral 'credited'.
|
|
35
|
-
*
|
|
36
|
-
* Entirely wrapped in try/catch and logs with the referral id on failure --
|
|
37
|
-
* a Stripe failure here must never break invoice.paid processing for an
|
|
38
|
-
* unrelated membership.
|
|
39
|
-
*
|
|
40
|
-
* IDEMPOTENT BY DESIGN -- this is also what makes it safe for
|
|
41
|
-
* admin-referral-retry to call again on a grant_failed row: before each
|
|
42
|
-
* Stripe call it checks whether this referral already has a txn id
|
|
43
|
-
* persisted, and each Stripe call carries a fixed idempotency key derived
|
|
44
|
-
* from the referral id, so a retry only attempts whichever side didn't
|
|
45
|
-
* already complete. Never write a second, separate recovery path -- retry
|
|
46
|
-
* by calling this function again.
|
|
17
|
+
* @deprecated SUPERSEDED -- no-op. Crediting is owned by gc-io's
|
|
18
|
+
* referral-qualify-daily job (30 days after signup). Never touches Stripe or
|
|
19
|
+
* the database; signature kept for published-package compatibility.
|
|
47
20
|
*/
|
|
48
|
-
export declare function maybeGrantReferralCredit(
|
|
21
|
+
export declare function maybeGrantReferralCredit(_supabase: SupabaseLike, _stripe: Stripe, referredMembershipId: string, _fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
|
|
49
22
|
export {};
|
package/dist/referralGrant.js
CHANGED
|
@@ -1,38 +1,15 @@
|
|
|
1
|
-
// Referral program
|
|
1
|
+
// Referral program failure recorder + SUPERSEDED grant entry point.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
// longer byte-identical to the original inline version, and should not be
|
|
10
|
-
// described that way again:
|
|
11
|
-
// - `fromStatuses` is now a parameter (default ['signed_up'], the
|
|
12
|
-
// webhook's original single case) instead of a hardcoded 'signed_up'
|
|
13
|
-
// literal, so admin-referral-retry can call this SAME function on a
|
|
14
|
-
// grant_failed row directly -- no separate reset-to-signed_up step,
|
|
15
|
-
// no window where the row sits in a state nothing recognizes.
|
|
16
|
-
// - A failed persist of either side's Stripe transaction id is now a
|
|
17
|
-
// hard stop with a loud last_error, not a console.error-and-continue
|
|
18
|
-
// (see the two `partialUpdErr` blocks below) -- see "24h idempotency
|
|
19
|
-
// key" comment for why this matters.
|
|
20
|
-
// The Supabase and Stripe clients are explicit parameters (same convention
|
|
21
|
-
// as _shared/membershipWelcome.ts and _shared/bookingEffects.ts) instead of
|
|
22
|
-
// closure captures, and console.error tags read [referralGrant] instead of
|
|
23
|
-
// [stripe-webhook] since this code now runs from two different callers.
|
|
3
|
+
// maybeGrantReferralCredit is now an immediate no-op. Referral credits are no
|
|
4
|
+
// longer paid at first-invoice-paid under the old terms; gc-io's
|
|
5
|
+
// referral-qualify-daily job pays 50% of the referred member's first-month
|
|
6
|
+
// plan price to each side, 30 days after signup. The export and its signature
|
|
7
|
+
// are kept only because other repos import them from the published package.
|
|
8
|
+
// It never touches Stripe or the database.
|
|
24
9
|
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// index.ts -- they're deliberately NOT extracted here. There are two
|
|
28
|
-
// different clawback code paths and a clawback_failed row alone doesn't
|
|
29
|
-
// say which one failed, so clawback retry is a human decision for now
|
|
30
|
-
// (see AdminReferrals.tsx), not an automated one. recordReferralFailure is
|
|
31
|
-
// still exported here since both index.ts's clawback functions and this
|
|
32
|
-
// file's grant function need it -- index.ts imports it from here rather
|
|
33
|
-
// than keeping a second copy.
|
|
10
|
+
// recordReferralFailure is still live: the clawback functions in
|
|
11
|
+
// stripe-webhook.ts use it to mark a referrals row clawback_failed.
|
|
34
12
|
import { logOps } from './ops.js';
|
|
35
|
-
import { computeReferralCredits } from './referralCredits.js';
|
|
36
13
|
/**
|
|
37
14
|
* Records a permanent grant/clawback failure on the referrals row itself
|
|
38
15
|
* (fix #4 from the round-2 review) instead of only console.error/warn --
|
|
@@ -62,207 +39,10 @@ export async function recordReferralFailure(supabase, referralId, fromStatus, to
|
|
|
62
39
|
await logOps(supabase, 'referral_' + toStatus, { referral_id: referralId, message }, { severity: 'error' }).catch(() => { });
|
|
63
40
|
}
|
|
64
41
|
/**
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* swap in the invoice.paid handler actually affected a row (genuinely the
|
|
69
|
-
* first real paid invoice for this membership) -- that call passes no
|
|
70
|
-
* `fromStatuses` override, so it only ever matches a 'signed_up' row.
|
|
71
|
-
*
|
|
72
|
-
* admin-referral-retry calls this SAME function with
|
|
73
|
-
* `fromStatuses: ['grant_failed']` to retry a previously-failed grant --
|
|
74
|
-
* see that function's own header comment for why it gates on the referred
|
|
75
|
-
* membership's live status first, and why it does NOT reset the row to
|
|
76
|
-
* 'signed_up' before calling this (that reset-then-call shape was tried and
|
|
77
|
-
* reverted after a second-model review found it opened a stranded-row
|
|
78
|
-
* window and a same-row race between two concurrent retries).
|
|
79
|
-
*
|
|
80
|
-
* Computes real credit amounts, grants a NEGATIVE Stripe Customer Balance
|
|
81
|
-
* Transaction (a credit) on each of the two Stripe customers, and marks the
|
|
82
|
-
* referral 'credited'.
|
|
83
|
-
*
|
|
84
|
-
* Entirely wrapped in try/catch and logs with the referral id on failure --
|
|
85
|
-
* a Stripe failure here must never break invoice.paid processing for an
|
|
86
|
-
* unrelated membership.
|
|
87
|
-
*
|
|
88
|
-
* IDEMPOTENT BY DESIGN -- this is also what makes it safe for
|
|
89
|
-
* admin-referral-retry to call again on a grant_failed row: before each
|
|
90
|
-
* Stripe call it checks whether this referral already has a txn id
|
|
91
|
-
* persisted, and each Stripe call carries a fixed idempotency key derived
|
|
92
|
-
* from the referral id, so a retry only attempts whichever side didn't
|
|
93
|
-
* already complete. Never write a second, separate recovery path -- retry
|
|
94
|
-
* by calling this function again.
|
|
42
|
+
* @deprecated SUPERSEDED -- no-op. Crediting is owned by gc-io's
|
|
43
|
+
* referral-qualify-daily job (30 days after signup). Never touches Stripe or
|
|
44
|
+
* the database; signature kept for published-package compatibility.
|
|
95
45
|
*/
|
|
96
|
-
export async function maybeGrantReferralCredit(
|
|
97
|
-
|
|
98
|
-
// Guard used by every recordReferralFailure call below -- always the
|
|
99
|
-
// row's REAL current status as read from the DB just now, never an
|
|
100
|
-
// assumption, so the optimistic-concurrency guard inside
|
|
101
|
-
// recordReferralFailure actually protects against a concurrent winner.
|
|
102
|
-
let currentStatus = 'signed_up';
|
|
103
|
-
try {
|
|
104
|
-
const { data: rawReferral, error: refErr } = await supabase
|
|
105
|
-
.from('referrals')
|
|
106
|
-
.select('id,status,referring_membership_id,referred_membership_id,referred_plan_price_cents,is_private_office,' +
|
|
107
|
-
'stripe_balance_txn_id_referrer,stripe_balance_txn_id_referred')
|
|
108
|
-
.eq('referred_membership_id', referredMembershipId)
|
|
109
|
-
.in('status', fromStatuses)
|
|
110
|
-
.maybeSingle();
|
|
111
|
-
if (refErr) {
|
|
112
|
-
console.error('[referralGrant] referral lookup failed', {
|
|
113
|
-
membership_id: referredMembershipId, message: refErr.message,
|
|
114
|
-
});
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
if (!rawReferral)
|
|
118
|
-
return; // this membership has no referral in a retryable state -- normal case
|
|
119
|
-
const typedReferral = rawReferral;
|
|
120
|
-
referralId = typedReferral.id;
|
|
121
|
-
currentStatus = typedReferral.status;
|
|
122
|
-
const { referrerCents, referredCents } = computeReferralCredits(typedReferral.referred_plan_price_cents ?? 0, typedReferral.is_private_office === true);
|
|
123
|
-
const { data: parties, error: partiesErr } = await supabase
|
|
124
|
-
.from('memberships')
|
|
125
|
-
.select('id,stripe_customer_id')
|
|
126
|
-
.in('id', [typedReferral.referring_membership_id, typedReferral.referred_membership_id]);
|
|
127
|
-
if (partiesErr || !parties) {
|
|
128
|
-
console.error('[referralGrant] referral credit membership lookup failed', {
|
|
129
|
-
referral_id: typedReferral.id, message: partiesErr?.message ?? 'no rows',
|
|
130
|
-
});
|
|
131
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', partiesErr ?? new Error('membership lookup returned no rows'));
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
const referringCustomerId = parties.find((m) => m.id === typedReferral.referring_membership_id)?.stripe_customer_id ?? null;
|
|
135
|
-
const referredCustomerId = parties.find((m) => m.id === typedReferral.referred_membership_id)?.stripe_customer_id ?? null;
|
|
136
|
-
if (!referringCustomerId || !referredCustomerId) {
|
|
137
|
-
console.error('[referralGrant] referral credit missing stripe_customer_id', { referral_id: typedReferral.id });
|
|
138
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error('missing stripe_customer_id on one or both parties'));
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
// Each call carries a deterministic idempotency key derived from the
|
|
142
|
-
// referral row's own id -- a webhook redelivery, or our own retry after
|
|
143
|
-
// a transient failure below, can never double-credit either party even
|
|
144
|
-
// if our own DB state is momentarily inconsistent; Stripe itself
|
|
145
|
-
// refuses to apply the same key twice.
|
|
146
|
-
//
|
|
147
|
-
// Round-3 review foot-gun: idempotency keys expire after 24h (Stripe),
|
|
148
|
-
// but a `grant_failed` row can be manually flipped back for retry well
|
|
149
|
-
// after that -- at which point a stale key would no longer protect
|
|
150
|
-
// against a double charge. The real guard is checking whether this
|
|
151
|
-
// referral ALREADY has a txn id persisted (from a prior partial
|
|
152
|
-
// attempt) and skipping straight past re-charging Stripe for that side
|
|
153
|
-
// if so -- which is exactly why a failure to PERSIST that txn id after
|
|
154
|
-
// a successful Stripe call (the `partialUpdErr`/`partialUpdErr2` blocks
|
|
155
|
-
// below) must be treated as fatal, not logged-and-ignored: if the id
|
|
156
|
-
// never lands in the DB, a later retry past the 24h window has no way
|
|
157
|
-
// to know the money already moved, and will move it again.
|
|
158
|
-
let referrerTxnId = typedReferral.stripe_balance_txn_id_referrer ?? null;
|
|
159
|
-
if (!referrerTxnId) {
|
|
160
|
-
try {
|
|
161
|
-
// A NEGATIVE amount on a Customer Balance Transaction decreases what
|
|
162
|
-
// the customer owes -- i.e. grants them a credit against their next
|
|
163
|
-
// invoice. POST /v1/customers/{customer}/balance_transactions.
|
|
164
|
-
const referrerTxn = await stripe.customers.createBalanceTransaction(referringCustomerId, {
|
|
165
|
-
amount: -referrerCents,
|
|
166
|
-
currency: 'usd',
|
|
167
|
-
description: `Referral credit: friend joined via your referral link (referral ${typedReferral.id})`,
|
|
168
|
-
}, { idempotencyKey: `ref-${typedReferral.id}-referrer-grant` });
|
|
169
|
-
referrerTxnId = referrerTxn.id;
|
|
170
|
-
}
|
|
171
|
-
catch (e) {
|
|
172
|
-
console.error('[referralGrant] referral referrer balance transaction creation failed', {
|
|
173
|
-
referral_id: typedReferral.id, message: e instanceof Error ? e.message : String(e),
|
|
174
|
-
});
|
|
175
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', e);
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
// Persist immediately -- if the referred-side call below throws, this
|
|
179
|
-
// row already shows real money moved once, with the txn id needed to
|
|
180
|
-
// reconcile or manually complete the pair. A failure to persist THIS
|
|
181
|
-
// txn id is fatal (see the 24h-idempotency-key comment above): the
|
|
182
|
-
// Stripe transaction already exists for real, so silently continuing
|
|
183
|
-
// would leave a retry blind to that fact.
|
|
184
|
-
const { error: partialUpdErr } = await supabase
|
|
185
|
-
.from('referrals')
|
|
186
|
-
.update({ stripe_balance_txn_id_referrer: referrerTxnId, referrer_credit_cents: referrerCents })
|
|
187
|
-
.eq('id', typedReferral.id);
|
|
188
|
-
if (partialUpdErr) {
|
|
189
|
-
console.error('[referralGrant] referral partial grant persist failed -- REFERRER STRIPE CREDIT ALREADY GRANTED', {
|
|
190
|
-
referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, message: partialUpdErr.message,
|
|
191
|
-
});
|
|
192
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error(`REFERRER CREDIT GRANTED (txn ${referrerTxnId}) BUT TXN ID NOT PERSISTED (${partialUpdErr.message}) -- reconcile in Stripe before retrying; a retry past 24h without this id would charge again`));
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
let referredTxnId = typedReferral.stripe_balance_txn_id_referred ?? null;
|
|
197
|
-
if (!referredTxnId) {
|
|
198
|
-
try {
|
|
199
|
-
const referredTxn = await stripe.customers.createBalanceTransaction(referredCustomerId, {
|
|
200
|
-
amount: -referredCents,
|
|
201
|
-
currency: 'usd',
|
|
202
|
-
description: `Referral credit: welcome credit for signing up with a referral code (referral ${typedReferral.id})`,
|
|
203
|
-
}, { idempotencyKey: `ref-${typedReferral.id}-referred-grant` });
|
|
204
|
-
referredTxnId = referredTxn.id;
|
|
205
|
-
}
|
|
206
|
-
catch (e) {
|
|
207
|
-
console.error('[referralGrant] referral referred balance transaction creation failed -- referrer side already credited above', {
|
|
208
|
-
referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, message: e instanceof Error ? e.message : String(e),
|
|
209
|
-
});
|
|
210
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', e);
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
// Same reasoning as the referrer side above -- a failed persist here
|
|
214
|
-
// means a real Stripe credit exists with no durable record of its id.
|
|
215
|
-
const { error: partialUpdErr2 } = await supabase
|
|
216
|
-
.from('referrals')
|
|
217
|
-
.update({ stripe_balance_txn_id_referred: referredTxnId, referred_credit_cents: referredCents })
|
|
218
|
-
.eq('id', typedReferral.id);
|
|
219
|
-
if (partialUpdErr2) {
|
|
220
|
-
console.error('[referralGrant] referral partial grant persist (referred side) failed -- REFERRED STRIPE CREDIT ALREADY GRANTED', {
|
|
221
|
-
referral_id: typedReferral.id, referred_txn_id: referredTxnId, message: partialUpdErr2.message,
|
|
222
|
-
});
|
|
223
|
-
await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error(`REFERRED CREDIT GRANTED (txn ${referredTxnId}) BUT TXN ID NOT PERSISTED (${partialUpdErr2.message}) -- reconcile in Stripe before retrying; a retry past 24h without this id would charge again`));
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
// referrer_credit_cents/referred_credit_cents are NOT set here -- each
|
|
228
|
-
// was already persisted, atomically with its own txn id, above (round-4
|
|
229
|
-
// review finding) -- so the amount recorded always matches what that
|
|
230
|
-
// specific Stripe transaction actually charged, even across a retry
|
|
231
|
-
// where the formula or the referral's price_cents might have changed.
|
|
232
|
-
//
|
|
233
|
-
// Guarded on `currentStatus` (the row's real status as read at the top
|
|
234
|
-
// of this call), not a hardcoded 'signed_up' -- a retry from
|
|
235
|
-
// grant_failed must flip FROM grant_failed, not from a status the row
|
|
236
|
-
// was never actually in.
|
|
237
|
-
const { error: creditUpdErr } = await supabase
|
|
238
|
-
.from('referrals')
|
|
239
|
-
.update({
|
|
240
|
-
status: 'credited',
|
|
241
|
-
credited_at: new Date().toISOString(),
|
|
242
|
-
clawback_eligible_until: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
|
|
243
|
-
})
|
|
244
|
-
.eq('id', typedReferral.id)
|
|
245
|
-
.eq('status', currentStatus);
|
|
246
|
-
if (creditUpdErr) {
|
|
247
|
-
console.error('[referralGrant] referral row update after crediting failed -- BOTH stripe transactions already succeeded, only this status flip failed', {
|
|
248
|
-
referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, referred_txn_id: referredTxnId,
|
|
249
|
-
message: creditUpdErr.message,
|
|
250
|
-
});
|
|
251
|
-
await logOps(supabase, 'referral_credited_status_flip_failed', { referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, referred_txn_id: referredTxnId, message: creditUpdErr.message }, { severity: 'error' }).catch(() => { });
|
|
252
|
-
// Deliberately NOT recordReferralFailure here -- both Stripe
|
|
253
|
-
// transactions already succeeded, so 'grant_failed' would misleadingly
|
|
254
|
-
// imply the grant itself failed. The row stays at `currentStatus` with
|
|
255
|
-
// both txn ids already persisted above, so a later retry of this
|
|
256
|
-
// function is now SAFE: it will skip both createBalanceTransaction
|
|
257
|
-
// calls (already have referrerTxnId/referredTxnId) and just
|
|
258
|
-
// re-attempt this status flip.
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
catch (e) {
|
|
262
|
-
console.error('[referralGrant] maybeGrantReferralCredit failed', {
|
|
263
|
-
membership_id: referredMembershipId, message: e instanceof Error ? e.message : String(e),
|
|
264
|
-
});
|
|
265
|
-
if (referralId)
|
|
266
|
-
await recordReferralFailure(supabase, referralId, currentStatus, 'grant_failed', e);
|
|
267
|
-
}
|
|
46
|
+
export async function maybeGrantReferralCredit(_supabase, _stripe, referredMembershipId, _fromStatuses = ['signed_up']) {
|
|
47
|
+
console.warn('[referralGrant] maybeGrantReferralCredit is superseded and does nothing: referral credits are paid by gc-io referral-qualify-daily 30 days after signup', { membership_id: referredMembershipId });
|
|
268
48
|
}
|