@simplelayer/graniteer-core 0.3.29 → 0.3.31

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.
@@ -10,6 +10,24 @@ 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
+ type MembershipRow = {
14
+ id: string;
15
+ email: string | null;
16
+ status: string;
17
+ pricing_grace_ends_at: string | null;
18
+ door_managed: boolean;
19
+ access_state: {
20
+ entitled: boolean;
21
+ group_ids: string[];
22
+ wifi_enabled: boolean;
23
+ } | null;
24
+ plan_id: string | null;
25
+ membership_plans: {
26
+ unifi_group_ids: string[] | null;
27
+ wifi_enabled: boolean | null;
28
+ } | null;
29
+ door_access_not_before: string | null;
30
+ };
13
31
  /**
14
32
  * Loads membership_id -> add-on UniFi group ids for LIVE subscriptions to
15
33
  * grants_access add-ons. Throws on any read error so the tick aborts before
@@ -28,5 +46,18 @@ export declare function computeDesiredGroupIds(entitledRows: Array<{
28
46
  unifi_group_ids: string[] | null;
29
47
  } | null;
30
48
  }>, addonGroupsByMembership: Map<string, string[]>): string[];
49
+ /**
50
+ * True if CommonSignal has ever (as far as the DB can tell) granted this email door access.
51
+ * Emails that are not ever-entitled are left OUT of the Phase 2 snapshot so the middleware
52
+ * never treats them as revoke candidates: their access (if any) predates CommonSignal
53
+ * (legacy Proximity / UniFi Fabric Roles) or the row is still mid-checkout.
54
+ * Any managed row qualifies if it is (1) currently entitled, (2) has a stored
55
+ * access_state.entitled === true, or (3) has a status that is NOT a known pre-checkout status
56
+ * (deny-list: incomplete, incomplete_expired, pending) and its door gate has already opened.
57
+ * Deny-list rather than allow-list because Phase 1 overwrites access_state with entitled:false
58
+ * on the same tick, so (2) only protects once; unknown/future statuses (e.g. 'paused') must
59
+ * stay revoke candidates instead of silently dropping out of the snapshot.
60
+ */
61
+ export declare function everEntitledInCommonSignal(managed: MembershipRow[], currentlyEntitled: boolean, now: number): boolean;
31
62
  export declare function createMembershipDoorSyncHandler(config: MembershipDoorSyncConfig): (req: Request) => Promise<Response>;
32
63
  export {};
@@ -174,6 +174,27 @@ function doorGateOk(row, now) {
174
174
  return false;
175
175
  return t <= now;
176
176
  }
177
+ // Deny-list, not allow-list: any status NOT known to be pre-checkout (including
178
+ // 'paused' and any future Stripe status) stays a revoke candidate. Unknown => revoke-eligible.
179
+ const PRE_CHECKOUT_STATUSES = ['incomplete', 'incomplete_expired', 'pending'];
180
+ /**
181
+ * True if CommonSignal has ever (as far as the DB can tell) granted this email door access.
182
+ * Emails that are not ever-entitled are left OUT of the Phase 2 snapshot so the middleware
183
+ * never treats them as revoke candidates: their access (if any) predates CommonSignal
184
+ * (legacy Proximity / UniFi Fabric Roles) or the row is still mid-checkout.
185
+ * Any managed row qualifies if it is (1) currently entitled, (2) has a stored
186
+ * access_state.entitled === true, or (3) has a status that is NOT a known pre-checkout status
187
+ * (deny-list: incomplete, incomplete_expired, pending) and its door gate has already opened.
188
+ * Deny-list rather than allow-list because Phase 1 overwrites access_state with entitled:false
189
+ * on the same tick, so (2) only protects once; unknown/future statuses (e.g. 'paused') must
190
+ * stay revoke candidates instead of silently dropping out of the snapshot.
191
+ */
192
+ export function everEntitledInCommonSignal(managed, currentlyEntitled, now) {
193
+ if (currentlyEntitled)
194
+ return true;
195
+ return managed.some((r) => r.access_state?.entitled === true ||
196
+ (!PRE_CHECKOUT_STATUSES.includes(r.status) && doorGateOk(r, now)));
197
+ }
177
198
  export function createMembershipDoorSyncHandler(config) {
178
199
  const PROTECTED_ALLOWLIST = new Set(config.protectedAllowlist.map((e) => e.trim().toLowerCase()));
179
200
  const { membershipBusSync, membershipBusEnforce, membershipBusRevoke } = config;
@@ -227,6 +248,7 @@ export function createMembershipDoorSyncHandler(config) {
227
248
  const wouldRevoke = [];
228
249
  let skippedAllowlist = 0;
229
250
  let skippedNotManaged = 0;
251
+ let skippedNeverEntitled = 0;
230
252
  let unchanged = 0;
231
253
  let bootstrapped = 0;
232
254
  const totalEvaluated = byEmail.size;
@@ -266,17 +288,23 @@ export function createMembershipDoorSyncHandler(config) {
266
288
  groupIds = computeDesiredGroupIds(entitledRows, addonGroupsByMembership);
267
289
  }
268
290
  const desired = { entitled, group_ids: groupIds, wifi_enabled: wifiEnabled };
269
- // Every managed, non-protected email goes into the snapshot -- entitled or not.
270
- // The NOT-entitled ones are exactly the revoke candidates, so omitting them would
271
- // make Stage 2 blind to the whole reason Stage 2 exists. This is placed before the
272
- // unchanged/continue branch below so unchanged rows are included too: Stage 1's
273
- // "unchanged" means "the tenant app's stored intent didn't move", which says nothing about
274
- // whether UniFi matches that intent.
275
- snapshot.push({
276
- email,
277
- desired_group_ids: desired.group_ids,
278
- desired_wifi: desired.wifi_enabled,
279
- });
291
+ // Every managed, non-protected email that CommonSignal has ever entitled goes into the
292
+ // snapshot -- entitled or not. The NOT-entitled ones are exactly the revoke candidates,
293
+ // so omitting them would make Stage 2 blind to the whole reason Stage 2 exists. Emails
294
+ // CommonSignal never entitled (mid-checkout rows, future-dated gates with no history)
295
+ // are omitted: the middleware leaves absent emails untouched, so their legacy access
296
+ // is not revoked. Placed before the unchanged/continue branch so unchanged rows are
297
+ // included too: Stage 1's "unchanged" says nothing about whether UniFi matches intent.
298
+ if (everEntitledInCommonSignal(managed, entitled, now)) {
299
+ snapshot.push({
300
+ email,
301
+ desired_group_ids: desired.group_ids,
302
+ desired_wifi: desired.wifi_enabled,
303
+ });
304
+ }
305
+ else {
306
+ skippedNeverEntitled++;
307
+ }
280
308
  // Per-email change detection uses the FIRST managed row's stored
281
309
  // access_state as the reference; write-on-change updates every managed
282
310
  // row for this email so they stay mutually consistent.
@@ -328,6 +356,7 @@ export function createMembershipDoorSyncHandler(config) {
328
356
  await logOps(supabase, 'door_sync_write_failed', { email, error: upErr.message }, { severity: 'warning' });
329
357
  }
330
358
  }
359
+ console.log(`[door-sync] skipped_never_entitled=${skippedNeverEntitled}`);
331
360
  const wouldChangeTotal = wouldGrant.length + wouldRevoke.length;
332
361
  const severity = wouldChangeTotal > WOULD_CHANGE_WARN_THRESHOLD ? 'warning' : 'info';
333
362
  await logOps(supabase, 'door_sync_shadow', {
@@ -335,6 +364,7 @@ export function createMembershipDoorSyncHandler(config) {
335
364
  total_evaluated: totalEvaluated,
336
365
  skipped_allowlist: skippedAllowlist,
337
366
  skipped_not_managed: skippedNotManaged,
367
+ skipped_never_entitled: skippedNeverEntitled,
338
368
  would_grant: wouldGrant.length,
339
369
  would_revoke: wouldRevoke.length,
340
370
  bootstrapped,
@@ -911,6 +941,7 @@ export function createMembershipDoorSyncHandler(config) {
911
941
  total_evaluated: totalEvaluated,
912
942
  skipped_allowlist: skippedAllowlist,
913
943
  skipped_not_managed: skippedNotManaged,
944
+ skipped_never_entitled: skippedNeverEntitled,
914
945
  would_grant: wouldGrant.length,
915
946
  would_revoke: wouldRevoke.length,
916
947
  bootstrapped,
@@ -40,6 +40,11 @@ export type VirtualOfficeWelcomeConfig = {
40
40
  virtualOfficeSlug: string;
41
41
  /** Absolute URL the magic link lands on once the member clicks it. */
42
42
  portalRedirectUrl: string;
43
+ /**
44
+ * Accepted for config symmetry only: this sender emits a Supabase magic link,
45
+ * not GHL html, so there is no body to add the setup line to.
46
+ */
47
+ setupUrl?: string;
43
48
  };
44
49
  export declare function sendVirtualOfficeWelcome(supabase: SupabaseLike, email: string, planId: string | null, plan: WelcomePlan, config: VirtualOfficeWelcomeConfig): Promise<WelcomeResult>;
45
50
  /** Tenant-owned inputs to the host-hours card. */
@@ -68,6 +73,11 @@ export type MembershipWelcomeConfig = {
68
73
  */
69
74
  addressRoomSlug: string;
70
75
  hostHours: HostHoursConfig;
76
+ /**
77
+ * Optional https URL of the portal setup page. Rendered as one extra line in
78
+ * the email when set; omitted/invalid leaves the email unchanged.
79
+ */
80
+ setupUrl?: string;
71
81
  };
72
82
  export declare function sendMembershipWelcome(supabase: SupabaseLike, email: string, planId: string | null, customerName: string | null, status: string | null, plan: WelcomePlan, config: MembershipWelcomeConfig, startsOnIso: string | null): Promise<WelcomeResult>;
73
83
  /**
@@ -95,12 +105,22 @@ export type PrivateOfficeWelcomeConfig = {
95
105
  * move-in. Tenant-owned; pass [] to send without a CC.
96
106
  */
97
107
  staffCc: readonly string[];
108
+ /**
109
+ * Optional https URL of the portal setup page. Rendered as one extra line in
110
+ * the email when set; omitted/invalid leaves the email unchanged.
111
+ */
112
+ setupUrl?: string;
98
113
  };
99
114
  export declare function sendPrivateOfficeWelcome(supabase: SupabaseLike, email: string, name: string | null, plan: WelcomePlan, config: PrivateOfficeWelcomeConfig, billing?: PrivateOfficeBilling | null): Promise<WelcomeResult>;
100
115
  export type TeamSeatWelcomeConfig = {
101
116
  operator: WelcomeOperator;
102
117
  /** Plan slug of the operator's sponsored-seat ("company member") plan. */
103
118
  teamSeatSlug: string;
119
+ /**
120
+ * Optional https URL of the portal setup page. Rendered as one extra line in
121
+ * the email when set; omitted/invalid leaves the email unchanged.
122
+ */
123
+ setupUrl?: string;
104
124
  };
105
125
  /**
106
126
  * Team-seat ("Company member") welcome.
@@ -27,6 +27,16 @@ function esc(v) {
27
27
  .replace(/"/g, '&quot;')
28
28
  .replace(/'/g, '&#39;');
29
29
  }
30
+ /**
31
+ * Optional "finish setting up" paragraph. Rendered only for a non-empty https
32
+ * URL; otherwise returns '' so the email is unchanged.
33
+ */
34
+ function setupLine(p, setupUrl) {
35
+ const url = typeof setupUrl === 'string' ? setupUrl.trim() : '';
36
+ if (!/^https:\/\/\S+$/i.test(url))
37
+ return '';
38
+ return p(`<strong>Finish setting up your membership:</strong> add your photo and get your door app and WiFi login at <a href="${esc(url)}" style="color:#C98A5E">${esc(url.replace(/^https:\/\//i, ''))}</a>. It takes about a minute.`) + '\n';
39
+ }
30
40
  /** Classify a caught error as transient (worth another event) or hopeless. */
31
41
  function classifyError(e) {
32
42
  const name = e instanceof Error ? e.name : '';
@@ -248,7 +258,7 @@ ${startsOnLabel
248
258
  ${p('<strong>You\'ll get a separate email inviting you to an app called UniFi Endpoint. That invitation is from us — it\'s how you unlock the door with your phone.</strong> It arrives with Ubiquiti branding, so please don\'t delete it as spam.')}
249
259
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${doorCard}${wifiCard}${hostHoursCard}</table>
250
260
  ${p(`We're at ${esc(address)}.`)}
251
- ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
261
+ ${setupLine(p, config.setupUrl)}${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
252
262
  <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name} · ${esc(address)}</p>
253
263
  </td></tr></table></td></tr></table></div>`;
254
264
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
@@ -382,7 +392,7 @@ ${p(`Hi ${esc(greetingName)},`)}
382
392
  ${p(`You're all set — welcome to ${operator.name}. We're glad to have you as part of the community.`)}
383
393
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin-top:12px">${nextCard}${billingCard}</table>
384
394
 
385
- ${p(`If anything's unclear or you need something before you move in, just reply here or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a> — we're happy to help.`)}
395
+ ${setupLine(p, config.setupUrl)}${p(`If anything's unclear or you need something before you move in, just reply here or write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a> — we're happy to help.`)}
386
396
  ${p(`Welcome again,<br>The ${operator.name} team`)}
387
397
  </td></tr></table></td></tr></table></div>`;
388
398
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
@@ -471,7 +481,7 @@ ${p(`Hi ${esc(greetingName)},`)}
471
481
  ${p(companyLine)}
472
482
  ${p(`<strong>Setting up your login:</strong> go to <a href="https://${operator.domain}/portal/login" style="color:#C98A5E">${operator.domain}/portal/login</a> and enter this email address (${esc(email)}). We'll email you a sign-in link — there's no password to remember.`)}
473
483
  ${p('<strong>Door and WiFi access:</strong> if your seat includes it, access is being set up now and can take a little while to go live. You may also receive a separate invite to an app called <strong>UniFi Endpoint</strong> — that\'s from us, and it\'s how you unlock the door with your phone.')}
474
- ${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
484
+ ${setupLine(p, config.setupUrl)}${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
475
485
  <p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
476
486
  </td></tr></table></td></tr></table></div>`;
477
487
  const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.29",
3
+ "version": "0.3.31",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",