@simplelayer/graniteer-core 0.3.21-referral.2 → 0.3.22-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.
@@ -20,7 +20,13 @@ const Body = z.object({
20
20
  // Referral program Phase 1. Case-sensitive exact match against
21
21
  // memberships.referral_code, resolved just below. An unresolvable code is
22
22
  // silently ignored -- it must never block or error checkout.
23
- referral_code: z.string().trim().min(1).max(32).optional(),
23
+ // Payment must never be blocked by a referral code: anything that is not a
24
+ // string passing the allowlist (empty, whitespace, over-long, wildcard,
25
+ // non-string) is dropped before validation, as if the field were absent.
26
+ referral_code: z.preprocess((v) => {
27
+ const t = typeof v === 'string' ? v.trim() : v;
28
+ return isValidReferralCode(t) ? t : undefined;
29
+ }, z.string().optional()),
24
30
  // Internal `coupons` code. Unlike referral_code, an unusable code here is a
25
31
  // hard 400 -- the member typed it expecting a discount, so charging them
26
32
  // full price silently is the wrong failure mode.
@@ -10,5 +10,23 @@ export interface MembershipDoorSyncConfig {
10
10
  membershipBusEnforce: (members: MembershipSnapshotMember[], supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
11
11
  membershipBusRevoke: (members: MembershipSnapshotMember[], generatedAt: string, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
12
12
  }
13
+ /**
14
+ * Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
15
+ * grants_access add-ons. Throws on any read error so the tick aborts before
16
+ * any Phase 2/3/4 call: falling back to "no add-on groups" could make the
17
+ * revoke phase strip real access.
18
+ */
19
+ export declare function loadAddonGroupIds(supabase: SupabaseClient): Promise<Map<string, string[]>>;
20
+ /**
21
+ * Desired UniFi group ids = union of entitled rows' plan groups and those
22
+ * same rows' live add-on groups. Not entitled (no entitled rows) => [].
23
+ * Sorted + de-duplicated; empty/null ids ignored.
24
+ */
25
+ export declare function computeDesiredGroupIds(entitledRows: Array<{
26
+ id: string;
27
+ membership_plans: {
28
+ unifi_group_ids: string[] | null;
29
+ } | null;
30
+ }>, addonGroupsByMembership: Map<string, string[]>): string[];
13
31
  export declare function createMembershipDoorSyncHandler(config: MembershipDoorSyncConfig): (req: Request) => Promise<Response>;
14
32
  export {};
@@ -83,6 +83,80 @@ function stateEquals(a, b) {
83
83
  }
84
84
  return true;
85
85
  }
86
+ const LIVE_ADDON_STATUSES = ['active', 'past_due', 'pending_removal'];
87
+ function assertNotTruncated(table, res) {
88
+ const data = res.data ?? [];
89
+ const count = res.count;
90
+ if (typeof count !== 'number' || count !== data.length) {
91
+ throw new Error(`${table} read truncated: got ${data.length} of ${count} -- aborting tick before any Phase 2/3/4 call`);
92
+ }
93
+ }
94
+ /**
95
+ * Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
96
+ * grants_access add-ons. Throws on any read error so the tick aborts before
97
+ * any Phase 2/3/4 call: falling back to "no add-on groups" could make the
98
+ * revoke phase strip real access.
99
+ */
100
+ export async function loadAddonGroupIds(supabase) {
101
+ const result = new Map();
102
+ const subsRes = (await supabase
103
+ .from('member_addon_subscriptions')
104
+ .select('membership_id,addon_id,status', { count: 'exact' })
105
+ .in('status', LIVE_ADDON_STATUSES)
106
+ .order('id'));
107
+ if (subsRes.error)
108
+ throw new Error('member_addon_subscriptions read failed: ' + subsRes.error.message);
109
+ assertNotTruncated('member_addon_subscriptions', subsRes);
110
+ // Re-check status locally so correctness never depends solely on the filter.
111
+ const subs = (subsRes.data ?? [])
112
+ .filter((s) => s.membership_id && s.addon_id && LIVE_ADDON_STATUSES.includes(s.status));
113
+ if (subs.length === 0)
114
+ return result;
115
+ const addonIds = Array.from(new Set(subs.map((s) => s.addon_id)));
116
+ const addonsRes = (await supabase
117
+ .from('member_addons')
118
+ .select('id,unifi_group_ids,grants_access', { count: 'exact' })
119
+ .in('id', addonIds)
120
+ .eq('grants_access', true)
121
+ .order('id'));
122
+ if (addonsRes.error)
123
+ throw new Error('member_addons read failed: ' + addonsRes.error.message);
124
+ assertNotTruncated('member_addons', addonsRes);
125
+ const groupsByAddon = new Map();
126
+ for (const a of (addonsRes.data ?? [])) {
127
+ if (a.grants_access !== true)
128
+ continue;
129
+ groupsByAddon.set(a.id, a.unifi_group_ids ?? []);
130
+ }
131
+ for (const s of subs) {
132
+ const gids = groupsByAddon.get(s.addon_id);
133
+ if (!gids)
134
+ continue;
135
+ const list = result.get(s.membership_id) ?? [];
136
+ for (const g of gids)
137
+ if (g)
138
+ list.push(g);
139
+ result.set(s.membership_id, list);
140
+ }
141
+ return result;
142
+ }
143
+ /**
144
+ * Desired UniFi group ids = union of entitled rows' plan groups and those
145
+ * same rows' live add-on groups. Not entitled (no entitled rows) => [].
146
+ * Sorted + de-duplicated; empty/null ids ignored.
147
+ */
148
+ export function computeDesiredGroupIds(entitledRows, addonGroupsByMembership) {
149
+ const set = new Set();
150
+ for (const r of entitledRows) {
151
+ for (const g of r.membership_plans?.unifi_group_ids ?? [])
152
+ if (g)
153
+ set.add(g);
154
+ for (const g of addonGroupsByMembership.get(r.id) ?? [])
155
+ if (g)
156
+ set.add(g);
157
+ }
158
+ return Array.from(set).sort();
159
+ }
86
160
  /**
87
161
  * Door-access start-date gate, separate from (and layered AFTER) pricing
88
162
  * entitlement. An UNGATED row (door_access_not_before === null) is never
@@ -134,6 +208,7 @@ export function createMembershipDoorSyncHandler(config) {
134
208
  if (rows.length > 0 && !('door_access_not_before' in rows[0])) {
135
209
  throw new Error('shape_guard_failed: door_access_not_before missing from memberships select result -- aborting tick before any Phase 2/3/4 call');
136
210
  }
211
+ const addonGroupsByMembership = await loadAddonGroupIds(supabase);
137
212
  // Group by lowercased email. Rows with no email are ignored (nothing to
138
213
  // key door/WiFi state to). resolveIsMember() likewise treats "" as "not
139
214
  // a member" — keep that behavior aligned.
@@ -184,16 +259,11 @@ export function createMembershipDoorSyncHandler(config) {
184
259
  let groupIds = [];
185
260
  let wifiEnabled = false;
186
261
  if (entitled) {
187
- const set = new Set();
188
262
  for (const r of entitledRows) {
189
- const gids = r.membership_plans?.unifi_group_ids ?? [];
190
- for (const g of gids)
191
- if (g)
192
- set.add(g);
193
263
  if (r.membership_plans?.wifi_enabled === true)
194
264
  wifiEnabled = true;
195
265
  }
196
- groupIds = Array.from(set).sort();
266
+ groupIds = computeDesiredGroupIds(entitledRows, addonGroupsByMembership);
197
267
  }
198
268
  const desired = { entitled, group_ids: groupIds, wifi_enabled: wifiEnabled };
199
269
  // Every managed, non-protected email goes into the snapshot -- entitled or not.
@@ -577,8 +577,8 @@ function buildStripeWebhookHandler(config, connect) {
577
577
  * fallback baked in), not re-derived from sub.metadata here.
578
578
  *
579
579
  * Inserts a 'signed_up' referrals row only -- no credit amounts, no Stripe
580
- * balance calls. Those happen later, at first-invoice-paid (see
581
- * maybeGrantReferralCredit below). We do NOT call computeReferralCredits
580
+ * balance calls. The grant happens later, at day 30, via the daily
581
+ * qualify job in gc-io (not at first-invoice-paid). We do NOT call computeReferralCredits
582
582
  * here to "validate" plan.price_cents -- Math.max/Math.round never throw,
583
583
  * so that validated nothing. Instead we check price_cents directly and
584
584
  * refuse to insert a referrals row at all if it's missing, rather than
@@ -653,8 +653,9 @@ function buildStripeWebhookHandler(config, connect) {
653
653
  // maybeGrantReferralCredit moved verbatim to ../_shared/referralGrant.ts
654
654
  // (2026-08-24) so admin-referral-retry can call the exact same, already-
655
655
  // idempotent function on a grant_failed row instead of a second
656
- // hand-written copy of this Stripe balance-transaction logic. Imported
657
- // above; the call site below now passes supabase/stripe explicitly.
656
+ // hand-written copy of this Stripe balance-transaction logic. The grant
657
+ // is no longer made at first-invoice-paid: it happens at day 30 via the
658
+ // daily qualify job in gc-io (this file makes no balance call).
658
659
  /**
659
660
  * Referral program Phase 1, step 3 (clawback on fast cancel).
660
661
  *
@@ -2537,17 +2538,11 @@ function buildStripeWebhookHandler(config, connect) {
2537
2538
  // an earlier migration) -- this is the actual ongoing writer.
2538
2539
  const isGenuineInvoicePayment = inv.billing_reason !== 'subscription_create' || (inv.amount_paid ?? 0) > 0;
2539
2540
  if (isGenuineInvoicePayment) {
2540
- // .select('id') added so the referral-credit step below can tell
2541
- // whether this call actually WON the compare-and-swap (this was
2542
- // genuinely the first real paid invoice) vs. a repeat event that
2543
- // found the column already set -- the update's own predicate and
2544
- // payload are unchanged.
2545
- const { data: fipRows, error: fipErr } = await supabase
2541
+ const { error: fipErr } = await supabase
2546
2542
  .from('memberships')
2547
2543
  .update({ first_invoice_paid_at: new Date().toISOString() })
2548
2544
  .eq('stripe_subscription_id', subId)
2549
- .is('first_invoice_paid_at', null)
2550
- .select('id');
2545
+ .is('first_invoice_paid_at', null);
2551
2546
  if (fipErr)
2552
2547
  console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
2553
2548
  // Referral crediting is NOT done here any more: gc-io's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.21-referral.2",
3
+ "version": "0.3.22-referral.1",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",