@simplelayer/graniteer-core 0.3.1 → 0.3.3
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.
|
@@ -163,7 +163,18 @@ export async function handle(req) {
|
|
|
163
163
|
const visitorId = str(args.visitor_id);
|
|
164
164
|
if (!grantId)
|
|
165
165
|
return await fail('invalid_args', {});
|
|
166
|
-
const
|
|
166
|
+
const extra = { visitor_id: visitorId };
|
|
167
|
+
// D35 (two-pin organizer unlock/relock): unlock_visitor_id/relock_visitor_id
|
|
168
|
+
// are only ever sent by ftw-middleware for a door configured for two-pin
|
|
169
|
+
// grants; every other caller omits them, so this CAS patch is byte-identical
|
|
170
|
+
// to before for every existing single-visitor door.
|
|
171
|
+
const unlockVisitorId = str(args.unlock_visitor_id);
|
|
172
|
+
const relockVisitorId = str(args.relock_visitor_id);
|
|
173
|
+
if (unlockVisitorId)
|
|
174
|
+
extra.unlock_visitor_id = unlockVisitorId;
|
|
175
|
+
if (relockVisitorId)
|
|
176
|
+
extra.relock_visitor_id = relockVisitorId;
|
|
177
|
+
const r = await cas(grantId, 'pending', 'active', extra);
|
|
167
178
|
if ('err' in r)
|
|
168
179
|
return await fail('db_error', { message: r.err });
|
|
169
180
|
return json(200, { ok: true, result: r.row });
|
|
@@ -206,6 +217,15 @@ export async function handle(req) {
|
|
|
206
217
|
};
|
|
207
218
|
if (visitorId)
|
|
208
219
|
patch.visitor_id = visitorId; // COALESCE semantics
|
|
220
|
+
// D35 (two-pin organizer unlock/relock): same COALESCE-on-presence
|
|
221
|
+
// semantics for the two new columns -- an omitted arg leaves whatever
|
|
222
|
+
// is already in the DB column untouched.
|
|
223
|
+
const unlockVisitorId = str(args.unlock_visitor_id);
|
|
224
|
+
const relockVisitorId = str(args.relock_visitor_id);
|
|
225
|
+
if (unlockVisitorId)
|
|
226
|
+
patch.unlock_visitor_id = unlockVisitorId;
|
|
227
|
+
if (relockVisitorId)
|
|
228
|
+
patch.relock_visitor_id = relockVisitorId;
|
|
209
229
|
const { data, error } = await supabase
|
|
210
230
|
.from('booking_access_grants').update(patch).eq('id', grantId).select('*').maybeSingle();
|
|
211
231
|
if (error)
|
|
@@ -264,6 +284,20 @@ export async function handle(req) {
|
|
|
264
284
|
return await fail('db_error', { message: error.message });
|
|
265
285
|
return json(200, { ok: true, result: data ?? [] });
|
|
266
286
|
}
|
|
287
|
+
case 'get_active_two_pin_grants': {
|
|
288
|
+
// D35 (event_access_pin_tick.py, DRY-RUN ONLY poller): grants whose door
|
|
289
|
+
// was provisioned with two separate Unlock/Relock PIN visitor credentials
|
|
290
|
+
// rather than a single visitor_id. No time-window filter here -- the
|
|
291
|
+
// poller itself checks the matched log entry's timestamp against the
|
|
292
|
+
// grant's own access_start/access_end.
|
|
293
|
+
const { data, error } = await supabase
|
|
294
|
+
.from('booking_access_grants').select('*')
|
|
295
|
+
.eq('status', 'active')
|
|
296
|
+
.or('unlock_visitor_id.not.is.null,relock_visitor_id.not.is.null');
|
|
297
|
+
if (error)
|
|
298
|
+
return await fail('db_error', { message: error.message });
|
|
299
|
+
return json(200, { ok: true, result: data ?? [] });
|
|
300
|
+
}
|
|
267
301
|
case 'try_transition_reconciling_to_active': {
|
|
268
302
|
const grantId = reqUuid(args, 'grant_id');
|
|
269
303
|
const visitorId = str(args.visitor_id);
|
|
@@ -332,6 +366,72 @@ export async function handle(req) {
|
|
|
332
366
|
return await fail('db_error', { message: error.message });
|
|
333
367
|
return json(200, { ok: true, result: { event_id: eventId } });
|
|
334
368
|
}
|
|
369
|
+
case 'get_pin_tick_cursor': {
|
|
370
|
+
// D35 (S-A/S1): persisted high-water-mark for event_access_pin_tick.py's
|
|
371
|
+
// poller, replacing its in-memory-only cursor so a container restart
|
|
372
|
+
// doesn't replay or (worse) permanently drop an out-of-order log entry.
|
|
373
|
+
// One row per poller instance, keyed by a caller-chosen id (today there's
|
|
374
|
+
// only ever one: 'commons_pin_tick').
|
|
375
|
+
const cursorId = str(args.cursor_id);
|
|
376
|
+
if (!cursorId)
|
|
377
|
+
return await fail('invalid_args', {});
|
|
378
|
+
const { data, error } = await supabase
|
|
379
|
+
.from('event_access_pin_cursor').select('*').eq('id', cursorId).maybeSingle();
|
|
380
|
+
if (error)
|
|
381
|
+
return await fail('db_error', { message: error.message });
|
|
382
|
+
return json(200, { ok: true, result: data ?? null });
|
|
383
|
+
}
|
|
384
|
+
case 'set_pin_tick_cursor': {
|
|
385
|
+
// D35 (S-A/S1): upsert with a floor -- the poller should never regress
|
|
386
|
+
// its own high-water-mark by writing a strictly older created_time than
|
|
387
|
+
// what's already stored. An intersecting duplicate hwm_ids_at_time entry
|
|
388
|
+
// is still fine to resend as-is.
|
|
389
|
+
//
|
|
390
|
+
// 2026-09-22 (FINDINGS3.md S2-4): this used to READ the stored
|
|
391
|
+
// hwm_created_time, compare it here in JS, then upsert -- a read-then-
|
|
392
|
+
// write TOCTOU. The poller is a single logical writer today, but two
|
|
393
|
+
// writers exist transiently on any deploy where the old and new
|
|
394
|
+
// containers overlap (and would exist permanently if a future add_job
|
|
395
|
+
// forgot max_instances=1). Interleaved: A reads 100, B reads 100, B
|
|
396
|
+
// writes 200, A writes 150 -- the cursor regresses to 150 with A's id
|
|
397
|
+
// set, and NEITHER caller gets regressed:true, so neither alerts. The
|
|
398
|
+
// entries between 150 and 200 then replay on the next tick: duplicate
|
|
399
|
+
// audit rows today, a replayed unlock/relock pair once armed.
|
|
400
|
+
//
|
|
401
|
+
// The floor now lives inside a single statement, in the ON CONFLICT
|
|
402
|
+
// WHERE clause of set_pin_tick_cursor_atomic() (see
|
|
403
|
+
// D35_EDGE_FUNCTION_MIGRATION_DRAFT.sql) -- PostgREST's .upsert()
|
|
404
|
+
// cannot express that WHERE, which is why it has to be an RPC.
|
|
405
|
+
const cursorId = str(args.cursor_id);
|
|
406
|
+
if (!cursorId)
|
|
407
|
+
return await fail('invalid_args', {});
|
|
408
|
+
const hwmCreatedTime = typeof args.hwm_created_time === 'number' ? args.hwm_created_time : null;
|
|
409
|
+
const hwmIds = Array.isArray(args.hwm_ids_at_time)
|
|
410
|
+
? args.hwm_ids_at_time.filter((v) => typeof v === 'string')
|
|
411
|
+
: [];
|
|
412
|
+
if (hwmCreatedTime === null)
|
|
413
|
+
return await fail('invalid_args', {});
|
|
414
|
+
const { data, error } = await supabase.rpc('set_pin_tick_cursor_atomic', {
|
|
415
|
+
p_cursor_id: cursorId,
|
|
416
|
+
p_hwm_created_time: hwmCreatedTime,
|
|
417
|
+
p_hwm_ids_at_time: hwmIds,
|
|
418
|
+
});
|
|
419
|
+
if (error)
|
|
420
|
+
return await fail('db_error', { message: error.message });
|
|
421
|
+
// The function returns the cursor row in BOTH outcomes: the row it just
|
|
422
|
+
// wrote, or -- when the floor rejected the write -- the untouched
|
|
423
|
+
// existing row. So `regressed` is derived from what came back (the
|
|
424
|
+
// stored value is not the value we sent), never from a separate
|
|
425
|
+
// pre-read that another writer could have invalidated in between.
|
|
426
|
+
const row = Array.isArray(data) ? data[0] : data;
|
|
427
|
+
if (!row)
|
|
428
|
+
return await fail('db_error', { message: 'set_pin_tick_cursor_atomic returned no row' });
|
|
429
|
+
const stored = typeof row.hwm_created_time === 'number' ? row.hwm_created_time : null;
|
|
430
|
+
if (stored === null || stored !== hwmCreatedTime) {
|
|
431
|
+
return json(200, { ok: true, result: { regressed: true, kept_hwm_created_time: stored } });
|
|
432
|
+
}
|
|
433
|
+
return json(200, { ok: true, result: row });
|
|
434
|
+
}
|
|
335
435
|
default:
|
|
336
436
|
return await fail('unknown_op', {});
|
|
337
437
|
}
|
|
@@ -1634,7 +1634,26 @@ export function createStripeWebhookHandler(config) {
|
|
|
1634
1634
|
break;
|
|
1635
1635
|
}
|
|
1636
1636
|
const booking = await findBooking(session);
|
|
1637
|
-
|
|
1637
|
+
// A replayed/out-of-order webhook must never resurrect a booking the
|
|
1638
|
+
// customer or staff already cancelled. booking.status is untyped
|
|
1639
|
+
// (findBooking's select is not run through generated DB types), so
|
|
1640
|
+
// nullish-coalesce before .startsWith: a null/absent status must not
|
|
1641
|
+
// throw here -- that would reach the outer catch, delete the
|
|
1642
|
+
// stripe_events ledger row, and 500 (Stripe retries ~16x, paging
|
|
1643
|
+
// each time, booking never provisions). Preserves the pre-fix
|
|
1644
|
+
// behavior for that case (null !== 'paid' -> proceed) exactly.
|
|
1645
|
+
const bkStatus = booking?.status ?? '';
|
|
1646
|
+
// All three cancelled_* terminal states (see manage-booking.ts's
|
|
1647
|
+
// `b.status.startsWith('cancelled_')` idiom and stripe-db-reconcile.ts's
|
|
1648
|
+
// BOOKING_POST_PAID_OK set) are excluded, not just 'cancelled_credited'.
|
|
1649
|
+
// Hoisted (rather than inlined in the condition below) so the
|
|
1650
|
+
// else-if branch further down -- which handles the actual
|
|
1651
|
+
// cancelled_* case -- can reuse it without recomputing.
|
|
1652
|
+
const bkIsCancelled = bkStatus.startsWith('cancelled_');
|
|
1653
|
+
if (booking &&
|
|
1654
|
+
bkStatus !== 'paid' &&
|
|
1655
|
+
bkStatus !== 'deposit_paid' &&
|
|
1656
|
+
!bkIsCancelled) {
|
|
1638
1657
|
const paymentIntent = typeof session.payment_intent === 'string'
|
|
1639
1658
|
? session.payment_intent
|
|
1640
1659
|
: session.payment_intent?.id ?? null;
|
|
@@ -1653,6 +1672,16 @@ export function createStripeWebhookHandler(config) {
|
|
|
1653
1672
|
// status='pending', because this generic path legitimately serves
|
|
1654
1673
|
// other non-pending recoveries (e.g. a re-paid expired hold).
|
|
1655
1674
|
.neq('status', 'deposit_paid')
|
|
1675
|
+
// Never resurrect an already-cancelled booking on a replayed/
|
|
1676
|
+
// out-of-order webhook (all 3 terminal cancelled_* states --
|
|
1677
|
+
// see stripe-db-reconcile.ts's BOOKING_POST_PAID_OK). Explicit
|
|
1678
|
+
// .neq() chain to match this file's existing idiom, rather than
|
|
1679
|
+
// a LIKE pattern -- this file elsewhere notes '_' is a live SQL
|
|
1680
|
+
// wildcard, not just a literal underscore, so an unescaped
|
|
1681
|
+
// 'cancelled_%' LIKE could match unintended values.
|
|
1682
|
+
.neq('status', 'cancelled_credited')
|
|
1683
|
+
.neq('status', 'cancelled_forfeited')
|
|
1684
|
+
.neq('status', 'cancelled_refunded')
|
|
1656
1685
|
.select('id');
|
|
1657
1686
|
if (!flipErr && flipped && flipped.length > 0) {
|
|
1658
1687
|
// Post-payment side effects — MUST NOT break the webhook.
|
|
@@ -1769,6 +1798,60 @@ export function createStripeWebhookHandler(config) {
|
|
|
1769
1798
|
console.error('[stripe-webhook] post-paid side effects error', e);
|
|
1770
1799
|
}
|
|
1771
1800
|
}
|
|
1801
|
+
else if (flipErr) {
|
|
1802
|
+
console.error('[stripe-webhook] booking paid-flip update failed', flipErr);
|
|
1803
|
+
const persisted = await logOps(supabase, 'booking_paid_flip_failed', { session_id: session.id, message: flipErr.message }, { severity: 'error', bookingId: booking.id });
|
|
1804
|
+
if (!persisted.ok) {
|
|
1805
|
+
console.error('[stripe-webhook] booking-paid-flip-failed alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: persisted.error });
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
else {
|
|
1809
|
+
// Guard blocked the flip even though the JS-level read saw this
|
|
1810
|
+
// booking as flippable (not paid/deposit_paid/cancelled_*) --
|
|
1811
|
+
// a TOCTOU race: something else (another webhook delivery,
|
|
1812
|
+
// manage-booking, the reconciler) changed the row's status
|
|
1813
|
+
// between our read and this UPDATE's WHERE clause evaluating.
|
|
1814
|
+
// `read_status` below is that STALE pre-UPDATE value, not the
|
|
1815
|
+
// row's current status -- never rename it back to `db_status`,
|
|
1816
|
+
// which would wrongly imply it reflects what's in the DB right
|
|
1817
|
+
// now. Always 'warning' (never conditionally 'info'): whatever
|
|
1818
|
+
// the row's status became, Stripe says this session is paid
|
|
1819
|
+
// and nothing got flipped or provisioned for it here -- that's
|
|
1820
|
+
// never a routine no-op (project invariant: "divergence
|
|
1821
|
+
// alarms, not silence").
|
|
1822
|
+
const raced = await logOps(supabase, 'paid_session_flip_raced', {
|
|
1823
|
+
session_id: session.id,
|
|
1824
|
+
read_status: booking.status,
|
|
1825
|
+
amount_total: session.amount_total ?? null,
|
|
1826
|
+
}, {
|
|
1827
|
+
severity: 'warning',
|
|
1828
|
+
bookingId: booking.id,
|
|
1829
|
+
});
|
|
1830
|
+
if (!raced.ok) {
|
|
1831
|
+
console.error('[stripe-webhook] paid-session-flip-raced alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: raced.error });
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
else if (booking && bkIsCancelled) {
|
|
1836
|
+
// The actual bug this fix exists to catch: a Stripe payment
|
|
1837
|
+
// landed on a booking that is cancelled_* right now, per the
|
|
1838
|
+
// JS-level read above (not a TOCTOU race -- see the `else`
|
|
1839
|
+
// branch above for that case). Must never be silent (project
|
|
1840
|
+
// invariant: "divergence alarms, not silence"). dedupeKey so a
|
|
1841
|
+
// replayed/retried webhook for the same session doesn't page
|
|
1842
|
+
// Slack a second time for the same collision.
|
|
1843
|
+
const flagged = await logOps(supabase, 'paid_session_for_cancelled_booking', {
|
|
1844
|
+
session_id: session.id,
|
|
1845
|
+
booking_status: bkStatus,
|
|
1846
|
+
amount_total: session.amount_total ?? null,
|
|
1847
|
+
}, {
|
|
1848
|
+
severity: 'error',
|
|
1849
|
+
bookingId: booking.id,
|
|
1850
|
+
dedupeKey: `paid_session_for_cancelled_booking:${booking.id}:${session.id}`,
|
|
1851
|
+
});
|
|
1852
|
+
if (!flagged.ok) {
|
|
1853
|
+
console.error('[stripe-webhook] cancelled-booking paid-session alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: flagged.error });
|
|
1854
|
+
}
|
|
1772
1855
|
}
|
|
1773
1856
|
break;
|
|
1774
1857
|
}
|
package/dist/printBilling.js
CHANGED
|
@@ -45,22 +45,22 @@ export function gcCodeOf(e) {
|
|
|
45
45
|
* minimum is applied on this side. v14 also had a per-period `>= 50` inside
|
|
46
46
|
* M-11's claim UPDATE; that predicate is DELETED, because it silently billed
|
|
47
47
|
* a member who owed $9.30 nothing at all, every month (T-85). */
|
|
48
|
-
export const ELIGIBILITY_SQL = `
|
|
49
|
-
select p.membership_id,
|
|
50
|
-
array_agg(p.id order by p.period_month) as period_ids,
|
|
51
|
-
array_agg(distinct p.period_month) as period_months,
|
|
52
|
-
sum(p.charge_cents_total)::integer as amount_cents
|
|
53
|
-
from public.print_usage_periods p
|
|
54
|
-
where p.status = 'pending_bill'
|
|
55
|
-
and p.billing_run_id is null
|
|
56
|
-
and p.billed_run_id is null
|
|
57
|
-
and p.charge_cents_total > 0
|
|
58
|
-
group by p.membership_id
|
|
59
|
-
having sum(p.charge_cents_total) >= ${STRIPE_MIN_CENTS}
|
|
60
|
-
and not exists (
|
|
61
|
-
select 1 from public.print_billing_runs r
|
|
62
|
-
where r.membership_id = p.membership_id
|
|
63
|
-
and r.completed_at is null
|
|
48
|
+
export const ELIGIBILITY_SQL = `
|
|
49
|
+
select p.membership_id,
|
|
50
|
+
array_agg(p.id order by p.period_month) as period_ids,
|
|
51
|
+
array_agg(distinct p.period_month) as period_months,
|
|
52
|
+
sum(p.charge_cents_total)::integer as amount_cents
|
|
53
|
+
from public.print_usage_periods p
|
|
54
|
+
where p.status = 'pending_bill'
|
|
55
|
+
and p.billing_run_id is null
|
|
56
|
+
and p.billed_run_id is null
|
|
57
|
+
and p.charge_cents_total > 0
|
|
58
|
+
group by p.membership_id
|
|
59
|
+
having sum(p.charge_cents_total) >= ${STRIPE_MIN_CENTS}
|
|
60
|
+
and not exists (
|
|
61
|
+
select 1 from public.print_billing_runs r
|
|
62
|
+
where r.membership_id = p.membership_id
|
|
63
|
+
and r.completed_at is null
|
|
64
64
|
)`;
|
|
65
65
|
/** [v18/B12-1] The baseline query. The ORDER BY and LIMIT MUST live in a
|
|
66
66
|
* subquery: v6..v17 printed an ungrouped avg() with a bare ORDER BY, which
|
|
@@ -69,41 +69,41 @@ having sum(p.charge_cents_total) >= ${STRIPE_MIN_CENTS}
|
|
|
69
69
|
* a 25x baseline error on the v18 fixture (T-46b). Returns BOTH operands rule 2
|
|
70
70
|
* needs; the old form returned no count at all, so the rule was unimplementable
|
|
71
71
|
* from its own stated input. */
|
|
72
|
-
export const BASELINE_SQL = `
|
|
73
|
-
select coalesce(avg(b.billed_amount_cents), 0)::numeric as baseline_cents,
|
|
74
|
-
count(*)::integer as qualifying_periods
|
|
75
|
-
from (
|
|
76
|
-
select p.billed_amount_cents, p.period_month
|
|
77
|
-
from public.print_usage_periods p
|
|
78
|
-
where p.membership_id = $1
|
|
79
|
-
and p.status = 'billed'
|
|
80
|
-
and p.billed_amount_cents > 0
|
|
81
|
-
order by p.period_month desc
|
|
82
|
-
limit ${BASELINE_WINDOW}
|
|
72
|
+
export const BASELINE_SQL = `
|
|
73
|
+
select coalesce(avg(b.billed_amount_cents), 0)::numeric as baseline_cents,
|
|
74
|
+
count(*)::integer as qualifying_periods
|
|
75
|
+
from (
|
|
76
|
+
select p.billed_amount_cents, p.period_month
|
|
77
|
+
from public.print_usage_periods p
|
|
78
|
+
where p.membership_id = $1
|
|
79
|
+
and p.status = 'billed'
|
|
80
|
+
and p.billed_amount_cents > 0
|
|
81
|
+
order by p.period_month desc
|
|
82
|
+
limit ${BASELINE_WINDOW}
|
|
83
83
|
) b`;
|
|
84
84
|
/** section 5.3's escalation ladder. A held run gets louder rather than expiring —
|
|
85
85
|
* an automatic expiry that frees the periods is exactly what created the
|
|
86
86
|
* double-charge hole in R7 F4 / R8 F2. */
|
|
87
|
-
export const STUCK_ESCALATION_SQL = `
|
|
88
|
-
insert into public.ops_events (kind, severity, detail, dedupe_key)
|
|
89
|
-
select
|
|
90
|
-
'print_billing_run_stuck',
|
|
91
|
-
case
|
|
92
|
-
when r.updated_at < now() - interval '7 days' then 'critical'
|
|
93
|
-
when r.updated_at < now() - interval '24 hours' then 'error'
|
|
94
|
-
else 'warning'
|
|
95
|
-
end,
|
|
96
|
-
jsonb_build_object(
|
|
97
|
-
'run_id', r.id, 'membership_id', r.membership_id, 'status', r.status,
|
|
98
|
-
'hold_reason', r.hold_reason, 'amount_cents', r.amount_cents,
|
|
99
|
-
'stripe_invoice_id', r.stripe_invoice_id,
|
|
100
|
-
'stuck_for', now() - r.updated_at,
|
|
101
|
-
'blocking_future_runs_for_membership', true),
|
|
102
|
-
'print_billing_run_stuck:' || r.id::text || ':'
|
|
103
|
-
|| (now() at time zone 'UTC')::date::text
|
|
104
|
-
from public.print_billing_runs r
|
|
105
|
-
where r.completed_at is null
|
|
106
|
-
and r.status = 'held'
|
|
87
|
+
export const STUCK_ESCALATION_SQL = `
|
|
88
|
+
insert into public.ops_events (kind, severity, detail, dedupe_key)
|
|
89
|
+
select
|
|
90
|
+
'print_billing_run_stuck',
|
|
91
|
+
case
|
|
92
|
+
when r.updated_at < now() - interval '7 days' then 'critical'
|
|
93
|
+
when r.updated_at < now() - interval '24 hours' then 'error'
|
|
94
|
+
else 'warning'
|
|
95
|
+
end,
|
|
96
|
+
jsonb_build_object(
|
|
97
|
+
'run_id', r.id, 'membership_id', r.membership_id, 'status', r.status,
|
|
98
|
+
'hold_reason', r.hold_reason, 'amount_cents', r.amount_cents,
|
|
99
|
+
'stripe_invoice_id', r.stripe_invoice_id,
|
|
100
|
+
'stuck_for', now() - r.updated_at,
|
|
101
|
+
'blocking_future_runs_for_membership', true),
|
|
102
|
+
'print_billing_run_stuck:' || r.id::text || ':'
|
|
103
|
+
|| (now() at time zone 'UTC')::date::text
|
|
104
|
+
from public.print_billing_runs r
|
|
105
|
+
where r.completed_at is null
|
|
106
|
+
and r.status = 'held'
|
|
107
107
|
on conflict (dedupe_key) where dedupe_key is not null do nothing`;
|
|
108
108
|
/** Rules 1-3 of section 4.2's gate. The two gates are INDEPENDENT and both are
|
|
109
109
|
* evaluated — a run can trip the cap without the ratio and vice versa, and
|