@simplelayer/graniteer-core 0.0.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +98 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/bookingHoldReclaim.ts +94 -0
- package/src/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/conductorAdmin.ts +141 -0
- package/src/email-templates/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/reauthentication.tsx +60 -0
- package/src/functions/admin-cancel-membership.ts +311 -0
- package/src/functions/admin-change-membership-plan.ts +308 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- package/src/functions/admin-photo-upload.ts +128 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- package/src/functions/admin-reset-mfa.ts +138 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- package/src/functions/day-pass-status.ts +89 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- package/src/functions/get-signing-link.ts +211 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- package/src/functions/print-billing-recover.ts +97 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -0
- package/src/functions/space-availability-range.ts +142 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- package/src/functions/voice-inquiry.test.ts +301 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/membership.ts +109 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +34 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/slackAlert.ts +38 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/tier1Agreement.ts +125 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
2
|
+
import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
|
|
3
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
4
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
5
|
+
|
|
6
|
+
const corsHeaders = {
|
|
7
|
+
'Access-Control-Allow-Origin': '*',
|
|
8
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
9
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
interface CallerClaims {
|
|
13
|
+
sub: string;
|
|
14
|
+
email?: string;
|
|
15
|
+
aal?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
|
|
19
|
+
let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
20
|
+
function getJwks(supabaseUrl: string) {
|
|
21
|
+
if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
|
|
22
|
+
return jwksCache;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
|
|
26
|
+
if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
|
|
27
|
+
const token = authHeader.slice(7).trim();
|
|
28
|
+
try {
|
|
29
|
+
const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
|
|
30
|
+
const claims = payload as unknown as CallerClaims;
|
|
31
|
+
if (!claims.sub) return null;
|
|
32
|
+
return claims;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function json(status: number, body: unknown) {
|
|
39
|
+
return new Response(JSON.stringify(body), {
|
|
40
|
+
status,
|
|
41
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Staff-only wrapper around public.end_office_assignment_and_promote().
|
|
47
|
+
*
|
|
48
|
+
* The RPC is SECURITY DEFINER and REVOKEd from PUBLIC, so it can only be
|
|
49
|
+
* reached with the service-role client from here. It atomically ends an
|
|
50
|
+
* 'active' assignment (status='ended', ended_at, ended_by) and promotes any
|
|
51
|
+
* 'awaiting_handoff' row on the same room to 'active'.
|
|
52
|
+
*
|
|
53
|
+
* Auth scaffold mirrors create-agreement: JWKS verify -> aal2 -> rate limit ->
|
|
54
|
+
* admin_users allowlist.
|
|
55
|
+
*/
|
|
56
|
+
export async function handle(req: Request): Promise<Response> {
|
|
57
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
58
|
+
if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
|
|
59
|
+
|
|
60
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
61
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
62
|
+
|
|
63
|
+
const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
|
|
64
|
+
const caller = await verifyCaller(authHeader, SUPABASE_URL);
|
|
65
|
+
if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
|
|
66
|
+
if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
|
|
67
|
+
const callerEmail = (caller.email ?? '').toLowerCase();
|
|
68
|
+
if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
|
|
69
|
+
|
|
70
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
71
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const [ipOk, emailOk] = await Promise.all([
|
|
75
|
+
checkRateLimit(admin, 'office-assignment-end-ip', clientIp(req), 30, 300),
|
|
76
|
+
checkRateLimit(admin, 'office-assignment-end-email', callerEmail, 20, 300),
|
|
77
|
+
]);
|
|
78
|
+
if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
|
|
79
|
+
|
|
80
|
+
const { data: allow, error: allowErr } = await admin
|
|
81
|
+
.from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
|
|
82
|
+
if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
|
|
83
|
+
if (!allow) return json(403, { ok: false, error: 'not_authorized' });
|
|
84
|
+
|
|
85
|
+
let body: { assignment_id?: string };
|
|
86
|
+
try {
|
|
87
|
+
body = await req.json();
|
|
88
|
+
} catch {
|
|
89
|
+
return json(400, { ok: false, error: 'invalid_json' });
|
|
90
|
+
}
|
|
91
|
+
const assignmentId = (body.assignment_id ?? '').trim();
|
|
92
|
+
if (!/^[0-9a-f-]{36}$/i.test(assignmentId)) {
|
|
93
|
+
return json(400, { ok: false, error: 'invalid_assignment_id' });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Sponsored team members ("Company members") must be removed first — ending
|
|
97
|
+
// the assignment here would leave them with a dangling sponsor and live
|
|
98
|
+
// access. Never cascade-delete them automatically.
|
|
99
|
+
const { data: assignmentRow, error: assignErr } = await admin
|
|
100
|
+
.from('office_assignments')
|
|
101
|
+
.select('id,membership_id')
|
|
102
|
+
.eq('id', assignmentId)
|
|
103
|
+
.maybeSingle();
|
|
104
|
+
if (assignErr) return json(500, { ok: false, error: 'assignment_lookup_failed', detail: assignErr.message });
|
|
105
|
+
if (!assignmentRow) return json(404, { ok: false, error: 'assignment_not_found' });
|
|
106
|
+
if (assignmentRow.membership_id) {
|
|
107
|
+
const { data: seats, error: seatsErr } = await admin
|
|
108
|
+
.from('memberships')
|
|
109
|
+
.select('id,email,customer_name,status')
|
|
110
|
+
.eq('sponsor_membership_id', assignmentRow.membership_id)
|
|
111
|
+
.neq('status', 'canceled');
|
|
112
|
+
if (seatsErr) return json(500, { ok: false, error: 'team_member_lookup_failed', detail: seatsErr.message });
|
|
113
|
+
if ((seats ?? []).length > 0) {
|
|
114
|
+
return json(409, {
|
|
115
|
+
ok: false,
|
|
116
|
+
error: 'has_team_members',
|
|
117
|
+
team_members: seats,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const { data, error } = await admin.rpc('end_office_assignment_and_promote', {
|
|
123
|
+
p_ending_assignment_id: assignmentId,
|
|
124
|
+
p_actor: callerEmail,
|
|
125
|
+
});
|
|
126
|
+
if (error) {
|
|
127
|
+
await logOps(admin, 'office_assignment_end_failed', {
|
|
128
|
+
assignment_id: assignmentId, actor: callerEmail, message: error.message,
|
|
129
|
+
}, { severity: 'error' }).catch(() => {});
|
|
130
|
+
return json(500, { ok: false, error: 'rpc_failed', detail: error.message });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const result = (data ?? {}) as { ok?: boolean; error?: string; room_id?: string | null; ended_assignment_id?: string | null; promoted_assignment_id?: string | null };
|
|
134
|
+
if (result.ok === false) {
|
|
135
|
+
return json(409, { ok: false, error: result.error ?? 'not_active_or_not_found' });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
await logOps(admin, 'office_assignment_ended', {
|
|
139
|
+
assignment_id: assignmentId,
|
|
140
|
+
actor: callerEmail,
|
|
141
|
+
room_id: result.room_id ?? null,
|
|
142
|
+
promoted_assignment_id: result.promoted_assignment_id ?? null,
|
|
143
|
+
}, { severity: 'info' }).catch(() => {});
|
|
144
|
+
|
|
145
|
+
return json(200, { ok: true, ...result });
|
|
146
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Member-portal "your booking access" read.
|
|
2
|
+
//
|
|
3
|
+
// Returns, for the CALLER'S OWN upcoming/current bookings, the room and the
|
|
4
|
+
// booking window only. This function makes NO outbound call to the door
|
|
5
|
+
// middleware and holds no HMAC credential: booking-level access codes are not
|
|
6
|
+
// issued yet, so every parseable booking reports status 'pending'.
|
|
7
|
+
//
|
|
8
|
+
// Identity model: the caller is resolved from their portal session JWT only.
|
|
9
|
+
// No email and no booking id is ever read from the request body — the booking
|
|
10
|
+
// set is derived server-side from bookings.contact_email = the verified email.
|
|
11
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
12
|
+
import { resolvePortalSessionEmail } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
13
|
+
import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
14
|
+
|
|
15
|
+
const corsHeaders = {
|
|
16
|
+
'Access-Control-Allow-Origin': '*',
|
|
17
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
18
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const MAX_BOOKINGS = 10;
|
|
22
|
+
|
|
23
|
+
function json(status: number, body: unknown) {
|
|
24
|
+
return new Response(JSON.stringify(body), {
|
|
25
|
+
status,
|
|
26
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** tstzrange text -> ISO bounds. Never pass raw range text to new Date(). */
|
|
31
|
+
function parseRange(during: string): { start: string; end: string } | null {
|
|
32
|
+
const m = during.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
|
|
33
|
+
if (!m) return null;
|
|
34
|
+
const norm = (raw: string) =>
|
|
35
|
+
raw.trim().replace(/ /g, 'T').replace(/([+-]\d{2})$/, '$1:00');
|
|
36
|
+
const s = new Date(norm(m[1]));
|
|
37
|
+
const e = new Date(norm(m[2]));
|
|
38
|
+
if (isNaN(s.getTime()) || isNaN(e.getTime())) return null;
|
|
39
|
+
return { start: s.toISOString(), end: e.toISOString() };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type Status = 'pending' | 'unavailable';
|
|
43
|
+
|
|
44
|
+
export async function handle(req: Request): Promise<Response> {
|
|
45
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
46
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
47
|
+
|
|
48
|
+
const admin = createClient(
|
|
49
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
50
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
51
|
+
{ auth: { persistSession: false, autoRefreshToken: false } },
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
const email = await resolvePortalSessionEmail(req, admin);
|
|
56
|
+
if (!email) return json(401, { error: 'unauthorized' });
|
|
57
|
+
|
|
58
|
+
const ok = await checkRateLimit(admin, 'portal-booking-access', email, 30, 300);
|
|
59
|
+
if (!ok) return json(429, { error: 'rate_limited' });
|
|
60
|
+
|
|
61
|
+
const nowIso = new Date().toISOString();
|
|
62
|
+
const { data: rows, error } = await admin
|
|
63
|
+
.from('bookings')
|
|
64
|
+
.select('id,during,status,rooms(name,slug)')
|
|
65
|
+
.eq('contact_email', email)
|
|
66
|
+
.eq('status', 'paid')
|
|
67
|
+
.overlaps('during', `[${nowIso},)`)
|
|
68
|
+
.order('during', { ascending: true })
|
|
69
|
+
.limit(MAX_BOOKINGS);
|
|
70
|
+
|
|
71
|
+
if (error) return json(200, { bookings: [], access_check_failed: true });
|
|
72
|
+
|
|
73
|
+
const nowMs = Date.now();
|
|
74
|
+
const bookings = (rows ?? []).map((r) => {
|
|
75
|
+
const room = (r as { rooms?: { name?: string; slug?: string } | null }).rooms ?? null;
|
|
76
|
+
const range = parseRange(String((r as { during: string }).during));
|
|
77
|
+
const startMs = range ? Date.parse(range.start) : null;
|
|
78
|
+
return {
|
|
79
|
+
booking_id: String((r as { id: string }).id),
|
|
80
|
+
room_name: room?.name ?? 'Your room',
|
|
81
|
+
start: range?.start ?? null,
|
|
82
|
+
end: range?.end ?? null,
|
|
83
|
+
status: (range ? 'pending' : 'unavailable') as Status,
|
|
84
|
+
// Mirrors manage-booking/index.ts's own cancellable/within48h logic
|
|
85
|
+
// exactly -- do not let these two definitions drift apart.
|
|
86
|
+
cancellable: startMs !== null && startMs > nowMs,
|
|
87
|
+
within48h: startMs !== null && (startMs - nowMs) < 48 * 60 * 60 * 1000,
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
return json(200, { bookings });
|
|
92
|
+
} catch {
|
|
93
|
+
return json(200, { bookings: [], access_check_failed: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Member-portal invoice list. Thin read-only wrapper around Stripe's invoice
|
|
2
|
+
// list, needed because the Stripe secret key must never reach the browser.
|
|
3
|
+
//
|
|
4
|
+
// Auth is the SAME portal-session mode already added to manage-booking /
|
|
5
|
+
// reschedule-booking: `Authorization: Bearer <supabase jwt>` verified with
|
|
6
|
+
// `_shared/portalSession.ts`. No new secret is introduced — it reuses the
|
|
7
|
+
// existing STRIPE_SECRET_KEY.
|
|
8
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
9
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
10
|
+
import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
11
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
12
|
+
|
|
13
|
+
const corsHeaders = {
|
|
14
|
+
'Access-Control-Allow-Origin': '*',
|
|
15
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
16
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function json(status: number, body: unknown) {
|
|
20
|
+
return new Response(JSON.stringify(body), {
|
|
21
|
+
status,
|
|
22
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function handle(req: Request): Promise<Response> {
|
|
27
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
28
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
29
|
+
|
|
30
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
31
|
+
if (!stripeKey) return json(500, { error: 'not_configured' });
|
|
32
|
+
|
|
33
|
+
const admin = createClient(
|
|
34
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
35
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
36
|
+
{ auth: { persistSession: false, autoRefreshToken: false } },
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
const ipOk = await checkRateLimit(admin, 'portal-invoices-ip', clientIp(req), 60, 300);
|
|
40
|
+
if (!ipOk) return json(429, { error: 'rate_limited' });
|
|
41
|
+
|
|
42
|
+
const session = await resolvePortalSession(req, admin);
|
|
43
|
+
if (!session) return json(401, { error: 'unauthorized' });
|
|
44
|
+
const email = session.email;
|
|
45
|
+
|
|
46
|
+
const emailLower = email.toLowerCase();
|
|
47
|
+
|
|
48
|
+
// Step A: identity match on the linked auth user id.
|
|
49
|
+
const { data: byIdRows, error: byIdErr } = await admin
|
|
50
|
+
.from('memberships')
|
|
51
|
+
.select('stripe_customer_id,email')
|
|
52
|
+
.eq('auth_user_id', session.id)
|
|
53
|
+
.not('stripe_customer_id', 'is', null)
|
|
54
|
+
.order('created_at', { ascending: false });
|
|
55
|
+
if (byIdErr) return json(500, { error: 'lookup_failed' });
|
|
56
|
+
let membership: { stripe_customer_id: string; email: string } | undefined = (byIdRows ?? [])[0];
|
|
57
|
+
|
|
58
|
+
// Step B (transition): case-insensitive DB round-trip, then an exact JS match
|
|
59
|
+
// so a session email containing LIKE wildcards (_ or %) can never select
|
|
60
|
+
// another member's row. Restricted to still-unlinked rows.
|
|
61
|
+
if (!membership) {
|
|
62
|
+
const { data: membershipRows, error: membershipErr } = await admin
|
|
63
|
+
.from('memberships')
|
|
64
|
+
.select('stripe_customer_id,email')
|
|
65
|
+
.ilike('email', emailLower)
|
|
66
|
+
.is('auth_user_id', null)
|
|
67
|
+
.not('stripe_customer_id', 'is', null)
|
|
68
|
+
.order('created_at', { ascending: false });
|
|
69
|
+
if (membershipErr) return json(500, { error: 'lookup_failed' });
|
|
70
|
+
membership = (membershipRows ?? []).find(
|
|
71
|
+
(r) => (r.email ?? '').toLowerCase() === emailLower,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const customer = membership?.stripe_customer_id;
|
|
76
|
+
// No Stripe customer on file is a normal state (booking-only customer).
|
|
77
|
+
if (!customer) return json(200, { invoices: [] });
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const stripe = new Stripe(stripeKey, {
|
|
81
|
+
apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion,
|
|
82
|
+
});
|
|
83
|
+
const list = await stripe.invoices.list({ customer, limit: 20 });
|
|
84
|
+
const invoices = list.data.map((inv) => ({
|
|
85
|
+
id: inv.id,
|
|
86
|
+
number: inv.number ?? null,
|
|
87
|
+
created: new Date(inv.created * 1000).toISOString(),
|
|
88
|
+
amount_due_cents: inv.amount_due ?? 0,
|
|
89
|
+
amount_paid_cents: inv.amount_paid ?? 0,
|
|
90
|
+
status: inv.status ?? null,
|
|
91
|
+
hosted_invoice_url: inv.hosted_invoice_url ?? null,
|
|
92
|
+
invoice_pdf: inv.invoice_pdf ?? null,
|
|
93
|
+
}));
|
|
94
|
+
return json(200, { invoices });
|
|
95
|
+
} catch (e) {
|
|
96
|
+
console.error('[portal-list-invoices] stripe list failed', e);
|
|
97
|
+
return json(502, { error: 'invoices_unavailable' });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// supabase/functions/print-billing-recover/index.ts
|
|
2
|
+
//
|
|
3
|
+
// print-usage-bill P2 — the recovery sweep. Design: PRINT-USAGE-BILL-DESIGN.md
|
|
4
|
+
// v19 section 5.
|
|
5
|
+
//
|
|
6
|
+
// RUNS EVERY 5 MINUTES, PERMANENTLY — not monthly (section 5.1, cadence PINNED by
|
|
7
|
+
// R6 finding 2). The run itself is monthly; recovery is not. Two reasons, both
|
|
8
|
+
// load-bearing:
|
|
9
|
+
// 1. It is what makes ORACLE LAYER 3 (idempotency-key replay, which Stripe
|
|
10
|
+
// expires at 24h) reachable at all. At a monthly cadence that layer is dead.
|
|
11
|
+
// 2. It bounds the time a crashed run sits unresolved to minutes rather than a
|
|
12
|
+
// month, during which its membership cannot be billed at all.
|
|
13
|
+
//
|
|
14
|
+
// Every run this picks up arrives with NO recorded failure origin — section 5.2
|
|
15
|
+
// selects purely on lease age, and there is deliberately no failure_origin column
|
|
16
|
+
// (section 4.4.1). So section 4.4 rows 23-25 are the COMMON path here, not an exotic
|
|
17
|
+
// one, and every decision is made by the ORACLE and the run's persisted status.
|
|
18
|
+
// The question is always what actually happened, never what we intended.
|
|
19
|
+
|
|
20
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
21
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
22
|
+
import { runRecoverySweep, type RunInput, type RunRow } from 'npm:@simplelayer/graniteer-core/printBilling';
|
|
23
|
+
import { makeDb, makeStripe } from 'npm:@simplelayer/graniteer-core/printBillingAdapters';
|
|
24
|
+
|
|
25
|
+
function safeEqual(a: string, b: string): boolean {
|
|
26
|
+
const enc = new TextEncoder();
|
|
27
|
+
const ab = enc.encode(a), bb = enc.encode(b);
|
|
28
|
+
if (ab.length !== bb.length) return false;
|
|
29
|
+
let diff = 0;
|
|
30
|
+
for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
|
|
31
|
+
return diff === 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function handle(req: Request): Promise<Response> {
|
|
35
|
+
const supabase = createClient(
|
|
36
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
37
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
const { data: secret } = await supabase.rpc('get_print_billing_run_secret');
|
|
41
|
+
const provided = req.headers.get('x-gc-print-billing-secret') ?? '';
|
|
42
|
+
if (!secret || !safeEqual(String(secret), provided)) {
|
|
43
|
+
return new Response(JSON.stringify({ ok: false, error: 'forbidden' }), {
|
|
44
|
+
status: 403, headers: { 'Content-Type': 'application/json' },
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
49
|
+
const expectedAccountId = Deno.env.get('STRIPE_ACCOUNT_ID');
|
|
50
|
+
if (!stripeKey || !expectedAccountId) {
|
|
51
|
+
return new Response(JSON.stringify({ ok: false, error: 'stripe_config_missing' }), {
|
|
52
|
+
status: 500, headers: { 'Content-Type': 'application/json' },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const stripe = makeStripe(
|
|
57
|
+
new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion }),
|
|
58
|
+
);
|
|
59
|
+
const db = makeDb(supabase as never);
|
|
60
|
+
|
|
61
|
+
// section 5.3's escalation ladder. A held run gets LOUDER rather than expiring —
|
|
62
|
+
// an automatic expiry that frees the periods is exactly what created the
|
|
63
|
+
// double-charge hole in R7 F4 / R8 F2. warning -> error at 24h -> critical at 7d.
|
|
64
|
+
// The ladder now ends somewhere: public.print_run_resolve (M-21), surfaced in
|
|
65
|
+
// the admin panel as "Resolve held run".
|
|
66
|
+
await supabase.rpc('print_billing_escalate_stuck');
|
|
67
|
+
|
|
68
|
+
const results = await runRecoverySweep({
|
|
69
|
+
stripe,
|
|
70
|
+
db,
|
|
71
|
+
expectedAccountId,
|
|
72
|
+
expectedLivemode: (Deno.env.get('ENVIRONMENT') ?? '') === 'production',
|
|
73
|
+
|
|
74
|
+
// Rebuild the RunInput a recovered run needs to resume. period_ids is the
|
|
75
|
+
// snapshot taken at claim time and never revised; STEP 3.1 re-checks each
|
|
76
|
+
// period is still claimed by this run before posting its item (v17/B11-1).
|
|
77
|
+
loadRunInput: async (run: RunRow): Promise<RunInput> => {
|
|
78
|
+
const { data: months } = await supabase.rpc('print_billing_run_months',
|
|
79
|
+
{ p_run_id: run.id });
|
|
80
|
+
return {
|
|
81
|
+
runId: run.id,
|
|
82
|
+
membershipId: run.membership_id,
|
|
83
|
+
customerId: run.stripe_customer_id,
|
|
84
|
+
periodIds: run.period_ids,
|
|
85
|
+
periodMonths: (months ?? []) as string[],
|
|
86
|
+
amountCents: 0, // not re-asserted on resume; the claim already did
|
|
87
|
+
defaultPaymentMethod: null, // the invoice already exists by this point
|
|
88
|
+
expectedAccountId,
|
|
89
|
+
expectedLivemode: (Deno.env.get('ENVIRONMENT') ?? '') === 'production',
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
return new Response(JSON.stringify({ ok: true, swept: results.length, results }), {
|
|
95
|
+
headers: { 'Content-Type': 'application/json' },
|
|
96
|
+
});
|
|
97
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// supabase/functions/print-billing-run/index.ts
|
|
2
|
+
//
|
|
3
|
+
// print-usage-bill P2 — the monthly billing run. Design: PRINT-USAGE-BILL-DESIGN.md
|
|
4
|
+
// v19 section 4.2. Runs on the 5th of each month; the 5th is a STAFF BUFFER giving four
|
|
5
|
+
// days to catch a reconciliation mismatch before money moves (section 2.1).
|
|
6
|
+
//
|
|
7
|
+
// All of the decision logic lives in _shared/printBilling.ts, which imports
|
|
8
|
+
// nothing and is fully exercised against a mocked Stripe client in
|
|
9
|
+
// _shared/printBilling.test.ts. This file is the adapter: it builds a real Stripe
|
|
10
|
+
// client and a real Supabase client, enumerates eligible memberships, applies
|
|
11
|
+
// section 4.2's anomaly/cap gate, and hands each membership to the core.
|
|
12
|
+
//
|
|
13
|
+
// C-01: ONE standalone invoice per membership per month, customer-scoped, with no
|
|
14
|
+
// subscription attached and nothing on it but print charges.
|
|
15
|
+
//
|
|
16
|
+
// SECRET-GATED, like the other scheduled functions in this project. It is invoked
|
|
17
|
+
// by pg_cron via net.http_post and by nothing else.
|
|
18
|
+
|
|
19
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
20
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
21
|
+
import {
|
|
22
|
+
evaluateGate,
|
|
23
|
+
executeBillingRun,
|
|
24
|
+
resolveDefaultPaymentMethod,
|
|
25
|
+
type RunInput,
|
|
26
|
+
} from 'npm:@simplelayer/graniteer-core/printBilling';
|
|
27
|
+
import { makeDb, makeStripe } from 'npm:@simplelayer/graniteer-core/printBillingAdapters';
|
|
28
|
+
|
|
29
|
+
function safeEqual(a: string, b: string): boolean {
|
|
30
|
+
const enc = new TextEncoder();
|
|
31
|
+
const ab = enc.encode(a), bb = enc.encode(b);
|
|
32
|
+
if (ab.length !== bb.length) return false;
|
|
33
|
+
let diff = 0;
|
|
34
|
+
for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
|
|
35
|
+
return diff === 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface EligibleRow {
|
|
39
|
+
membership_id: string;
|
|
40
|
+
period_ids: string[];
|
|
41
|
+
period_months: string[];
|
|
42
|
+
amount_cents: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function handle(req: Request): Promise<Response> {
|
|
46
|
+
const supabase = createClient(
|
|
47
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
48
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
// ---- gate ---------------------------------------------------------------
|
|
52
|
+
const { data: secret } = await supabase.rpc('get_print_billing_run_secret');
|
|
53
|
+
const provided = req.headers.get('x-gc-print-billing-secret') ?? '';
|
|
54
|
+
if (!secret || !safeEqual(String(secret), provided)) {
|
|
55
|
+
return new Response(JSON.stringify({ ok: false, error: 'forbidden' }), {
|
|
56
|
+
status: 403, headers: { 'Content-Type': 'application/json' },
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
61
|
+
const expectedAccountId = Deno.env.get('STRIPE_ACCOUNT_ID');
|
|
62
|
+
if (!stripeKey || !expectedAccountId) {
|
|
63
|
+
// STEP 0.2 cannot be satisfied without both. Refuse rather than guess: it is
|
|
64
|
+
// the account assertion that makes a later 404 interpretable at all (R8 F3).
|
|
65
|
+
return new Response(JSON.stringify({ ok: false, error: 'stripe_config_missing' }), {
|
|
66
|
+
status: 500, headers: { 'Content-Type': 'application/json' },
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const rawStripe = new Stripe(stripeKey, {
|
|
71
|
+
apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion,
|
|
72
|
+
});
|
|
73
|
+
const stripe = makeStripe(rawStripe);
|
|
74
|
+
const db = makeDb(supabase as never);
|
|
75
|
+
const expectedLivemode = (Deno.env.get('ENVIRONMENT') ?? '') === 'production';
|
|
76
|
+
|
|
77
|
+
// ---- section 4.2 eligibility -------------------------------------------------
|
|
78
|
+
// Wrapped server-side for the same reason section 5.2's selection is (v18/B12-2):
|
|
79
|
+
// the aggregate + HAVING + NOT EXISTS shape is not expressible through PostgREST.
|
|
80
|
+
const { data: eligible, error: eligErr } =
|
|
81
|
+
await supabase.rpc('print_billing_eligible_memberships');
|
|
82
|
+
if (eligErr) {
|
|
83
|
+
return new Response(JSON.stringify({ ok: false, error: eligErr.message }), {
|
|
84
|
+
status: 500, headers: { 'Content-Type': 'application/json' },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const rows = (eligible ?? []) as EligibleRow[];
|
|
89
|
+
const results: Record<string, unknown>[] = [];
|
|
90
|
+
|
|
91
|
+
for (const row of rows) {
|
|
92
|
+
// ---- section 4.2's anomaly / cap gate. Runs entirely on DB reads, BEFORE the
|
|
93
|
+
// claim, and it decides whether money moves at all.
|
|
94
|
+
const baseline = await db.baseline(row.membership_id);
|
|
95
|
+
const gate = evaluateGate({
|
|
96
|
+
amountCents: row.amount_cents,
|
|
97
|
+
baselineCents: baseline.baseline_cents,
|
|
98
|
+
qualifyingPeriods: baseline.qualifying_periods,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
if (gate.blocked) {
|
|
102
|
+
// Both gates are evaluated and BOTH rows are written when both fire — staff
|
|
103
|
+
// need to know which rule caught it, because the two mean different things.
|
|
104
|
+
// The periods stay pending_bill and unclaimed; this needs staff approval.
|
|
105
|
+
if (gate.overCap) {
|
|
106
|
+
await db.opsEvent('print_billing_over_cap', 'error', {
|
|
107
|
+
membership_id: row.membership_id,
|
|
108
|
+
amount_cents: row.amount_cents,
|
|
109
|
+
cap_cents: 7500,
|
|
110
|
+
period_ids: row.period_ids,
|
|
111
|
+
}, `print_billing_over_cap:${row.membership_id}:${row.period_months[0]}`);
|
|
112
|
+
}
|
|
113
|
+
if (gate.anomaly) {
|
|
114
|
+
await db.opsEvent('print_billing_anomaly', 'error', {
|
|
115
|
+
membership_id: row.membership_id,
|
|
116
|
+
amount_cents: row.amount_cents,
|
|
117
|
+
baseline_cents: baseline.baseline_cents,
|
|
118
|
+
qualifying_periods: baseline.qualifying_periods,
|
|
119
|
+
period_ids: row.period_ids,
|
|
120
|
+
}, `print_billing_anomaly:${row.membership_id}:${row.period_months[0]}`);
|
|
121
|
+
}
|
|
122
|
+
results.push({ membership_id: row.membership_id, status: 'gated', ...gate });
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---- STEP 0.3 / 0.4 ---------------------------------------------------
|
|
127
|
+
// C-12: a CANCELED member is billed here like anyone else, using their
|
|
128
|
+
// existing Stripe customer id, with no subscription required.
|
|
129
|
+
// C-13: standalone customer-scoped invoices do NOT inherit
|
|
130
|
+
// subscription.default_payment_method, so it is resolved and set explicitly.
|
|
131
|
+
// print_billing_resolve_customer (the DB function) returns identifiers ONLY
|
|
132
|
+
// -- stripe_customer_id and stripe_subscription_id. It cannot itself call
|
|
133
|
+
// Stripe (C-03: no synchronous HTTP extension in this Postgres), so it does
|
|
134
|
+
// NOT resolve a payment method; resolveDefaultPaymentMethod() below does
|
|
135
|
+
// that, against a live Stripe client, in the (a) -> (b) -> (c) preference
|
|
136
|
+
// order the design requires.
|
|
137
|
+
const { data: resolved, error: resolveErr } =
|
|
138
|
+
await supabase.rpc('print_billing_resolve_customer',
|
|
139
|
+
{ p_membership_id: row.membership_id });
|
|
140
|
+
if (resolveErr || !resolved?.stripe_customer_id) {
|
|
141
|
+
results.push({ membership_id: row.membership_id, status: 'no_customer' });
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Preference order (C-13): (a) the subscription's own default_payment_method
|
|
146
|
+
// (if the member has a live sub), then (b) the customer's own
|
|
147
|
+
// invoice_settings default, then (c) none -- the invoice still finalizes and
|
|
148
|
+
// duns. 3 of 20 live subscriptions have a different card at (a) than at (b),
|
|
149
|
+
// which is why (a) wins and is set explicitly on the invoice.
|
|
150
|
+
const pm = await resolveDefaultPaymentMethod(stripe, {
|
|
151
|
+
stripeCustomerId: resolved.stripe_customer_id,
|
|
152
|
+
stripeSubscriptionId: resolved.stripe_subscription_id ?? null,
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const input: RunInput = {
|
|
156
|
+
runId: crypto.randomUUID(), // minted BEFORE T1, stable across retries
|
|
157
|
+
membershipId: row.membership_id,
|
|
158
|
+
customerId: resolved.stripe_customer_id,
|
|
159
|
+
periodIds: row.period_ids,
|
|
160
|
+
periodMonths: row.period_months,
|
|
161
|
+
amountCents: row.amount_cents,
|
|
162
|
+
defaultPaymentMethod: pm,
|
|
163
|
+
expectedAccountId,
|
|
164
|
+
expectedLivemode,
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const outcome = await executeBillingRun(stripe, db, input);
|
|
169
|
+
results.push({ membership_id: row.membership_id, run_id: input.runId, ...outcome });
|
|
170
|
+
} catch (e) {
|
|
171
|
+
results.push({
|
|
172
|
+
membership_id: row.membership_id,
|
|
173
|
+
run_id: input.runId,
|
|
174
|
+
status: 'error',
|
|
175
|
+
detail: String((e as Error)?.message ?? e),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return new Response(JSON.stringify({ ok: true, considered: rows.length, results }), {
|
|
181
|
+
headers: { 'Content-Type': 'application/json' },
|
|
182
|
+
});
|
|
183
|
+
}
|