@simplelayer/graniteer-core 0.3.22 → 0.3.24
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/functions/booking-access-grant.d.ts +32 -0
- package/dist/functions/booking-access-grant.js +195 -0
- package/dist/functions/booking-access-revoke-backstop.d.ts +7 -0
- package/dist/functions/booking-access-revoke-backstop.js +11 -0
- package/dist/functions/create-subscription-checkout.js +14 -3
- package/dist/functions/stripe-webhook.js +18 -26
- 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 +9 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
export type SupabaseLike = SupabaseClient<any, any, any>;
|
|
3
|
+
export declare const ORGANIZER_GRANT_TIMEOUT_MS = 95000;
|
|
4
|
+
export interface RequestOrganizerGrantOptions {
|
|
5
|
+
bookingId: string;
|
|
6
|
+
/** gc-io doors.id (uuid), NOT the UniFi id; resolved from the doors table. */
|
|
7
|
+
doorId: string;
|
|
8
|
+
organizer: {
|
|
9
|
+
name?: string | null;
|
|
10
|
+
email?: string | null;
|
|
11
|
+
phone?: string | null;
|
|
12
|
+
};
|
|
13
|
+
startUtc: string;
|
|
14
|
+
endUtc: string;
|
|
15
|
+
/** Caller supplied, e.g. commons:<bookingId>:<doorId>. */
|
|
16
|
+
idempotencyKey: string;
|
|
17
|
+
actingUserId: string;
|
|
18
|
+
busBase?: string;
|
|
19
|
+
fetchImpl?: typeof fetch;
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
}
|
|
22
|
+
export type RequestOrganizerGrantError = 'invalid_input' | 'door_lookup_failed' | 'door_not_found' | 'door_not_provisioned' | 'door_not_live' | 'lockdown_not_verified' | 'secret_missing' | 'middleware_unreachable' | 'middleware_rejected' | 'middleware_error' | 'bad_response' | 'unexpected';
|
|
23
|
+
export type RequestOrganizerGrantResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
grant_id: string;
|
|
26
|
+
idempotent: boolean;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
error: RequestOrganizerGrantError;
|
|
30
|
+
status?: number;
|
|
31
|
+
};
|
|
32
|
+
export declare function requestOrganizerGrant(admin: SupabaseLike, opts: RequestOrganizerGrantOptions): Promise<RequestOrganizerGrantResult>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Request an organizer door-access grant for a booking via the tenant
|
|
2
|
+
// middleware's signed /admin/event-access/grant path (same e1 HMAC contract and
|
|
3
|
+
// outbound body as the staff "grant" branch in event-access-admin.ts).
|
|
4
|
+
//
|
|
5
|
+
// Unattended path that can open physical doors: every step fails closed, the
|
|
6
|
+
// function never throws, and nothing sensitive (PINs, organizer PII, secret,
|
|
7
|
+
// signature, raw response) is returned or logged.
|
|
8
|
+
import { logOps } from '../ops.js';
|
|
9
|
+
import { sha256Hex, signBusMessage } from '../busSignature.js';
|
|
10
|
+
import { getEventAccessBusBase } from '../tenant-config.js';
|
|
11
|
+
// Grant-only headroom, same as event-access-admin's GRANT_TIMEOUT_MS: the
|
|
12
|
+
// middleware mints PINs with a retry loop (worst case ~85s) and the Cloudflare
|
|
13
|
+
// Tunnel edge cuts proxied HTTP at ~100s, so 95s clears the former and there
|
|
14
|
+
// is no point going higher.
|
|
15
|
+
export const ORGANIZER_GRANT_TIMEOUT_MS = 95_000;
|
|
16
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
17
|
+
const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
|
|
18
|
+
// Explicit zone required: a zone-less string would be parsed as server-local time.
|
|
19
|
+
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i;
|
|
20
|
+
const MAX_IDEMPOTENCY_KEY_LENGTH = 200;
|
|
21
|
+
function errorName(e) {
|
|
22
|
+
if (e instanceof Error && e.name)
|
|
23
|
+
return e.name;
|
|
24
|
+
return 'Error';
|
|
25
|
+
}
|
|
26
|
+
async function safeLog(admin, kind, detail, bookingId) {
|
|
27
|
+
try {
|
|
28
|
+
await logOps(admin, kind, detail, { severity: 'error', ...(bookingId ? { bookingId } : {}) });
|
|
29
|
+
}
|
|
30
|
+
catch { /* logging must never throw or change the result */ }
|
|
31
|
+
}
|
|
32
|
+
function optionalText(v) {
|
|
33
|
+
if (v === undefined || v === null)
|
|
34
|
+
return null;
|
|
35
|
+
if (typeof v !== 'string')
|
|
36
|
+
return undefined;
|
|
37
|
+
const t = v.trim();
|
|
38
|
+
return t === '' ? null : t;
|
|
39
|
+
}
|
|
40
|
+
function requiredText(v) {
|
|
41
|
+
if (typeof v !== 'string')
|
|
42
|
+
return null;
|
|
43
|
+
const t = v.trim();
|
|
44
|
+
return t === '' ? null : t;
|
|
45
|
+
}
|
|
46
|
+
function instant(v) {
|
|
47
|
+
if (typeof v !== 'string')
|
|
48
|
+
return null;
|
|
49
|
+
const t = v.trim();
|
|
50
|
+
if (!ISO_INSTANT.test(t))
|
|
51
|
+
return null;
|
|
52
|
+
const ms = Date.parse(t);
|
|
53
|
+
if (!Number.isFinite(ms))
|
|
54
|
+
return null;
|
|
55
|
+
return new Date(ms).toISOString();
|
|
56
|
+
}
|
|
57
|
+
function validate(opts) {
|
|
58
|
+
if (!opts || typeof opts !== 'object')
|
|
59
|
+
return null;
|
|
60
|
+
const bookingId = requiredText(opts.bookingId);
|
|
61
|
+
const doorId = requiredText(opts.doorId);
|
|
62
|
+
if (!bookingId || !UUID.test(bookingId) || !doorId || !UUID.test(doorId))
|
|
63
|
+
return null;
|
|
64
|
+
const start = instant(opts.startUtc);
|
|
65
|
+
const end = instant(opts.endUtc);
|
|
66
|
+
if (!start || !end)
|
|
67
|
+
return null;
|
|
68
|
+
if (!(Date.parse(end) > Date.parse(start)))
|
|
69
|
+
return null;
|
|
70
|
+
const idempotencyKey = requiredText(opts.idempotencyKey);
|
|
71
|
+
const actingUserId = requiredText(opts.actingUserId);
|
|
72
|
+
if (!idempotencyKey || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH || !actingUserId)
|
|
73
|
+
return null;
|
|
74
|
+
const org = opts.organizer;
|
|
75
|
+
if (!org || typeof org !== 'object')
|
|
76
|
+
return null;
|
|
77
|
+
const name = optionalText(org.name);
|
|
78
|
+
const email = optionalText(org.email);
|
|
79
|
+
const phone = optionalText(org.phone);
|
|
80
|
+
if (name === undefined || email === undefined || phone === undefined)
|
|
81
|
+
return null;
|
|
82
|
+
return { bookingId, doorId, person: { name, email, phone }, start, end, idempotencyKey, actingUserId };
|
|
83
|
+
}
|
|
84
|
+
export async function requestOrganizerGrant(admin, opts) {
|
|
85
|
+
let logBookingId;
|
|
86
|
+
try {
|
|
87
|
+
const input = validate(opts);
|
|
88
|
+
if (!input)
|
|
89
|
+
return { ok: false, error: 'invalid_input' };
|
|
90
|
+
logBookingId = input.bookingId;
|
|
91
|
+
// Door resolution: doors.id -> UniFi door id. Stricter than the staff path
|
|
92
|
+
// (this is the unattended path): must be live and lockdown-verified.
|
|
93
|
+
const { data: doorData, error: doorErr } = await admin
|
|
94
|
+
.from('doors').select('id,unifi_door_id,status,lockdown_verified').eq('id', input.doorId).maybeSingle();
|
|
95
|
+
if (doorErr) {
|
|
96
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_lookup_failed' }, logBookingId);
|
|
97
|
+
return { ok: false, error: 'door_lookup_failed' };
|
|
98
|
+
}
|
|
99
|
+
if (!doorData) {
|
|
100
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_found' }, logBookingId);
|
|
101
|
+
return { ok: false, error: 'door_not_found' };
|
|
102
|
+
}
|
|
103
|
+
const door = doorData;
|
|
104
|
+
const unifi = typeof door.unifi_door_id === 'string' ? door.unifi_door_id.trim() : '';
|
|
105
|
+
if (!unifi || unifi === 'PENDING') {
|
|
106
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_provisioned' }, logBookingId);
|
|
107
|
+
return { ok: false, error: 'door_not_provisioned' };
|
|
108
|
+
}
|
|
109
|
+
if (door.status !== 'live') {
|
|
110
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'door_not_live' }, logBookingId);
|
|
111
|
+
return { ok: false, error: 'door_not_live' };
|
|
112
|
+
}
|
|
113
|
+
if (door.lockdown_verified !== true) {
|
|
114
|
+
await safeLog(admin, 'commons_organizer_grant_door_rejected', { reason: 'lockdown_not_verified' }, logBookingId);
|
|
115
|
+
return { ok: false, error: 'lockdown_not_verified' };
|
|
116
|
+
}
|
|
117
|
+
const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
|
|
118
|
+
const secret = typeof secretRaw === 'string' ? secretRaw : null;
|
|
119
|
+
if (secretErr || !secret) {
|
|
120
|
+
await safeLog(admin, 'commons_organizer_grant_secret_missing', {}, logBookingId);
|
|
121
|
+
return { ok: false, error: 'secret_missing' };
|
|
122
|
+
}
|
|
123
|
+
// Mirrors event-access-admin.ts's grant branch (key order is part of the signed bytes).
|
|
124
|
+
const outbound = {
|
|
125
|
+
acting_user_id: input.actingUserId,
|
|
126
|
+
person: {
|
|
127
|
+
name: input.person.name,
|
|
128
|
+
email: input.person.email,
|
|
129
|
+
phone: input.person.phone,
|
|
130
|
+
},
|
|
131
|
+
room: { booking_id: input.bookingId },
|
|
132
|
+
door_id: unifi,
|
|
133
|
+
start: input.start,
|
|
134
|
+
end: input.end,
|
|
135
|
+
idempotency_key: input.idempotencyKey,
|
|
136
|
+
};
|
|
137
|
+
const rawBody = JSON.stringify(outbound);
|
|
138
|
+
const bodyHash = await sha256Hex(rawBody);
|
|
139
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
140
|
+
const signature = await signBusMessage(['e1', 'grant', ts, bodyHash].join('\n'), secret);
|
|
141
|
+
const busBase = opts.busBase ?? getEventAccessBusBase();
|
|
142
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
143
|
+
const timeoutMs = typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
|
|
144
|
+
? opts.timeoutMs
|
|
145
|
+
: ORGANIZER_GRANT_TIMEOUT_MS;
|
|
146
|
+
let res;
|
|
147
|
+
try {
|
|
148
|
+
res = await doFetch(`${busBase}/admin/event-access/grant`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: {
|
|
151
|
+
'Content-Type': 'application/json',
|
|
152
|
+
'X-Event-Access-Signature': signature,
|
|
153
|
+
'X-Event-Access-Timestamp': ts,
|
|
154
|
+
},
|
|
155
|
+
body: rawBody,
|
|
156
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
|
|
161
|
+
return { ok: false, error: 'middleware_unreachable' };
|
|
162
|
+
}
|
|
163
|
+
let parsed = null;
|
|
164
|
+
try {
|
|
165
|
+
const text = await res.text();
|
|
166
|
+
parsed = text ? JSON.parse(text) : null;
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
parsed = null;
|
|
170
|
+
}
|
|
171
|
+
const parsedObj = parsed && typeof parsed === 'object' ? parsed : null;
|
|
172
|
+
if (!res.ok) {
|
|
173
|
+
const detail = { status: res.status };
|
|
174
|
+
const code = parsedObj?.error;
|
|
175
|
+
if (typeof code === 'string' && SAFE_ERROR_CODE.test(code))
|
|
176
|
+
detail.error_code = code;
|
|
177
|
+
await safeLog(admin, 'commons_organizer_grant_call_failed', detail, logBookingId);
|
|
178
|
+
return {
|
|
179
|
+
ok: false,
|
|
180
|
+
error: res.status === 401 || res.status === 403 ? 'middleware_rejected' : 'middleware_error',
|
|
181
|
+
status: res.status,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const grantId = parsedObj?.grant_id;
|
|
185
|
+
if (!parsedObj || parsedObj.ok !== true || typeof grantId !== 'string' || grantId.trim() === '') {
|
|
186
|
+
await safeLog(admin, 'commons_organizer_grant_bad_response', { status: res.status }, logBookingId);
|
|
187
|
+
return { ok: false, error: 'bad_response', status: res.status };
|
|
188
|
+
}
|
|
189
|
+
return { ok: true, grant_id: grantId, idempotent: parsedObj.idempotent === true };
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
await safeLog(admin, 'commons_organizer_grant_call_error', { error_name: errorName(e) }, logBookingId);
|
|
193
|
+
return { ok: false, error: 'unexpected' };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -9,3 +9,10 @@ export declare function bookingRowRequiresBackstopRevoke(booking: {
|
|
|
9
9
|
access_revoke_required_at?: string | null;
|
|
10
10
|
}): boolean;
|
|
11
11
|
export declare function handle(req: Request): Promise<Response>;
|
|
12
|
+
export interface BookingAccessRevokeBackstopConfig {
|
|
13
|
+
/** Hand-maintained deploy-verification marker returned by the GET branch. */
|
|
14
|
+
buildMarker: string;
|
|
15
|
+
}
|
|
16
|
+
/** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
|
|
17
|
+
* every other method is delegated to `handle` unchanged. */
|
|
18
|
+
export declare function createBookingAccessRevokeBackstopHandler(config: BookingAccessRevokeBackstopConfig): (req: Request) => Promise<Response>;
|
|
@@ -119,3 +119,14 @@ export async function handle(req) {
|
|
|
119
119
|
headers: { 'Content-Type': 'application/json' },
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
|
+
/** Wraps `handle` with an unauthenticated deploy-verification GET (no DB, no secrets);
|
|
123
|
+
* every other method is delegated to `handle` unchanged. */
|
|
124
|
+
export function createBookingAccessRevokeBackstopHandler(config) {
|
|
125
|
+
const buildMarker = config.buildMarker;
|
|
126
|
+
return (req) => {
|
|
127
|
+
if (req.method === 'GET') {
|
|
128
|
+
return Promise.resolve(new Response(JSON.stringify({ ok: true, function: 'booking-access-revoke-backstop', build: buildMarker }), { status: 200, headers: { 'Content-Type': 'application/json' } }));
|
|
129
|
+
}
|
|
130
|
+
return handle(req);
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -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),
|
|
@@ -19,7 +20,13 @@ const Body = z.object({
|
|
|
19
20
|
// Referral program Phase 1. Case-sensitive exact match against
|
|
20
21
|
// memberships.referral_code, resolved just below. An unresolvable code is
|
|
21
22
|
// silently ignored -- it must never block or error checkout.
|
|
22
|
-
|
|
23
|
+
// Payment must never be blocked by a referral code: anything that is not a
|
|
24
|
+
// string passing the allowlist (empty, whitespace, over-long, wildcard,
|
|
25
|
+
// non-string) is dropped before validation, as if the field were absent.
|
|
26
|
+
referral_code: z.preprocess((v) => {
|
|
27
|
+
const t = typeof v === 'string' ? v.trim() : v;
|
|
28
|
+
return isValidReferralCode(t) ? t : undefined;
|
|
29
|
+
}, z.string().optional()),
|
|
23
30
|
// Internal `coupons` code. Unlike referral_code, an unusable code here is a
|
|
24
31
|
// hard 400 -- the member typed it expecting a discount, so charging them
|
|
25
32
|
// full price silently is the wrong failure mode.
|
|
@@ -205,12 +212,16 @@ export async function handle(req, operator) {
|
|
|
205
212
|
// code, malicious input) is NOT an error -- it just means no referral
|
|
206
213
|
// metadata gets attached, same as if the field had been omitted.
|
|
207
214
|
let referralCode;
|
|
208
|
-
|
|
215
|
+
// Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a '*'
|
|
216
|
+
// wildcard) is treated exactly like an omitted/unknown code -- no lookup.
|
|
217
|
+
if (referral_code && isValidReferralCode(referral_code)) {
|
|
209
218
|
try {
|
|
210
219
|
const { data: referrer, error: refErr } = await supabase
|
|
211
220
|
.from('memberships')
|
|
212
221
|
.select('id')
|
|
213
|
-
.
|
|
222
|
+
.ilike('referral_code', escapeLikePattern(referral_code))
|
|
223
|
+
.order('id', { ascending: true })
|
|
224
|
+
.limit(1)
|
|
214
225
|
.maybeSingle();
|
|
215
226
|
if (!refErr && referrer)
|
|
216
227
|
referralCode = referral_code;
|
|
@@ -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';
|
|
@@ -576,8 +577,8 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
576
577
|
* fallback baked in), not re-derived from sub.metadata here.
|
|
577
578
|
*
|
|
578
579
|
* Inserts a 'signed_up' referrals row only -- no credit amounts, no Stripe
|
|
579
|
-
* balance calls.
|
|
580
|
-
*
|
|
580
|
+
* balance calls. The grant happens later, at day 30, via the daily
|
|
581
|
+
* qualify job in gc-io (not at first-invoice-paid). We do NOT call computeReferralCredits
|
|
581
582
|
* here to "validate" plan.price_cents -- Math.max/Math.round never throw,
|
|
582
583
|
* so that validated nothing. Instead we check price_cents directly and
|
|
583
584
|
* refuse to insert a referrals row at all if it's missing, rather than
|
|
@@ -590,10 +591,16 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
590
591
|
const refCode = sub.metadata?.referral_code;
|
|
591
592
|
if (!refCode)
|
|
592
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;
|
|
593
598
|
const { data: referrer, error: referrerErr } = await supabase
|
|
594
599
|
.from('memberships')
|
|
595
600
|
.select('id')
|
|
596
|
-
.
|
|
601
|
+
.ilike('referral_code', escapeLikePattern(refCode))
|
|
602
|
+
.order('id', { ascending: true })
|
|
603
|
+
.limit(1)
|
|
597
604
|
.maybeSingle();
|
|
598
605
|
if (referrerErr || !referrer)
|
|
599
606
|
return; // unresolvable code -- silently skip, never block signup
|
|
@@ -646,8 +653,9 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
646
653
|
// maybeGrantReferralCredit moved verbatim to ../_shared/referralGrant.ts
|
|
647
654
|
// (2026-08-24) so admin-referral-retry can call the exact same, already-
|
|
648
655
|
// idempotent function on a grant_failed row instead of a second
|
|
649
|
-
// hand-written copy of this Stripe balance-transaction logic.
|
|
650
|
-
//
|
|
656
|
+
// hand-written copy of this Stripe balance-transaction logic. The grant
|
|
657
|
+
// is no longer made at first-invoice-paid: it happens at day 30 via the
|
|
658
|
+
// daily qualify job in gc-io (this file makes no balance call).
|
|
651
659
|
/**
|
|
652
660
|
* Referral program Phase 1, step 3 (clawback on fast cancel).
|
|
653
661
|
*
|
|
@@ -2530,31 +2538,15 @@ function buildStripeWebhookHandler(config, connect) {
|
|
|
2530
2538
|
// an earlier migration) -- this is the actual ongoing writer.
|
|
2531
2539
|
const isGenuineInvoicePayment = inv.billing_reason !== 'subscription_create' || (inv.amount_paid ?? 0) > 0;
|
|
2532
2540
|
if (isGenuineInvoicePayment) {
|
|
2533
|
-
|
|
2534
|
-
// whether this call actually WON the compare-and-swap (this was
|
|
2535
|
-
// genuinely the first real paid invoice) vs. a repeat event that
|
|
2536
|
-
// found the column already set -- the update's own predicate and
|
|
2537
|
-
// payload are unchanged.
|
|
2538
|
-
const { data: fipRows, error: fipErr } = await supabase
|
|
2541
|
+
const { error: fipErr } = await supabase
|
|
2539
2542
|
.from('memberships')
|
|
2540
2543
|
.update({ first_invoice_paid_at: new Date().toISOString() })
|
|
2541
2544
|
.eq('stripe_subscription_id', subId)
|
|
2542
|
-
.is('first_invoice_paid_at', null)
|
|
2543
|
-
.select('id');
|
|
2545
|
+
.is('first_invoice_paid_at', null);
|
|
2544
2546
|
if (fipErr)
|
|
2545
2547
|
console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
|
|
2546
|
-
//
|
|
2547
|
-
//
|
|
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
|
-
}
|
|
2548
|
+
// Referral crediting is NOT done here any more: gc-io's
|
|
2549
|
+
// referral-qualify-daily job pays it 30 days after signup.
|
|
2558
2550
|
}
|
|
2559
2551
|
}
|
|
2560
2552
|
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplelayer/graniteer-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.24",
|
|
4
4
|
"description": "Shared platform core for Graniteer",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -417,6 +417,14 @@
|
|
|
417
417
|
"types": "./dist/functions/boldsign-sender-identity.d.ts",
|
|
418
418
|
"default": "./dist/functions/boldsign-sender-identity.js"
|
|
419
419
|
},
|
|
420
|
+
"./functions/booking-access-grant": {
|
|
421
|
+
"types": "./dist/functions/booking-access-grant.d.ts",
|
|
422
|
+
"default": "./dist/functions/booking-access-grant.js"
|
|
423
|
+
},
|
|
424
|
+
"./functions/booking-access-revoke": {
|
|
425
|
+
"types": "./dist/functions/booking-access-revoke.d.ts",
|
|
426
|
+
"default": "./dist/functions/booking-access-revoke.js"
|
|
427
|
+
},
|
|
420
428
|
"./functions/booking-access-revoke-backstop": {
|
|
421
429
|
"types": "./dist/functions/booking-access-revoke-backstop.d.ts",
|
|
422
430
|
"default": "./dist/functions/booking-access-revoke-backstop.js"
|