@simplelayer/graniteer-core 0.3.19 → 0.3.21-referral.1
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/bookingSource.d.ts +2 -0
- package/dist/bookingSource.js +11 -0
- package/dist/businessHours.d.ts +11 -0
- package/dist/businessHours.js +55 -0
- package/dist/connectBookingCharge.d.ts +49 -0
- package/dist/connectBookingCharge.js +68 -0
- package/dist/functions/admin-create-booking.d.ts +3 -0
- package/dist/functions/admin-create-booking.js +15 -2
- package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
- package/dist/functions/admin-mark-booking-paid.js +27 -3
- package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
- package/dist/functions/booking-access-revoke-backstop.js +121 -0
- package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
- package/dist/functions/booking-access-revoke-door-state.js +61 -0
- package/dist/functions/booking-access-revoke.d.ts +35 -0
- package/dist/functions/booking-access-revoke.js +279 -0
- package/dist/functions/booking-availability.d.ts +2 -1
- package/dist/functions/booking-availability.js +14 -5
- package/dist/functions/create-booking.d.ts +5 -0
- package/dist/functions/create-booking.js +22 -4
- package/dist/functions/create-subscription-checkout.js +4 -1
- package/dist/functions/manage-booking.d.ts +6 -0
- package/dist/functions/manage-booking.js +36 -13
- package/dist/functions/reschedule-booking.d.ts +5 -0
- package/dist/functions/reschedule-booking.js +39 -2
- package/dist/functions/space-availability-range.d.ts +2 -1
- package/dist/functions/space-availability-range.js +8 -1
- package/dist/functions/stripe-webhook.d.ts +4 -0
- package/dist/functions/stripe-webhook.js +200 -16
- package/dist/functions/sync-gcal-blackouts.js +1 -1
- package/dist/gcalBookingEvents.d.ts +59 -0
- package/dist/gcalBookingEvents.js +182 -0
- package/dist/gcalSync.d.ts +1 -0
- package/dist/gcalSync.js +5 -0
- package/dist/pricing.d.ts +10 -2
- package/dist/pricing.js +14 -9
- package/dist/referralCodeLookup.d.ts +1 -0
- package/dist/referralCodeLookup.js +3 -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/dist/stripeConnectEvents.d.ts +11 -0
- package/dist/stripeConnectEvents.js +37 -0
- package/dist/tenant-config.d.ts +8 -0
- package/dist/tenant-config.js +24 -0
- package/package.json +26 -2
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { JWT } from 'google-auth-library';
|
|
2
|
+
import { parsePgRange } from './availability.js';
|
|
3
|
+
import { CS_BOOKING_ID_KEY } from './gcalSync.js';
|
|
4
|
+
const EVENTS_SCOPE = 'https://www.googleapis.com/auth/calendar.events';
|
|
5
|
+
const CAL_BASE = 'https://www.googleapis.com/calendar/v3/calendars';
|
|
6
|
+
const TZ = 'America/Los_Angeles';
|
|
7
|
+
// Deterministic id (Google allows client ids of [a-v0-9], 5-1024 chars; a UUID's
|
|
8
|
+
// hex digits qualify) so create is idempotent and update/delete need no stored id.
|
|
9
|
+
export function eventIdForBooking(bookingId) {
|
|
10
|
+
return `csb${bookingId.replace(/-/g, '').toLowerCase()}`;
|
|
11
|
+
}
|
|
12
|
+
async function defaultGetAccessToken() {
|
|
13
|
+
const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
|
|
14
|
+
const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
|
|
15
|
+
if (!clientEmail || !rawKey)
|
|
16
|
+
return null;
|
|
17
|
+
const jwt = new JWT({ email: clientEmail, key: rawKey.replace(/\\n/g, '\n'), scopes: [EVENTS_SCOPE] });
|
|
18
|
+
const tok = await jwt.getAccessToken();
|
|
19
|
+
return tok?.token ?? null;
|
|
20
|
+
}
|
|
21
|
+
function eventBody(input, includeId) {
|
|
22
|
+
return {
|
|
23
|
+
...(includeId ? { id: eventIdForBooking(input.bookingId) } : {}),
|
|
24
|
+
summary: input.summary,
|
|
25
|
+
description: input.description,
|
|
26
|
+
location: input.location,
|
|
27
|
+
start: { dateTime: input.startIso, timeZone: TZ },
|
|
28
|
+
end: { dateTime: input.endIso, timeZone: TZ },
|
|
29
|
+
transparency: 'opaque',
|
|
30
|
+
extendedProperties: { private: { [CS_BOOKING_ID_KEY]: input.bookingId } },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
async function call(method, calendarId, eventId, body, deps) {
|
|
34
|
+
const token = await (deps.getAccessToken ?? defaultGetAccessToken)();
|
|
35
|
+
if (!token)
|
|
36
|
+
return { noToken: true, status: 0 };
|
|
37
|
+
const url = `${CAL_BASE}/${encodeURIComponent(calendarId)}/events${eventId ? `/${encodeURIComponent(eventId)}` : ''}`;
|
|
38
|
+
const res = await (deps.fetch ?? fetch)(url, {
|
|
39
|
+
method,
|
|
40
|
+
headers: {
|
|
41
|
+
Authorization: `Bearer ${token}`,
|
|
42
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
43
|
+
},
|
|
44
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
45
|
+
signal: AbortSignal.timeout(15000),
|
|
46
|
+
});
|
|
47
|
+
return { noToken: false, status: res.status };
|
|
48
|
+
}
|
|
49
|
+
const isOk = (s) => s >= 200 && s < 300;
|
|
50
|
+
const noCreds = { ok: false, reason: 'no_credentials' };
|
|
51
|
+
const httpFail = (status) => ({ ok: false, reason: 'http_error', status });
|
|
52
|
+
export async function createBookingEvent(input, deps = {}) {
|
|
53
|
+
if (!input.calendarId)
|
|
54
|
+
return { ok: false, reason: 'no_calendar' };
|
|
55
|
+
try {
|
|
56
|
+
const eventId = eventIdForBooking(input.bookingId);
|
|
57
|
+
const r = await call('POST', input.calendarId, null, eventBody(input, true), deps);
|
|
58
|
+
if (r.noToken)
|
|
59
|
+
return noCreds;
|
|
60
|
+
if (isOk(r.status))
|
|
61
|
+
return { ok: true, eventId, action: 'created' };
|
|
62
|
+
// Deterministic id already exists (retry / duplicate delivery): converge via update.
|
|
63
|
+
if (r.status === 409)
|
|
64
|
+
return await updateBookingEvent(input, deps);
|
|
65
|
+
return httpFail(r.status);
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export async function updateBookingEvent(input, deps = {}) {
|
|
72
|
+
if (!input.calendarId)
|
|
73
|
+
return { ok: false, reason: 'no_calendar' };
|
|
74
|
+
try {
|
|
75
|
+
const eventId = eventIdForBooking(input.bookingId);
|
|
76
|
+
const r = await call('PATCH', input.calendarId, eventId, eventBody(input, false), deps);
|
|
77
|
+
if (r.noToken)
|
|
78
|
+
return noCreds;
|
|
79
|
+
if (isOk(r.status))
|
|
80
|
+
return { ok: true, eventId, action: 'updated' };
|
|
81
|
+
if (r.status === 404) {
|
|
82
|
+
const c = await call('POST', input.calendarId, null, eventBody(input, true), deps);
|
|
83
|
+
if (c.noToken)
|
|
84
|
+
return noCreds;
|
|
85
|
+
return isOk(c.status) ? { ok: true, eventId, action: 'created' } : httpFail(c.status);
|
|
86
|
+
}
|
|
87
|
+
return httpFail(r.status);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export async function deleteBookingEvent(calendarId, bookingId, deps = {}) {
|
|
94
|
+
if (!calendarId)
|
|
95
|
+
return { ok: false, reason: 'no_calendar' };
|
|
96
|
+
try {
|
|
97
|
+
const eventId = eventIdForBooking(bookingId);
|
|
98
|
+
const r = await call('DELETE', calendarId, eventId, null, deps);
|
|
99
|
+
if (r.noToken)
|
|
100
|
+
return noCreds;
|
|
101
|
+
if (isOk(r.status))
|
|
102
|
+
return { ok: true, eventId, action: 'deleted' };
|
|
103
|
+
if (r.status === 404 || r.status === 410)
|
|
104
|
+
return { ok: true, eventId, action: 'already_absent' };
|
|
105
|
+
return httpFail(r.status);
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export function isGcalWritebackEnabled(operator) {
|
|
112
|
+
return operator?.googleCalendarWriteback === true;
|
|
113
|
+
}
|
|
114
|
+
export function bookingRowToEventInput(row) {
|
|
115
|
+
const calendarId = row.rooms?.google_calendar_id;
|
|
116
|
+
const range = parsePgRange(row.during);
|
|
117
|
+
if (!calendarId || !range)
|
|
118
|
+
return null;
|
|
119
|
+
const who = row.contact_name || row.contact_email || 'Guest';
|
|
120
|
+
const lines = [
|
|
121
|
+
row.contact_name ? `Name: ${row.contact_name}` : null,
|
|
122
|
+
row.contact_email ? `Email: ${row.contact_email}` : null,
|
|
123
|
+
row.contact_phone ? `Phone: ${row.contact_phone}` : null,
|
|
124
|
+
`Booking: ${row.id}`,
|
|
125
|
+
].filter(Boolean);
|
|
126
|
+
return {
|
|
127
|
+
calendarId,
|
|
128
|
+
bookingId: row.id,
|
|
129
|
+
startIso: new Date(range[0]).toISOString(),
|
|
130
|
+
endIso: new Date(range[1]).toISOString(),
|
|
131
|
+
summary: `${row.rooms?.name ?? 'Booking'} — ${who}`,
|
|
132
|
+
description: lines.join('\n'),
|
|
133
|
+
location: row.rooms?.address ?? undefined,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const defaultLog = (m, d) => console.warn(m, d);
|
|
137
|
+
/**
|
|
138
|
+
* Fail-soft create for a paid booking row. Never throws; returns null when the
|
|
139
|
+
* operator flag is off (the default), so callers can invoke it unconditionally.
|
|
140
|
+
*/
|
|
141
|
+
export async function writebackBookingCreated(operator, row, deps = {}, log = defaultLog) {
|
|
142
|
+
if (!isGcalWritebackEnabled(operator))
|
|
143
|
+
return null;
|
|
144
|
+
try {
|
|
145
|
+
const input = bookingRowToEventInput(row);
|
|
146
|
+
if (!input)
|
|
147
|
+
return { ok: false, reason: 'no_calendar' };
|
|
148
|
+
const res = await createBookingEvent(input, deps);
|
|
149
|
+
if (!res.ok)
|
|
150
|
+
log('[gcalBookingEvents] create failed', { bookingId: row.id, ...res });
|
|
151
|
+
return res;
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
log('[gcalBookingEvents] create threw', { bookingId: row.id, error: String(e) });
|
|
155
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
export async function writebackBookingCancelled(operator, calendarId, bookingId, deps = {}, log = defaultLog) {
|
|
159
|
+
if (!isGcalWritebackEnabled(operator))
|
|
160
|
+
return null;
|
|
161
|
+
try {
|
|
162
|
+
const res = await deleteBookingEvent(calendarId, bookingId, deps);
|
|
163
|
+
if (!res.ok)
|
|
164
|
+
log('[gcalBookingEvents] delete failed', { bookingId, ...res });
|
|
165
|
+
return res;
|
|
166
|
+
}
|
|
167
|
+
catch (e) {
|
|
168
|
+
log('[gcalBookingEvents] delete threw', { bookingId, error: String(e) });
|
|
169
|
+
return { ok: false, reason: 'exception', detail: String(e) };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Adapter matching the `createCalendarEvent` dep shape used by create-booking,
|
|
174
|
+
* admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
|
|
175
|
+
* without door hardware can pass this as that dep; it is the only way to cover
|
|
176
|
+
* stripe-webhook's paid path without editing the webhook.
|
|
177
|
+
*/
|
|
178
|
+
export function makeWritebackCreateCalendarEvent(operator, deps = {}) {
|
|
179
|
+
return async (_admin, row) => {
|
|
180
|
+
await writebackBookingCreated(operator, row, deps);
|
|
181
|
+
};
|
|
182
|
+
}
|
package/dist/gcalSync.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export declare function allDayToUtcRange(startDate: string, endDate: string): {
|
|
|
5
5
|
endIso: string;
|
|
6
6
|
};
|
|
7
7
|
export declare function laMidnightUtc(dateStr: string): Date;
|
|
8
|
+
export declare const CS_BOOKING_ID_KEY = "cs_booking_id";
|
|
8
9
|
export interface GcalEventStartEnd {
|
|
9
10
|
dateTime?: string;
|
|
10
11
|
date?: string;
|
package/dist/gcalSync.js
CHANGED
|
@@ -62,6 +62,7 @@ export function laMidnightUtc(dateStr) {
|
|
|
62
62
|
// Fallback (should not happen for real LA dates).
|
|
63
63
|
return new Date(Date.UTC(y, mo - 1, d, 8, 0));
|
|
64
64
|
}
|
|
65
|
+
export const CS_BOOKING_ID_KEY = 'cs_booking_id';
|
|
65
66
|
// True when this event was created by our own booking system and must NOT be
|
|
66
67
|
// re-imported as a blackout (belt & braces: gc_source marker OR known booking
|
|
67
68
|
// google_event_id). Also drops cancelled and transparent (free) events.
|
|
@@ -75,6 +76,10 @@ export function shouldSkipEvent(ev, selfIds) {
|
|
|
75
76
|
const source = ev.extendedProperties?.private?.gc_source;
|
|
76
77
|
if (source === 'gc-connect')
|
|
77
78
|
return true;
|
|
79
|
+
// Events written back by gcalBookingEvents.ts carry cs_booking_id; importing
|
|
80
|
+
// them as blackouts would make every booking block its own slot.
|
|
81
|
+
if (ev.extendedProperties?.private?.[CS_BOOKING_ID_KEY])
|
|
82
|
+
return true;
|
|
78
83
|
if (selfIds.has(ev.id))
|
|
79
84
|
return true;
|
|
80
85
|
return false;
|
package/dist/pricing.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
import type { NoticeConfig } from './businessHours.js';
|
|
2
3
|
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
3
4
|
export interface RoomForPricing {
|
|
4
5
|
id: string;
|
|
@@ -95,8 +96,8 @@ export declare function resolveHalfDayWindow(room: RoomForPricing, dayMode: 'hal
|
|
|
95
96
|
ok: false;
|
|
96
97
|
error: string;
|
|
97
98
|
};
|
|
98
|
-
export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number): Promise<PricingResult>;
|
|
99
|
-
export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number): Promise<PricingResult>;
|
|
99
|
+
export declare function validateAndPriceDayBlock(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputDayBlock, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
|
|
100
|
+
export declare function validateAndPriceHourly(supabase: SupabaseLike, room: RoomForPricing, input: PricingInputHourly, nowMs: number, notice?: NoticeConfig | null): Promise<PricingResult>;
|
|
100
101
|
/**
|
|
101
102
|
* Entry point: dispatches to hourly or day_block based on room.booking_mode.
|
|
102
103
|
* `quote` rooms cannot be booked via checkout.
|
|
@@ -302,5 +303,12 @@ export declare function validateAndPriceForRoom(supabase: SupabaseLike, room: Ro
|
|
|
302
303
|
discount_cents: number;
|
|
303
304
|
rule_type: string | null;
|
|
304
305
|
};
|
|
306
|
+
/**
|
|
307
|
+
* Optional per-operator minimum-notice config (minNoticeBusinessHours /
|
|
308
|
+
* holidays). Public customer paths (create-booking, reschedule-booking)
|
|
309
|
+
* pass it; staff paths (admin-create-booking) omit it and keep the plain
|
|
310
|
+
* 15-minute floor. Unset => exactly the historical 15-minute floor.
|
|
311
|
+
*/
|
|
312
|
+
notice?: NoticeConfig | null;
|
|
305
313
|
}): Promise<PricingResult>;
|
|
306
314
|
export {};
|
package/dist/pricing.js
CHANGED
|
@@ -6,11 +6,16 @@
|
|
|
6
6
|
// rangeLiteral } describing a fully-validated booking window.
|
|
7
7
|
import { getBusyRangesDetailed } from './availability.js';
|
|
8
8
|
import { logOps } from './ops.js';
|
|
9
|
+
import { DEFAULT_MIN_NOTICE_MS, earliestBookingStartMs, minNoticeErrorMessage } from './businessHours.js';
|
|
9
10
|
// Minimum lead time required between "now" and a booking's start time.
|
|
10
11
|
// Mirrors the same purpose as GHL's `allowBookingAfter` setting on the tour
|
|
11
12
|
// calendars, but for meeting rooms — previously there was no floor at all
|
|
12
13
|
// beyond "not literally in the past" (see 2026-08-25 same-day-tour review).
|
|
13
|
-
const MIN_BOOKING_NOTICE_MS =
|
|
14
|
+
const MIN_BOOKING_NOTICE_MS = DEFAULT_MIN_NOTICE_MS;
|
|
15
|
+
// Earliest allowed start. Unset notice config => exactly now + 15 minutes.
|
|
16
|
+
function noticeFloorMs(nowMs, notice) {
|
|
17
|
+
return notice ? earliestBookingStartMs(nowMs, notice) : nowMs + MIN_BOOKING_NOTICE_MS;
|
|
18
|
+
}
|
|
14
19
|
function laOffsetHours(atUtc) {
|
|
15
20
|
const parts = new Intl.DateTimeFormat('en-US', {
|
|
16
21
|
timeZone: 'America/Los_Angeles',
|
|
@@ -126,7 +131,7 @@ export function resolveHalfDayWindow(room, dayMode, wd, dateStr, openUtc, closeU
|
|
|
126
131
|
endUtc: laWallToUtc(y, mo, d, Math.floor(endMin / 60), endMin % 60),
|
|
127
132
|
};
|
|
128
133
|
}
|
|
129
|
-
export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
|
|
134
|
+
export async function validateAndPriceDayBlock(supabase, room, input, nowMs, notice) {
|
|
130
135
|
const { date, day_mode } = input;
|
|
131
136
|
if (!date || !day_mode)
|
|
132
137
|
return { ok: false, status: 400, error: 'date and day_mode are required for this room' };
|
|
@@ -165,8 +170,8 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
|
|
|
165
170
|
endUtc = win.endUtc;
|
|
166
171
|
price_cents = room.half_day_cents;
|
|
167
172
|
}
|
|
168
|
-
if (startUtc.getTime() < nowMs
|
|
169
|
-
return { ok: false, status: 400, error:
|
|
173
|
+
if (startUtc.getTime() < noticeFloorMs(nowMs, notice)) {
|
|
174
|
+
return { ok: false, status: 400, error: minNoticeErrorMessage(nowMs, notice) };
|
|
170
175
|
}
|
|
171
176
|
if (price_cents <= 0)
|
|
172
177
|
return { ok: false, status: 400, error: 'invalid price' };
|
|
@@ -179,7 +184,7 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
|
|
|
179
184
|
list_rule_type: null,
|
|
180
185
|
};
|
|
181
186
|
}
|
|
182
|
-
export async function validateAndPriceHourly(supabase, room, input, nowMs) {
|
|
187
|
+
export async function validateAndPriceHourly(supabase, room, input, nowMs, notice) {
|
|
183
188
|
const { start, end } = input;
|
|
184
189
|
if (!start || !end)
|
|
185
190
|
return { ok: false, status: 400, error: 'start and end are required' };
|
|
@@ -190,8 +195,8 @@ export async function validateAndPriceHourly(supabase, room, input, nowMs) {
|
|
|
190
195
|
}
|
|
191
196
|
if (!(startUtc < endUtc))
|
|
192
197
|
return { ok: false, status: 400, error: 'end must be after start' };
|
|
193
|
-
if (startUtc.getTime() < nowMs
|
|
194
|
-
return { ok: false, status: 400, error:
|
|
198
|
+
if (startUtc.getTime() < noticeFloorMs(nowMs, notice)) {
|
|
199
|
+
return { ok: false, status: 400, error: minNoticeErrorMessage(nowMs, notice) };
|
|
195
200
|
}
|
|
196
201
|
if (startUtc.getUTCSeconds() !== 0 || startUtc.getUTCMilliseconds() !== 0 ||
|
|
197
202
|
endUtc.getUTCSeconds() !== 0 || endUtc.getUTCMilliseconds() !== 0 ||
|
|
@@ -699,8 +704,8 @@ export async function validateAndPriceForRoom(supabase, room, input, nowMs, opts
|
|
|
699
704
|
}
|
|
700
705
|
const isDayBlock = room.booking_mode === 'day_block';
|
|
701
706
|
const price = () => (isDayBlock
|
|
702
|
-
? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs)
|
|
703
|
-
: validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs));
|
|
707
|
+
? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs, opts.notice)
|
|
708
|
+
: validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs, opts.notice));
|
|
704
709
|
const baseRaw = await price();
|
|
705
710
|
if (!baseRaw.ok)
|
|
706
711
|
return baseRaw;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function escapeLikePattern(input: string): string;
|
|
@@ -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
|
}
|