@simplelayer/graniteer-core 0.3.21-referral.1 → 0.3.21

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.
@@ -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,7 +11,6 @@ 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 } from '../referralCodeLookup.js';
15
14
  const Body = z.object({
16
15
  plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
17
16
  email: z.string().email().max(255),
@@ -211,9 +210,7 @@ export async function handle(req, operator) {
211
210
  const { data: referrer, error: refErr } = await supabase
212
211
  .from('memberships')
213
212
  .select('id')
214
- .ilike('referral_code', escapeLikePattern(referral_code))
215
- .order('id', { ascending: true })
216
- .limit(1)
213
+ .eq('referral_code', referral_code)
217
214
  .maybeSingle();
218
215
  if (!refErr && referrer)
219
216
  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,8 +6,7 @@ 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 } from '../referralGrant.js';
10
- import { escapeLikePattern } from '../referralCodeLookup.js';
9
+ import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.js';
11
10
  import { findBaseItem } from '../membershipSubscriptionItems.js';
12
11
  import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
13
12
  import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
@@ -101,7 +100,9 @@ function buildStripeWebhookHandler(config, connect) {
101
100
  .from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
102
101
  return data;
103
102
  }
103
+ let bookingLookupErrored = false;
104
104
  async function findBookingIdByPaymentIntent(paymentIntentId) {
105
+ bookingLookupErrored = false;
105
106
  const { data: rows, error } = await supabase
106
107
  .from('bookings')
107
108
  .select('id')
@@ -113,6 +114,7 @@ function buildStripeWebhookHandler(config, connect) {
113
114
  payment_intent_id: paymentIntentId,
114
115
  ...(typeof code === 'string' ? { error_code: code } : {}),
115
116
  }, { severity: 'error', bookingId: null });
117
+ bookingLookupErrored = true;
116
118
  return null;
117
119
  }
118
120
  const list = (rows ?? []);
@@ -150,8 +152,11 @@ function buildStripeWebhookHandler(config, connect) {
150
152
  let markerFailed = false;
151
153
  try {
152
154
  bookingId = await findBookingIdByPaymentIntent(piId);
153
- if (!bookingId)
154
- return 'skipped';
155
+ if (!bookingId) {
156
+ // Connect: the marker is the only thing blocking self-service credit,
157
+ // so a lookup DB error must be retried by Stripe, not silently acked.
158
+ return connect && bookingLookupErrored ? 'marker_failed' : 'skipped';
159
+ }
155
160
  if (connect) {
156
161
  // Connect (direct-charge) bookings are refunded outside the app, so
157
162
  // nothing cancels the booking: status stays 'paid', the slot stays
@@ -588,9 +593,7 @@ function buildStripeWebhookHandler(config, connect) {
588
593
  const { data: referrer, error: referrerErr } = await supabase
589
594
  .from('memberships')
590
595
  .select('id')
591
- .ilike('referral_code', escapeLikePattern(refCode))
592
- .order('id', { ascending: true })
593
- .limit(1)
596
+ .eq('referral_code', refCode)
594
597
  .maybeSingle();
595
598
  if (referrerErr || !referrer)
596
599
  return; // unresolvable code -- silently skip, never block signup
@@ -2117,10 +2120,17 @@ function buildStripeWebhookHandler(config, connect) {
2117
2120
  }
2118
2121
  }
2119
2122
  catch (e) {
2123
+ const permanentStripeError = e?.type === 'StripeInvalidRequestError' && !isRetryableStripeError(e);
2120
2124
  await logOps(supabase, 'booking_access_revoke_step_failed', {
2121
2125
  reason: 'charge_dispute_created',
2122
2126
  error_name: errorNameFromUnknown(e),
2127
+ permanent_stripe_error: permanentStripeError,
2123
2128
  }, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
2129
+ if (connect && !permanentStripeError) {
2130
+ // Marker is the only thing blocking self-service credit on Connect; let Stripe retry.
2131
+ await releaseStripeEventLedgerForRetry(event.id);
2132
+ return webhookResponseMarkerFailedForRetry();
2133
+ }
2124
2134
  }
2125
2135
  break;
2126
2136
  }
@@ -2533,8 +2543,18 @@ function buildStripeWebhookHandler(config, connect) {
2533
2543
  .select('id');
2534
2544
  if (fipErr)
2535
2545
  console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
2536
- // Referral crediting is NOT done here any more: gc-io's
2537
- // referral-qualify-daily job pays it 30 days after signup.
2546
+ // Round-3 review finding: isGenuineInvoicePayment is an OR that
2547
+ // only blocks a $0 invoice when billing_reason ===
2548
+ // 'subscription_create' -- every other billing_reason
2549
+ // (subscription_cycle after a 100%-off code, a $0 invoice
2550
+ // covered entirely by account balance, etc.) bypasses the
2551
+ // amount check entirely. Gate the referral grant itself on a
2552
+ // genuinely nonzero amount_paid, separately from
2553
+ // first_invoice_paid_at (which has other consumers and should
2554
+ // keep its existing, broader semantics).
2555
+ if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
2556
+ await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id);
2557
+ }
2538
2558
  }
2539
2559
  }
2540
2560
  break;
@@ -2,9 +2,4 @@ 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
- */
10
5
  export declare function computeReferralCredits(planPriceCents: number, isPrivateOffice: boolean): ReferralCredits;
@@ -13,11 +13,6 @@
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
- */
21
16
  export function computeReferralCredits(planPriceCents, isPrivateOffice) {
22
17
  const referrerCents = isPrivateOffice
23
18
  ? PRIVATE_OFFICE_REFERRER_CENTS
@@ -14,9 +14,36 @@ 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
- * @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.
17
+ * Referral program Phase 1, step 2 (grant at first-invoice-paid).
18
+ *
19
+ * Called from the webhook only when the first_invoice_paid_at compare-and-
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.
20
47
  */
21
- export declare function maybeGrantReferralCredit(_supabase: SupabaseLike, _stripe: Stripe, referredMembershipId: string, _fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
48
+ export declare function maybeGrantReferralCredit(supabase: SupabaseLike, stripe: Stripe, referredMembershipId: string, fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
22
49
  export {};
@@ -1,15 +1,38 @@
1
- // Referral program failure recorder + SUPERSEDED grant entry point.
1
+ // Referral program grant logic + failure recorder.
2
2
  //
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.
3
+ // Originally moved verbatim out of stripe-webhook/index.ts so the SAME
4
+ // grant logic could be re-invoked on demand by admin-referral-retry (a
5
+ // grant_failed referral needs to re-run this exact function, not a second
6
+ // hand-written copy of Stripe balance-transaction logic that could drift
7
+ // from it over time). Since then (second-model review, 2026-08-24) it has
8
+ // picked up real behavioral fixes on top of that extraction -- it is no
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.
9
24
  //
10
- // recordReferralFailure is still live: the clawback functions in
11
- // stripe-webhook.ts use it to mark a referrals row clawback_failed.
25
+ // The two clawback functions (maybeClawbackReferralCredit and
26
+ // maybeClawbackReferralCreditForRefundOrDispute) stay in stripe-webhook/
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.
12
34
  import { logOps } from './ops.js';
35
+ import { computeReferralCredits } from './referralCredits.js';
13
36
  /**
14
37
  * Records a permanent grant/clawback failure on the referrals row itself
15
38
  * (fix #4 from the round-2 review) instead of only console.error/warn --
@@ -39,10 +62,207 @@ export async function recordReferralFailure(supabase, referralId, fromStatus, to
39
62
  await logOps(supabase, 'referral_' + toStatus, { referral_id: referralId, message }, { severity: 'error' }).catch(() => { });
40
63
  }
41
64
  /**
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.
65
+ * Referral program Phase 1, step 2 (grant at first-invoice-paid).
66
+ *
67
+ * Called from the webhook only when the first_invoice_paid_at compare-and-
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.
45
95
  */
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 });
96
+ export async function maybeGrantReferralCredit(supabase, stripe, referredMembershipId, fromStatuses = ['signed_up']) {
97
+ let referralId = null;
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
+ }
48
268
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.21-referral.1",
3
+ "version": "0.3.21",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- export declare function escapeLikePattern(input: string): string;
@@ -1,3 +0,0 @@
1
- export function escapeLikePattern(input) {
2
- return input.replace(/[\\%_]/g, (ch) => '\\' + ch);
3
- }