@simplelayer/graniteer-core 0.3.21-referral.1 → 0.3.22
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 +1 -4
- package/dist/functions/manage-booking.js +2 -0
- package/dist/functions/membership-door-sync.d.ts +18 -0
- package/dist/functions/membership-door-sync.js +76 -6
- package/dist/functions/stripe-webhook.js +29 -9
- package/dist/referralCredits.d.ts +0 -5
- package/dist/referralCredits.js +0 -5
- package/dist/referralGrant.d.ts +31 -4
- package/dist/referralGrant.js +234 -14
- package/package.json +1 -1
- package/dist/referralCodeLookup.d.ts +0 -1
- package/dist/referralCodeLookup.js +0 -3
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,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
|
-
.
|
|
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
|
|
@@ -10,5 +10,23 @@ export interface MembershipDoorSyncConfig {
|
|
|
10
10
|
membershipBusEnforce: (members: MembershipSnapshotMember[], supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
|
|
11
11
|
membershipBusRevoke: (members: MembershipSnapshotMember[], generatedAt: string, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
|
|
15
|
+
* grants_access add-ons. Throws on any read error so the tick aborts before
|
|
16
|
+
* any Phase 2/3/4 call: falling back to "no add-on groups" could make the
|
|
17
|
+
* revoke phase strip real access.
|
|
18
|
+
*/
|
|
19
|
+
export declare function loadAddonGroupIds(supabase: SupabaseClient): Promise<Map<string, string[]>>;
|
|
20
|
+
/**
|
|
21
|
+
* Desired UniFi group ids = union of entitled rows' plan groups and those
|
|
22
|
+
* same rows' live add-on groups. Not entitled (no entitled rows) => [].
|
|
23
|
+
* Sorted + de-duplicated; empty/null ids ignored.
|
|
24
|
+
*/
|
|
25
|
+
export declare function computeDesiredGroupIds(entitledRows: Array<{
|
|
26
|
+
id: string;
|
|
27
|
+
membership_plans: {
|
|
28
|
+
unifi_group_ids: string[] | null;
|
|
29
|
+
} | null;
|
|
30
|
+
}>, addonGroupsByMembership: Map<string, string[]>): string[];
|
|
13
31
|
export declare function createMembershipDoorSyncHandler(config: MembershipDoorSyncConfig): (req: Request) => Promise<Response>;
|
|
14
32
|
export {};
|
|
@@ -83,6 +83,80 @@ function stateEquals(a, b) {
|
|
|
83
83
|
}
|
|
84
84
|
return true;
|
|
85
85
|
}
|
|
86
|
+
const LIVE_ADDON_STATUSES = ['active', 'past_due', 'pending_removal'];
|
|
87
|
+
function assertNotTruncated(table, res) {
|
|
88
|
+
const data = res.data ?? [];
|
|
89
|
+
const count = res.count;
|
|
90
|
+
if (typeof count !== 'number' || count !== data.length) {
|
|
91
|
+
throw new Error(`${table} read truncated: got ${data.length} of ${count} -- aborting tick before any Phase 2/3/4 call`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
|
|
96
|
+
* grants_access add-ons. Throws on any read error so the tick aborts before
|
|
97
|
+
* any Phase 2/3/4 call: falling back to "no add-on groups" could make the
|
|
98
|
+
* revoke phase strip real access.
|
|
99
|
+
*/
|
|
100
|
+
export async function loadAddonGroupIds(supabase) {
|
|
101
|
+
const result = new Map();
|
|
102
|
+
const subsRes = (await supabase
|
|
103
|
+
.from('member_addon_subscriptions')
|
|
104
|
+
.select('membership_id,addon_id,status', { count: 'exact' })
|
|
105
|
+
.in('status', LIVE_ADDON_STATUSES)
|
|
106
|
+
.order('id'));
|
|
107
|
+
if (subsRes.error)
|
|
108
|
+
throw new Error('member_addon_subscriptions read failed: ' + subsRes.error.message);
|
|
109
|
+
assertNotTruncated('member_addon_subscriptions', subsRes);
|
|
110
|
+
// Re-check status locally so correctness never depends solely on the filter.
|
|
111
|
+
const subs = (subsRes.data ?? [])
|
|
112
|
+
.filter((s) => s.membership_id && s.addon_id && LIVE_ADDON_STATUSES.includes(s.status));
|
|
113
|
+
if (subs.length === 0)
|
|
114
|
+
return result;
|
|
115
|
+
const addonIds = Array.from(new Set(subs.map((s) => s.addon_id)));
|
|
116
|
+
const addonsRes = (await supabase
|
|
117
|
+
.from('member_addons')
|
|
118
|
+
.select('id,unifi_group_ids,grants_access', { count: 'exact' })
|
|
119
|
+
.in('id', addonIds)
|
|
120
|
+
.eq('grants_access', true)
|
|
121
|
+
.order('id'));
|
|
122
|
+
if (addonsRes.error)
|
|
123
|
+
throw new Error('member_addons read failed: ' + addonsRes.error.message);
|
|
124
|
+
assertNotTruncated('member_addons', addonsRes);
|
|
125
|
+
const groupsByAddon = new Map();
|
|
126
|
+
for (const a of (addonsRes.data ?? [])) {
|
|
127
|
+
if (a.grants_access !== true)
|
|
128
|
+
continue;
|
|
129
|
+
groupsByAddon.set(a.id, a.unifi_group_ids ?? []);
|
|
130
|
+
}
|
|
131
|
+
for (const s of subs) {
|
|
132
|
+
const gids = groupsByAddon.get(s.addon_id);
|
|
133
|
+
if (!gids)
|
|
134
|
+
continue;
|
|
135
|
+
const list = result.get(s.membership_id) ?? [];
|
|
136
|
+
for (const g of gids)
|
|
137
|
+
if (g)
|
|
138
|
+
list.push(g);
|
|
139
|
+
result.set(s.membership_id, list);
|
|
140
|
+
}
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Desired UniFi group ids = union of entitled rows' plan groups and those
|
|
145
|
+
* same rows' live add-on groups. Not entitled (no entitled rows) => [].
|
|
146
|
+
* Sorted + de-duplicated; empty/null ids ignored.
|
|
147
|
+
*/
|
|
148
|
+
export function computeDesiredGroupIds(entitledRows, addonGroupsByMembership) {
|
|
149
|
+
const set = new Set();
|
|
150
|
+
for (const r of entitledRows) {
|
|
151
|
+
for (const g of r.membership_plans?.unifi_group_ids ?? [])
|
|
152
|
+
if (g)
|
|
153
|
+
set.add(g);
|
|
154
|
+
for (const g of addonGroupsByMembership.get(r.id) ?? [])
|
|
155
|
+
if (g)
|
|
156
|
+
set.add(g);
|
|
157
|
+
}
|
|
158
|
+
return Array.from(set).sort();
|
|
159
|
+
}
|
|
86
160
|
/**
|
|
87
161
|
* Door-access start-date gate, separate from (and layered AFTER) pricing
|
|
88
162
|
* entitlement. An UNGATED row (door_access_not_before === null) is never
|
|
@@ -134,6 +208,7 @@ export function createMembershipDoorSyncHandler(config) {
|
|
|
134
208
|
if (rows.length > 0 && !('door_access_not_before' in rows[0])) {
|
|
135
209
|
throw new Error('shape_guard_failed: door_access_not_before missing from memberships select result -- aborting tick before any Phase 2/3/4 call');
|
|
136
210
|
}
|
|
211
|
+
const addonGroupsByMembership = await loadAddonGroupIds(supabase);
|
|
137
212
|
// Group by lowercased email. Rows with no email are ignored (nothing to
|
|
138
213
|
// key door/WiFi state to). resolveIsMember() likewise treats "" as "not
|
|
139
214
|
// a member" — keep that behavior aligned.
|
|
@@ -184,16 +259,11 @@ export function createMembershipDoorSyncHandler(config) {
|
|
|
184
259
|
let groupIds = [];
|
|
185
260
|
let wifiEnabled = false;
|
|
186
261
|
if (entitled) {
|
|
187
|
-
const set = new Set();
|
|
188
262
|
for (const r of entitledRows) {
|
|
189
|
-
const gids = r.membership_plans?.unifi_group_ids ?? [];
|
|
190
|
-
for (const g of gids)
|
|
191
|
-
if (g)
|
|
192
|
-
set.add(g);
|
|
193
263
|
if (r.membership_plans?.wifi_enabled === true)
|
|
194
264
|
wifiEnabled = true;
|
|
195
265
|
}
|
|
196
|
-
groupIds =
|
|
266
|
+
groupIds = computeDesiredGroupIds(entitledRows, addonGroupsByMembership);
|
|
197
267
|
}
|
|
198
268
|
const desired = { entitled, group_ids: groupIds, wifi_enabled: wifiEnabled };
|
|
199
269
|
// Every managed, non-protected email goes into the snapshot -- entitled or not.
|
|
@@ -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
|
-
|
|
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
|
-
.
|
|
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
|
-
//
|
|
2537
|
-
//
|
|
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;
|
package/dist/referralCredits.js
CHANGED
|
@@ -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
|
package/dist/referralGrant.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* the
|
|
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(
|
|
48
|
+
export declare function maybeGrantReferralCredit(supabase: SupabaseLike, stripe: Stripe, referredMembershipId: string, fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
|
|
22
49
|
export {};
|
package/dist/referralGrant.js
CHANGED
|
@@ -1,15 +1,38 @@
|
|
|
1
|
-
// Referral program
|
|
1
|
+
// Referral program grant logic + failure recorder.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// referral
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
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
|
-
//
|
|
11
|
-
// stripe-webhook
|
|
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
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* the
|
|
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(
|
|
47
|
-
|
|
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 +0,0 @@
|
|
|
1
|
-
export declare function escapeLikePattern(input: string): string;
|