@aglyn/tenant-data-admin 1.0.0 → 1.1.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0",
29
- "@aglyn/shared-util-email": "1.0.0",
30
- "@aglyn/shared-util-fbserver": "1.0.0",
31
- "@aglyn/shared-util-first-touch": "1.0.0",
32
- "@aglyn/shared-util-http": "1.0.0",
33
- "@aglyn/shared-util-tools": "1.0.0",
28
+ "@aglyn/aglyn": "1.1.0",
29
+ "@aglyn/shared-util-email": "1.1.0",
30
+ "@aglyn/shared-util-fbserver": "1.1.0",
31
+ "@aglyn/shared-util-first-touch": "1.1.0",
32
+ "@aglyn/shared-util-http": "1.1.0",
33
+ "@aglyn/shared-util-tools": "1.1.0",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -258,6 +258,22 @@ const membershipRef = (db, uid, hostId)=>db.collection('users').doc(uid).collect
258
258
  }
259
259
  update['seo.favicon'] = favicon.trim();
260
260
  }
261
+ // The logos a create writes with its favicon, in the one request (AGL-4119).
262
+ // Not mirrored into any row; they ride this write so a new site's three
263
+ // fields land together, with no client write to wait on.
264
+ for (const field of [
265
+ 'logoUrl',
266
+ 'logoDarkUrl'
267
+ ]){
268
+ if (!body || !(field in body)) continue;
269
+ const value = body[field];
270
+ if (typeof value !== 'string' || value.length > 2048) {
271
+ return {
272
+ error: 'A logo must be a link or a media reference.'
273
+ };
274
+ }
275
+ update[field] = value.trim();
276
+ }
261
277
  return {
262
278
  update: Object.keys(update).length ? update : null
263
279
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // The custom domain itself (AGL-3972), so a list shows the address the\n // site answers on rather than only its platform subdomain. Deleted, not\n // omitted, when the domain is released, for the merge reason the favicon\n // below gives.\n cname: hasCustomDomain(meta) ? String(meta?.cname).trim() : FieldValue.delete(),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/**\n * The host-document paths a membership row is derived from. A writer that\n * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the\n * rows are written by the Admin SDK at these writers and nowhere else, so a\n * change that skips the re-fan leaves every member's list on the old value\n * until something unrelated rewrites the row.\n */\nexport const PROJECTED_HOST_PATHS: readonly string[] = [\n 'displayName',\n 'subdomain',\n 'cname',\n 'seo.favicon',\n 'createdAt',\n]\n\n/** Whether a write that changed these paths owes the membership re-fan. */\nexport const changesProjectedHostFields = (paths: readonly string[]): boolean =>\n paths.some((path) => PROJECTED_HOST_PATHS.includes(path))\n\n/** The longest site name the console's Display name field accepts. */\nexport const HOST_DISPLAY_NAME_MAX = 200\n\n/**\n * The host-document update for a mirrored field a person changed in the\n * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.\n *\n * The console used to write `displayName` and `seo.favicon` from the browser\n * and then ping the server to re-fan the rows, chained on the write's\n * server acknowledgement. Under the multi-tab cache that acknowledgement can\n * take a minute (AGL-3806), and a page left in that minute, or a ping that\n * failed, left the rows on the old name for good. The server now writes the\n * field and re-fans in the same request, so the two cannot come apart.\n *\n * Answers `null` when the body names neither field (a plain re-fan), and an\n * error for a value the console would never send. A favicon of `''` is the\n * Remove button's clear, kept as `''` because that is what the card writes.\n */\nexport function projectedHostFieldsUpdate(\n body: Record<string, unknown> | null | undefined,\n): { update: Record<string, unknown> | null } | { error: string } {\n const update: Record<string, unknown> = {}\n if (body && 'displayName' in body) {\n const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : ''\n if (!name) return { error: 'A site needs a name.' }\n if (name.length > HOST_DISPLAY_NAME_MAX) {\n return { error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.` }\n }\n update['displayName'] = name\n }\n if (body && 'favicon' in body) {\n const favicon = body['favicon']\n if (typeof favicon !== 'string' || favicon.length > 2_048) {\n return { error: 'The favicon must be a link or a media reference.' }\n }\n update['seo.favicon'] = favicon.trim()\n }\n return { update: Object.keys(update).length ? update : null }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after\n * any write that changes one of `PROJECTED_HOST_PATHS`.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","String","delete","updatedAt","serverTimestamp","PROJECTED_HOST_PATHS","changesProjectedHostFields","paths","some","path","includes","HOST_DISPLAY_NAME_MAX","projectedHostFieldsUpdate","body","update","name","error","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","extraUids","uids","Set","filter","Boolean","deleteHostProjectionForUids"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,WAAW,EACXC,eAAe,EACfC,aAAa,QAGR,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,YAAY,IAAMD,cAAcE,GAAG,GAAGD,SAAS;AAErD,uEAAuE,GACvE,MAAME,QAAQ;AAcd,MAAMC,aAAa,OACjBC,IACAC;;IAEA,MAAMC,MAAM,AAAC,CAAA,MAAMF,GAAGG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,EAAC,EAAGC,IAAI;IAG/D,OAAOC,OAAOC,IAAI,SAACN,uBAAAA,IAAKO,KAAK,mBAAI,CAAC;AACpC;AAEA,MAAMC,eAAe,OACnBV,IACAW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AK;iBACxER,MAAMlB,MAAM,CAACuB;QACpB;IACA,MAAMR,cAAc1E,IAAI2E;IACxB,qEAAqE;IACrE,uEAAuE;IACvE,2EAA2E;IAC3E,8DAA8D;IAC9D,IAAIiB,4BAAAA,SAAUpE,MAAM,EAAE;QACpB,MAAMxB,GACHG,UAAU,CAAC,SACXC,GAAG,CAAC2B,QACJwC,MAAM,CAACpB,iBAAiByC,WACxBC,KAAK,CAAC,IAAMC;IACjB;AACF;AAEA,sFAAsF,GACtF,OAAO,eAAeC,4BACpB9F,KAAa,EACb6B,GAAW;IAEX,MAAM9B,KAAKJ;IACX,MAAMe,UAAU,MAAMZ,WAAWC,IAAIC;IACrC,MAAMyE,cACJ1E,IACAW,QAAQK,GAAG,CAAC,CAACe,SAAW,CAAC8C;YACvBA,MAAMlB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAEJ;AAEA,qEAAqE,GACrE,OAAO,eAAeiE,kCACpB/F,KAAa,EACb8B,MAAc,EACd;;;;GAIC,GACDkE,YAA+B,EAAE;IAEjC,MAAMjG,KAAKJ;IACX,MAAM+F,UAAU,MAAMlE,eAAezB,IAAIC;IACzC,MAAMiG,OAAO,IAAIC,IAAY;WACxBR,QAAQ3E,GAAG,CAAC,CAACiE,SAAWA,OAAOrD,GAAG;WAClCqE,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4BvE,QAAQ;WAAImE;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpBvE,MAAc,EACdmE,IAAuB;IAEvB,MAAMlG,KAAKJ;IACX,MAAM8E,cACJ1E,IACA;WAAI,IAAImG,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACrF,GAAG,CACpC,CAACc,MAAQ,CAAC+C;YACRA,MAAMlB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // The custom domain itself (AGL-3972), so a list shows the address the\n // site answers on rather than only its platform subdomain. Deleted, not\n // omitted, when the domain is released, for the merge reason the favicon\n // below gives.\n cname: hasCustomDomain(meta) ? String(meta?.cname).trim() : FieldValue.delete(),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/**\n * The host-document paths a membership row is derived from. A writer that\n * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the\n * rows are written by the Admin SDK at these writers and nowhere else, so a\n * change that skips the re-fan leaves every member's list on the old value\n * until something unrelated rewrites the row.\n */\nexport const PROJECTED_HOST_PATHS: readonly string[] = [\n 'displayName',\n 'subdomain',\n 'cname',\n 'seo.favicon',\n 'createdAt',\n]\n\n/** Whether a write that changed these paths owes the membership re-fan. */\nexport const changesProjectedHostFields = (paths: readonly string[]): boolean =>\n paths.some((path) => PROJECTED_HOST_PATHS.includes(path))\n\n/** The longest site name the console's Display name field accepts. */\nexport const HOST_DISPLAY_NAME_MAX = 200\n\n/**\n * The host-document update for a mirrored field a person changed in the\n * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.\n *\n * The console used to write `displayName` and `seo.favicon` from the browser\n * and then ping the server to re-fan the rows, chained on the write's\n * server acknowledgement. Under the multi-tab cache that acknowledgement can\n * take a minute (AGL-3806), and a page left in that minute, or a ping that\n * failed, left the rows on the old name for good. The server now writes the\n * field and re-fans in the same request, so the two cannot come apart.\n *\n * Answers `null` when the body names neither field (a plain re-fan), and an\n * error for a value the console would never send. A favicon of `''` is the\n * Remove button's clear, kept as `''` because that is what the card writes.\n */\nexport function projectedHostFieldsUpdate(\n body: Record<string, unknown> | null | undefined,\n): { update: Record<string, unknown> | null } | { error: string } {\n const update: Record<string, unknown> = {}\n if (body && 'displayName' in body) {\n const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : ''\n if (!name) return { error: 'A site needs a name.' }\n if (name.length > HOST_DISPLAY_NAME_MAX) {\n return { error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.` }\n }\n update['displayName'] = name\n }\n if (body && 'favicon' in body) {\n const favicon = body['favicon']\n if (typeof favicon !== 'string' || favicon.length > 2_048) {\n return { error: 'The favicon must be a link or a media reference.' }\n }\n update['seo.favicon'] = favicon.trim()\n }\n // The logos a create writes with its favicon, in the one request (AGL-4119).\n // Not mirrored into any row; they ride this write so a new site's three\n // fields land together, with no client write to wait on.\n for (const field of ['logoUrl', 'logoDarkUrl']) {\n if (!body || !(field in body)) continue\n const value = body[field]\n if (typeof value !== 'string' || value.length > 2_048) {\n return { error: 'A logo must be a link or a media reference.' }\n }\n update[field] = value.trim()\n }\n return { update: Object.keys(update).length ? update : null }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after\n * any write that changes one of `PROJECTED_HOST_PATHS`.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","String","delete","updatedAt","serverTimestamp","PROJECTED_HOST_PATHS","changesProjectedHostFields","paths","some","path","includes","HOST_DISPLAY_NAME_MAX","projectedHostFieldsUpdate","body","update","name","error","field","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","extraUids","uids","Set","filter","Boolean","deleteHostProjectionForUids"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,WAAW,EACXC,eAAe,EACfC,aAAa,QAGR,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,YAAY,IAAMD,cAAcE,GAAG,GAAGD,SAAS;AAErD,uEAAuE,GACvE,MAAME,QAAQ;AAcd,MAAMC,aAAa,OACjBC,IACAC;;IAEA,MAAMC,MAAM,AAAC,CAAA,MAAMF,GAAGG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,EAAC,EAA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Q5E,GAAG,CAAC,CAACkE,SAAWA,OAAOtD,GAAG;WAClCsE,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4BxE,QAAQ;WAAIoE;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpBxE,MAAc,EACdoE,IAAuB;IAEvB,MAAMnG,KAAKJ;IACX,MAAM+E,cACJ3E,IACA;WAAI,IAAIoG,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACtF,GAAG,CACpC,CAACc,MAAQ,CAACgD;YACRA,MAAMnB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
@@ -93,8 +93,9 @@ export declare function orgLeadsQueryForHost(hostId: string): Promise<{
93
93
  */
94
94
  export declare function leadReadTokensForHost(hostId: string, group?: ConsentGroup): Promise<ScopeToken[]>;
95
95
  /**
96
- * The `visibleTo` a capture on this site stamps: the consent group's sites,
97
- * or `['org']` where the org's CRM default (`crmDefaultScopeOf`) is `'org'`.
96
+ * The `visibleTo` a capture on this site stamps: `['org']` where the org's
97
+ * CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent
98
+ * group's sites where the org keeps its sites apart.
98
99
  *
99
100
  * Widened by the capture, never by the lookup — a site that has never
100
101
  * captured this person gains nothing by finding them, which is what keeps an
@@ -28,7 +28,7 @@ import { creditConversion } from "@aglyn/aglyn/plugin-manager/plugin-conversion-
28
28
  import { notifyHostManagers } from "./notifications.js";
29
29
  import { scheduleCapturedEmailCheck } from "./capture-email-check.js";
30
30
  import firebaseAdmin from "./firebase-admin.js";
31
- import { consentGroupForSite, orgDataCollectionForHost, scopedToHost } from "./organizations.js";
31
+ import { consentGroupForSite, getOrgForHost, orgDataCollectionForHost, scopedToHost } from "./organizations.js";
32
32
  import { composeContactName, crmLeadListFields, crmReadTokens, crmScopeTokens } from "@aglyn/aglyn/server";
33
33
  // The module path rather than the barrel, as `upsert-contact.ts` does: a spec
34
34
  // that substitutes the barrel keeps the real rule for which group a grant is.
@@ -104,8 +104,9 @@ const firestore = ()=>firebaseAdmin.app().firestore();
104
104
  return crmReadTokens(group != null ? group : await consentGroupForSite(hostId));
105
105
  }
106
106
  /**
107
- * The `visibleTo` a capture on this site stamps: the consent group's sites,
108
- * or `['org']` where the org's CRM default (`crmDefaultScopeOf`) is `'org'`.
107
+ * The `visibleTo` a capture on this site stamps: `['org']` where the org's
108
+ * CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent
109
+ * group's sites where the org keeps its sites apart.
109
110
  *
110
111
  * Widened by the capture, never by the lookup — a site that has never
111
112
  * captured this person gains nothing by finding them, which is what keeps an
@@ -113,8 +114,14 @@ const firestore = ()=>firebaseAdmin.app().firestore();
113
114
  * existing lead union these in rather than replacing, exactly as
114
115
  * `upsert-contact` does.
115
116
  */ export async function leadScopeForHost(hostId, org) {
116
- const group = await consentGroupForSite(hostId, org);
117
- return crmScopeTokens(org != null ? org : null, group);
117
+ var _ref;
118
+ var _this;
119
+ // The org document decides: a capture with none in hand reads it, rather
120
+ // than stamping the site alone for an org whose records belong to every
121
+ // site. An org that cannot be read stamps the site — never everyone.
122
+ const resolved = (_ref = org != null ? org : (_this = await getOrgForHost(hostId).catch(()=>null)) == null ? void 0 : _this.org) != null ? _ref : null;
123
+ const group = await consentGroupForSite(hostId, resolved);
124
+ return crmScopeTokens(resolved, group);
118
125
  }
119
126
  /**
120
127
  * The lead for an address, wherever it currently lives.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-visitor-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The durable half of the visitor-record ceilings (AGL-1529) — the lead\n * writer that enforces `LEADS_MAX_PER_HOST`, and the bookkeeping that makes a\n * trip of EITHER ceiling something a site's owner can see.\n *\n * The policy is pure and lives in `@aglyn/aglyn/server`\n * (`visitor-record-ceiling.ts`); this is the part that needs Firestore. Same\n * split as `visitorWriteRateLimitRefusal`, and for the same reason.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkVisitorRecordCeiling,\n containerMembershipField,\n LEADS_MAX_PER_HOST,\n marketingConsentFieldsForGroup,\n normalizeContainerIds,\n personKey,\n readMarketingBasis,\n utcMonthKey,\n VISITOR_RECORD_NOTICE_SENT_FIELD,\n visitorRecordAcceptFillsCeiling,\n visitorRecordCeilingAnnounced,\n visitorRecordRefusedCounterId,\n type VisitorRecordKind,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n creditConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { notifyHostManagers } from './notifications'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport firebaseAdmin from './firebase-admin'\nimport {\n consentGroupForSite,\n orgDataCollectionForHost,\n resolveOrgIdForHost,\n scopedToHost,\n} from './organizations'\nimport {\n composeContactName,\n crmLeadListFields,\n crmReadTokens,\n crmScopeTokens,\n} from '@aglyn/aglyn/server'\nimport type { ConsentGroup, ScopeToken } from '@aglyn/aglyn/server'\n// The module path rather than the barrel, as `upsert-contact.ts` does: a spec\n// that substitutes the barrel keeps the real rule for which group a grant is.\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * A lead's one home: `orgs/{orgId}/leads/{personKey}` (AGL-3275).\n *\n * ## Why leads moved\n *\n * A lead used to live at `hosts/{hostId}/leads/{personKey}` while the\n * contact for the same human lived on the org with a `visibleTo` array. The\n * path was doing the job `visibleTo` does, and doing it worse:\n *\n * - An AGENCY was isolated by the path. It is isolated by `visibleTo` too,\n * with no configuration — `consentGroupScope` on a group of one is\n * `['host:{id}']`.\n * - A MULTI-BRAND org could not be served at all. `personKey` is derived\n * from the address, so the same person captured on two sibling brands\n * produced two documents with byte-identical ids under different parents.\n * One person was two records by construction, which is the thing AGL-3232\n * had just finished eliminating for contacts.\n * - The two answers could disagree. A person's contact was visible to every\n * brand in the consent group they actually consented to — the disclosure\n * names those brands — while their lead was visible to whichever brand's\n * form they happened to land on. The lead was scoped more narrowly than\n * what the person was told, which is the safe direction to be wrong in and\n * still the wrong answer.\n *\n * So a lead is stamped with `crmScopeTokens` and read with `crmReadTokens`,\n * the same pair the contacts surface uses. Nothing here is a new mechanism;\n * this is leads arriving at the one the rest of the CRM already had.\n *\n * ## The fallback is READ-ONLY, and temporary\n *\n * This repo has run this migration once already — AGL-237 moved datasets,\n * contacts and media to the org, AGL-1040 backfilled, AGL-1050 deleted the\n * fallback — and `orgDataCollectionForHost` carries what it learned:\n *\n * \"a second storage path that can still be WRITTEN is a second boundary to\n * enforce forever, which undoes the premise of scoped sharing: one home\n * per resource plus an explicit scope.\"\n *\n * So the host path is never written here. It is read, once, to carry a\n * not-yet-migrated lead onto the org as a side effect of the next write that\n * touches it ({@link leadForWrite}) — which shrinks what AGL-3276's backfill\n * has left to fold, and means no read can be answered by a stale host row\n * after a write has moved on. AGL-3277 deletes the fallback and the rules\n * block behind it once that backfill reports nothing left to plan.\n */\n\n\n/**\n * The org collection a lead is written to. Always the org — see the\n * read-only note above.\n */\nexport async function orgLeadsForHost(\n hostId: string,\n): Promise<FirebaseFirestore.CollectionReference> {\n return orgDataCollectionForHost(hostId, 'leads')\n}\n\n/**\n * The leads one site may LIST, narrowed by `visibleTo`.\n *\n * The Admin SDK does not evaluate rules, so an unnarrowed read here would\n * serve one agency client's leads on another's site — the same reason\n * `scopedToHost` exists for every other org-owned collection.\n */\nexport async function orgLeadsQueryForHost(hostId: string): Promise<{\n ref: FirebaseFirestore.CollectionReference\n query: FirebaseFirestore.Query\n}> {\n const ref = await orgLeadsForHost(hostId)\n return { ref, query: scopedToHost(ref, hostId) }\n}\n\n/**\n * The tokens a reader holding this group may ask `array-contains-any` for.\n * Capped at 30 by `crmReadTokens`, as the contacts list is.\n */\nexport async function leadReadTokensForHost(\n hostId: string,\n group?: ConsentGroup,\n): Promise<ScopeToken[]> {\n return crmReadTokens(group ?? (await consentGroupForSite(hostId)))\n}\n\n/**\n * The `visibleTo` a capture on this site stamps: the consent group's sites,\n * or `['org']` where the org's CRM default (`crmDefaultScopeOf`) is `'org'`.\n *\n * Widened by the capture, never by the lookup — a site that has never\n * captured this person gains nothing by finding them, which is what keeps an\n * agency's clients apart on a record they share. Callers UPDATING an\n * existing lead union these in rather than replacing, exactly as\n * `upsert-contact` does.\n */\nexport async function leadScopeForHost(\n hostId: string,\n org?: Record<string, unknown> | null,\n): Promise<ScopeToken[]> {\n const group = await consentGroupForSite(hostId, org)\n return crmScopeTokens(org ?? null, group)\n}\n\n/**\n * The lead for an address, wherever it currently lives.\n *\n * ## The lookup is UNSCOPED, and has to be\n *\n * One human who touched two sibling brands is one person. Narrowing this to\n * what the capturing site may already see would let a second submission on a\n * sibling brand mint a SECOND record for the same address — the duplication\n * this migration exists to end, reintroduced one layer up. Recognizing\n * somebody and being allowed to read their row are different acts:\n * this finds the person, {@link leadScopeForHost} decides who may see them.\n *\n * `upsert-contact` states the same rule at its own dedupe lookup, and for the\n * same reason. A caller that wants only what a site may SEE wants\n * {@link orgLeadsQueryForHost}.\n *\n * @returns the org row; else the not-yet-migrated host row; else `null`.\n */\nexport async function readLeadForHost(\n hostId: string,\n key: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const orgRow = await (await orgLeadsForHost(hostId)).doc(key).get()\n return orgRow.exists ? orgRow : null\n}\n\n/**\n * The ref a write should target.\n *\n * This carried a not-yet-backfilled host row onto the org first, and reported\n * whether it had (`carried`). AGL-3276 emptied the host path and AGL-3277\n * removed it, so there is nothing left to carry: the org row is the only row.\n * `carried` stays on the shape, always `false`, because several callers\n * destructure it and a lie is cheaper to read than a signature change that\n * says nothing.\n */\nexport async function leadForWrite(\n hostId: string,\n key: string,\n): Promise<{\n ref: FirebaseFirestore.DocumentReference\n existed: boolean\n carried: boolean\n}> {\n const ref = (await orgLeadsForHost(hostId)).doc(key)\n return { ref, existed: (await ref.get()).exists, carried: false }\n}\n\n\n/**\n * Make a tripped ceiling OBSERVABLE rather than a silent drop — the * standing rule that a control which is not visible in the console does not\n * count as shipped.\n *\n * Two audiences, one call, in exactly `recordAbuseCeilingTrip`'s shape\n * (`libs/plugins/forms/src/lib/server/form-submit.ts`, AGL-1655):\n *\n * - A durable per-month refusal count at\n * `hosts/{id}/counters/{siteMembers|leads}Refused`. Counters are excluded\n * from every client write in `cloud/firebase-firestore.rules` (AGL-1367),\n * so the record cannot be edited away by the site it describes, and host\n * admins can already READ it — which is what lets the inbox console page\n * render it with no rules change.\n * - One notification to the site's managers per CROSSING (AGL-3442): on the\n * first refusal after the site reaches the ceiling, and not again while it\n * stays there. A notification per refused bot request would be the flood\n * again, delivered, and one a month would repeat an alarm about a state a\n * site can sit in for months. {@link rearmVisitorRecordCeilingNotice}\n * re-arms it once the site is seen below the ceiling, so reaching it again\n * is announced again.\n *\n * The counter is month-keyed even though the CEILING is a total, because the\n * two facts are different: the ceiling is \"how many records exist\" and this is\n * \"how many were turned away recently\". The inbox reports the second; the\n * notice announces the first, which is why it follows the crossing and not\n * the month.\n *\n * Best-effort throughout: bookkeeping that failed must never turn a contained\n * refusal into a 500, because a 500 is an invitation to retry.\n */\nexport async function recordVisitorRecordCeilingTrip(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n kind: VisitorRecordKind\n ceiling: number\n monthKey?: string\n}): Promise<void> {\n const { hostRef, hostId, kind, ceiling } = options\n const monthKey = options.monthKey ?? utcMonthKey()\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n // Announced already for this crossing, by this writer or by the\n // month-scoped one before it — see `visitorRecordCeilingAnnounced`.\n const announced = visitorRecordCeilingAnnounced(refusedSnapshot.data())\n const now = Date.now()\n await refusedRef.set(\n {\n [monthKey]: FieldValue.increment(1),\n // Explicit values only — Firestore rejects `undefined`.\n ceiling,\n lastRefusedAtMs: now,\n // Marked in the same write as the refusal, so the next refusal reads\n // the crossing as announced without a write of its own.\n ...(announced ? {} : { [VISITOR_RECORD_NOTICE_SENT_FIELD]: now }),\n },\n { merge: true },\n )\n if (!announced) {\n const leads = kind === 'leads'\n /*\n * What is refused, said exactly (AGL-3432). A lead door — a form\n * routed to leads, a booking — stores its own record BEFORE it files\n * the lead, so at the ceiling the visitor's submission or booking is\n * still kept and only the new lead is not. A member sign-up is refused\n * whole: no account is created. `{site}` is the site's name, filled by\n * `notifyHostManagers` from the host doc it already reads.\n */\n await notifyHostManagers(hostId, {\n type: 'system.visitorRecordsPaused',\n title: leads\n ? 'Lead capture paused on {site} — platform limit reached'\n : 'Sign-ups paused on {site} — platform limit reached',\n body: leads\n ? `{site} holds ${ceiling.toLocaleString()} leads, the platform ` +\n 'safety limit, so new people are no longer added as leads. What ' +\n 'they send, such as a form submission or a booking, is still ' +\n 'saved; only the new lead is not. This limit is not part of your ' +\n 'plan — every plan includes unlimited leads — and nothing is ' +\n 'charged. Remove some leads, or contact support if this is real ' +\n 'traffic.'\n : `{site} has ${ceiling.toLocaleString()} member accounts, the ` +\n 'platform safety limit, so new sign-ups are refused and no ' +\n 'account is created. This limit is not part of your plan — every ' +\n 'plan includes unlimited member accounts — and nothing is ' +\n 'charged. Remove some members, or contact support if this is ' +\n 'real traffic.',\n link: `/${hostId}/inbox`,\n })\n }\n } catch (error) {\n console.error('visitor record ceiling bookkeeping failed', error)\n }\n}\n\n/**\n * Re-arm the ceiling notice when an accepted record shows the site was below\n * the ceiling (AGL-3442).\n *\n * Called by every writer that judges a new record against the ceiling, with\n * the count it judged. It does nothing unless the record it just accepted took\n * the site's LAST free slot: a site that dropped below the ceiling can reach\n * it again only through that accept, so it is where the re-arm is observed,\n * and every other accept pays nothing for it. That accept reads the refusal\n * counter, and clears the notice marker only when the previous crossing was\n * announced, so a site that never reached the ceiling gains no document.\n *\n * Best-effort and never throws, for the reason the trip's bookkeeping is: the\n * record is already stored, and a failure here only costs a notice.\n */\nexport async function rearmVisitorRecordCeilingNotice(options: {\n hostRef: FirebaseFirestore.DocumentReference\n kind: VisitorRecordKind\n /** The live count the accept was judged against, before its own record. */\n used: number\n ceiling: number\n}): Promise<void> {\n const { hostRef, kind, used, ceiling } = options\n if (!visitorRecordAcceptFillsCeiling(used, ceiling)) return\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n if (!visitorRecordCeilingAnnounced(refusedSnapshot.data())) return\n await refusedRef.set(\n { [VISITOR_RECORD_NOTICE_SENT_FIELD]: null },\n { merge: true },\n )\n } catch (error) {\n console.error('visitor record ceiling re-arm failed', error)\n }\n}\n\n/** What a caller wants stored on the lead. `createdAt` is stamped here. */\nexport interface HostLeadInput {\n email: string\n /** The name the person typed, when they typed one (AGL-2303). */\n name?: string\n /** `signup`, `booking`, `form:{formId}` — the surface that produced it. */\n source: string\n /**\n * Explicit marketing opt-in, with a consent timestamp — the same shape\n * `upsertHostContact` already carries (AGL-301). Omitted or `false` writes\n * nothing: a lead is a side effect of an action the visitor DID take\n * (sign up, book), which is not by itself consent to be emailed\n * marketing, so this is only set when the caller captured an explicit\n * checkbox.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` the capture surface rendered beside that\n * checkbox (AGL-3320). The grant pools across the site's consent group only\n * when it is the group's current key, and is this site's alone otherwise —\n * the same rule `upsertHostContact` applies.\n */\n disclosedConsentGroup?: string | null\n /**\n * The campaigns the capture SURFACE is filed under (AGL-3458) — a form's\n * `campaignIds`, read by the door off the verified form document. Never the\n * campaign touch, which is where the visitor came from: this is which\n * campaigns the merchant put the form in, and it is true of everybody who\n * fills that form in.\n *\n * Unioned into the lead's own `campaignIds` — the field the enroll route\n * and the bulk bar write — so a campaign the lead joined by hand or by a\n * sequence is kept, and the Leads list's Campaign filter\n * (`scopedCampaignIds`) is restamped from the union in the same write.\n */\n campaignIds?: readonly string[]\n /**\n * A phone the capture learned (AGL-3493), E.164 as the door normalized\n * it. Written only when the lead holds none: a number a rep typed on the\n * lead, or an earlier capture brought, is not replaced by this one.\n */\n phoneFill?: string\n}\n\n/**\n * Record one lead at `hosts/{hostId}/leads/{personKey}`, bounded by\n * `LEADS_MAX_PER_HOST` (AGL-1529).\n *\n * ## One person is one document\n *\n * `docs/specs/reusable-forms.md` §4b. This used to be `tx.create(ref.doc())`\n * — an auto-id per capture event — so one returning customer who signed up\n * and booked twice was three \"leads\". The Members & leads tab presented a\n * list of events as a list of people, and the only thing holding two rows for\n * one person together was string equality on the address at render time.\n *\n * The events are not lost, they are just no longer the record: `sources`\n * carries every surface that produced a capture, `submissionCount` counts\n * them, and `firstSeenAtMs`/`lastSeenAtMs` bracket them. The submissions, the\n * bookings and the member document are still there and still one row each.\n *\n * The id is {@link personKey} — `sha256(normalizeContactEmail(email))`, the\n * SAME derivation a list membership's `memberKey` uses, imported rather than\n * restated. Two specs named this function and the rule both stated is that\n * whichever ships second imports the first's helper: a second copy is how\n * `emailSuppressionKey` and `suppressionId` came to disagree.\n *\n * ## Why every lead writer goes through here\n *\n * There are three lead writes in the repo — the sign-up handler and the two\n * bookings paths — and all three were `hostRef.collection('leads').add(…)`\n * with a `.catch()` on the end. A cap enforced at two of three call sites is\n * not a cap, and the fourth writer somebody adds next month would not have\n * one either. One function is the only shape that survives that.\n *\n * ## The count is evaluated INSIDE the transaction that writes\n *\n * A create-time quota can be laundered by WHEN it is evaluated, not by the\n * counting rule (AGL-2231/2265/2266). Read-then-decide-then-`add()` lets N\n * concurrent visitors each read the same pre-count, each find room, and each\n * land — and nothing re-counts afterwards, so the extra rows are permanent.\n * `Transaction.get(AggregateQuery)` serialises the count against a concurrent\n * create into the same collection: the loser retries, re-reads the higher\n * count, and is refused. The count is of LIVE documents, so triaging leads in\n * the inbox frees the slots.\n *\n * ## Refusing a lead never fails the visitor's action\n *\n * A lead is a SIDE EFFECT — of a sign-up, or of a booking. The visitor did\n * not ask for it and cannot see it, so refusing one must not refuse the thing\n * they did ask for. This returns a boolean and never throws; the trip is\n * recorded and the caller carries on. That is the honest split, and it is why\n * `SITE_MEMBERS_MAX_PER_HOST` (which governs an action a visitor DID take) is\n * enforced with a 429 in the sign-up handler and this is not.\n */\nexport async function addHostLeadOutcome(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n lead: HostLeadInput\n /**\n * The ceiling to compare against. Defaults to `LEADS_MAX_PER_HOST` and is\n * passed by NOTHING in production — it exists so the suite can re-drive the\n * same count against a ceiling one higher and require the write to succeed.\n * A refusal that survives its own ceiling being raised was never that\n * ceiling's refusal, and there is exactly ONE comparison below, so knifing\n * it cannot be absorbed by a fallback branch.\n */\n ceiling?: number\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * Resolved rather than raw, and passed rather than looked up, because one\n * visitor action reaches several writers: a form submission that creates a\n * submission, a contact AND a lead must pay for the touch lookup once. A\n * door that hands none — every order path, every import — attributes\n * nothing, which is how a lead that no campaign caused stays uncredited.\n */\n touch?: PluginConversionTouch | null\n}): Promise<HostLeadOutcome> {\n const { hostRef, hostId, lead } = options\n const maxPerHost = options.ceiling ?? LEADS_MAX_PER_HOST\n try {\n const leadsRef = await orgLeadsForHost(hostId)\n const firestore = hostRef.firestore\n /*\n * `null` for anything that is not a usable address — a lead captured\n * against a malformed one keeps an auto-id and stays its own row. Keying\n * several unusable addresses under one guessed id would merge two\n * different people, which is worse than two rows for one.\n */\n const key = personKey(lead.email)\n /*\n * A lead the org has not taken over yet is carried across BEFORE the\n * transaction opens (AGL-3275). It has to happen outside: the carry is\n * itself a read-then-write, and a transaction that also counted the\n * collection would be reading a row it was about to create. Two doors\n * carrying the same person in the same second both write the legacy\n * fields under `merge`, so the race is a no-op rather than a conflict.\n */\n const leadRef = key\n ? (await leadForWrite(hostId, key)).ref\n : leadsRef.doc()\n /*\n * The scope this capture stamps, and the group whose terms its consent is\n * recorded under. Both resolved HERE rather than in the transaction body:\n * a contended transaction re-runs that body, and neither of these can\n * change between attempts, so resolving them inside would pay for the org\n * read again on every retry.\n */\n const scope = await leadScopeForHost(hostId)\n const group = await consentGroupForSite(hostId)\n const now = Date.now()\n const seen = {\n // `arrayUnion`, so a person who books twice has `['booking']` and one\n // who signed up and then submitted a form has both. Bounded by the\n // number of surfaces, not by the number of captures.\n sources: FieldValue.arrayUnion(lead.source),\n lastSeenAtMs: now,\n submissionCount: FieldValue.increment(1),\n ...(lead.name ? { name: lead.name } : {}),\n }\n let created = false\n let sourceAdded = false\n let predicted = false\n // The count a new person was judged against, for the notice re-arm.\n let usedBeforeCreate: number | null = null\n const refused = await firestore.runTransaction(async (tx) => {\n // Reset per attempt: a contended transaction re-runs its body, and a\n // flag left standing from an aborted attempt would credit a campaign\n // with a person who turned out to exist already.\n created = false\n sourceAdded = false\n usedBeforeCreate = null\n // ALL READS BEFORE THE WRITE, which Firestore requires.\n const existing = await tx.get(leadRef)\n // Whether the lead already reads \"Would bounce\", for the check below.\n predicted = (existing.data() ?? {})['emailStatus'] === 'undeliverable'\n /*\n * ⛔ THE CEILING GATES A NEW PERSON, NEVER AN EXISTING ONE.\n *\n * A returning visitor's capture is an UPDATE — it does not grow the\n * collection, so refusing it buys no capacity and costs the customer\n * the source and the timestamp they would have learned. That is the\n * enforcement-at-use shape the capacity rule exists to forbid: a limit\n * must refuse the addition, never a person already recorded or the\n * data attached to them.\n *\n * It also means the count is only paid on a genuinely new person,\n * which is the case that can move it.\n */\n if (!existing.exists) {\n /*\n * COUNTED OVER WHAT THIS SITE MAY SEE, not over the org (AGL-3275).\n *\n * The collection is org-wide now, and `LEADS_MAX_PER_HOST` is a\n * per-SITE ceiling. An unfiltered count would charge every brand in\n * an agency's account for every other brand's leads, and the first\n * client to fill its allowance would refuse captures on sites that\n * had taken none. `scopedToHost` is the same narrowing every other\n * org-owned read uses, so a single-site org counts exactly what it\n * counted before this moved.\n *\n * A lead shared by two brands in one consent group is counted by\n * both, which is the honest answer: each of them holds it.\n */\n const used = (\n await tx.get(scopedToHost(leadsRef, hostId).count())\n ).data().count\n if (checkVisitorRecordCeiling(used, maxPerHost).exceeded) return true\n usedBeforeCreate = used\n }\n /*\n * Consent is carried forward and never cleared.\n *\n * A basis is written only when this capture carried an explicit\n * opt-in, so a later booking by someone who did not tick the box\n * leaves an earlier grant standing — absent-or-granted, the shape\n * every other writer uses. The TIMESTAMP is carried over rather than\n * restamped, for the reason given at the read below.\n */\n /*\n * The EARLIEST grant is the one that happened, so a later capture\n * carrying the same checkbox keeps the original date rather than\n * restamping when this person opted in. Read back through the shared\n * reader so \"already consented\" means the same thing here as it does\n * at send time.\n */\n /*\n * THE SITE'S REAL GROUP, because the silo that justified a group of one\n * is gone (AGL-3275).\n *\n * This read `soloConsentGroup(hostId)` for as long as a lead lived at\n * `hosts/{hostId}/leads`, and the reason was the path: private by\n * construction, so pooling a lead's basis would have recorded a\n * disclosure that reached nothing, while the contact written by the\n * same capture door was org-shared and pooled.\n *\n * A lead is now org-shared on exactly the terms the contact is, so the\n * premise is false and keeping the group of one would leave a\n * multi-brand org holding a lead its sibling brand can SEE but may not\n * MAIL — a narrower basis than the one `consentGroupDisclosure` named\n * beside the checkbox this person ticked. Pooling here records what\n * they were actually told, and only that: the grant reaches the group\n * when the capture surface sent back the group's current disclosure\n * key (AGL-3320), and this site alone otherwise. An undeclared group is\n * still a group of one, so an agency is unchanged and configures\n * nothing.\n *\n * Resolved above the transaction — see `group`'s declaration.\n */\n const prior = readMarketingBasis(existing.data() ?? null, group)\n const consentAtMs =\n prior.basis === 'granted' && prior.basisAtMs !== null\n ? prior.basisAtMs\n : now\n created = !existing.exists\n /*\n * Whether this capture puts its surface on the person for the FIRST\n * time: a new lead, or one first met through another door. A form\n * counts its leads by this (AGL-3330) — the people it filed, which is\n * what a recount of `sources` finds — so a returning visitor's second\n * submission moves no form's lead count.\n */\n const storedSources = (existing.data() ?? {})['sources']\n sourceAdded =\n created || !(Array.isArray(storedSources) && storedSources.includes(lead.source))\n /*\n * THE FIELDS THE LEADS LIST QUERIES (AGL-3321), from the lead as it\n * will stand: what the transaction read, the address and name this\n * capture brings and the scope it widens. A new lead is written\n * `status: 'new'`, so the Open view's `status in [new, working]`\n * finds a lead nobody has touched — an absent field matches no query.\n */\n const stored = existing.data() ?? {}\n const phoneFill =\n lead.phoneFill && !String(stored['phone'] ?? '').trim()\n ? { phone: lead.phoneFill }\n : {}\n const storedScope = Array.isArray(stored['visibleTo']) ? (stored['visibleTo'] as unknown[]) : []\n /*\n * THE CAMPAIGNS, unioned (AGL-3458). Computed from what the transaction\n * read rather than written as an `arrayUnion`, so the Campaign filter's\n * scoped keys below are derived from the same list the write stores,\n * and the union is held to the membership cap every reader applies.\n * Written only when the capture names one, so a door with no campaign\n * never rewrites the field a person or a sequence filled.\n */\n // The field a lead holds its campaigns in, at the top of its document.\n const campaignsField = lead.campaignIds?.length ? containerMembershipField('campaign') : null\n const campaigns = campaignsField\n ? normalizeContainerIds([\n ...normalizeContainerIds(stored[campaignsField]),\n ...(lead.campaignIds ?? []),\n ])\n : null\n /*\n * A lead that keeps a first or last name keeps the name they make\n * (AGL-3513): a capture's typed name does not replace it.\n */\n const composedName = composeContactName(stored['firstName'], stored['lastName'])\n const name = composedName || lead.name\n const listFields = crmLeadListFields({\n ...stored,\n email: lead.email,\n ...(name ? { name } : {}),\n visibleTo: [...new Set([...storedScope, ...scope])],\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n })\n tx.set(\n leadRef,\n {\n email: lead.email,\n ...seen,\n ...(composedName ? { name: composedName } : {}),\n ...phoneFill,\n ...listFields,\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n /*\n * WIDENED BY THE CAPTURE, NEVER BY THE LOOKUP (AGL-3275).\n *\n * `arrayUnion` rather than a replace, exactly as `upsert-contact`\n * stamps a contact: this site just collected this person, so it may\n * see the row. A site that merely FOUND them — the unscoped dedupe\n * lookup in `readLeadForHost` — gains nothing, which is what keeps\n * an agency's clients apart on a record they share.\n */\n visibleTo: FieldValue.arrayUnion(...scope),\n /*\n * EVERY SITE THAT CAPTURED THIS PERSON, not just the first\n * (AGL-3275).\n *\n * This was written once, on create, and that was sound while the\n * collection sat under one host and could hold only that host's\n * name. On the org the row is shared, so a sibling brand capturing\n * a person the first brand already holds has to be recorded here or\n * the \"Known by\" answer silently omits it — the same `arrayUnion`\n * the contact door has always used for this field, now that a lead\n * has the same question to answer.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(hostId),\n ...(existing.exists\n ? {}\n : {\n firstSeenAtMs: now,\n createdAt: FieldValue.serverTimestamp(),\n }),\n /*\n * The basis is recorded under the GROUP, keyed by its host, because\n * {@link readMarketingBasis} is one function over four silos and a\n * silo whose basis lived somewhere else would need the reader to\n * know which collection it was handed. A reader that has to be told\n * the shape is a reader that can be told the wrong one.\n */\n ...(lead.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, lead.disclosedConsentGroup),\n consentAtMs,\n )\n : {}),\n },\n { merge: true },\n )\n return false\n })\n if (refused) {\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'leads',\n ceiling: maxPerHost,\n })\n return NOT_STORED\n }\n if (created && usedBeforeCreate !== null) {\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'leads',\n used: usedBeforeCreate,\n ceiling: maxPerHost,\n })\n }\n /*\n * ATTRIBUTED ON CREATION ONLY.\n *\n * A returning visitor's capture is an update — the campaign did not\n * produce a lead, it produced another visit by a person the site already\n * held — and crediting it would let whichever campaign ran most recently\n * re-earn every lead on the list. `created` is set inside the transaction\n * that decides it, so the attribution and the write agree about whether\n * this person is new.\n *\n * Awaited rather than fired off: `addHostLead` already returns only after\n * its own write, and a caller that `void`s it (every one of them) is\n * unaffected. Never throws, so a failure here cannot cost the lead.\n */\n /*\n * THE ADDRESS'S DOMAIN, checked after the response (AGL-3328): a lead\n * whose domain takes no mail reads \"Would bounce\". Queued, never\n * awaited — the write above is the capture, and this costs it nothing.\n */\n scheduleCapturedEmailCheck({\n orgId: leadsRef.parent?.id ?? null,\n hostId,\n email: lead.email,\n predicted,\n })\n if (created && options.touch) {\n await creditConversion({\n hostId,\n kind: 'lead',\n refId: leadRef.id,\n touch: options.touch,\n convertedAtMs: now,\n })\n }\n return { stored: true, created, sourceAdded }\n } catch (error) {\n // Same posture the three original call sites had (`.catch(() => undefined)`\n // / `.catch(console.error)`): a lead that failed to store must not fail\n // the sign-up or the booking that produced it.\n console.error('lead write failed', error)\n return NOT_STORED\n }\n}\n\n/** What {@link addHostLeadOutcome} did with one capture. */\nexport interface HostLeadOutcome {\n /** Whether the lead was written — false when refused or failed. */\n stored: boolean\n /** Whether it was a new person. */\n created: boolean\n /** Whether this capture's `source` was new on the lead — see the write. */\n sourceAdded: boolean\n}\n\nconst NOT_STORED: HostLeadOutcome = { stored: false, created: false, sourceAdded: false }\n\n/**\n * {@link addHostLeadOutcome}, answering only whether the lead was stored —\n * the question every door but a form's asks.\n */\nexport async function addHostLead(\n options: Parameters<typeof addHostLeadOutcome>[0],\n): Promise<boolean> {\n return (await addHostLeadOutcome(options)).stored\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkVisitorRecordCeiling","containerMembershipField","LEADS_MAX_PER_HOST","marketingConsentFieldsForGroup","normalizeContainerIds","personKey","readMarketingBasis","utcMonthKey","VISITOR_RECORD_NOTICE_SENT_FIELD","visitorRecordAcceptFillsCeiling","visitorRecordCeilingAnnounced","visitorRecordRefusedCounterId","FieldValue","creditConversion","notifyHostManagers","scheduleCapturedEmailCheck","firebaseAdmin","consentGroupForSite","orgDataCollectionForHost","scopedToHost","composeContactName","crmLeadListFields","crmReadTokens","crmScopeTokens","consentGroupForGrant","firestore","app","orgLeadsForHost","hostId","orgLeadsQueryForHost","ref","query","leadReadTokensForHost","group","leadScopeForHost","org","readLeadForHost","key","orgRow","doc","get","exists","leadForWrite","existed","carried","recordVisitorRecordCeilingTrip","options","hostRef","kind","ceiling","monthKey","refusedRef","collection","refusedSnapshot","announced","data","now","Date","set","increment","lastRefusedAtMs","merge","leads","type","title","body","toLocaleString","link","error","console","rearmVisitorRecordCeilingNotice","used","addHostLeadOutcome","lead","maxPerHost","leadsRef","email","leadRef","scope","seen","sources","arrayUnion","source","lastSeenAtMs","submissionCount","name","created","sourceAdded","predicted","usedBeforeCreate","refused","runTransaction","tx","existing","stored","count","exceeded","prior","consentAtMs","basis","basisAtMs","storedSources","Array","isArray","includes","phoneFill","String","trim","phone","storedScope","campaignsField","campaignIds","length","campaigns","composedName","listFields","visibleTo","Set","firstSeenAtMs","createdAt","serverTimestamp","marketingConsent","disclosedConsentGroup","NOT_STORED","orgId","parent","id","touch","refId","convertedAtMs","addHostLead"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,SACEA,sBAAsB,EACtBC,yBAAyB,EACzBC,wBAAwB,EACxBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,SAAS,EACTC,kBAAkB,EAClBC,WAAW,EACXC,gCAAgC,EAChCC,+BAA+B,EAC/BC,6BAA6B,EAC7BC,6BAA6B,QAExB,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,gBAAgB,QAEX,uDAAsD;AAC7D,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,2BAAuB;AAClE,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,mBAAmB,EACnBC,wBAAwB,EAExBC,Y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;QAC/CC,QAAQD,KAAK,CAAC,qBAAqBA;QACnC,OAAOuD;IACT;AACF;AAYA,MAAMA,aAA8B;IAAE7B,QAAQ;IAAOR,SAAS;IAAOC,aAAa;AAAM;AAExF;;;CAGC,GACD,OAAO,eAAe2C,YACpBpF,OAAiD;IAEjD,OAAO,AAAC,CAAA,MAAM0B,mBAAmB1B,QAAO,EAAGgD,MAAM;AACnD"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-visitor-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The durable half of the visitor-record ceilings (AGL-1529) — the lead\n * writer that enforces `LEADS_MAX_PER_HOST`, and the bookkeeping that makes a\n * trip of EITHER ceiling something a site's owner can see.\n *\n * The policy is pure and lives in `@aglyn/aglyn/server`\n * (`visitor-record-ceiling.ts`); this is the part that needs Firestore. Same\n * split as `visitorWriteRateLimitRefusal`, and for the same reason.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkVisitorRecordCeiling,\n containerMembershipField,\n LEADS_MAX_PER_HOST,\n marketingConsentFieldsForGroup,\n normalizeContainerIds,\n personKey,\n readMarketingBasis,\n utcMonthKey,\n VISITOR_RECORD_NOTICE_SENT_FIELD,\n visitorRecordAcceptFillsCeiling,\n visitorRecordCeilingAnnounced,\n visitorRecordRefusedCounterId,\n type VisitorRecordKind,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n creditConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { notifyHostManagers } from './notifications'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport firebaseAdmin from './firebase-admin'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n resolveOrgIdForHost,\n scopedToHost,\n} from './organizations'\nimport {\n composeContactName,\n crmLeadListFields,\n crmReadTokens,\n crmScopeTokens,\n} from '@aglyn/aglyn/server'\nimport type { ConsentGroup, ScopeToken } from '@aglyn/aglyn/server'\n// The module path rather than the barrel, as `upsert-contact.ts` does: a spec\n// that substitutes the barrel keeps the real rule for which group a grant is.\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * A lead's one home: `orgs/{orgId}/leads/{personKey}` (AGL-3275).\n *\n * ## Why leads moved\n *\n * A lead used to live at `hosts/{hostId}/leads/{personKey}` while the\n * contact for the same human lived on the org with a `visibleTo` array. The\n * path was doing the job `visibleTo` does, and doing it worse:\n *\n * - An AGENCY was isolated by the path. It is isolated by `visibleTo` too,\n * with no configuration — `consentGroupScope` on a group of one is\n * `['host:{id}']`.\n * - A MULTI-BRAND org could not be served at all. `personKey` is derived\n * from the address, so the same person captured on two sibling brands\n * produced two documents with byte-identical ids under different parents.\n * One person was two records by construction, which is the thing AGL-3232\n * had just finished eliminating for contacts.\n * - The two answers could disagree. A person's contact was visible to every\n * brand in the consent group they actually consented to — the disclosure\n * names those brands — while their lead was visible to whichever brand's\n * form they happened to land on. The lead was scoped more narrowly than\n * what the person was told, which is the safe direction to be wrong in and\n * still the wrong answer.\n *\n * So a lead is stamped with `crmScopeTokens` and read with `crmReadTokens`,\n * the same pair the contacts surface uses. Nothing here is a new mechanism;\n * this is leads arriving at the one the rest of the CRM already had.\n *\n * ## The fallback is READ-ONLY, and temporary\n *\n * This repo has run this migration once already — AGL-237 moved datasets,\n * contacts and media to the org, AGL-1040 backfilled, AGL-1050 deleted the\n * fallback — and `orgDataCollectionForHost` carries what it learned:\n *\n * \"a second storage path that can still be WRITTEN is a second boundary to\n * enforce forever, which undoes the premise of scoped sharing: one home\n * per resource plus an explicit scope.\"\n *\n * So the host path is never written here. It is read, once, to carry a\n * not-yet-migrated lead onto the org as a side effect of the next write that\n * touches it ({@link leadForWrite}) — which shrinks what AGL-3276's backfill\n * has left to fold, and means no read can be answered by a stale host row\n * after a write has moved on. AGL-3277 deletes the fallback and the rules\n * block behind it once that backfill reports nothing left to plan.\n */\n\n\n/**\n * The org collection a lead is written to. Always the org — see the\n * read-only note above.\n */\nexport async function orgLeadsForHost(\n hostId: string,\n): Promise<FirebaseFirestore.CollectionReference> {\n return orgDataCollectionForHost(hostId, 'leads')\n}\n\n/**\n * The leads one site may LIST, narrowed by `visibleTo`.\n *\n * The Admin SDK does not evaluate rules, so an unnarrowed read here would\n * serve one agency client's leads on another's site — the same reason\n * `scopedToHost` exists for every other org-owned collection.\n */\nexport async function orgLeadsQueryForHost(hostId: string): Promise<{\n ref: FirebaseFirestore.CollectionReference\n query: FirebaseFirestore.Query\n}> {\n const ref = await orgLeadsForHost(hostId)\n return { ref, query: scopedToHost(ref, hostId) }\n}\n\n/**\n * The tokens a reader holding this group may ask `array-contains-any` for.\n * Capped at 30 by `crmReadTokens`, as the contacts list is.\n */\nexport async function leadReadTokensForHost(\n hostId: string,\n group?: ConsentGroup,\n): Promise<ScopeToken[]> {\n return crmReadTokens(group ?? (await consentGroupForSite(hostId)))\n}\n\n/**\n * The `visibleTo` a capture on this site stamps: `['org']` where the org's\n * CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent\n * group's sites where the org keeps its sites apart.\n *\n * Widened by the capture, never by the lookup — a site that has never\n * captured this person gains nothing by finding them, which is what keeps an\n * agency's clients apart on a record they share. Callers UPDATING an\n * existing lead union these in rather than replacing, exactly as\n * `upsert-contact` does.\n */\nexport async function leadScopeForHost(\n hostId: string,\n org?: Record<string, unknown> | null,\n): Promise<ScopeToken[]> {\n // The org document decides: a capture with none in hand reads it, rather\n // than stamping the site alone for an org whose records belong to every\n // site. An org that cannot be read stamps the site — never everyone.\n const resolved =\n org ?? ((await getOrgForHost(hostId).catch(() => null))?.org as Record<string, unknown> | undefined) ?? null\n const group = await consentGroupForSite(hostId, resolved)\n return crmScopeTokens(resolved, group)\n}\n\n/**\n * The lead for an address, wherever it currently lives.\n *\n * ## The lookup is UNSCOPED, and has to be\n *\n * One human who touched two sibling brands is one person. Narrowing this to\n * what the capturing site may already see would let a second submission on a\n * sibling brand mint a SECOND record for the same address — the duplication\n * this migration exists to end, reintroduced one layer up. Recognizing\n * somebody and being allowed to read their row are different acts:\n * this finds the person, {@link leadScopeForHost} decides who may see them.\n *\n * `upsert-contact` states the same rule at its own dedupe lookup, and for the\n * same reason. A caller that wants only what a site may SEE wants\n * {@link orgLeadsQueryForHost}.\n *\n * @returns the org row; else the not-yet-migrated host row; else `null`.\n */\nexport async function readLeadForHost(\n hostId: string,\n key: string,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const orgRow = await (await orgLeadsForHost(hostId)).doc(key).get()\n return orgRow.exists ? orgRow : null\n}\n\n/**\n * The ref a write should target.\n *\n * This carried a not-yet-backfilled host row onto the org first, and reported\n * whether it had (`carried`). AGL-3276 emptied the host path and AGL-3277\n * removed it, so there is nothing left to carry: the org row is the only row.\n * `carried` stays on the shape, always `false`, because several callers\n * destructure it and a lie is cheaper to read than a signature change that\n * says nothing.\n */\nexport async function leadForWrite(\n hostId: string,\n key: string,\n): Promise<{\n ref: FirebaseFirestore.DocumentReference\n existed: boolean\n carried: boolean\n}> {\n const ref = (await orgLeadsForHost(hostId)).doc(key)\n return { ref, existed: (await ref.get()).exists, carried: false }\n}\n\n\n/**\n * Make a tripped ceiling OBSERVABLE rather than a silent drop — the * standing rule that a control which is not visible in the console does not\n * count as shipped.\n *\n * Two audiences, one call, in exactly `recordAbuseCeilingTrip`'s shape\n * (`libs/plugins/forms/src/lib/server/form-submit.ts`, AGL-1655):\n *\n * - A durable per-month refusal count at\n * `hosts/{id}/counters/{siteMembers|leads}Refused`. Counters are excluded\n * from every client write in `cloud/firebase-firestore.rules` (AGL-1367),\n * so the record cannot be edited away by the site it describes, and host\n * admins can already READ it — which is what lets the inbox console page\n * render it with no rules change.\n * - One notification to the site's managers per CROSSING (AGL-3442): on the\n * first refusal after the site reaches the ceiling, and not again while it\n * stays there. A notification per refused bot request would be the flood\n * again, delivered, and one a month would repeat an alarm about a state a\n * site can sit in for months. {@link rearmVisitorRecordCeilingNotice}\n * re-arms it once the site is seen below the ceiling, so reaching it again\n * is announced again.\n *\n * The counter is month-keyed even though the CEILING is a total, because the\n * two facts are different: the ceiling is \"how many records exist\" and this is\n * \"how many were turned away recently\". The inbox reports the second; the\n * notice announces the first, which is why it follows the crossing and not\n * the month.\n *\n * Best-effort throughout: bookkeeping that failed must never turn a contained\n * refusal into a 500, because a 500 is an invitation to retry.\n */\nexport async function recordVisitorRecordCeilingTrip(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n kind: VisitorRecordKind\n ceiling: number\n monthKey?: string\n}): Promise<void> {\n const { hostRef, hostId, kind, ceiling } = options\n const monthKey = options.monthKey ?? utcMonthKey()\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n // Announced already for this crossing, by this writer or by the\n // month-scoped one before it — see `visitorRecordCeilingAnnounced`.\n const announced = visitorRecordCeilingAnnounced(refusedSnapshot.data())\n const now = Date.now()\n await refusedRef.set(\n {\n [monthKey]: FieldValue.increment(1),\n // Explicit values only — Firestore rejects `undefined`.\n ceiling,\n lastRefusedAtMs: now,\n // Marked in the same write as the refusal, so the next refusal reads\n // the crossing as announced without a write of its own.\n ...(announced ? {} : { [VISITOR_RECORD_NOTICE_SENT_FIELD]: now }),\n },\n { merge: true },\n )\n if (!announced) {\n const leads = kind === 'leads'\n /*\n * What is refused, said exactly (AGL-3432). A lead door — a form\n * routed to leads, a booking — stores its own record BEFORE it files\n * the lead, so at the ceiling the visitor's submission or booking is\n * still kept and only the new lead is not. A member sign-up is refused\n * whole: no account is created. `{site}` is the site's name, filled by\n * `notifyHostManagers` from the host doc it already reads.\n */\n await notifyHostManagers(hostId, {\n type: 'system.visitorRecordsPaused',\n title: leads\n ? 'Lead capture paused on {site} — platform limit reached'\n : 'Sign-ups paused on {site} — platform limit reached',\n body: leads\n ? `{site} holds ${ceiling.toLocaleString()} leads, the platform ` +\n 'safety limit, so new people are no longer added as leads. What ' +\n 'they send, such as a form submission or a booking, is still ' +\n 'saved; only the new lead is not. This limit is not part of your ' +\n 'plan — every plan includes unlimited leads — and nothing is ' +\n 'charged. Remove some leads, or contact support if this is real ' +\n 'traffic.'\n : `{site} has ${ceiling.toLocaleString()} member accounts, the ` +\n 'platform safety limit, so new sign-ups are refused and no ' +\n 'account is created. This limit is not part of your plan — every ' +\n 'plan includes unlimited member accounts — and nothing is ' +\n 'charged. Remove some members, or contact support if this is ' +\n 'real traffic.',\n link: `/${hostId}/inbox`,\n })\n }\n } catch (error) {\n console.error('visitor record ceiling bookkeeping failed', error)\n }\n}\n\n/**\n * Re-arm the ceiling notice when an accepted record shows the site was below\n * the ceiling (AGL-3442).\n *\n * Called by every writer that judges a new record against the ceiling, with\n * the count it judged. It does nothing unless the record it just accepted took\n * the site's LAST free slot: a site that dropped below the ceiling can reach\n * it again only through that accept, so it is where the re-arm is observed,\n * and every other accept pays nothing for it. That accept reads the refusal\n * counter, and clears the notice marker only when the previous crossing was\n * announced, so a site that never reached the ceiling gains no document.\n *\n * Best-effort and never throws, for the reason the trip's bookkeeping is: the\n * record is already stored, and a failure here only costs a notice.\n */\nexport async function rearmVisitorRecordCeilingNotice(options: {\n hostRef: FirebaseFirestore.DocumentReference\n kind: VisitorRecordKind\n /** The live count the accept was judged against, before its own record. */\n used: number\n ceiling: number\n}): Promise<void> {\n const { hostRef, kind, used, ceiling } = options\n if (!visitorRecordAcceptFillsCeiling(used, ceiling)) return\n try {\n const refusedRef = hostRef\n .collection('counters')\n .doc(visitorRecordRefusedCounterId(kind))\n const refusedSnapshot = await refusedRef.get()\n if (!visitorRecordCeilingAnnounced(refusedSnapshot.data())) return\n await refusedRef.set(\n { [VISITOR_RECORD_NOTICE_SENT_FIELD]: null },\n { merge: true },\n )\n } catch (error) {\n console.error('visitor record ceiling re-arm failed', error)\n }\n}\n\n/** What a caller wants stored on the lead. `createdAt` is stamped here. */\nexport interface HostLeadInput {\n email: string\n /** The name the person typed, when they typed one (AGL-2303). */\n name?: string\n /** `signup`, `booking`, `form:{formId}` — the surface that produced it. */\n source: string\n /**\n * Explicit marketing opt-in, with a consent timestamp — the same shape\n * `upsertHostContact` already carries (AGL-301). Omitted or `false` writes\n * nothing: a lead is a side effect of an action the visitor DID take\n * (sign up, book), which is not by itself consent to be emailed\n * marketing, so this is only set when the caller captured an explicit\n * checkbox.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` the capture surface rendered beside that\n * checkbox (AGL-3320). The grant pools across the site's consent group only\n * when it is the group's current key, and is this site's alone otherwise —\n * the same rule `upsertHostContact` applies.\n */\n disclosedConsentGroup?: string | null\n /**\n * The campaigns the capture SURFACE is filed under (AGL-3458) — a form's\n * `campaignIds`, read by the door off the verified form document. Never the\n * campaign touch, which is where the visitor came from: this is which\n * campaigns the merchant put the form in, and it is true of everybody who\n * fills that form in.\n *\n * Unioned into the lead's own `campaignIds` — the field the enroll route\n * and the bulk bar write — so a campaign the lead joined by hand or by a\n * sequence is kept, and the Leads list's Campaign filter\n * (`scopedCampaignIds`) is restamped from the union in the same write.\n */\n campaignIds?: readonly string[]\n /**\n * A phone the capture learned (AGL-3493), E.164 as the door normalized\n * it. Written only when the lead holds none: a number a rep typed on the\n * lead, or an earlier capture brought, is not replaced by this one.\n */\n phoneFill?: string\n}\n\n/**\n * Record one lead at `hosts/{hostId}/leads/{personKey}`, bounded by\n * `LEADS_MAX_PER_HOST` (AGL-1529).\n *\n * ## One person is one document\n *\n * `docs/specs/reusable-forms.md` §4b. This used to be `tx.create(ref.doc())`\n * — an auto-id per capture event — so one returning customer who signed up\n * and booked twice was three \"leads\". The Members & leads tab presented a\n * list of events as a list of people, and the only thing holding two rows for\n * one person together was string equality on the address at render time.\n *\n * The events are not lost, they are just no longer the record: `sources`\n * carries every surface that produced a capture, `submissionCount` counts\n * them, and `firstSeenAtMs`/`lastSeenAtMs` bracket them. The submissions, the\n * bookings and the member document are still there and still one row each.\n *\n * The id is {@link personKey} — `sha256(normalizeContactEmail(email))`, the\n * SAME derivation a list membership's `memberKey` uses, imported rather than\n * restated. Two specs named this function and the rule both stated is that\n * whichever ships second imports the first's helper: a second copy is how\n * `emailSuppressionKey` and `suppressionId` came to disagree.\n *\n * ## Why every lead writer goes through here\n *\n * There are three lead writes in the repo — the sign-up handler and the two\n * bookings paths — and all three were `hostRef.collection('leads').add(…)`\n * with a `.catch()` on the end. A cap enforced at two of three call sites is\n * not a cap, and the fourth writer somebody adds next month would not have\n * one either. One function is the only shape that survives that.\n *\n * ## The count is evaluated INSIDE the transaction that writes\n *\n * A create-time quota can be laundered by WHEN it is evaluated, not by the\n * counting rule (AGL-2231/2265/2266). Read-then-decide-then-`add()` lets N\n * concurrent visitors each read the same pre-count, each find room, and each\n * land — and nothing re-counts afterwards, so the extra rows are permanent.\n * `Transaction.get(AggregateQuery)` serialises the count against a concurrent\n * create into the same collection: the loser retries, re-reads the higher\n * count, and is refused. The count is of LIVE documents, so triaging leads in\n * the inbox frees the slots.\n *\n * ## Refusing a lead never fails the visitor's action\n *\n * A lead is a SIDE EFFECT — of a sign-up, or of a booking. The visitor did\n * not ask for it and cannot see it, so refusing one must not refuse the thing\n * they did ask for. This returns a boolean and never throws; the trip is\n * recorded and the caller carries on. That is the honest split, and it is why\n * `SITE_MEMBERS_MAX_PER_HOST` (which governs an action a visitor DID take) is\n * enforced with a 429 in the sign-up handler and this is not.\n */\nexport async function addHostLeadOutcome(options: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n lead: HostLeadInput\n /**\n * The ceiling to compare against. Defaults to `LEADS_MAX_PER_HOST` and is\n * passed by NOTHING in production — it exists so the suite can re-drive the\n * same count against a ceiling one higher and require the write to succeed.\n * A refusal that survives its own ceiling being raised was never that\n * ceiling's refusal, and there is exactly ONE comparison below, so knifing\n * it cannot be absorbed by a fallback branch.\n */\n ceiling?: number\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * Resolved rather than raw, and passed rather than looked up, because one\n * visitor action reaches several writers: a form submission that creates a\n * submission, a contact AND a lead must pay for the touch lookup once. A\n * door that hands none — every order path, every import — attributes\n * nothing, which is how a lead that no campaign caused stays uncredited.\n */\n touch?: PluginConversionTouch | null\n}): Promise<HostLeadOutcome> {\n const { hostRef, hostId, lead } = options\n const maxPerHost = options.ceiling ?? LEADS_MAX_PER_HOST\n try {\n const leadsRef = await orgLeadsForHost(hostId)\n const firestore = hostRef.firestore\n /*\n * `null` for anything that is not a usable address — a lead captured\n * against a malformed one keeps an auto-id and stays its own row. Keying\n * several unusable addresses under one guessed id would merge two\n * different people, which is worse than two rows for one.\n */\n const key = personKey(lead.email)\n /*\n * A lead the org has not taken over yet is carried across BEFORE the\n * transaction opens (AGL-3275). It has to happen outside: the carry is\n * itself a read-then-write, and a transaction that also counted the\n * collection would be reading a row it was about to create. Two doors\n * carrying the same person in the same second both write the legacy\n * fields under `merge`, so the race is a no-op rather than a conflict.\n */\n const leadRef = key\n ? (await leadForWrite(hostId, key)).ref\n : leadsRef.doc()\n /*\n * The scope this capture stamps, and the group whose terms its consent is\n * recorded under. Both resolved HERE rather than in the transaction body:\n * a contended transaction re-runs that body, and neither of these can\n * change between attempts, so resolving them inside would pay for the org\n * read again on every retry.\n */\n const scope = await leadScopeForHost(hostId)\n const group = await consentGroupForSite(hostId)\n const now = Date.now()\n const seen = {\n // `arrayUnion`, so a person who books twice has `['booking']` and one\n // who signed up and then submitted a form has both. Bounded by the\n // number of surfaces, not by the number of captures.\n sources: FieldValue.arrayUnion(lead.source),\n lastSeenAtMs: now,\n submissionCount: FieldValue.increment(1),\n ...(lead.name ? { name: lead.name } : {}),\n }\n let created = false\n let sourceAdded = false\n let predicted = false\n // The count a new person was judged against, for the notice re-arm.\n let usedBeforeCreate: number | null = null\n const refused = await firestore.runTransaction(async (tx) => {\n // Reset per attempt: a contended transaction re-runs its body, and a\n // flag left standing from an aborted attempt would credit a campaign\n // with a person who turned out to exist already.\n created = false\n sourceAdded = false\n usedBeforeCreate = null\n // ALL READS BEFORE THE WRITE, which Firestore requires.\n const existing = await tx.get(leadRef)\n // Whether the lead already reads \"Would bounce\", for the check below.\n predicted = (existing.data() ?? {})['emailStatus'] === 'undeliverable'\n /*\n * ⛔ THE CEILING GATES A NEW PERSON, NEVER AN EXISTING ONE.\n *\n * A returning visitor's capture is an UPDATE — it does not grow the\n * collection, so refusing it buys no capacity and costs the customer\n * the source and the timestamp they would have learned. That is the\n * enforcement-at-use shape the capacity rule exists to forbid: a limit\n * must refuse the addition, never a person already recorded or the\n * data attached to them.\n *\n * It also means the count is only paid on a genuinely new person,\n * which is the case that can move it.\n */\n if (!existing.exists) {\n /*\n * COUNTED OVER WHAT THIS SITE MAY SEE, not over the org (AGL-3275).\n *\n * The collection is org-wide now, and `LEADS_MAX_PER_HOST` is a\n * per-SITE ceiling. An unfiltered count would charge every brand in\n * an agency's account for every other brand's leads, and the first\n * client to fill its allowance would refuse captures on sites that\n * had taken none. `scopedToHost` is the same narrowing every other\n * org-owned read uses, so a single-site org counts exactly what it\n * counted before this moved.\n *\n * A lead shared by two brands in one consent group is counted by\n * both, which is the honest answer: each of them holds it.\n */\n const used = (\n await tx.get(scopedToHost(leadsRef, hostId).count())\n ).data().count\n if (checkVisitorRecordCeiling(used, maxPerHost).exceeded) return true\n usedBeforeCreate = used\n }\n /*\n * Consent is carried forward and never cleared.\n *\n * A basis is written only when this capture carried an explicit\n * opt-in, so a later booking by someone who did not tick the box\n * leaves an earlier grant standing — absent-or-granted, the shape\n * every other writer uses. The TIMESTAMP is carried over rather than\n * restamped, for the reason given at the read below.\n */\n /*\n * The EARLIEST grant is the one that happened, so a later capture\n * carrying the same checkbox keeps the original date rather than\n * restamping when this person opted in. Read back through the shared\n * reader so \"already consented\" means the same thing here as it does\n * at send time.\n */\n /*\n * THE SITE'S REAL GROUP, because the silo that justified a group of one\n * is gone (AGL-3275).\n *\n * This read `soloConsentGroup(hostId)` for as long as a lead lived at\n * `hosts/{hostId}/leads`, and the reason was the path: private by\n * construction, so pooling a lead's basis would have recorded a\n * disclosure that reached nothing, while the contact written by the\n * same capture door was org-shared and pooled.\n *\n * A lead is now org-shared on exactly the terms the contact is, so the\n * premise is false and keeping the group of one would leave a\n * multi-brand org holding a lead its sibling brand can SEE but may not\n * MAIL — a narrower basis than the one `consentGroupDisclosure` named\n * beside the checkbox this person ticked. Pooling here records what\n * they were actually told, and only that: the grant reaches the group\n * when the capture surface sent back the group's current disclosure\n * key (AGL-3320), and this site alone otherwise. An undeclared group is\n * still a group of one, so an agency is unchanged and configures\n * nothing.\n *\n * Resolved above the transaction — see `group`'s declaration.\n */\n const prior = readMarketingBasis(existing.data() ?? null, group)\n const consentAtMs =\n prior.basis === 'granted' && prior.basisAtMs !== null\n ? prior.basisAtMs\n : now\n created = !existing.exists\n /*\n * Whether this capture puts its surface on the person for the FIRST\n * time: a new lead, or one first met through another door. A form\n * counts its leads by this (AGL-3330) — the people it filed, which is\n * what a recount of `sources` finds — so a returning visitor's second\n * submission moves no form's lead count.\n */\n const storedSources = (existing.data() ?? {})['sources']\n sourceAdded =\n created || !(Array.isArray(storedSources) && storedSources.includes(lead.source))\n /*\n * THE FIELDS THE LEADS LIST QUERIES (AGL-3321), from the lead as it\n * will stand: what the transaction read, the address and name this\n * capture brings and the scope it widens. A new lead is written\n * `status: 'new'`, so the Open view's `status in [new, working]`\n * finds a lead nobody has touched — an absent field matches no query.\n */\n const stored = existing.data() ?? {}\n const phoneFill =\n lead.phoneFill && !String(stored['phone'] ?? '').trim()\n ? { phone: lead.phoneFill }\n : {}\n const storedScope = Array.isArray(stored['visibleTo']) ? (stored['visibleTo'] as unknown[]) : []\n /*\n * THE CAMPAIGNS, unioned (AGL-3458). Computed from what the transaction\n * read rather than written as an `arrayUnion`, so the Campaign filter's\n * scoped keys below are derived from the same list the write stores,\n * and the union is held to the membership cap every reader applies.\n * Written only when the capture names one, so a door with no campaign\n * never rewrites the field a person or a sequence filled.\n */\n // The field a lead holds its campaigns in, at the top of its document.\n const campaignsField = lead.campaignIds?.length ? containerMembershipField('campaign') : null\n const campaigns = campaignsField\n ? normalizeContainerIds([\n ...normalizeContainerIds(stored[campaignsField]),\n ...(lead.campaignIds ?? []),\n ])\n : null\n /*\n * A lead that keeps a first or last name keeps the name they make\n * (AGL-3513): a capture's typed name does not replace it.\n */\n const composedName = composeContactName(stored['firstName'], stored['lastName'])\n const name = composedName || lead.name\n const listFields = crmLeadListFields({\n ...stored,\n email: lead.email,\n ...(name ? { name } : {}),\n visibleTo: [...new Set([...storedScope, ...scope])],\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n })\n tx.set(\n leadRef,\n {\n email: lead.email,\n ...seen,\n ...(composedName ? { name: composedName } : {}),\n ...phoneFill,\n ...listFields,\n ...(campaignsField && campaigns ? { [campaignsField]: campaigns } : {}),\n /*\n * WIDENED BY THE CAPTURE, NEVER BY THE LOOKUP (AGL-3275).\n *\n * `arrayUnion` rather than a replace, exactly as `upsert-contact`\n * stamps a contact: this site just collected this person, so it may\n * see the row. A site that merely FOUND them — the unscoped dedupe\n * lookup in `readLeadForHost` — gains nothing, which is what keeps\n * an agency's clients apart on a record they share.\n */\n visibleTo: FieldValue.arrayUnion(...scope),\n /*\n * EVERY SITE THAT CAPTURED THIS PERSON, not just the first\n * (AGL-3275).\n *\n * This was written once, on create, and that was sound while the\n * collection sat under one host and could hold only that host's\n * name. On the org the row is shared, so a sibling brand capturing\n * a person the first brand already holds has to be recorded here or\n * the \"Known by\" answer silently omits it — the same `arrayUnion`\n * the contact door has always used for this field, now that a lead\n * has the same question to answer.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(hostId),\n ...(existing.exists\n ? {}\n : {\n firstSeenAtMs: now,\n createdAt: FieldValue.serverTimestamp(),\n }),\n /*\n * The basis is recorded under the GROUP, keyed by its host, because\n * {@link readMarketingBasis} is one function over four silos and a\n * silo whose basis lived somewhere else would need the reader to\n * know which collection it was handed. A reader that has to be told\n * the shape is a reader that can be told the wrong one.\n */\n ...(lead.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, lead.disclosedConsentGroup),\n consentAtMs,\n )\n : {}),\n },\n { merge: true },\n )\n return false\n })\n if (refused) {\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'leads',\n ceiling: maxPerHost,\n })\n return NOT_STORED\n }\n if (created && usedBeforeCreate !== null) {\n await rearmVisitorRecordCeilingNotice({\n hostRef,\n kind: 'leads',\n used: usedBeforeCreate,\n ceiling: maxPerHost,\n })\n }\n /*\n * ATTRIBUTED ON CREATION ONLY.\n *\n * A returning visitor's capture is an update — the campaign did not\n * produce a lead, it produced another visit by a person the site already\n * held — and crediting it would let whichever campaign ran most recently\n * re-earn every lead on the list. `created` is set inside the transaction\n * that decides it, so the attribution and the write agree about whether\n * this person is new.\n *\n * Awaited rather than fired off: `addHostLead` already returns only after\n * its own write, and a caller that `void`s it (every one of them) is\n * unaffected. Never throws, so a failure here cannot cost the lead.\n */\n /*\n * THE ADDRESS'S DOMAIN, checked after the response (AGL-3328): a lead\n * whose domain takes no mail reads \"Would bounce\". Queued, never\n * awaited — the write above is the capture, and this costs it nothing.\n */\n scheduleCapturedEmailCheck({\n orgId: leadsRef.parent?.id ?? null,\n hostId,\n email: lead.email,\n predicted,\n })\n if (created && options.touch) {\n await creditConversion({\n hostId,\n kind: 'lead',\n refId: leadRef.id,\n touch: options.touch,\n convertedAtMs: now,\n })\n }\n return { stored: true, created, sourceAdded }\n } catch (error) {\n // Same posture the three original call sites had (`.catch(() => undefined)`\n // / `.catch(console.error)`): a lead that failed to store must not fail\n // the sign-up or the booking that produced it.\n console.error('lead write failed', error)\n return NOT_STORED\n }\n}\n\n/** What {@link addHostLeadOutcome} did with one capture. */\nexport interface HostLeadOutcome {\n /** Whether the lead was written — false when refused or failed. */\n stored: boolean\n /** Whether it was a new person. */\n created: boolean\n /** Whether this capture's `source` was new on the lead — see the write. */\n sourceAdded: boolean\n}\n\nconst NOT_STORED: HostLeadOutcome = { stored: false, created: false, sourceAdded: false }\n\n/**\n * {@link addHostLeadOutcome}, answering only whether the lead was stored —\n * the question every door but a form's asks.\n */\nexport async function addHostLead(\n options: Parameters<typeof addHostLeadOutcome>[0],\n): Promise<boolean> {\n return (await addHostLeadOutcome(options)).stored\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkVisitorRecordCeiling","containerMembershipField","LEADS_MAX_PER_HOST","marketingConsentFieldsForGroup","normalizeContainerIds","personKey","readMarketingBasis","utcMonthKey","VISITOR_RECORD_NOTICE_SENT_FIELD","visitorRecordAcceptFillsCeiling","visitorRecordCeilingAnnounced","visitorRecordRefusedCounterId","FieldValue","creditConversion","notifyHostManagers","scheduleCapturedEmailCheck","firebaseAdmin","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","scopedToHost","composeContactName","crmLeadListFields","crmReadTokens","crmScopeTokens","consentGroupForGrant","firestore","app","orgLeadsForHost","hostId","orgLeadsQueryForHost","ref","query","leadReadTokensForHost","group","leadScopeForHost","org","resolved","catch","readLeadForHost","key","orgRow","doc","get","exists","leadForWrite","existed","carried","recordVisitorRecordCeilingTrip","options","hostRef","kind","ceiling","monthKey","refusedRef","collection","refusedSnapshot","announced","data","now","Date","set","increment","lastRefusedAtMs","merge","leads","type","title","body","toLocaleString","link","error","console","rearmVisitorRecordCeilingNotice","used","addHostLeadOutcome","lead","maxPerHost","leadsRef","email","leadRef","scope","seen","sources","arrayUnion","source","lastSeenAtMs","submissionCount","name","created","sourceAdded","predicted","usedBeforeCreate","refused","runTransaction","tx","existing","stored","count","exceeded","prior","consentAtMs","basis","basisAtMs","storedSources","Array","isArray","includes","phoneFill","String","trim","phone","storedScope","campaignsField","campaignIds","length","campaigns","composedName","listFields","visibleTo","Set","firstSeenAtMs","createdAt","serverTimestamp","marketingConsent","disclosedConsentGroup","NOT_STORED","orgId","parent","id","touch","refId","convertedAtMs","addHostLead"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,SACEA,sBAAsB,EACtBC,yBAAyB,EACzBC,wBAAwB,EACxBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,SAAS,EACTC,kBAAkB,EAClBC,WAAW,EACXC,gCAAgC,EAChCC,+BAA+B,EAC/BC,6BAA6B,EAC7BC,6BAA6B,QAExB,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,gBAAgB,QAEX,uDAAsD;AAC7D,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,2BAAuB;AAClE,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,EAExBC,YAAY,QACP,qBAAiB;AACxB,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,aAAa,EACbC,cAAc,QACT,sBAAqB;AAE5B,8EAA8E;AAC9E,8EAA8E;AAC9E,SAASC,oBAAoB,QAAQ,wCAAuC;AAE5E,MAAMC,YAAY,IAAMV,cAAcW,GAAG,GAAGD,SAAS;AAErD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GAGD;;;CAGC,GACD,OAAO,eAAeE,gBACpBC,MAAc;IAEd,OAAOV,yBAAyBU,QAAQ;AAC1C;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,qBAAqBD,MAAc;IAIvD,MAAME,M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108,7 +108,10 @@ export interface SiteStarterPickRefusal {
108
108
  * it refused, so Create site can tell a refused pick from a refused name.
109
109
  *
110
110
  * `resolved` is what the starter source answered; `pagesAllowed` is the
111
- * plan's `screensPerHost`.
111
+ * plan's `screensPerHost`. `aiStart` is whether the person creating the site
112
+ * is offered the AI start (AGL-4049 phase 4): an AI starter fills in its
113
+ * questions, so without it there is nothing to create one from, and with it
114
+ * the site is created empty for the start, whose own page band applies.
112
115
  */
113
116
  export declare function siteStarterPickRefusal(resolved: SiteStarterPayload | {
114
117
  error: string;
@@ -117,4 +120,5 @@ export declare function siteStarterPickRefusal(resolved: SiteStarterPayload | {
117
120
  }, input: {
118
121
  listingId: string;
119
122
  pagesAllowed: number;
123
+ aiStart?: boolean;
120
124
  }): SiteStarterPickRefusal | null;
@@ -194,7 +194,10 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
194
194
  * it refused, so Create site can tell a refused pick from a refused name.
195
195
  *
196
196
  * `resolved` is what the starter source answered; `pagesAllowed` is the
197
- * plan's `screensPerHost`.
197
+ * plan's `screensPerHost`. `aiStart` is whether the person creating the site
198
+ * is offered the AI start (AGL-4049 phase 4): an AI starter fills in its
199
+ * questions, so without it there is nothing to create one from, and with it
200
+ * the site is created empty for the start, whose own page band applies.
198
201
  */ export function siteStarterPickRefusal(resolved, input) {
199
202
  if (!isRecord(resolved)) {
200
203
  return {
@@ -225,10 +228,11 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
225
228
  };
226
229
  }
227
230
  if (resolved.mode === 'ai') {
231
+ if (input.aiStart === true) return null;
228
232
  return {
229
233
  status: 409,
230
234
  body: {
231
- error: 'This starter needs the AI start, which is coming soon',
235
+ error: 'This starter needs the AI start, which is not available to you in this workspace',
232
236
  listingId: input.listingId
233
237
  }
234
238
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/provision-starter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-slug'\nimport type {\n SiteStarterChoice,\n SiteStarterPayload,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport { starterLinksById } from '@aglyn/aglyn/app-utils/site-starter-links'\nimport { planSiteStarterTheme } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport {\n THEME_LIBRARY_COLLECTION,\n type ThemeLibraryEntryWrite,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport {\n FieldValue,\n type DocumentReference,\n type Transaction,\n} from 'firebase-admin/firestore'\n\n/**\n * A site created from a site starter (AGL-4049): the starter twin of the\n * default site's writes (`defaultSiteWrites` and `queueStarterPages` in the\n * console's `provision-host.ts`), written by the same create transaction.\n *\n * Every page the starter carries becomes a page of the new site, its first\n * version holding the starter's nodes; the shared layout becomes the site's\n * header and footer, and every page sits in it; the theme is planned against\n * the empty host (`planSiteStarterTheme`). A page routed in the starter is\n * routed and published on the new site, and the Home page at `/` is named\n * `defaultHomeScreenId`: the platform-made page the owner's own home page\n * replaces (AGL-3478). A page with no address, or one the starter marks\n * unpublished, is a draft.\n *\n * Nodes are copied as published. A link to another page travels by slug in\n * the starter (`site-starter-links.ts`) and becomes the new page's id here;\n * a token such as `{{host.businessName}}` renders per site on its own, so\n * nothing is substituted.\n */\n\n/** A starter resolved for a create: its payload, and the listing it came from. */\nexport interface SiteStarterInstall {\n payload: SiteStarterPayload\n /**\n * The listing it came from. `kind` is the kind of site the listing names\n * (AGL-4049), which the site records over the one its stored pages carry:\n * a listing's kind is kept current by its publisher and by staff.\n */\n listing: { listingId: string; version: string | number; displayName: string; kind?: string | null }\n}\n\n/** Every document a starter's site is born with, ids minted, ready to queue. */\nexport interface SiteStarterWrites {\n /** The Home page at `/`; `null` only for a payload that failed its check. */\n homeScreenId: string | null\n /** Every published page: screen id → slug, the host's `screens` map. */\n routing: Record<string, string>\n screens: Array<{\n id: string\n versionId: string\n screen: Record<string, unknown>\n version: Record<string, unknown>\n }>\n layout: {\n id: string\n versionId: string\n layout: Record<string, unknown>\n version: Record<string, unknown>\n }\n /** Theme fields for the host's create, from `planSiteStarterTheme`. */\n host: Record<string, unknown>\n /** Theme library entries to create under the host. */\n themeEntries: ThemeLibraryEntryWrite[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, any> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/** Nodes as a version stores them: msgpack at rest, as `/api/hosts/versions` writes them. */\nfunction storedNodes(nodes: Record<string, unknown>): unknown {\n const packed = encodeStoredNodes(nodes)\n return packed ? Buffer.from(packed) : nodes\n}\n\n/**\n * The documents a site created from `install` starts with, every id minted:\n * the pages' ids first, so each page's links and the layout's can name them.\n */\nexport function siteStarterWrites(install: SiteStarterInstall): SiteStarterWrites {\n const now = () => FieldValue.serverTimestamp()\n const payload = install.payload\n const pages = (Array.isArray(payload.screens) ? payload.screens : [])\n .filter(isRecord)\n .map((screen) => ({ screen, id: createResourceUid(), versionId: createResourceUid() }))\n const layoutId = createResourceUid()\n const layoutVersionId = createResourceUid()\n\n // Routed: a page with an address that is not marked unpublished, the\n // first to claim an address keeping it. Links resolve to routed pages\n // first, then to a draft that names an address nobody routes.\n const routing: Record<string, string> = {}\n const slugToId: Record<string, string> = {}\n const routed = new Set<string>()\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (!slug || page.screen['published'] === false || slug in slugToId) continue\n routing[page.id] = slug\n slugToId[slug] = page.id\n routed.add(page.id)\n }\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (slug && !(slug in slugToId)) slugToId[slug] = page.id\n }\n const homeScreenId =\n Object.keys(routing).find((id) => routing[id] === SCREEN_ROOT_PATH) ?? null\n\n const screens = pages.map(({ screen, id, versionId }) => {\n const isRouted = routed.has(id)\n const fields = {\n displayName: text(screen['displayName']) || 'Page',\n ...(isRouted ? { slug: routing[id] } : {}),\n versionId,\n }\n const description = text(screen['description'])\n const nodes = starterLinksById(isRecord(screen['nodes']) ? screen['nodes'] : {}, slugToId)\n return {\n id,\n versionId,\n screen: {\n ...fields,\n ...artifactCreateListKeys('screens', fields),\n layoutId,\n ...(isRecord(screen['seo']) ? { seo: screen['seo'] } : {}),\n ...(description ? { description } : {}),\n // What `publishScreenRoute` stamps, so the console lists a routed\n // page as Published rather than as a draft that happens to be served.\n ...(isRouted ? { publishedAt: now() } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n screenId: id,\n displayName: 'Initial version',\n nodes: storedNodes(nodes),\n createdAt: now(),\n updatedAt: now(),\n },\n }\n })\n\n const source = isRecord(payload.layout) ? payload.layout : {}\n const layoutFields = {\n displayName: text(source['displayName']) || 'Site header and footer',\n versionId: layoutVersionId,\n }\n const layoutDescription = text(source['description'])\n const layoutNodes = starterLinksById(isRecord(source['nodes']) ? source['nodes'] : {}, slugToId)\n const props = Array.isArray(source['props']) && source['props'].length ? source['props'] : null\n\n const theme = planSiteStarterTheme({\n theme: payload.theme,\n presets: listServerThemePresets(),\n listing: install.listing,\n newId: createResourceUid,\n })\n\n return {\n homeScreenId,\n routing,\n screens,\n layout: {\n id: layoutId,\n versionId: layoutVersionId,\n layout: {\n ...layoutFields,\n ...artifactCreateListKeys('layouts', layoutFields),\n ...(layoutDescription ? { description: layoutDescription } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n layoutId,\n displayName: 'Initial version',\n nodes: storedNodes(layoutNodes),\n // The properties the layout's tree binds to (AGL-2932), on the\n // version it is served from, as Use template writes them.\n ...(props ? { props } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n },\n host: theme.host,\n themeEntries: theme.entries,\n }\n}\n\n/**\n * Queues a starter's documents in the create transaction: every page and its\n * first version, the layout and its first version (which carries the host\n * id, as the default layout's does), and the theme library entries. An empty\n * host's theme plan creates entries and nothing else, so a create is all a\n * new site's library takes.\n */\nexport function queueSiteStarterWrites(\n tx: Transaction,\n hostRef: DocumentReference,\n hostId: string,\n writes: SiteStarterWrites,\n): void {\n for (const page of writes.screens) {\n const pageRef = hostRef.collection('screens').doc(page.id)\n tx.set(pageRef, page.screen)\n tx.set(pageRef.collection('versions').doc(page.versionId), page.version)\n }\n const layoutRef = hostRef.collection('layouts').doc(writes.layout.id)\n tx.set(layoutRef, writes.layout.layout)\n tx.set(layoutRef.collection('versions').doc(writes.layout.versionId), {\n ...writes.layout.version,\n hostId,\n })\n const library = hostRef.collection(THEME_LIBRARY_COLLECTION)\n for (const entry of writes.themeEntries) {\n if (entry.op !== 'create') continue\n tx.set(library.doc(entry.id), {\n ...(entry.data as unknown as Record<string, unknown>),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n}\n\n/** A listing id as a document id may be one: no path separator, nothing reserved. */\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\n/** A pinned version: the number of one of the listing's versions. */\nconst LISTING_VERSION = /^[1-9][0-9]{0,8}$/\n\n/**\n * A create request's starter pick (`body.starter`), or `null` when it is not\n * one: an object naming a listing id, and optionally the version it pins.\n * The id becomes a document path on the way to the listing, so anything that\n * could name another document is not a pick.\n */\nexport function readSiteStarterChoice(value: unknown): SiteStarterChoice | null {\n if (!isRecord(value)) return null\n const listingId = text(value['listingId'])\n if (!LISTING_ID.test(listingId) || /^__.*__$/.test(listingId)) return null\n const pinned = value['version']\n if (pinned === undefined || pinned === null) return { listingId }\n const version = typeof pinned === 'number' ? String(pinned) : text(pinned)\n return LISTING_VERSION.test(version) ? { listingId, version } : null\n}\n\n/** The answer a create gives a starter pick it refuses: a status and its JSON body. */\nexport interface SiteStarterPickRefusal {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Why a create refuses the starter it was asked for, or `null` when the\n * site can be created from it (AGL-4049). Every refusal is decided before the\n * site exists, so a refused pick creates nothing, and a 402 is answered with\n * what the person needs to buy it: the listing and its price. Once bought,\n * the same request again creates the site. Every refusal names the listing\n * it refused, so Create site can tell a refused pick from a refused name.\n *\n * `resolved` is what the starter source answered; `pagesAllowed` is the\n * plan's `screensPerHost`.\n */\nexport function siteStarterPickRefusal(\n resolved: SiteStarterPayload | { error: string; status: 402 | 403 | 404; priceUsd?: number },\n input: { listingId: string; pagesAllowed: number },\n): SiteStarterPickRefusal | null {\n if (!isRecord(resolved)) {\n return { status: 404, body: { error: 'That starter is no longer available', listingId: input.listingId } }\n }\n if ('error' in resolved) {\n const status = [402, 403, 404].includes(resolved.status) ? resolved.status : 404\n return {\n status,\n body: {\n error: resolved.error,\n ...(status === 402 ? { code: 'purchase_required' } : {}),\n listingId: input.listingId,\n ...(typeof resolved.priceUsd === 'number' ? { priceUsd: resolved.priceUsd } : {}),\n },\n }\n }\n if (resolved.mode === 'ai') {\n return {\n status: 409,\n body: { error: 'This starter needs the AI start, which is coming soon', listingId: input.listingId },\n }\n }\n const pages = Array.isArray(resolved.screens) ? resolved.screens.length : 0\n if (pages > input.pagesAllowed) {\n return {\n status: 403,\n body: {\n error:\n `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` +\n 'Pick a smaller starter or upgrade in Billing.',\n listingId: input.listingId,\n },\n }\n }\n return null\n}\n"],"names":["artifactCreateListKeys","createResourceUid","SCREEN_ROOT_PATH","starterLinksById","planSiteStarterTheme","encodeStoredNodes","THEME_LIBRARY_COLLECTION","listServerThemePresets","FieldValue","isRecord","value","Array","isArray","text","trim","storedNodes","nodes","packed","Buffer","from","siteStarterWrites","install","Object","now","serverTimestamp","payload","pages","screens","filter","map","screen","id","versionId","layoutId","layoutVersionId","routing","slugToId","routed","Set","page","slug","add","homeScreenId","keys","find","isRouted","has","fields","displayName","description","seo","publishedAt","createdAt","updatedAt","version","screenId","source","layout","layoutFields","layoutDescription","layoutNodes","props","length","theme","presets","listing","newId","host","themeEntries","entries","queueSiteStarterWrites","tx","hostRef","hostId","writes","pageRef","collection","doc","set","layoutRef","library","entry","op","data","LISTING_ID","LISTING_VERSION","readSiteStarterChoice","listingId","test","pinned","undefined","String","siteStarterPickRefusal","resolved","input","status","body","error","includes","code","priceUsd","mode","pagesAllowed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,qCAAoC;AAKrE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,wBAAwB,QAEnB,uCAAsC;AAC7C,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,UAAU,QAGL,2BAA0B;AAyDjC,MAAMC,WAAW,CAACC,QAChB,CAAC,CAACA,SAAS,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF;AAEzD,MAAMG,OAAO,CAACH,QACZ,OAAOA,UAAU,WAAWA,MAAMI,IAAI,KAAK;AAE7C,2FAA2F,GAC3F,SAASC,YAAYC,KAA8B;IACjD,MAAMC,SAASZ,kBAAkBW;IACjC,OAAOC,SAASC,OAAOC,IAAI,CAACF,UAAUD;AACxC;AAEA;;;CAGC,GACD,OAAO,SAASI,kBAAkBC,OAA2B;QA2BzD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AAEA,UAAUP,SAASO,QAAQ;YAAC,IAAI,CAAC;QAEnF;IACF;IACA,IAAIP,SAASQ,IAAI,KAAK,MAAM;QAC1B,OAAO;YACLN,QAAQ;YACRC,MAAM;gBAAEC,OAAO;gBAAyDV,WAAWO,MAAMP,SAAS;YAAC;QACrG;IACF;IACA,MAAM7D,QAAQf,MAAMC,OAAO,CAACiF,SAASlE,OAAO,IAAIkE,SAASlE,OAAO,CAACmC,MAAM,GAAG;IAC1E,IAAIpC,QAAQoE,MAAMQ,YAAY,EAAE;QAC9B,OAAO;YACLP,QAAQ;YACRC,MAAM;gBACJC,OACE,CAAC,iBAAiB,EAAEvE,MAAM,2BAA2B,EAAEoE,MAAMQ,YAAY,CAAC,EAAE,CAAC,GAC7E;gBACFf,WAAWO,MAAMP,SAAS;YAC5B;QACF;IACF;IACA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/provision-starter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-slug'\nimport type {\n SiteStarterChoice,\n SiteStarterPayload,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport { starterLinksById } from '@aglyn/aglyn/app-utils/site-starter-links'\nimport { planSiteStarterTheme } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport {\n THEME_LIBRARY_COLLECTION,\n type ThemeLibraryEntryWrite,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport {\n FieldValue,\n type DocumentReference,\n type Transaction,\n} from 'firebase-admin/firestore'\n\n/**\n * A site created from a site starter (AGL-4049): the starter twin of the\n * default site's writes (`defaultSiteWrites` and `queueStarterPages` in the\n * console's `provision-host.ts`), written by the same create transaction.\n *\n * Every page the starter carries becomes a page of the new site, its first\n * version holding the starter's nodes; the shared layout becomes the site's\n * header and footer, and every page sits in it; the theme is planned against\n * the empty host (`planSiteStarterTheme`). A page routed in the starter is\n * routed and published on the new site, and the Home page at `/` is named\n * `defaultHomeScreenId`: the platform-made page the owner's own home page\n * replaces (AGL-3478). A page with no address, or one the starter marks\n * unpublished, is a draft.\n *\n * Nodes are copied as published. A link to another page travels by slug in\n * the starter (`site-starter-links.ts`) and becomes the new page's id here;\n * a token such as `{{host.businessName}}` renders per site on its own, so\n * nothing is substituted.\n */\n\n/** A starter resolved for a create: its payload, and the listing it came from. */\nexport interface SiteStarterInstall {\n payload: SiteStarterPayload\n /**\n * The listing it came from. `kind` is the kind of site the listing names\n * (AGL-4049), which the site records over the one its stored pages carry:\n * a listing's kind is kept current by its publisher and by staff.\n */\n listing: { listingId: string; version: string | number; displayName: string; kind?: string | null }\n}\n\n/** Every document a starter's site is born with, ids minted, ready to queue. */\nexport interface SiteStarterWrites {\n /** The Home page at `/`; `null` only for a payload that failed its check. */\n homeScreenId: string | null\n /** Every published page: screen id → slug, the host's `screens` map. */\n routing: Record<string, string>\n screens: Array<{\n id: string\n versionId: string\n screen: Record<string, unknown>\n version: Record<string, unknown>\n }>\n layout: {\n id: string\n versionId: string\n layout: Record<string, unknown>\n version: Record<string, unknown>\n }\n /** Theme fields for the host's create, from `planSiteStarterTheme`. */\n host: Record<string, unknown>\n /** Theme library entries to create under the host. */\n themeEntries: ThemeLibraryEntryWrite[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, any> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/** Nodes as a version stores them: msgpack at rest, as `/api/hosts/versions` writes them. */\nfunction storedNodes(nodes: Record<string, unknown>): unknown {\n const packed = encodeStoredNodes(nodes)\n return packed ? Buffer.from(packed) : nodes\n}\n\n/**\n * The documents a site created from `install` starts with, every id minted:\n * the pages' ids first, so each page's links and the layout's can name them.\n */\nexport function siteStarterWrites(install: SiteStarterInstall): SiteStarterWrites {\n const now = () => FieldValue.serverTimestamp()\n const payload = install.payload\n const pages = (Array.isArray(payload.screens) ? payload.screens : [])\n .filter(isRecord)\n .map((screen) => ({ screen, id: createResourceUid(), versionId: createResourceUid() }))\n const layoutId = createResourceUid()\n const layoutVersionId = createResourceUid()\n\n // Routed: a page with an address that is not marked unpublished, the\n // first to claim an address keeping it. Links resolve to routed pages\n // first, then to a draft that names an address nobody routes.\n const routing: Record<string, string> = {}\n const slugToId: Record<string, string> = {}\n const routed = new Set<string>()\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (!slug || page.screen['published'] === false || slug in slugToId) continue\n routing[page.id] = slug\n slugToId[slug] = page.id\n routed.add(page.id)\n }\n for (const page of pages) {\n const slug = text(page.screen['slug'])\n if (slug && !(slug in slugToId)) slugToId[slug] = page.id\n }\n const homeScreenId =\n Object.keys(routing).find((id) => routing[id] === SCREEN_ROOT_PATH) ?? null\n\n const screens = pages.map(({ screen, id, versionId }) => {\n const isRouted = routed.has(id)\n const fields = {\n displayName: text(screen['displayName']) || 'Page',\n ...(isRouted ? { slug: routing[id] } : {}),\n versionId,\n }\n const description = text(screen['description'])\n const nodes = starterLinksById(isRecord(screen['nodes']) ? screen['nodes'] : {}, slugToId)\n return {\n id,\n versionId,\n screen: {\n ...fields,\n ...artifactCreateListKeys('screens', fields),\n layoutId,\n ...(isRecord(screen['seo']) ? { seo: screen['seo'] } : {}),\n ...(description ? { description } : {}),\n // What `publishScreenRoute` stamps, so the console lists a routed\n // page as Published rather than as a draft that happens to be served.\n ...(isRouted ? { publishedAt: now() } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n screenId: id,\n displayName: 'Initial version',\n nodes: storedNodes(nodes),\n createdAt: now(),\n updatedAt: now(),\n },\n }\n })\n\n const source = isRecord(payload.layout) ? payload.layout : {}\n const layoutFields = {\n displayName: text(source['displayName']) || 'Site header and footer',\n versionId: layoutVersionId,\n }\n const layoutDescription = text(source['description'])\n const layoutNodes = starterLinksById(isRecord(source['nodes']) ? source['nodes'] : {}, slugToId)\n const props = Array.isArray(source['props']) && source['props'].length ? source['props'] : null\n\n const theme = planSiteStarterTheme({\n theme: payload.theme,\n presets: listServerThemePresets(),\n listing: install.listing,\n newId: createResourceUid,\n })\n\n return {\n homeScreenId,\n routing,\n screens,\n layout: {\n id: layoutId,\n versionId: layoutVersionId,\n layout: {\n ...layoutFields,\n ...artifactCreateListKeys('layouts', layoutFields),\n ...(layoutDescription ? { description: layoutDescription } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n version: {\n layoutId,\n displayName: 'Initial version',\n nodes: storedNodes(layoutNodes),\n // The properties the layout's tree binds to (AGL-2932), on the\n // version it is served from, as Use template writes them.\n ...(props ? { props } : {}),\n createdAt: now(),\n updatedAt: now(),\n },\n },\n host: theme.host,\n themeEntries: theme.entries,\n }\n}\n\n/**\n * Queues a starter's documents in the create transaction: every page and its\n * first version, the layout and its first version (which carries the host\n * id, as the default layout's does), and the theme library entries. An empty\n * host's theme plan creates entries and nothing else, so a create is all a\n * new site's library takes.\n */\nexport function queueSiteStarterWrites(\n tx: Transaction,\n hostRef: DocumentReference,\n hostId: string,\n writes: SiteStarterWrites,\n): void {\n for (const page of writes.screens) {\n const pageRef = hostRef.collection('screens').doc(page.id)\n tx.set(pageRef, page.screen)\n tx.set(pageRef.collection('versions').doc(page.versionId), page.version)\n }\n const layoutRef = hostRef.collection('layouts').doc(writes.layout.id)\n tx.set(layoutRef, writes.layout.layout)\n tx.set(layoutRef.collection('versions').doc(writes.layout.versionId), {\n ...writes.layout.version,\n hostId,\n })\n const library = hostRef.collection(THEME_LIBRARY_COLLECTION)\n for (const entry of writes.themeEntries) {\n if (entry.op !== 'create') continue\n tx.set(library.doc(entry.id), {\n ...(entry.data as unknown as Record<string, unknown>),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n}\n\n/** A listing id as a document id may be one: no path separator, nothing reserved. */\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\n/** A pinned version: the number of one of the listing's versions. */\nconst LISTING_VERSION = /^[1-9][0-9]{0,8}$/\n\n/**\n * A create request's starter pick (`body.starter`), or `null` when it is not\n * one: an object naming a listing id, and optionally the version it pins.\n * The id becomes a document path on the way to the listing, so anything that\n * could name another document is not a pick.\n */\nexport function readSiteStarterChoice(value: unknown): SiteStarterChoice | null {\n if (!isRecord(value)) return null\n const listingId = text(value['listingId'])\n if (!LISTING_ID.test(listingId) || /^__.*__$/.test(listingId)) return null\n const pinned = value['version']\n if (pinned === undefined || pinned === null) return { listingId }\n const version = typeof pinned === 'number' ? String(pinned) : text(pinned)\n return LISTING_VERSION.test(version) ? { listingId, version } : null\n}\n\n/** The answer a create gives a starter pick it refuses: a status and its JSON body. */\nexport interface SiteStarterPickRefusal {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Why a create refuses the starter it was asked for, or `null` when the\n * site can be created from it (AGL-4049). Every refusal is decided before the\n * site exists, so a refused pick creates nothing, and a 402 is answered with\n * what the person needs to buy it: the listing and its price. Once bought,\n * the same request again creates the site. Every refusal names the listing\n * it refused, so Create site can tell a refused pick from a refused name.\n *\n * `resolved` is what the starter source answered; `pagesAllowed` is the\n * plan's `screensPerHost`. `aiStart` is whether the person creating the site\n * is offered the AI start (AGL-4049 phase 4): an AI starter fills in its\n * questions, so without it there is nothing to create one from, and with it\n * the site is created empty for the start, whose own page band applies.\n */\nexport function siteStarterPickRefusal(\n resolved: SiteStarterPayload | { error: string; status: 402 | 403 | 404; priceUsd?: number },\n input: { listingId: string; pagesAllowed: number; aiStart?: boolean },\n): SiteStarterPickRefusal | null {\n if (!isRecord(resolved)) {\n return { status: 404, body: { error: 'That starter is no longer available', listingId: input.listingId } }\n }\n if ('error' in resolved) {\n const status = [402, 403, 404].includes(resolved.status) ? resolved.status : 404\n return {\n status,\n body: {\n error: resolved.error,\n ...(status === 402 ? { code: 'purchase_required' } : {}),\n listingId: input.listingId,\n ...(typeof resolved.priceUsd === 'number' ? { priceUsd: resolved.priceUsd } : {}),\n },\n }\n }\n if (resolved.mode === 'ai') {\n if (input.aiStart === true) return null\n return {\n status: 409,\n body: {\n error: 'This starter needs the AI start, which is not available to you in this workspace',\n listingId: input.listingId,\n },\n }\n }\n const pages = Array.isArray(resolved.screens) ? resolved.screens.length : 0\n if (pages > input.pagesAllowed) {\n return {\n status: 403,\n body: {\n error:\n `This starter has ${pages} pages; your plan includes ${input.pagesAllowed}. ` +\n 'Pick a smaller starter or upgrade in Billing.',\n listingId: input.listingId,\n },\n }\n }\n return null\n}\n"],"names":["artifactCreateListKeys","createResourceUid","SCREEN_ROOT_PATH","starterLinksById","planSiteStarterTheme","encodeStoredNodes","THEME_LIBRARY_COLLECTION","listServerThemePresets","FieldValue","isRecord","value","Array","isArray","text","trim","storedNodes","nodes","packed","Buffer","from","siteStarterWrites","install","Object","now","serverTimestamp","payload","pages","screens","filter","map","screen","id","versionId","layoutId","layoutVersionId","routing","slugToId","routed","Set","page","slug","add","homeScreenId","keys","find","isRouted","has","fields","displayName","description","seo","publishedAt","createdAt","updatedAt","version","screenId","source","layout","layoutFields","layoutDescription","layoutNodes","props","length","theme","presets","listing","newId","host","themeEntries","entries","queueSiteStarterWrites","tx","hostRef","hostId","writes","pageRef","collection","doc","set","layoutRef","library","entry","op","data","LISTING_ID","LISTING_VERSION","readSiteStarterChoice","listingId","test","pinned","undefined","String","siteStarterPickRefusal","resolved","input","status","body","error","includes","code","priceUsd","mode","aiStart","pagesAllowed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,qCAAoC;AAKrE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,wBAAwB,QAEnB,uCAAsC;AAC7C,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,UAAU,QAGL,2BAA0B;AAyDjC,MAAMC,WAAW,CAACC,QAChB,CAAC,CAACA,SAAS,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF;AAEzD,MAAMG,OAAO,CAACH,QACZ,OAAOA,UAAU,WAAWA,MAAMI,IAAI,KAAK;AAE7C,2FAA2F,GAC3F,SAASC,YAAYC,KAA8B;IACjD,MAAMC,SAASZ,kBAAkBW;IACjC,OAAOC,SAASC,OAAOC,IAAI,CAACF,UAAUD;AACxC;AAEA;;;CAGC,GACD,OAAO,SAASI,kBAAkBC,OAA2B;QA2BzDC;IA1BF,MAAMC,MAAM,IAAMf,WAAWgB,eAAe;IAC5C,MAAMC,UAAUJ,QAAQI,OAAO;IAC/B,MAAMC,QAAQ,AAACf,CAAAA,MAAMC,OAAO,CAACa,QAAQE,OAAO,IAAIF,QAAQE,OAAO,GAAG,EAAE,AAAD,EAChEC,MAAM,CAACnB,UACPoB,GAAG,CAAC,CAACC,SAAY,CAAA;YAAEA;YAAQC,IAAI9B;YAAqB+B,WAAW/B;QAAoB,CAAA;IACtF,MAAMgC,WAAWhC;IACjB,MAAMiC,kBAAkBjC;IAExB,qEAAqE;IACrE,sEAAsE;IACtE,8DAA8D;IAC9D,MAAMkC,UAAkC,CAAC;IACzC,MAAMC,WA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iBAAiB,EAAEvE,MAAM,2BAA2B,EAAEoE,MAAMS,YAAY,CAAC,EAAE,CAAC,GAC7E;gBACFhB,WAAWO,MAAMP,SAAS;YAC5B;QACF;IACF;IACA,OAAO;AACT"}
@@ -17,6 +17,8 @@
17
17
  import { type ConsentGroup, type ContactFacet, type ContactInteraction, type ContactLifecycleStage, type ContactSource } from '@aglyn/aglyn/server';
18
18
  import { type PluginConversionTouch } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit';
19
19
  import { type MarketingConsentSource } from '@aglyn/aglyn/app-utils/marketing-consent';
20
+ import { type ContactCustomValue } from '@aglyn/aglyn/app-utils/crm';
21
+ import { normalizeAddress } from '@aglyn/aglyn/foundation/definitions/contact.types';
20
22
  import { getOrgForHost } from './organizations';
21
23
  /**
22
24
  * What an upsert did, for the callers that need to know (AGL-2602).
@@ -63,6 +65,40 @@ export type UpsertHostContactFacet = Partial<Pick<ContactFacet, 'phone' | 'jobTi
63
65
  * the same group the values are written to.
64
66
  */
65
67
  export type ContactProfileInput = UpsertHostContactFacet;
68
+ /**
69
+ * The profile as it may be STORED: every value normalized, every unusable
70
+ * one dropped, and nothing present that was not given.
71
+ *
72
+ * Only the keys given come back, which is what lets a merge write this
73
+ * straight into the facet: a door that knows the phone number and nothing
74
+ * else leaves the title, the owner and the stage exactly as another door
75
+ * left them. An address given as `null` is a deliberate clearing and is kept
76
+ * as `null`; one that normalizes to nothing is the same thing.
77
+ */
78
+ export declare function storableProfile(input: ContactProfileInput | undefined): {
79
+ phone?: string;
80
+ jobTitle?: string;
81
+ leadSource?: string;
82
+ address?: ReturnType<typeof normalizeAddress>;
83
+ companyId?: string;
84
+ companyName?: string;
85
+ ownerUid?: string;
86
+ lifecycleStage?: ContactFacet['lifecycleStage'];
87
+ custom?: Record<string, ContactCustomValue>;
88
+ salutation?: string;
89
+ firstName?: string;
90
+ lastName?: string;
91
+ department?: string;
92
+ mobilePhone?: string;
93
+ homePhone?: string;
94
+ otherPhone?: string;
95
+ fax?: string;
96
+ birthdate?: string;
97
+ assistantName?: string;
98
+ assistantPhone?: string;
99
+ otherAddress?: ReturnType<typeof normalizeAddress>;
100
+ doNotCall?: true;
101
+ };
66
102
  /**
67
103
  * Contacts ingestion (AGL-197): upserts an org-scoped contact doc (AGL-237)
68
104
  * keyed by normalized email from any capture point (forms, membership,
@@ -44,7 +44,7 @@ import { consentGroupForSite, getOrgForHost, orgDataCollectionForHost } from "./
44
44
  * else leaves the title, the owner and the stage exactly as another door
45
45
  * left them. An address given as `null` is a deliberate clearing and is kept
46
46
  * as `null`; one that normalizes to nothing is the same thing.
47
- */ function storableProfile(input) {
47
+ */ export function storableProfile(input) {
48
48
  if (!input) return {};
49
49
  const out = {};
50
50
  /*
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upsert-contact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynPostalAddress,\n CAPTURED_BY_HOST_FIELD,\n checkCrmRecordsQuota,\n composeContactName,\n CONTACT_EXTRA_PHONE_FIELDS,\n type ConsentGroup,\n consentGroupScope,\n crmDefaultScopeOf,\n CONTACT_FACETS_FIELD,\n CONTACT_FORM_IDS_CAP,\n CONTACT_FORM_IDS_FIELD,\n type ContactFacet,\n type ContactInteraction,\n type ContactLifecycleStage,\n type ContactSource,\n marketingConsentFieldsForGroup,\n mergeContactInteraction,\n normalizeContactBirthdate,\n normalizeContainerIds,\n readContactFacet,\n normalizeContactEmail,\n ORG_SCOPE_TOKEN,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { firebaseAdmin } from './firebase-admin'\nimport { countCrmRecords, restampCrmListFieldsAt } from './crm-records'\nimport { hostErasedEmails, hostRefusesCaptureForErasure } from './email-suppression'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport {\n creditConversion,\n creditOrderConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\nimport {\n declineMarketingConsentFields,\n MARKETING_CONSENT_SOURCE_FIELD,\n type MarketingConsentSource,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\n/*\n * The module paths, like `name-search` above, rather than the barrel: the\n * pure helpers this door leans on are exactly the ones a spec of the door\n * substitutes a fixture barrel for, and a fixture that has to re-export the\n * whole of `@aglyn/aglyn` to keep a normalizer reachable is a fixture that\n * drifts. A direct path is real in every harness.\n */\nimport {\n advanceContactLifecycleStage,\n CONTACT_COMPANY_IDS_FIELD,\n CONTACT_FIELD_KEY_PATTERN,\n type ContactCustomValue,\n CRM_COLLECTIONS,\n crmNewRecordListFields,\n isContactLifecycleStage,\n planContactCompanyLink,\n readContactCompanyLink,\n} from '@aglyn/aglyn/app-utils/crm'\nimport {\n normalizeAddress,\n normalizePhone,\n} from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport {\n contactCompanyMirrorValue,\n settleCompanyContactsCounts,\n} from './contact-company-link'\nimport {\n emailIndexBeside,\n findContactByEmail,\n findContactsByEmail,\n writeContactEmailIndex,\n} from './contact-email-index'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n} from './organizations'\n\n/**\n * What an upsert did, for the callers that need to know (AGL-2602).\n *\n * The capture doors never look: a form submission or an order must succeed\n * whatever happened to the CRM record, which is why this function swallows\n * its own errors and why every existing caller `await`s it for its side\n * effect alone. An IMPORT is the caller that has to know, row by row —\n * \"created\" and \"merged\" are its two headline numbers, and a row the\n * audience band refused has to be handed back to the operator as a row\n * rather than becoming one more tick on a counter nobody reconciles against\n * a file. A verdict is returned rather than thrown so the swallowing stays:\n * `refused: 'error'` is the same silence the doors have always had, now with\n * a name.\n */\nexport type UpsertHostContactVerdict =\n | {\n contactId: string\n /** True when this call created the row; false when it merged into one. */\n created: boolean\n }\n | {\n /**\n * `erased`: the site holds an erasure row for the address (AGL-2623),\n * so no record is created — a capture must not quietly rebuild a\n * person the workspace erased. Only a CREATE is refused; a merge\n * cannot arise, because the erasure removed the row it would merge\n * into.\n */\n refused: 'invalid-email' | 'band' | 'erased' | 'error'\n }\n\n/**\n * The per-holder profile fields a door may write alongside the identity.\n *\n * `Pick`ed from the facet rather than typed afresh so the two cannot drift:\n * a field the facet grows is a field this option may carry the moment the\n * pick names it, and one it does not name is refused at compile time.\n */\nexport type UpsertHostContactFacet = Partial<\n Pick<\n ContactFacet,\n | 'phone'\n | 'jobTitle'\n | 'leadSource'\n | 'companyId'\n | 'companyName'\n | 'address'\n | 'ownerUid'\n | 'lifecycleStage'\n | 'custom'\n // Salesforce's standard contact fields (AGL-3515) a door may know —\n // the reports-to is not one: it names another record, and only the\n // profile route can check that the holder sees it.\n | 'salutation'\n | 'firstName'\n | 'lastName'\n | 'department'\n | 'mobilePhone'\n | 'homePhone'\n | 'otherPhone'\n | 'fax'\n | 'birthdate'\n | 'assistantName'\n | 'assistantPhone'\n | 'otherAddress'\n | 'doNotCall'\n >\n>\n\n/**\n * The profile fields a door may hand this function (AGL-2596): the parts of\n * a person's record that no capture surface collects — the console's create\n * drawer and the import do, and the order door adds the stage. `custom` is\n * the holder's own field values, keyed by `ContactFieldDefinition.key`; the\n * import maps spreadsheet columns onto them, and the definitions live under\n * the same group the values are written to.\n */\nexport type ContactProfileInput = UpsertHostContactFacet\n\n/**\n * The profile as it may be STORED: every value normalized, every unusable\n * one dropped, and nothing present that was not given.\n *\n * Only the keys given come back, which is what lets a merge write this\n * straight into the facet: a door that knows the phone number and nothing\n * else leaves the title, the owner and the stage exactly as another door\n * left them. An address given as `null` is a deliberate clearing and is kept\n * as `null`; one that normalizes to nothing is the same thing.\n */\nfunction storableProfile(input: ContactProfileInput | undefined): {\n phone?: string\n jobTitle?: string\n leadSource?: string\n address?: ReturnType<typeof normalizeAddress>\n companyId?: string\n companyName?: string\n ownerUid?: string\n lifecycleStage?: ContactFacet['lifecycleStage']\n custom?: Record<string, ContactCustomValue>\n salutation?: string\n firstName?: string\n lastName?: string\n department?: string\n mobilePhone?: string\n homePhone?: string\n otherPhone?: string\n fax?: string\n birthdate?: string\n assistantName?: string\n assistantPhone?: string\n otherAddress?: ReturnType<typeof normalizeAddress>\n doNotCall?: true\n} {\n if (!input) return {}\n const out: ReturnType<typeof storableProfile> = {}\n /*\n * Salesforce's standard contact fields (AGL-3515), under the same rule as\n * the rest: given keys only, each normalized, an unusable value dropped.\n * The salutation is judged against the org's list by the door that took\n * it and held here to the label's shape, like the lead source. Do not\n * call is written only as `true`: a door may learn that a person asked\n * not to be phoned, and no capture is the person taking it back.\n */\n if (typeof input.salutation === 'string') {\n const salutation = input.salutation.trim().replace(/\\s+/g, ' ').slice(0, 120)\n if (salutation) out.salutation = salutation\n }\n if (input.firstName !== undefined) {\n const firstName = composeContactName(input.firstName, '')\n if (firstName) out.firstName = firstName\n }\n if (input.lastName !== undefined) {\n const lastName = composeContactName('', input.lastName)\n if (lastName) out.lastName = lastName\n }\n for (const key of ['department', 'assistantName'] as const) {\n if (typeof input[key] !== 'string') continue\n const value = (input[key] as string).trim().slice(0, 120)\n if (value) out[key] = value\n }\n for (const key of CONTACT_EXTRA_PHONE_FIELDS) {\n if (input[key] === undefined) continue\n const phone = normalizePhone(input[key])\n if (phone) out[key] = phone\n }\n if (input.birthdate !== undefined) {\n const birthdate = normalizeContactBirthdate(input.birthdate)\n if (birthdate) out.birthdate = birthdate\n }\n if (input.otherAddress !== undefined) out.otherAddress = normalizeAddress(input.otherAddress)\n if (input.doNotCall === true) out.doNotCall = true\n if (input.phone !== undefined) {\n const phone = normalizePhone(input.phone)\n if (phone) out.phone = phone\n }\n if (typeof input.jobTitle === 'string') {\n const jobTitle = input.jobTitle.trim().slice(0, 120)\n if (jobTitle) out.jobTitle = jobTitle\n }\n // The lead's value, carried on conversion (AGL-3298). Judged against the\n // org's list by the door that took it; held here to the label's shape.\n if (typeof input.leadSource === 'string') {\n const leadSource = input.leadSource.trim().replace(/\\s+/g, ' ').slice(0, 120)\n if (leadSource) out.leadSource = leadSource\n }\n if (input.address !== undefined) out.address = normalizeAddress(input.address)\n if (typeof input.companyId === 'string' && input.companyId.trim()) {\n out.companyId = input.companyId.trim().slice(0, 128)\n }\n // The name as this holder knows it, beside the link — the merge fields\n // read `facet.companyName`, and a link with no name renders as nothing.\n if (typeof input.companyName === 'string' && input.companyName.trim()) {\n out.companyName = input.companyName.trim().slice(0, 120)\n }\n if (typeof input.ownerUid === 'string' && input.ownerUid.trim()) {\n out.ownerUid = input.ownerUid.trim().slice(0, 128)\n }\n if (isContactLifecycleStage(input.lifecycleStage)) {\n out.lifecycleStage = input.lifecycleStage\n }\n if (input.custom && typeof input.custom === 'object') {\n /*\n * Only a key a field definition could have, and only a value the field\n * types can hold. A nested object here is a map the merge below would\n * write as a subtree nobody can render; a key with a dot in it would be\n * read as a PATH by the next dotted update to touch the facet. Nothing is\n * coerced — a door that has a number should send one — and an empty map\n * is left off rather than written as `{}` over a holder's values.\n */\n const custom: Record<string, ContactCustomValue> = {}\n for (const [key, value] of Object.entries(input.custom)) {\n if (!CONTACT_FIELD_KEY_PATTERN.test(key)) continue\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n custom[key] = typeof value === 'string' ? value.slice(0, 2000) : value\n }\n }\n if (Object.keys(custom).length) out.custom = custom\n }\n return out\n}\n\n/**\n * A door's {@link UpsertHostContactOptions.facetFill}, folded into the\n * profile it is about to write: each field only where neither the door's\n * own profile nor the holder's stored facet holds one.\n */\nfunction fillProfile(\n profile: ReturnType<typeof storableProfile>,\n fill: UpsertHostContactOptions['facetFill'],\n stored: { phone?: unknown } | null,\n): void {\n const given = storableProfile(fill)\n if (given.phone && !profile.phone && !String(stored?.phone ?? '').trim()) {\n profile.phone = given.phone\n }\n}\n\n/**\n * The org's companies collection, beside its contacts one.\n *\n * Reached through the contacts reference's parent — the org document —\n * because that is the one handle this function holds on the org. `parent`\n * is `null` only for a root collection, which an org subcollection never\n * is; answered as `null` rather than thrown so a count that has nowhere to\n * land is skipped, and never costs the capture.\n */\nfunction companiesBeside(\n contactsRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.CollectionReference | null {\n const parent = contactsRef.parent\n return parent ? parent.collection(CRM_COLLECTIONS.companies) : null\n}\n\n/**\n * Tags as the profile drawer stores them: trimmed, lowercased, deduplicated\n * and capped at twenty — so an imported `VIP` and a typed `vip` are one tag.\n */\nfunction normalizeTags(tags: readonly string[] | undefined): string[] {\n return [\n ...new Set(\n (tags ?? [])\n .map((tag) => String(tag ?? '').trim().toLowerCase())\n .filter(Boolean),\n ),\n ].slice(0, 20)\n}\n\n/**\n * Contacts ingestion (AGL-197): upserts an org-scoped contact doc (AGL-237)\n * keyed by normalized email from any capture point (forms, membership,\n * orders, bookings). Fire-and-forget by design — callers should never\n * fail their primary write because contact capture had a problem.\n *\n * Quota (AGL-890): contacts are audience BANDS, not hard caps. Paid plans\n * always create — contacts past the included band meter onto the monthly\n * invoice (report-usage cron). Free hard-bands at the included count:\n * only there do dropped creations increment `counters/contactsDropped`,\n * surfaced as a console alert (AGL-891). Interactions on existing\n * contacts always append regardless of plan.\n */\n/**\n * What a capture door learns when its capture made a NEW person.\n *\n * Handed to {@link UpsertHostContactOptions.onCreated} once, on the create\n * branch only. The merge branch is a visit by somebody the org already held,\n * which is another interaction and not a new contact — the same line\n * `conversionTouch` draws for attribution. Scalars and one string array, so\n * the runtime can flatten it into an event payload without inventing keys.\n */\nexport interface HostContactCreated {\n contactId: string\n hostId: string\n email: string\n name?: string\n source: ContactSource\n /** The capture surface's campaigns, normalized — `[]` when it had none. */\n campaignIds: string[]\n /**\n * The stage the create wrote onto the capturing facet — the door's\n * {@link UpsertHostContactOptions.initialLifecycleStage}, or the profile's\n * own — and absent when the capture named none, so an automation can\n * filter `lifecycleStage == \"lead\"` on the day the person appears.\n */\n lifecycleStage?: ContactLifecycleStage\n}\n\nexport interface UpsertHostContactOptions {\n hostId: string\n email: unknown\n name?: string\n source: ContactSource\n interaction: Omit<ContactInteraction, 'type' | 'atMs'> & { atMs?: number }\n /**\n * Explicit marketing opt-in (AGL-301) with a consent timestamp, recorded\n * against {@link hostId} — the brand whose form carried the checkbox — and\n * against the rest of its consent group only as far as\n * {@link disclosedConsentGroup} proves the group was shown.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` of the sentence the capture surface\n * rendered beside the checkbox (AGL-3320), as the surface sent it back.\n *\n * The grant pools across the site's consent group only when this is the\n * group's CURRENT key; absent, stale or mistyped, it is recorded for\n * {@link hostId} alone. Every surface that renders no disclosure passes\n * none, so its grant is one site's however the org is grouped. Only the\n * grant narrows: the record's `visibleTo` and its holder are the group's\n * either way, because who may see a person is not who may mail them.\n */\n disclosedConsentGroup?: string | null\n /**\n * An explicit REFUSAL, recorded against {@link hostId} (AGL-3185).\n *\n * Its own flag rather than `marketingConsent: false`, because every door\n * that passes a checkbox's value passes `false` for a box left alone, and\n * a box left alone records nothing — absence is the third state, and\n * turning it into a refusal would silently make every unticked visitor\n * unmailable. A door sets this only for an act of refusal: a switch turned\n * off, a prompt answered no. Ignored when {@link marketingConsent} is true.\n */\n declineMarketingConsent?: boolean\n /**\n * The provenance stored on the consent entry {@link marketingConsent} or\n * {@link declineMarketingConsent} writes (AGL-3185): who recorded it, which\n * door, which wording version. The console doors pass the person's own\n * (`actor: 'person'`); a site's capture surface passes none, which the\n * reader takes as the person's own act anyway.\n */\n marketingConsentSource?: MarketingConsentSource\n /**\n * Order value in cents — rolls into RFM fields (AGL-328).\n *\n * WHAT IT COUNTS (AGL-1748). GROSS of the platform fee and GROSS of\n * refunds — the money the customer handed over, not the money the merchant\n * kept. Every writer passes the same thing: whatever was actually charged\n * (`amount_total` for a Stripe path, `totals.totalCents` for POS), never a\n * figure re-derived from product docs, which is the AGL-1698/AGL-1711\n * lesson. Gross of the fee because this is a CUSTOMER attribute answering\n * \"what is this person worth to me?\", and the fee is a cost of the channel,\n * not something the buyer failed to spend.\n *\n * Refunds are still NOT netted here, and now they are recorded elsewhere\n * (AGL-1754). `refund.ts` writes `refundedCents`, `refundedOrdersCount` and\n * `lastRefundAtMs` BESIDE these fields — the shape AGL-1747 chose for the\n * same question on the orders CSV — rather than decrementing a stored number\n * whose meaning would then differ between rows written before and after that\n * commit. So `ltvCents` and `ordersCount` remain gross by definition, and a\n * READER that wants the net computes `ltvCents - refundedCents`, clamping\n * only what it ranks on: the difference can be negative for a customer whose\n * pre-AGL-1748 purchase was never counted and whose refund was, which is a\n * missing purchase showing itself rather than a corrupt contact. AGL-1753 is\n * the backfill that reconciles it. See `contact-refund.ts` in the commerce\n * plugin for the full reasoning and for why a refund never CREATES a contact.\n *\n * Passing 0 or omitting it means \"no purchase\": `ltvCents`, `ordersCount`,\n * `lastPurchaseAtMs` and `firstPurchaseAtMs` are all left untouched, which\n * is why a caller that formats the amount into the interaction summary and\n * forgets this field records a customer who has apparently never bought\n * anything.\n */\n purchaseCents?: number\n /**\n * The currency {@link purchaseCents} is in, lowercase, when the door knows.\n *\n * Absent everywhere today, because no order document carries a currency and\n * every checkout door writes `currency: 'usd'` onto the Stripe line items.\n * The plugin that credits orders defaults it on that basis and says so. The field\n * exists so a door that ever charges in something else can pass it, and the\n * campaign revenue report keeps it in its own bucket rather than adding it\n * to the dollars.\n */\n purchaseCurrency?: string\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * ⛔ The ORDER path passes none, and must not start. An order already has\n * its own credit one branch below — `creditOrderConversion`, keyed on the\n * order id — and a second record for the same sale would be the same money\n * counted twice under two rules. This is the door for the moments an order\n * does NOT cover: a form submission, a membership sign-up, a booking, a\n * newsletter capture.\n *\n * Resolved rather than raw, for the reason `addHostLead` states: one\n * visitor action reaches several writers and the touch lookup is paid once.\n */\n conversionTouch?: PluginConversionTouch | null\n /**\n * The campaigns the CAPTURE SURFACE is filed under.\n *\n * ⚠️ A different fact from {@link conversionTouch} beside it, and the two must\n * never be folded together. A touch is where the visitor came FROM — an ad,\n * a link, a browser-supplied label resolved through an allowlist. This is\n * which campaigns the merchant put the form itself in, which is the\n * merchant's own act and is true of everybody who fills that form in,\n * including the visitor who arrived by typing the address.\n *\n * ⛔ And it is not consent. Filing a form under a campaign says nothing\n * about what the person agreed to; `marketingConsent` above is the only\n * input that records a basis.\n */\n campaignIds?: readonly string[]\n /**\n * Tags to put on THIS holder's facet (AGL-2602).\n *\n * Added to, never replaced, on a merge: a person the merchant tagged by\n * hand and later imported keeps the hand-written tag beside the file's.\n */\n tags?: readonly string[]\n /**\n * The profile a door knows about the person — phone, title, company,\n * address, owner, stage, custom values — written into THIS holder's facet\n * (AGL-2602). Only the keys present are written, so a door that knows the\n * phone and nothing else does not blank the title somebody typed.\n */\n facet?: UpsertHostContactFacet\n /**\n * Profile fields written only where THIS holder's facet has none\n * (AGL-3493) — what a door learned in passing, like the phone a booking\n * form asked for, which must not replace a number somebody typed on the\n * record. A key {@link facet} also carries is `facet`'s to write.\n */\n facetFill?: Pick<UpsertHostContactFacet, 'phone'>\n /**\n * The EARLIEST stage that describes what this capture was (AGL-2612).\n *\n * Every door names one: a form submission is a `lead`, a newsletter opt-in\n * or a member sign-up is a `subscriber`, a purchase — an order, a paid\n * booking — is a `customer`. The rule applied to it is\n * `advanceContactLifecycleStage`: it fills an empty stage and advances an\n * earlier one, and never moves anybody back, so a customer who fills in\n * the contact form is still a customer and a subscriber who then submits\n * a form becomes a lead. Applied on top of `facet.lifecycleStage` when a\n * door carries both — the caller's stage is the base and this is its\n * floor.\n *\n * A FLOOR and not a value, which is why it is not the facet field: the\n * facet's `lifecycleStage` is a SET, the shape the console's create\n * drawer and the import need — the merchant typed a stage and that is the\n * stage — and a capture door writing a set would put every returning\n * customer back to `lead` on their next enquiry. Omitted by the doors\n * that carry the caller's own stage or none (manual, import, API, a lead\n * conversion), whose contacts read as \"no stage\", which is true.\n */\n initialLifecycleStage?: ContactLifecycleStage\n /**\n * Told when this capture created a contact (AGL-2605).\n *\n * A HOOK rather than an event emitted from here, and the reason is the\n * dependency direction: the event fan-out lives in `libs/tenant/runtime`,\n * which imports THIS library for its Firestore handle and its org helpers.\n * An import back up from here would be a cycle, and the module boundaries\n * (`scope:data` may depend on data and util only) refuse it besides. So\n * this module reports the fact and the runtime's `captureHostContact`\n * turns it into `contactCreated` — every server door goes through that\n * wrapper, and a door that calls this function directly has chosen to\n * create contacts nothing can react to.\n *\n * Awaited with its own catch, like the order join above: the least\n * important write on the path, and a failure in it must not cost the\n * capture that already happened.\n */\n onCreated?: (created: HostContactCreated) => void | Promise<void>\n /**\n * The lookups of a whole file, read once (AGL-3423) — see\n * {@link prepareContactCaptureBatch}.\n *\n * A door capturing many addresses at once prepares one batch and hands it\n * to every capture; each one then takes the site, the group, the person\n * the address already is, the erasure and the band from it instead of\n * reading them. Every decision below is made by the same lines either way.\n * A batch prepared for another site is ignored.\n */\n batch?: ContactCaptureBatch\n}\n\nexport async function upsertHostContact(\n options: UpsertHostContactOptions,\n): Promise<UpsertHostContactVerdict> {\n try {\n const email = normalizeContactEmail(options.email)\n if (!email) return { refused: 'invalid-email' }\n const tags = normalizeTags(options.tags)\n\n /*==========================================\n * THE PURCHASE DOOR, AND THEREFORE THE ATTRIBUTION DOOR.\n *\n * Every way of buying something in this product — the cart, buy-now, the\n * POS register, a draft order, a reservation, a subscription renewal, a\n * booking — announces itself here, in exactly one shape: source `order`,\n * a `purchaseCents` amount, and a `refId` naming what was bought. That\n * shape IS the purchase chokepoint, which is why the revenue join hangs\n * off it rather than off seven call sites in a webhook.\n *\n * ABOVE the audience-band gate below, and deliberately. Contact creation\n * is band gated, so a Free org past its included count drops the CRM\n * record — and an attribution written inside that branch would drop the\n * revenue with it. The join keys on the address hash, exactly as the\n * touch and the suppression list do, so it never needs a contact document\n * to exist: a guest checkout by somebody who is not and never becomes a\n * contact still credits the campaign whose link they clicked.\n *\n * Its own `catch`, inside a function that already swallows: this is the\n * least important write on the path, and a failure here must not cost the\n * contact capture below it.\n *=========================================*/\n if (options.source === 'order' && options.interaction.refId) {\n await creditOrderConversion({\n hostId: options.hostId,\n orderId: String(options.interaction.refId),\n email,\n amountCents: Number(options.purchaseCents ?? 0),\n ...(options.purchaseCurrency\n ? { currency: options.purchaseCurrency }\n : {}),\n orderedAtMs: options.interaction.atMs ?? Date.now(),\n }).catch(() => null)\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(options.hostId)\n const batch =\n options.batch?.hostId === options.hostId ? options.batch : undefined\n // Contacts are org-scoped (AGL-237): every host in the org feeds one\n // shared list.\n const contactsRef: FirebaseFirestore.CollectionReference =\n batch?.contactsRef ??\n (await orgDataCollectionForHost(options.hostId, 'contacts'))\n /*\n * The consent group this capture belongs to — the sites declared to be\n * one sender, or this site alone. Resolved once and used for three\n * different decisions below, which must all agree: which controller the\n * basis is recorded for, which sites the row becomes visible to, and\n * which holder the profile is filed under.\n */\n const group = batch?.group ?? (await consentGroupForSite(options.hostId))\n /*\n * THE CONSENT ENTRY THIS CAPTURE WRITES, decided once for both branches.\n *\n * A grant outranks a refusal flag set beside it — one door cannot mean\n * both — and neither writes anything when the door carried no act, so\n * an unticked box stays the third state. The provenance rides inside the\n * per-host entry, where the reader looks for it, never at the top of a\n * document every brand in the org shares.\n *\n * The grant covers the group only when the capture surface proved it\n * showed the group's current disclosure — `consentGroupForGrant` answers\n * the site alone for every other capture. The visibility and the holder\n * below keep the whole group.\n */\n const consentExtra = options.marketingConsentSource\n ? { [MARKETING_CONSENT_SOURCE_FIELD]: options.marketingConsentSource }\n : undefined\n const consentFields = options.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, options.disclosedConsentGroup),\n Date.now(),\n consentExtra,\n )\n : options.declineMarketingConsent\n ? declineMarketingConsentFields(options.hostId, Date.now(), consentExtra)\n : {}\n const interaction: ContactInteraction = {\n type: options.source,\n atMs: options.interaction.atMs ?? Date.now(),\n // WHICH SITE this visit happened on. The row is shared; the history on\n // it is not, and a timeline with no site cannot be split for an\n // agency's client without showing them another client's activity.\n hostId: options.hostId,\n ...(options.interaction.refId\n ? { refId: options.interaction.refId }\n : {}),\n ...(options.interaction.summary\n ? { summary: options.interaction.summary.slice(0, 200) }\n : {}),\n // The entry point, when the door knows it. Written only when present:\n // an absent field is a door that has none, and Firestore rejects\n // `undefined` inside an array element outright.\n ...(options.interaction.formId\n ? { formId: String(options.interaction.formId).slice(0, 128) }\n : {}),\n ...(options.interaction.path\n ? { path: String(options.interaction.path).slice(0, 500) }\n : {}),\n }\n\n /*\n * THE CAMPAIGNS THIS CAPTURE FILES THE PERSON UNDER.\n *\n * Normalized here rather than trusted, because it reaches this function\n * from a public endpoint's document read and every reader of the stored\n * array goes through the same coercion.\n */\n const campaignIds = normalizeContainerIds(options.campaignIds ?? [])\n /*\n * THE CUSTOM FIELD VALUES THIS CAPTURE CARRIES, as one nested map.\n *\n * Only the keys the door resolved. Written in the NESTED form because both\n * writes below are merge-sets, which deep-merge a map one key at a time:\n * `custom: { tier: 'Gold' }` lands beside an existing `custom.vip` and\n * leaves it standing. A dotted `facets.h1.custom.tier` path would be a\n * literal field name to a `set`, and a `custom` written whole would take\n * every other key with it.\n */\n const customEntries = Object.entries(options.facet?.custom ?? {})\n const customFacet = customEntries.length\n ? { custom: Object.fromEntries(customEntries) }\n : {}\n\n /*==========================================\n * THE DEDUPE LOOKUP IS UNSCOPED, AND HAS TO BE.\n *\n * One human who touched two sites is ONE person. Narrowing this read to\n * what the capturing site may already see would make a second submission\n * on a sibling brand create a SECOND document for the same address —\n * which loses the dedupe the shared address book exists for, and bills\n * the org twice for one human.\n *\n * Recognizing somebody is not the same act as being allowed to read their\n * row, and the two were the same query while every contact was stamped\n * org-wide. They are separated here: this finds the person, and\n * `visibleTo` below decides who may see them — widened by the capture\n * that just happened, never by the lookup that found them.\n *\n * THROUGH THE ADDRESS INDEX FIRST (AGL-2625). A person whose two records\n * were merged answers to two addresses, and only one of them is the\n * document's `email`; the index is what lets a capture on the other one\n * land on the survivor instead of minting the duplicate again. The query\n * stays as the fallback, so a row the index has not seen costs one extra\n * read once and needs no backfill.\n *=========================================*/\n const prefetched = batch?.claim(email)\n const docSnapshot =\n prefetched !== undefined\n ? prefetched\n : await findContactByEmail(contactsRef, email)\n\n if (docSnapshot) {\n /*\n * MERGED INTO THIS GROUP'S FACET, not into the top of the document.\n *\n * `sources`, `interactions`, the tags, the notes and every commercial\n * figure are the HOLDER's own business records: a booking taken by one\n * client of an agency is that client's, and while these lived at the\n * top of a shared row every other client could read them. The identity\n * — the address, and a canonical name for a holder that has set none of\n * its own — stays shared, because that is what makes this one row.\n */\n const facet = readContactFacet(\n docSnapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const merged = mergeContactInteraction(\n {\n name: facet.name ?? undefined,\n sources: facet.sources,\n interactions: facet.interactions,\n },\n { source: options.source, interaction, name: options.name },\n )\n /*\n * THE PROFILE, as this door knows it (AGL-2596).\n *\n * Given keys only, so the merge below leaves untouched whatever another\n * door wrote. The stage is the one field with a rule of its own: the\n * door's `initialLifecycleStage` fills an empty stage and advances an\n * earlier one, and never moves anybody back —\n * `advanceContactLifecycleStage` is that rule, applied to the stage\n * this door asked for outright or, failing that, the one already\n * stored. Written only when it comes back with something: a door that\n * named no stage and found none leaves the key absent, which reads as\n * \"no stage\" rather than as a stage somebody picked.\n */\n const profile = storableProfile(options.facet)\n fillProfile(profile, options.facetFill, facet)\n /*\n * THE NAME FOLLOWS THE FIRST AND LAST NAMES (AGL-3515): a door that\n * carried either writes the holder's name as their composition, over\n * the name the facet held — the parts are the newer, structured\n * statement of the same thing. A door that carried neither leaves the\n * name to the rule above, where the existing name wins.\n */\n const composedName =\n profile.firstName !== undefined || profile.lastName !== undefined\n ? composeContactName(\n profile.firstName ?? facet.firstName,\n profile.lastName ?? facet.lastName,\n )\n : ''\n const facetName = composedName || merged.name\n const advanced = advanceContactLifecycleStage(\n profile.lifecycleStage ?? facet.lifecycleStage,\n options.initialLifecycleStage,\n )\n if (advanced) profile.lifecycleStage = advanced\n /*\n * THE FORM MIRROR, bounded (see `HostContact.formIds`).\n *\n * Read off the document the lookup already fetched, so the bound costs\n * no extra read: a person who has come in through twenty forms keeps\n * the twenty, and this capture's form stays on the interaction alone.\n * `arrayUnion` for the add, so a concurrent capture on a sibling site\n * cannot drop this one's id.\n */\n const heldFormIds: unknown[] = Array.isArray(\n docSnapshot.get(CONTACT_FORM_IDS_FIELD),\n )\n ? docSnapshot.get(CONTACT_FORM_IDS_FIELD)\n : []\n const formIdToAdd =\n interaction.formId &&\n !heldFormIds.includes(interaction.formId) &&\n heldFormIds.length < CONTACT_FORM_IDS_CAP\n ? interaction.formId\n : null\n /*\n * THE COMPANY LINK, when the door carried one (AGL-2613).\n *\n * The facet's `companyId` is written with the rest of the profile\n * below, but the facet is not the whole association: the top-level\n * `companyIds` mirror is what the company page queries, and the\n * company's `contactsCount` is what the companies list shows. The\n * planner reads the row as it stands — this holder's previous link,\n * the mirror, the other holders' ids — and says what the mirror\n * becomes and which counts move; the mirror change rides in this same\n * merge-set, and the counts settle after it.\n */\n const link =\n profile.companyId !== undefined\n ? planContactCompanyLink(\n readContactCompanyLink(\n docSnapshot.data() as Record<string, unknown>,\n group.groupId,\n ),\n profile.companyId,\n )\n : null\n const mirror = link ? contactCompanyMirrorValue(link) : undefined\n await docSnapshot.ref.set(\n {\n // The search keys travel WITH the name, and only when the name is\n // written: stamping an empty key over a real one would make the\n // contact unfindable by the name it still displays.\n ...(facetName ? nameSearchFields(facetName) : {}),\n // The search echo of the facet's phone — see `HostContact.phone`.\n ...(profile.phone ? { phone: profile.phone } : {}),\n // The search echo of the facet's company name — see `HostContact.companyName`.\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n ...(mirror !== undefined ? { [CONTACT_COMPANY_IDS_FIELD]: mirror } : {}),\n /*\n * NESTED, not dot-pathed. This is a `set(…, { merge: true })`, and\n * a merge-set treats a key containing dots as a literal field name\n * — only `update()` reads them as paths. The nested form is what\n * Firestore deep-merges, so this writes one holder's facet and\n * leaves every other holder's untouched.\n */\n [CONTACT_FACETS_FIELD]: {\n [group.groupId]: {\n sources: merged.sources,\n interactions: merged.interactions,\n ...(facetName ? { name: facetName } : {}),\n /*\n * ADDED TO, never replaced. A person who filled in the spring\n * form and later the summer one is in both pushes, and an\n * assignment that overwrote would take a campaign a merchant\n * filed them under back out with nothing on screen to say so —\n * the reason `container-membership.ts` made the field an array\n * and the automation step has always used `arrayUnion`.\n *\n * Nested under the group id rather than written at\n * `contactContainerFieldPath`, because this is a merge-`set`: a\n * `set` treats a dotted string as a literal field NAME and would\n * mint a top-level key with dots in it. Only `update()` reads\n * dots as a path. The nested form is what Firestore deep-merges,\n * so it reaches one holder's facet and leaves every other\n * holder's alone — the same guarantee the dotted path gives the\n * automation step, in the shape this write is allowed to take.\n */\n ...(campaignIds.length\n ? { campaignIds: FieldValue.arrayUnion(...campaignIds) }\n : {}),\n // The same union rule as the campaigns above it, for the same\n // reason: a tag the merchant put on by hand survives the file.\n ...(tags.length ? { tags: FieldValue.arrayUnion(...tags) } : {}),\n // Present keys only, deep-merged by the merge-set — so the\n // fields this door did not carry keep whatever they held.\n ...profile,\n ...(options.purchaseCents\n ? {\n ltvCents: FieldValue.increment(options.purchaseCents),\n ordersCount: FieldValue.increment(1),\n lastPurchaseAtMs: Date.now(),\n // A contact that EXISTED before their first purchase\n // reached this branch, and it never wrote\n // `firstPurchaseAtMs` — only the create path did. So\n // every converted lead permanently lacked RFM's R anchor\n // while walk-in buyers carried it. Set it on the first\n // purchase only; later purchases must not move it.\n ...(facet.firstPurchaseAtMs\n ? {}\n : { firstPurchaseAtMs: Date.now() }),\n }\n : {}),\n },\n },\n /*\n * ATTRIBUTION GROWS ON THE MERGE BRANCH, which the create-only\n * `hostId` beside it never did — so a person the first site\n * captured and the second site later met read as the first site's\n * alone, forever.\n *\n * `arrayUnion`, so the audience filter \"everyone captured on A, B\n * or C\" answers with the sites that actually met this person.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(options.hostId),\n ...(formIdToAdd\n ? { [CONTACT_FORM_IDS_FIELD]: FieldValue.arrayUnion(formIdToAdd) }\n : {}),\n /*\n * AND SO DOES VISIBILITY — by the capture, never by the lookup.\n *\n * This site just collected this person: it has its own relationship\n * with them and may see the row. A site that has never captured\n * them gains nothing here, which is what keeps an agency's clients\n * apart on a document all of them share. The per-interaction\n * `hostId` above is what keeps the HISTORY apart on the same row.\n */\n visibleTo: FieldValue.arrayUnion(...consentGroupScope(group)),\n /*\n * RECORDED AGAINST THE CAPTURING SITE, not against the org.\n *\n * The contact document is shared by every site in the org, which is\n * the point of it — one address book behind many brands. Its\n * consent is not shared on the same terms: the checkbox this\n * capture carried was ticked under one brand's name, on one brand's\n * form, and a basis written at the top of this document made the\n * person mailable by every other brand the account holds.\n *\n * A merge writes one key of the map and leaves the rest, so a\n * person who opts in to a second site accumulates two grants rather\n * than replacing the first.\n */\n ...consentFields,\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n await settleCompanyContactsCounts(companiesBeside(contactsRef), link)\n // The merged facet, name and scope are what the Contacts list\n // searches and filters by (AGL-3321): restamped from the stored row.\n await restampCrmListFieldsAt(docSnapshot.ref, 'contacts')\n // The address's domain, checked after the response (AGL-3328).\n scheduleCapturedEmailCheck({\n orgId: contactsRef.parent?.id ?? null,\n hostId: options.hostId,\n email,\n predicted: docSnapshot.get('emailStatus') === 'undeliverable',\n })\n return { contactId: docSnapshot.id, created: false }\n }\n\n /*\n * THE ERASED PERSON DOES NOT COME BACK (AGL-2623).\n *\n * Before the band, on the CREATE branch only — the one read this adds\n * is paid by a capture that would otherwise make a new row, never by\n * the merge above. An erasure wrote a row on this site's suppression\n * list with no address on it; finding that row here is what keeps the\n * next form fill or checkout from rebuilding the record the workspace\n * just erased. The order or booking that triggered the capture still\n * succeeds, exactly as it does when the band refuses: the person bought\n * something, and the merchant's record of the sale is not the CRM's\n * record of the person.\n */\n if (\n batch?.erased(email) ??\n (await hostRefusesCaptureForErasure(options.hostId, email, firestore))\n ) {\n return { refused: 'erased' }\n }\n\n // New contact: records-band check via the aggregate counts (cheap; no\n // doc reads) against the owning org's entitlements (AGL-238/890).\n // Metered plans always pass (overage bills via the report-usage\n // cron); only free's hard band drops the CRM record — visibly, via\n // the counter and the console alert (AGL-891). The signup/order that\n // triggered the capture always succeeds either way.\n //\n // THE RECORDS BAND, not the contacts headcount (AGL-2611): companies\n // and deals share this band, so a capture is refused on a Free org\n // whose hundred records are ninety companies and ten people — the same\n // verdict the company drawer would give the ninety-first company.\n // `contactsRef` is handed in so the contacts aggregate is the one this\n // door already reads; the org reference is its parent.\n //\n // A batch counted once and keeps the tally, in call order, so each of\n // its creates is admitted exactly as it would be here one at a time.\n const orgBilling = batch\n ? batch.orgBilling\n : await getOrgForHost(options.hostId)\n const admitted = batch\n ? batch.admitCreate(email)\n : await (async () => {\n const orgRef =\n contactsRef.parent ??\n firestore.collection('orgs').doc(String(orgBilling?.orgId ?? ''))\n const { crmRecordsCount } = await countCrmRecords(orgRef, contactsRef)\n return checkCrmRecordsQuota(\n (orgBilling?.org as any) ?? null,\n crmRecordsCount,\n ).allowed\n })()\n if (!admitted) {\n await hostRef\n .collection('counters')\n .doc('contactsDropped')\n .set({ total: FieldValue.increment(1) }, { merge: true })\n return { refused: 'band' }\n }\n\n /*\n * The profile on a create, with the door's stage floor applied the same\n * way as on a merge — there is no stored stage yet, so the floor is what\n * a door that named one writes. A `null` address is dropped rather than\n * written: there is nothing on a new document for it to clear.\n */\n const profile = storableProfile(options.facet)\n // A new person holds nothing yet, so the fill is written whole.\n fillProfile(profile, options.facetFill, null)\n const advanced = advanceContactLifecycleStage(\n profile.lifecycleStage,\n options.initialLifecycleStage,\n )\n if (advanced) profile.lifecycleStage = advanced\n if (profile.address === null) delete profile.address\n if (profile.otherAddress === null) delete profile.otherAddress\n // The holder's name is the first and last names' when the door gave\n // either (AGL-3515); the canonical name is the one the door gave, or\n // that composition for a door that gave only the parts.\n const composedName = composeContactName(profile.firstName, profile.lastName)\n const canonicalName = (options.name || composedName).slice(0, 120)\n const holderName = (composedName || options.name || '').slice(0, 120)\n\n const record: Record<string, unknown> = {\n hostId: options.hostId,\n /*\n * WHICH SITES HAVE MET THIS PERSON — attribution, and separate from\n * consent above.\n *\n * The scalar `hostId` beside it names the FIRST capturing site and is\n * never rewritten, which is provenance for the ROW. This array is the\n * one that grows and the one an audience query can filter on.\n */\n [CAPTURED_BY_HOST_FIELD]: [options.hostId],\n // The form mirror's first entry, when this capture came through one —\n // see `HostContact.formIds`. Absent otherwise, like the campaigns.\n ...(interaction.formId\n ? { [CONTACT_FORM_IDS_FIELD]: [interaction.formId] }\n : {}),\n /*\n * THE CAPTURING GROUP, not the whole org.\n *\n * Stamping `['org']` here made every contact readable by every site in\n * the account on the day it was created — so an agency's twelve clients\n * shared one address book by default, and closing the missing-field\n * fail-open would not have touched it, because the field was present\n * and said so.\n *\n * A group of one — the default — is this site alone. A declared group\n * is the sites that already present as one sender. Widening beyond that\n * is available and is an ACT: an org may set its CRM default\n * (`crmDefaultScopeOf`) to `'org'`, or a later capture on a sibling\n * site unions that site in.\n */\n visibleTo:\n crmDefaultScopeOf(\n orgBilling?.org as Record<string, unknown> | null | undefined,\n ) === 'org'\n ? [ORG_SCOPE_TOKEN]\n : consentGroupScope(group),\n email,\n ...(canonicalName ? nameSearchFields(canonicalName) : {}),\n // The search echo of the facet's phone — see `HostContact.phone`.\n ...(profile.phone ? { phone: profile.phone } : {}),\n // The search echo of the facet's company name — see `HostContact.companyName`.\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n // The company mirror the company page queries (AGL-2613) — a create\n // has nothing to union with, so the door's company is the whole list.\n ...(profile.companyId\n ? { [CONTACT_COMPANY_IDS_FIELD]: [profile.companyId] }\n : {}),\n // The facet this capture creates. Everything a holder owns lives under\n // its own group id; the address and the canonical name above are the\n // only shared identity.\n [CONTACT_FACETS_FIELD]: {\n [group.groupId]: {\n sources: { [options.source]: true },\n interactions: [interaction],\n tags,\n // A create has nothing to union with, so the normalized list is the\n // whole membership.\n ...(campaignIds.length ? { campaignIds } : {}),\n ...customFacet,\n ...(holderName ? { name: holderName } : {}),\n ...profile,\n ...(options.purchaseCents\n ? {\n ltvCents: options.purchaseCents,\n ordersCount: 1,\n lastPurchaseAtMs: Date.now(),\n firstPurchaseAtMs: Date.now(),\n }\n : {}),\n },\n },\n ...consentFields,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await contactsRef.add({\n ...record,\n // What the Contacts list searches and filters by (AGL-3321), from the\n // row as written — and nothing scheduled against a new person.\n ...crmNewRecordListFields('contacts', record),\n })\n // The address now resolves to this row (AGL-2625). Its own catch inside\n // the writer, so an index the capture could not reach costs nothing.\n await writeContactEmailIndex(emailIndexBeside(contactsRef), created.id, [email])\n // The company the door named now has one more contact naming it\n // (AGL-2613) — the fresh row's plan is the trivial one, nothing held\n // before and nothing held elsewhere.\n if (profile.companyId) {\n await settleCompanyContactsCounts(\n companiesBeside(contactsRef),\n planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n profile.companyId,\n ),\n )\n }\n /*\n * ATTRIBUTED ON CREATION ONLY, and therefore below the band gate rather\n * than above it — the opposite placement to the order join at the top of\n * this function, deliberately.\n *\n * The order join sits above because it credits MONEY, which is real\n * whether or not a CRM record was kept for the buyer, and a Free org past\n * its included band would otherwise silently drop the revenue with the\n * contact. This credits a contact, which does not exist when the band\n * dropped it: attributing one above the gate would report a campaign as\n * having produced people the customer cannot see anywhere in the console.\n *\n * The existing-contact branch above returns without reaching here, which\n * is the same rule `addHostLead` applies — an interaction appended to\n * somebody the site already held is another visit, not a new person, and\n * crediting it would let the most recent campaign re-earn the whole list.\n */\n if (options.conversionTouch) {\n await creditConversion({\n hostId: options.hostId,\n kind: 'contact',\n refId: created.id,\n touch: options.conversionTouch,\n convertedAtMs: interaction.atMs,\n })\n }\n /*\n * REPORTED ON CREATION ONLY, below the band gate for the reason the\n * attribution above is: a contact the band dropped does not exist, and\n * an automation told about it would act on a person the console cannot\n * show. The merge branch returned long before this line, so a repeat\n * visit by somebody already held is never announced as a new contact.\n */\n if (options.onCreated) {\n await Promise.resolve(\n options.onCreated({\n contactId: created.id,\n hostId: options.hostId,\n email,\n ...(holderName ? { name: holderName } : {}),\n source: options.source,\n campaignIds,\n ...(profile.lifecycleStage\n ? { lifecycleStage: profile.lifecycleStage }\n : {}),\n }),\n ).catch((error) => {\n console.error('upsertHostContact onCreated failed', error)\n })\n }\n // A new person's address, checked after the response (AGL-3328): a\n // domain that takes no mail reads \"Would bounce\" on the record.\n scheduleCapturedEmailCheck({\n orgId: contactsRef.parent?.id ?? null,\n hostId: options.hostId,\n email,\n })\n return { contactId: created.id, created: true }\n } catch (error) {\n console.error('upsertHostContact failed', error)\n return { refused: 'error' }\n }\n}\n\n/*\n * THE LOOKUPS OF MANY CAPTURES, PAID ONCE (AGL-3423).\n *\n * `upsertHostContact` is the one writer of the contacts collection, and for\n * a single capture it resolves everything it decides with on its own: the\n * site's org and consent group, the person the address already belongs to,\n * whether the site erased them, and how full the records band is. For a\n * form submission that is a handful of reads. For a file it was the same\n * handful again for every row, serially — a two-hundred-row chunk of an\n * Apollo export was thousands of round trips and three aggregate counts per\n * new person, and the request ran into the function's sixty seconds before\n * it could answer.\n *\n * A batch is those answers for every address in a request, read in a\n * number of round trips that does not grow with the file. The door is\n * handed it as {@link UpsertHostContactOptions.batch} and consults it in\n * place of each per-capture read; every decision is still the door's own,\n * made by the same code, so an import cannot drift into a second writer\n * with its own ideas about dedupe, consent, scope or the band.\n *\n * ## What a batch answers, and what it leaves to the door\n *\n * - **Who the address already is.** {@link findContactsByEmail} — the index\n * and the `email` query, for every address at once. `claim` hands an\n * address's answer out ONCE: a second capture of the same address in the\n * same batch is asked live, so a create earlier in the batch is found\n * rather than minted twice.\n * - **Whether the site erased them.** {@link hostErasedEmails}, one read.\n * - **Room in the records band.** One count, then a running tally in call\n * order, so N creates admit exactly as N serial door calls would. A\n * caller that creates OTHER records against the same band — the import's\n * companies — spends from the same tally with {@link ContactCaptureBatch.admit},\n * and may {@link ContactCaptureBatch.reserve} an address's room at its\n * place in the file, so the order in which rows are later written does\n * not decide which of them the band keeps.\n *\n * Any answer a batch does not have — a page of the lookup that failed, an\n * address it was not prepared with — is `undefined`, and the door reads for\n * itself exactly as it does without a batch.\n */\n\n/** The resolved answers a batch of captures on one site share. */\nexport interface ContactCaptureBatch {\n /** The site every capture in the batch is on; a door for another site ignores the batch. */\n readonly hostId: string\n readonly contactsRef: FirebaseFirestore.CollectionReference\n readonly group: ConsentGroup\n readonly orgBilling: Awaited<ReturnType<typeof getOrgForHost>>\n /**\n * What an address resolved to when the batch was prepared, without\n * spending it: the record, `null` for nobody, `undefined` for not known.\n */\n peek(email: string): FirebaseFirestore.DocumentSnapshot | null | undefined\n /**\n * The same answer, handed out once. Every later claim of the address is\n * `undefined`, so its door looks it up live.\n */\n claim(email: string): FirebaseFirestore.DocumentSnapshot | null | undefined\n /** Whether the site erased the address; `undefined` when the read failed. */\n erased(email: string): boolean | undefined\n /** Takes room for one more record in the band, now. False when the band refuses. */\n admit(): boolean\n /** Takes the address's room now, at its place in the caller's order. */\n reserve(email: string): boolean\n /** The door's question: the reserved answer when there is one, else {@link admit}. */\n admitCreate(email: string): boolean\n}\n\n/**\n * Reads, once, what every capture of `emails` on `hostId` would read for\n * itself. Throws only when the site or the band cannot be read at all —\n * the reads every capture would fail on — so a caller answers the request\n * rather than refusing every row one at a time.\n */\nexport async function prepareContactCaptureBatch(\n hostId: string,\n emails: readonly unknown[],\n): Promise<ContactCaptureBatch> {\n const firestore = firebaseAdmin.app().firestore()\n const [contactsRef, orgBilling] = await Promise.all([\n orgDataCollectionForHost(hostId, 'contacts'),\n getOrgForHost(hostId),\n ])\n const group = await consentGroupForSite(\n hostId,\n (orgBilling?.org as Record<string, unknown> | undefined) ?? null,\n )\n const orgRef =\n contactsRef.parent ??\n firestore.collection('orgs').doc(String(orgBilling?.orgId ?? ''))\n const addresses = [\n ...new Set(\n emails\n .map((email) => normalizeContactEmail(email))\n .filter((email): email is string => !!email),\n ),\n ]\n const [existing, erased, counted] = await Promise.all([\n findContactsByEmail(contactsRef, addresses),\n hostErasedEmails(hostId, addresses, firestore),\n countCrmRecords(orgRef, contactsRef),\n ])\n\n const org = (orgBilling?.org as never) ?? null\n let used = counted.crmRecordsCount\n const claimed = new Set<string>()\n const tickets = new Map<string, boolean>()\n const admit = (): boolean => {\n if (!checkCrmRecordsQuota(org, used).allowed) return false\n used += 1\n return true\n }\n\n return {\n hostId,\n contactsRef,\n group,\n orgBilling,\n peek: (email) => existing.get(email),\n claim: (email) => {\n if (claimed.has(email)) return undefined\n claimed.add(email)\n return existing.get(email)\n },\n erased: (email) => (erased ? erased.has(email) : undefined),\n admit,\n reserve: (email) => {\n const ticket = tickets.get(email)\n if (ticket !== undefined) return ticket\n const admitted = admit()\n tickets.set(email, admitted)\n return admitted\n },\n admitCreate: (email) => {\n const ticket = tickets.get(email)\n if (ticket === undefined) return admit()\n tickets.delete(email)\n return ticket\n },\n }\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkCrmRecordsQuota","composeContactName","CONTACT_EXTRA_PHONE_FIELDS","consentGroupScope","crmDefaultScopeOf","CONTACT_FACETS_FIELD","CONTACT_FORM_IDS_CAP","CONTACT_FORM_IDS_FIELD","marketingConsentFieldsForGroup","mergeContactInteraction","normalizeContactBirthdate","normalizeContainerIds","readContactFacet","normalizeContactEmail","ORG_SCOPE_TOKEN","FieldValue","firebaseAdmin","countCrmRecords","restampCrmListFieldsAt","hostErasedEmails","hostRefusesCaptureForErasure","scheduleCapturedEmailCheck","creditConversion","creditOrderConversion","nameSearchFields","consentGroupForGrant","declineMarketingConsentFields","MARKETING_CONSENT_SOURCE_FIELD","advanceContactLifecycleStage","CONTACT_COMPANY_IDS_FIELD","CONTACT_FIELD_KEY_PATTERN","CRM_COLLECTIONS","crmNewRecordListFields","isContactLifecycleStage","planContactCompanyLink","readContactCompanyLink","normalizeAddress","normalizePhone","contactCompanyMirrorValue","settleCompanyContactsCounts","emailIndexBeside","findContactByEmail","findContactsByEmail","writeContactEmailIndex","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","storableProfile","input","out","salutation","trim","replace","slice","firstName","undefined","lastName","key","value","phone","birthdate","otherAddress","doNotCall","jobTitle","leadSource","address","companyId","companyName","ownerUid","lifecycleStage","custom","Object","entries","test","keys","length","fillProfile","profile","fill","stored","given","String","companiesBeside","contactsRef","parent","collection","companies","normalizeTags","tags","Set","map","tag","toLowerCase","filter","Boolean","upsertHostContact","options","email","refused","source","interaction","refId","hostId","orderId","amountCents","Number","purchaseCents","purchaseCurrency","currency","orderedAtMs","atMs","Date","now","catch","firestore","app","hostRef","doc","batch","group","consentExtra","marketingConsentSource","consentFields","marketingConsent","disclosedConsentGroup","declineMarketingConsent","type","summary","formId","path","campaignIds","customEntries","facet","customFacet","fromEntries","prefetched","claim","docSnapshot","data","groupId","merged","name","sources","interactions","facetFill","composedName","facetName","advanced","initialLifecycleStage","heldFormIds","Array","isArray","get","formIdToAdd","includes","link","mirror","ref","set","arrayUnion","ltvCents","increment","ordersCount","lastPurchaseAtMs","firstPurchaseAtMs","visibleTo","updatedAt","serverTimestamp","merge","orgId","id","predicted","contactId","created","erased","orgBilling","admitted","admitCreate","orgRef","crmRecordsCount","org","allowed","total","canonicalName","holderName","record","createdAt","add","companyIds","heldElsewhere","conversionTouch","kind","touch","convertedAtMs","onCreated","Promise","resolve","error","console","prepareContactCaptureBatch","emails","all","addresses","existing","counted","used","claimed","tickets","Map","admit","peek","has","reserve","ticket","delete"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,sBAAsB,EACtBC,oBAAoB,EACpBC,kBAAkB,EAClBC,0BAA0B,EAE1BC,iBAAiB,EACjBC,iBAAiB,EACjBC,oBAAoB,EACpBC,oBAAoB,EACpBC,sBAAsB,EAKtBC,8BAA8B,EAC9BC,uBAAuB,EACvBC,yBAAyB,EACzBC,qBAAqB,EACrBC,gBAAgB,EAChBC,qBAAqB,EACrBC,eAAe,QACV,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,eAAe,EAAEC,sBAAsB,QAAQ,mBAAe;AACvE,SAASC,gBAAgB,EAAEC,4BAA4B,QAAQ,yBAAqB;AACpF,SAASC,0BAA0B,QAAQ,2BAAuB;AAClE,SACEC,gBAAgB,EAChBC,qBAAqB,QAEhB,uDAAsD;AAC7D,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,oBAAoB,QAAQ,wCAAuC;AAC5E,SACEC,6BAA6B,EAC7BC,8BAA8B,QAEzB,2CAA0C;AACjD;;;;;;CAMC,GACD,SACEC,4BAA4B,EAC5BC,yBAAyB,EACzBC,yBAAyB,EAEzBC,eAAe,EACfC,sBAAsB,EACtBC,uBAAuB,EACvBC,sBAAsB,EACtBC,sBAAsB,QACjB,6BAA4B;AACnC,SACEC,gBAAgB,EAChBC,cAAc,QACT,oDAAmD;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,QACtB,4BAAwB;AAC/B,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,EACnBC,sBAAsB,QACjB,2BAAuB;AAC9B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,QACnB,qBAAiB;AAiFxB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AAM2B,UAAU,IAAIrH;IACpB,MAAMsH,UAAU,IAAIC;IACpB,MAAMC,QAAQ;QACZ,IAAI,CAACjN,qBAAqBoL,KAAKyB,MAAMxB,OAAO,EAAE,OAAO;QACrDwB,QAAQ;QACR,OAAO;IACT;IAEA,OAAO;QACLvG;QACAnB;QACAoC;QACAwD;QACAmC,MAAM,CAACjH,QAAU0G,SAASnD,GAAG,CAACvD;QAC9BuC,OAAO,CAACvC;YACN,IAAI6G,QAAQK,GAAG,CAAClH,QAAQ,OAAO1C;YAC/BuJ,QAAQnB,GAAG,CAAC1F;YACZ,OAAO0G,SAASnD,GAAG,CAACvD;QACtB;QACA6E,QAAQ,CAAC7E,QAAW6E,SAASA,OAAOqC,GAAG,CAAClH,SAAS1C;QACjD0J;QACAG,SAAS,CAACnH;YACR,MAAMoH,SAASN,QAAQvD,GAAG,CAACvD;YAC3B,IAAIoH,WAAW9J,WAAW,OAAO8J;YACjC,MAAMrC,WAAWiC;YACjBF,QAAQjD,GAAG,CAAC7D,OAAO+E;YACnB,OAAOA;QACT;QACAC,aAAa,CAAChF;YACZ,MAAMoH,SAASN,QAAQvD,GAAG,CAACvD;YAC3B,IAAIoH,WAAW9J,WAAW,OAAO0J;YACjCF,QAAQO,MAAM,CAACrH;YACf,OAAOoH;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upsert-contact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynPostalAddress,\n CAPTURED_BY_HOST_FIELD,\n checkCrmRecordsQuota,\n composeContactName,\n CONTACT_EXTRA_PHONE_FIELDS,\n type ConsentGroup,\n consentGroupScope,\n crmDefaultScopeOf,\n CONTACT_FACETS_FIELD,\n CONTACT_FORM_IDS_CAP,\n CONTACT_FORM_IDS_FIELD,\n type ContactFacet,\n type ContactInteraction,\n type ContactLifecycleStage,\n type ContactSource,\n marketingConsentFieldsForGroup,\n mergeContactInteraction,\n normalizeContactBirthdate,\n normalizeContainerIds,\n readContactFacet,\n normalizeContactEmail,\n ORG_SCOPE_TOKEN,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { firebaseAdmin } from './firebase-admin'\nimport { countCrmRecords, restampCrmListFieldsAt } from './crm-records'\nimport { hostErasedEmails, hostRefusesCaptureForErasure } from './email-suppression'\nimport { scheduleCapturedEmailCheck } from './capture-email-check'\nimport {\n creditConversion,\n creditOrderConversion,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport { consentGroupForGrant } from '@aglyn/aglyn/app-utils/consent-groups'\nimport {\n declineMarketingConsentFields,\n MARKETING_CONSENT_SOURCE_FIELD,\n type MarketingConsentSource,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\n/*\n * The module paths, like `name-search` above, rather than the barrel: the\n * pure helpers this door leans on are exactly the ones a spec of the door\n * substitutes a fixture barrel for, and a fixture that has to re-export the\n * whole of `@aglyn/aglyn` to keep a normalizer reachable is a fixture that\n * drifts. A direct path is real in every harness.\n */\nimport {\n advanceContactLifecycleStage,\n CONTACT_COMPANY_IDS_FIELD,\n CONTACT_FIELD_KEY_PATTERN,\n type ContactCustomValue,\n CRM_COLLECTIONS,\n crmNewRecordListFields,\n isContactLifecycleStage,\n planContactCompanyLink,\n readContactCompanyLink,\n} from '@aglyn/aglyn/app-utils/crm'\nimport {\n normalizeAddress,\n normalizePhone,\n} from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport {\n contactCompanyMirrorValue,\n settleCompanyContactsCounts,\n} from './contact-company-link'\nimport {\n emailIndexBeside,\n findContactByEmail,\n findContactsByEmail,\n writeContactEmailIndex,\n} from './contact-email-index'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n} from './organizations'\n\n/**\n * What an upsert did, for the callers that need to know (AGL-2602).\n *\n * The capture doors never look: a form submission or an order must succeed\n * whatever happened to the CRM record, which is why this function swallows\n * its own errors and why every existing caller `await`s it for its side\n * effect alone. An IMPORT is the caller that has to know, row by row —\n * \"created\" and \"merged\" are its two headline numbers, and a row the\n * audience band refused has to be handed back to the operator as a row\n * rather than becoming one more tick on a counter nobody reconciles against\n * a file. A verdict is returned rather than thrown so the swallowing stays:\n * `refused: 'error'` is the same silence the doors have always had, now with\n * a name.\n */\nexport type UpsertHostContactVerdict =\n | {\n contactId: string\n /** True when this call created the row; false when it merged into one. */\n created: boolean\n }\n | {\n /**\n * `erased`: the site holds an erasure row for the address (AGL-2623),\n * so no record is created — a capture must not quietly rebuild a\n * person the workspace erased. Only a CREATE is refused; a merge\n * cannot arise, because the erasure removed the row it would merge\n * into.\n */\n refused: 'invalid-email' | 'band' | 'erased' | 'error'\n }\n\n/**\n * The per-holder profile fields a door may write alongside the identity.\n *\n * `Pick`ed from the facet rather than typed afresh so the two cannot drift:\n * a field the facet grows is a field this option may carry the moment the\n * pick names it, and one it does not name is refused at compile time.\n */\nexport type UpsertHostContactFacet = Partial<\n Pick<\n ContactFacet,\n | 'phone'\n | 'jobTitle'\n | 'leadSource'\n | 'companyId'\n | 'companyName'\n | 'address'\n | 'ownerUid'\n | 'lifecycleStage'\n | 'custom'\n // Salesforce's standard contact fields (AGL-3515) a door may know —\n // the reports-to is not one: it names another record, and only the\n // profile route can check that the holder sees it.\n | 'salutation'\n | 'firstName'\n | 'lastName'\n | 'department'\n | 'mobilePhone'\n | 'homePhone'\n | 'otherPhone'\n | 'fax'\n | 'birthdate'\n | 'assistantName'\n | 'assistantPhone'\n | 'otherAddress'\n | 'doNotCall'\n >\n>\n\n/**\n * The profile fields a door may hand this function (AGL-2596): the parts of\n * a person's record that no capture surface collects — the console's create\n * drawer and the import do, and the order door adds the stage. `custom` is\n * the holder's own field values, keyed by `ContactFieldDefinition.key`; the\n * import maps spreadsheet columns onto them, and the definitions live under\n * the same group the values are written to.\n */\nexport type ContactProfileInput = UpsertHostContactFacet\n\n/**\n * The profile as it may be STORED: every value normalized, every unusable\n * one dropped, and nothing present that was not given.\n *\n * Only the keys given come back, which is what lets a merge write this\n * straight into the facet: a door that knows the phone number and nothing\n * else leaves the title, the owner and the stage exactly as another door\n * left them. An address given as `null` is a deliberate clearing and is kept\n * as `null`; one that normalizes to nothing is the same thing.\n */\nexport function storableProfile(input: ContactProfileInput | undefined): {\n phone?: string\n jobTitle?: string\n leadSource?: string\n address?: ReturnType<typeof normalizeAddress>\n companyId?: string\n companyName?: string\n ownerUid?: string\n lifecycleStage?: ContactFacet['lifecycleStage']\n custom?: Record<string, ContactCustomValue>\n salutation?: string\n firstName?: string\n lastName?: string\n department?: string\n mobilePhone?: string\n homePhone?: string\n otherPhone?: string\n fax?: string\n birthdate?: string\n assistantName?: string\n assistantPhone?: string\n otherAddress?: ReturnType<typeof normalizeAddress>\n doNotCall?: true\n} {\n if (!input) return {}\n const out: ReturnType<typeof storableProfile> = {}\n /*\n * Salesforce's standard contact fields (AGL-3515), under the same rule as\n * the rest: given keys only, each normalized, an unusable value dropped.\n * The salutation is judged against the org's list by the door that took\n * it and held here to the label's shape, like the lead source. Do not\n * call is written only as `true`: a door may learn that a person asked\n * not to be phoned, and no capture is the person taking it back.\n */\n if (typeof input.salutation === 'string') {\n const salutation = input.salutation.trim().replace(/\\s+/g, ' ').slice(0, 120)\n if (salutation) out.salutation = salutation\n }\n if (input.firstName !== undefined) {\n const firstName = composeContactName(input.firstName, '')\n if (firstName) out.firstName = firstName\n }\n if (input.lastName !== undefined) {\n const lastName = composeContactName('', input.lastName)\n if (lastName) out.lastName = lastName\n }\n for (const key of ['department', 'assistantName'] as const) {\n if (typeof input[key] !== 'string') continue\n const value = (input[key] as string).trim().slice(0, 120)\n if (value) out[key] = value\n }\n for (const key of CONTACT_EXTRA_PHONE_FIELDS) {\n if (input[key] === undefined) continue\n const phone = normalizePhone(input[key])\n if (phone) out[key] = phone\n }\n if (input.birthdate !== undefined) {\n const birthdate = normalizeContactBirthdate(input.birthdate)\n if (birthdate) out.birthdate = birthdate\n }\n if (input.otherAddress !== undefined) out.otherAddress = normalizeAddress(input.otherAddress)\n if (input.doNotCall === true) out.doNotCall = true\n if (input.phone !== undefined) {\n const phone = normalizePhone(input.phone)\n if (phone) out.phone = phone\n }\n if (typeof input.jobTitle === 'string') {\n const jobTitle = input.jobTitle.trim().slice(0, 120)\n if (jobTitle) out.jobTitle = jobTitle\n }\n // The lead's value, carried on conversion (AGL-3298). Judged against the\n // org's list by the door that took it; held here to the label's shape.\n if (typeof input.leadSource === 'string') {\n const leadSource = input.leadSource.trim().replace(/\\s+/g, ' ').slice(0, 120)\n if (leadSource) out.leadSource = leadSource\n }\n if (input.address !== undefined) out.address = normalizeAddress(input.address)\n if (typeof input.companyId === 'string' && input.companyId.trim()) {\n out.companyId = input.companyId.trim().slice(0, 128)\n }\n // The name as this holder knows it, beside the link — the merge fields\n // read `facet.companyName`, and a link with no name renders as nothing.\n if (typeof input.companyName === 'string' && input.companyName.trim()) {\n out.companyName = input.companyName.trim().slice(0, 120)\n }\n if (typeof input.ownerUid === 'string' && input.ownerUid.trim()) {\n out.ownerUid = input.ownerUid.trim().slice(0, 128)\n }\n if (isContactLifecycleStage(input.lifecycleStage)) {\n out.lifecycleStage = input.lifecycleStage\n }\n if (input.custom && typeof input.custom === 'object') {\n /*\n * Only a key a field definition could have, and only a value the field\n * types can hold. A nested object here is a map the merge below would\n * write as a subtree nobody can render; a key with a dot in it would be\n * read as a PATH by the next dotted update to touch the facet. Nothing is\n * coerced — a door that has a number should send one — and an empty map\n * is left off rather than written as `{}` over a holder's values.\n */\n const custom: Record<string, ContactCustomValue> = {}\n for (const [key, value] of Object.entries(input.custom)) {\n if (!CONTACT_FIELD_KEY_PATTERN.test(key)) continue\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n custom[key] = typeof value === 'string' ? value.slice(0, 2000) : value\n }\n }\n if (Object.keys(custom).length) out.custom = custom\n }\n return out\n}\n\n/**\n * A door's {@link UpsertHostContactOptions.facetFill}, folded into the\n * profile it is about to write: each field only where neither the door's\n * own profile nor the holder's stored facet holds one.\n */\nfunction fillProfile(\n profile: ReturnType<typeof storableProfile>,\n fill: UpsertHostContactOptions['facetFill'],\n stored: { phone?: unknown } | null,\n): void {\n const given = storableProfile(fill)\n if (given.phone && !profile.phone && !String(stored?.phone ?? '').trim()) {\n profile.phone = given.phone\n }\n}\n\n/**\n * The org's companies collection, beside its contacts one.\n *\n * Reached through the contacts reference's parent — the org document —\n * because that is the one handle this function holds on the org. `parent`\n * is `null` only for a root collection, which an org subcollection never\n * is; answered as `null` rather than thrown so a count that has nowhere to\n * land is skipped, and never costs the capture.\n */\nfunction companiesBeside(\n contactsRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.CollectionReference | null {\n const parent = contactsRef.parent\n return parent ? parent.collection(CRM_COLLECTIONS.companies) : null\n}\n\n/**\n * Tags as the profile drawer stores them: trimmed, lowercased, deduplicated\n * and capped at twenty — so an imported `VIP` and a typed `vip` are one tag.\n */\nfunction normalizeTags(tags: readonly string[] | undefined): string[] {\n return [\n ...new Set(\n (tags ?? [])\n .map((tag) => String(tag ?? '').trim().toLowerCase())\n .filter(Boolean),\n ),\n ].slice(0, 20)\n}\n\n/**\n * Contacts ingestion (AGL-197): upserts an org-scoped contact doc (AGL-237)\n * keyed by normalized email from any capture point (forms, membership,\n * orders, bookings). Fire-and-forget by design — callers should never\n * fail their primary write because contact capture had a problem.\n *\n * Quota (AGL-890): contacts are audience BANDS, not hard caps. Paid plans\n * always create — contacts past the included band meter onto the monthly\n * invoice (report-usage cron). Free hard-bands at the included count:\n * only there do dropped creations increment `counters/contactsDropped`,\n * surfaced as a console alert (AGL-891). Interactions on existing\n * contacts always append regardless of plan.\n */\n/**\n * What a capture door learns when its capture made a NEW person.\n *\n * Handed to {@link UpsertHostContactOptions.onCreated} once, on the create\n * branch only. The merge branch is a visit by somebody the org already held,\n * which is another interaction and not a new contact — the same line\n * `conversionTouch` draws for attribution. Scalars and one string array, so\n * the runtime can flatten it into an event payload without inventing keys.\n */\nexport interface HostContactCreated {\n contactId: string\n hostId: string\n email: string\n name?: string\n source: ContactSource\n /** The capture surface's campaigns, normalized — `[]` when it had none. */\n campaignIds: string[]\n /**\n * The stage the create wrote onto the capturing facet — the door's\n * {@link UpsertHostContactOptions.initialLifecycleStage}, or the profile's\n * own — and absent when the capture named none, so an automation can\n * filter `lifecycleStage == \"lead\"` on the day the person appears.\n */\n lifecycleStage?: ContactLifecycleStage\n}\n\nexport interface UpsertHostContactOptions {\n hostId: string\n email: unknown\n name?: string\n source: ContactSource\n interaction: Omit<ContactInteraction, 'type' | 'atMs'> & { atMs?: number }\n /**\n * Explicit marketing opt-in (AGL-301) with a consent timestamp, recorded\n * against {@link hostId} — the brand whose form carried the checkbox — and\n * against the rest of its consent group only as far as\n * {@link disclosedConsentGroup} proves the group was shown.\n */\n marketingConsent?: boolean\n /**\n * The `consentGroupDisclosureKey` of the sentence the capture surface\n * rendered beside the checkbox (AGL-3320), as the surface sent it back.\n *\n * The grant pools across the site's consent group only when this is the\n * group's CURRENT key; absent, stale or mistyped, it is recorded for\n * {@link hostId} alone. Every surface that renders no disclosure passes\n * none, so its grant is one site's however the org is grouped. Only the\n * grant narrows: the record's `visibleTo` and its holder are the group's\n * either way, because who may see a person is not who may mail them.\n */\n disclosedConsentGroup?: string | null\n /**\n * An explicit REFUSAL, recorded against {@link hostId} (AGL-3185).\n *\n * Its own flag rather than `marketingConsent: false`, because every door\n * that passes a checkbox's value passes `false` for a box left alone, and\n * a box left alone records nothing — absence is the third state, and\n * turning it into a refusal would silently make every unticked visitor\n * unmailable. A door sets this only for an act of refusal: a switch turned\n * off, a prompt answered no. Ignored when {@link marketingConsent} is true.\n */\n declineMarketingConsent?: boolean\n /**\n * The provenance stored on the consent entry {@link marketingConsent} or\n * {@link declineMarketingConsent} writes (AGL-3185): who recorded it, which\n * door, which wording version. The console doors pass the person's own\n * (`actor: 'person'`); a site's capture surface passes none, which the\n * reader takes as the person's own act anyway.\n */\n marketingConsentSource?: MarketingConsentSource\n /**\n * Order value in cents — rolls into RFM fields (AGL-328).\n *\n * WHAT IT COUNTS (AGL-1748). GROSS of the platform fee and GROSS of\n * refunds — the money the customer handed over, not the money the merchant\n * kept. Every writer passes the same thing: whatever was actually charged\n * (`amount_total` for a Stripe path, `totals.totalCents` for POS), never a\n * figure re-derived from product docs, which is the AGL-1698/AGL-1711\n * lesson. Gross of the fee because this is a CUSTOMER attribute answering\n * \"what is this person worth to me?\", and the fee is a cost of the channel,\n * not something the buyer failed to spend.\n *\n * Refunds are still NOT netted here, and now they are recorded elsewhere\n * (AGL-1754). `refund.ts` writes `refundedCents`, `refundedOrdersCount` and\n * `lastRefundAtMs` BESIDE these fields — the shape AGL-1747 chose for the\n * same question on the orders CSV — rather than decrementing a stored number\n * whose meaning would then differ between rows written before and after that\n * commit. So `ltvCents` and `ordersCount` remain gross by definition, and a\n * READER that wants the net computes `ltvCents - refundedCents`, clamping\n * only what it ranks on: the difference can be negative for a customer whose\n * pre-AGL-1748 purchase was never counted and whose refund was, which is a\n * missing purchase showing itself rather than a corrupt contact. AGL-1753 is\n * the backfill that reconciles it. See `contact-refund.ts` in the commerce\n * plugin for the full reasoning and for why a refund never CREATES a contact.\n *\n * Passing 0 or omitting it means \"no purchase\": `ltvCents`, `ordersCount`,\n * `lastPurchaseAtMs` and `firstPurchaseAtMs` are all left untouched, which\n * is why a caller that formats the amount into the interaction summary and\n * forgets this field records a customer who has apparently never bought\n * anything.\n */\n purchaseCents?: number\n /**\n * The currency {@link purchaseCents} is in, lowercase, when the door knows.\n *\n * Absent everywhere today, because no order document carries a currency and\n * every checkout door writes `currency: 'usd'` onto the Stripe line items.\n * The plugin that credits orders defaults it on that basis and says so. The field\n * exists so a door that ever charges in something else can pass it, and the\n * campaign revenue report keeps it in its own bucket rather than adding it\n * to the dollars.\n */\n purchaseCurrency?: string\n /**\n * Where this person arrived from, already resolved by the door through the\n * plugin that credits outcomes (`plugin-conversion-credit`), and opaque\n * here.\n *\n * ⛔ The ORDER path passes none, and must not start. An order already has\n * its own credit one branch below — `creditOrderConversion`, keyed on the\n * order id — and a second record for the same sale would be the same money\n * counted twice under two rules. This is the door for the moments an order\n * does NOT cover: a form submission, a membership sign-up, a booking, a\n * newsletter capture.\n *\n * Resolved rather than raw, for the reason `addHostLead` states: one\n * visitor action reaches several writers and the touch lookup is paid once.\n */\n conversionTouch?: PluginConversionTouch | null\n /**\n * The campaigns the CAPTURE SURFACE is filed under.\n *\n * ⚠️ A different fact from {@link conversionTouch} beside it, and the two must\n * never be folded together. A touch is where the visitor came FROM — an ad,\n * a link, a browser-supplied label resolved through an allowlist. This is\n * which campaigns the merchant put the form itself in, which is the\n * merchant's own act and is true of everybody who fills that form in,\n * including the visitor who arrived by typing the address.\n *\n * ⛔ And it is not consent. Filing a form under a campaign says nothing\n * about what the person agreed to; `marketingConsent` above is the only\n * input that records a basis.\n */\n campaignIds?: readonly string[]\n /**\n * Tags to put on THIS holder's facet (AGL-2602).\n *\n * Added to, never replaced, on a merge: a person the merchant tagged by\n * hand and later imported keeps the hand-written tag beside the file's.\n */\n tags?: readonly string[]\n /**\n * The profile a door knows about the person — phone, title, company,\n * address, owner, stage, custom values — written into THIS holder's facet\n * (AGL-2602). Only the keys present are written, so a door that knows the\n * phone and nothing else does not blank the title somebody typed.\n */\n facet?: UpsertHostContactFacet\n /**\n * Profile fields written only where THIS holder's facet has none\n * (AGL-3493) — what a door learned in passing, like the phone a booking\n * form asked for, which must not replace a number somebody typed on the\n * record. A key {@link facet} also carries is `facet`'s to write.\n */\n facetFill?: Pick<UpsertHostContactFacet, 'phone'>\n /**\n * The EARLIEST stage that describes what this capture was (AGL-2612).\n *\n * Every door names one: a form submission is a `lead`, a newsletter opt-in\n * or a member sign-up is a `subscriber`, a purchase — an order, a paid\n * booking — is a `customer`. The rule applied to it is\n * `advanceContactLifecycleStage`: it fills an empty stage and advances an\n * earlier one, and never moves anybody back, so a customer who fills in\n * the contact form is still a customer and a subscriber who then submits\n * a form becomes a lead. Applied on top of `facet.lifecycleStage` when a\n * door carries both — the caller's stage is the base and this is its\n * floor.\n *\n * A FLOOR and not a value, which is why it is not the facet field: the\n * facet's `lifecycleStage` is a SET, the shape the console's create\n * drawer and the import need — the merchant typed a stage and that is the\n * stage — and a capture door writing a set would put every returning\n * customer back to `lead` on their next enquiry. Omitted by the doors\n * that carry the caller's own stage or none (manual, import, API, a lead\n * conversion), whose contacts read as \"no stage\", which is true.\n */\n initialLifecycleStage?: ContactLifecycleStage\n /**\n * Told when this capture created a contact (AGL-2605).\n *\n * A HOOK rather than an event emitted from here, and the reason is the\n * dependency direction: the event fan-out lives in `libs/tenant/runtime`,\n * which imports THIS library for its Firestore handle and its org helpers.\n * An import back up from here would be a cycle, and the module boundaries\n * (`scope:data` may depend on data and util only) refuse it besides. So\n * this module reports the fact and the runtime's `captureHostContact`\n * turns it into `contactCreated` — every server door goes through that\n * wrapper, and a door that calls this function directly has chosen to\n * create contacts nothing can react to.\n *\n * Awaited with its own catch, like the order join above: the least\n * important write on the path, and a failure in it must not cost the\n * capture that already happened.\n */\n onCreated?: (created: HostContactCreated) => void | Promise<void>\n /**\n * The lookups of a whole file, read once (AGL-3423) — see\n * {@link prepareContactCaptureBatch}.\n *\n * A door capturing many addresses at once prepares one batch and hands it\n * to every capture; each one then takes the site, the group, the person\n * the address already is, the erasure and the band from it instead of\n * reading them. Every decision below is made by the same lines either way.\n * A batch prepared for another site is ignored.\n */\n batch?: ContactCaptureBatch\n}\n\nexport async function upsertHostContact(\n options: UpsertHostContactOptions,\n): Promise<UpsertHostContactVerdict> {\n try {\n const email = normalizeContactEmail(options.email)\n if (!email) return { refused: 'invalid-email' }\n const tags = normalizeTags(options.tags)\n\n /*==========================================\n * THE PURCHASE DOOR, AND THEREFORE THE ATTRIBUTION DOOR.\n *\n * Every way of buying something in this product — the cart, buy-now, the\n * POS register, a draft order, a reservation, a subscription renewal, a\n * booking — announces itself here, in exactly one shape: source `order`,\n * a `purchaseCents` amount, and a `refId` naming what was bought. That\n * shape IS the purchase chokepoint, which is why the revenue join hangs\n * off it rather than off seven call sites in a webhook.\n *\n * ABOVE the audience-band gate below, and deliberately. Contact creation\n * is band gated, so a Free org past its included count drops the CRM\n * record — and an attribution written inside that branch would drop the\n * revenue with it. The join keys on the address hash, exactly as the\n * touch and the suppression list do, so it never needs a contact document\n * to exist: a guest checkout by somebody who is not and never becomes a\n * contact still credits the campaign whose link they clicked.\n *\n * Its own `catch`, inside a function that already swallows: this is the\n * least important write on the path, and a failure here must not cost the\n * contact capture below it.\n *=========================================*/\n if (options.source === 'order' && options.interaction.refId) {\n await creditOrderConversion({\n hostId: options.hostId,\n orderId: String(options.interaction.refId),\n email,\n amountCents: Number(options.purchaseCents ?? 0),\n ...(options.purchaseCurrency\n ? { currency: options.purchaseCurrency }\n : {}),\n orderedAtMs: options.interaction.atMs ?? Date.now(),\n }).catch(() => null)\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(options.hostId)\n const batch =\n options.batch?.hostId === options.hostId ? options.batch : undefined\n // Contacts are org-scoped (AGL-237): every host in the org feeds one\n // shared list.\n const contactsRef: FirebaseFirestore.CollectionReference =\n batch?.contactsRef ??\n (await orgDataCollectionForHost(options.hostId, 'contacts'))\n /*\n * The consent group this capture belongs to — the sites declared to be\n * one sender, or this site alone. Resolved once and used for three\n * different decisions below, which must all agree: which controller the\n * basis is recorded for, which sites the row becomes visible to, and\n * which holder the profile is filed under.\n */\n const group = batch?.group ?? (await consentGroupForSite(options.hostId))\n /*\n * THE CONSENT ENTRY THIS CAPTURE WRITES, decided once for both branches.\n *\n * A grant outranks a refusal flag set beside it — one door cannot mean\n * both — and neither writes anything when the door carried no act, so\n * an unticked box stays the third state. The provenance rides inside the\n * per-host entry, where the reader looks for it, never at the top of a\n * document every brand in the org shares.\n *\n * The grant covers the group only when the capture surface proved it\n * showed the group's current disclosure — `consentGroupForGrant` answers\n * the site alone for every other capture. The visibility and the holder\n * below keep the whole group.\n */\n const consentExtra = options.marketingConsentSource\n ? { [MARKETING_CONSENT_SOURCE_FIELD]: options.marketingConsentSource }\n : undefined\n const consentFields = options.marketingConsent\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, options.disclosedConsentGroup),\n Date.now(),\n consentExtra,\n )\n : options.declineMarketingConsent\n ? declineMarketingConsentFields(options.hostId, Date.now(), consentExtra)\n : {}\n const interaction: ContactInteraction = {\n type: options.source,\n atMs: options.interaction.atMs ?? Date.now(),\n // WHICH SITE this visit happened on. The row is shared; the history on\n // it is not, and a timeline with no site cannot be split for an\n // agency's client without showing them another client's activity.\n hostId: options.hostId,\n ...(options.interaction.refId\n ? { refId: options.interaction.refId }\n : {}),\n ...(options.interaction.summary\n ? { summary: options.interaction.summary.slice(0, 200) }\n : {}),\n // The entry point, when the door knows it. Written only when present:\n // an absent field is a door that has none, and Firestore rejects\n // `undefined` inside an array element outright.\n ...(options.interaction.formId\n ? { formId: String(options.interaction.formId).slice(0, 128) }\n : {}),\n ...(options.interaction.path\n ? { path: String(options.interaction.path).slice(0, 500) }\n : {}),\n }\n\n /*\n * THE CAMPAIGNS THIS CAPTURE FILES THE PERSON UNDER.\n *\n * Normalized here rather than trusted, because it reaches this function\n * from a public endpoint's document read and every reader of the stored\n * array goes through the same coercion.\n */\n const campaignIds = normalizeContainerIds(options.campaignIds ?? [])\n /*\n * THE CUSTOM FIELD VALUES THIS CAPTURE CARRIES, as one nested map.\n *\n * Only the keys the door resolved. Written in the NESTED form because both\n * writes below are merge-sets, which deep-merge a map one key at a time:\n * `custom: { tier: 'Gold' }` lands beside an existing `custom.vip` and\n * leaves it standing. A dotted `facets.h1.custom.tier` path would be a\n * literal field name to a `set`, and a `custom` written whole would take\n * every other key with it.\n */\n const customEntries = Object.entries(options.facet?.custom ?? {})\n const customFacet = customEntries.length\n ? { custom: Object.fromEntries(customEntries) }\n : {}\n\n /*==========================================\n * THE DEDUPE LOOKUP IS UNSCOPED, AND HAS TO BE.\n *\n * One human who touched two sites is ONE person. Narrowing this read to\n * what the capturing site may already see would make a second submission\n * on a sibling brand create a SECOND document for the same address —\n * which loses the dedupe the shared address book exists for, and bills\n * the org twice for one human.\n *\n * Recognizing somebody is not the same act as being allowed to read their\n * row, and the two were the same query while every contact was stamped\n * org-wide. They are separated here: this finds the person, and\n * `visibleTo` below decides who may see them — widened by the capture\n * that just happened, never by the lookup that found them.\n *\n * THROUGH THE ADDRESS INDEX FIRST (AGL-2625). A person whose two records\n * were merged answers to two addresses, and only one of them is the\n * document's `email`; the index is what lets a capture on the other one\n * land on the survivor instead of minting the duplicate again. The query\n * stays as the fallback, so a row the index has not seen costs one extra\n * read once and needs no backfill.\n *=========================================*/\n const prefetched = batch?.claim(email)\n const docSnapshot =\n prefetched !== undefined\n ? prefetched\n : await findContactByEmail(contactsRef, email)\n\n if (docSnapshot) {\n /*\n * MERGED INTO THIS GROUP'S FACET, not into the top of the document.\n *\n * `sources`, `interactions`, the tags, the notes and every commercial\n * figure are the HOLDER's own business records: a booking taken by one\n * client of an agency is that client's, and while these lived at the\n * top of a shared row every other client could read them. The identity\n * — the address, and a canonical name for a holder that has set none of\n * its own — stays shared, because that is what makes this one row.\n */\n const facet = readContactFacet(\n docSnapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const merged = mergeContactInteraction(\n {\n name: facet.name ?? undefined,\n sources: facet.sources,\n interactions: facet.interactions,\n },\n { source: options.source, interaction, name: options.name },\n )\n /*\n * THE PROFILE, as this door knows it (AGL-2596).\n *\n * Given keys only, so the merge below leaves untouched whatever another\n * door wrote. The stage is the one field with a rule of its own: the\n * door's `initialLifecycleStage` fills an empty stage and advances an\n * earlier one, and never moves anybody back —\n * `advanceContactLifecycleStage` is that rule, applied to the stage\n * this door asked for outright or, failing that, the one already\n * stored. Written only when it comes back with something: a door that\n * named no stage and found none leaves the key absent, which reads as\n * \"no stage\" rather than as a stage somebody picked.\n */\n const profile = storableProfile(options.facet)\n fillProfile(profile, options.facetFill, facet)\n /*\n * THE NAME FOLLOWS THE FIRST AND LAST NAMES (AGL-3515): a door that\n * carried either writes the holder's name as their composition, over\n * the name the facet held — the parts are the newer, structured\n * statement of the same thing. A door that carried neither leaves the\n * name to the rule above, where the existing name wins.\n */\n const composedName =\n profile.firstName !== undefined || profile.lastName !== undefined\n ? composeContactName(\n profile.firstName ?? facet.firstName,\n profile.lastName ?? facet.lastName,\n )\n : ''\n const facetName = composedName || merged.name\n const advanced = advanceContactLifecycleStage(\n profile.lifecycleStage ?? facet.lifecycleStage,\n options.initialLifecycleStage,\n )\n if (advanced) profile.lifecycleStage = advanced\n /*\n * THE FORM MIRROR, bounded (see `HostContact.formIds`).\n *\n * Read off the document the lookup already fetched, so the bound costs\n * no extra read: a person who has come in through twenty forms keeps\n * the twenty, and this capture's form stays on the interaction alone.\n * `arrayUnion` for the add, so a concurrent capture on a sibling site\n * cannot drop this one's id.\n */\n const heldFormIds: unknown[] = Array.isArray(\n docSnapshot.get(CONTACT_FORM_IDS_FIELD),\n )\n ? docSnapshot.get(CONTACT_FORM_IDS_FIELD)\n : []\n const formIdToAdd =\n interaction.formId &&\n !heldFormIds.includes(interaction.formId) &&\n heldFormIds.length < CONTACT_FORM_IDS_CAP\n ? interaction.formId\n : null\n /*\n * THE COMPANY LINK, when the door carried one (AGL-2613).\n *\n * The facet's `companyId` is written with the rest of the profile\n * below, but the facet is not the whole association: the top-level\n * `companyIds` mirror is what the company page queries, and the\n * company's `contactsCount` is what the companies list shows. The\n * planner reads the row as it stands — this holder's previous link,\n * the mirror, the other holders' ids — and says what the mirror\n * becomes and which counts move; the mirror change rides in this same\n * merge-set, and the counts settle after it.\n */\n const link =\n profile.companyId !== undefined\n ? planContactCompanyLink(\n readContactCompanyLink(\n docSnapshot.data() as Record<string, unknown>,\n group.groupId,\n ),\n profile.companyId,\n )\n : null\n const mirror = link ? contactCompanyMirrorValue(link) : undefined\n await docSnapshot.ref.set(\n {\n // The search keys travel WITH the name, and only when the name is\n // written: stamping an empty key over a real one would make the\n // contact unfindable by the name it still displays.\n ...(facetName ? nameSearchFields(facetName) : {}),\n // The search echo of the facet's phone — see `HostContact.phone`.\n ...(profile.phone ? { phone: profile.phone } : {}),\n // The search echo of the facet's company name — see `HostContact.companyName`.\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n ...(mirror !== undefined ? { [CONTACT_COMPANY_IDS_FIELD]: mirror } : {}),\n /*\n * NESTED, not dot-pathed. This is a `set(…, { merge: true })`, and\n * a merge-set treats a key containing dots as a literal field name\n * — only `update()` reads them as paths. The nested form is what\n * Firestore deep-merges, so this writes one holder's facet and\n * leaves every other holder's untouched.\n */\n [CONTACT_FACETS_FIELD]: {\n [group.groupId]: {\n sources: merged.sources,\n interactions: merged.interactions,\n ...(facetName ? { name: facetName } : {}),\n /*\n * ADDED TO, never replaced. A person who filled in the spring\n * form and later the summer one is in both pushes, and an\n * assignment that overwrote would take a campaign a merchant\n * filed them under back out with nothing on screen to say so —\n * the reason `container-membership.ts` made the field an array\n * and the automation step has always used `arrayUnion`.\n *\n * Nested under the group id rather than written at\n * `contactContainerFieldPath`, because this is a merge-`set`: a\n * `set` treats a dotted string as a literal field NAME and would\n * mint a top-level key with dots in it. Only `update()` reads\n * dots as a path. The nested form is what Firestore deep-merges,\n * so it reaches one holder's facet and leaves every other\n * holder's alone — the same guarantee the dotted path gives the\n * automation step, in the shape this write is allowed to take.\n */\n ...(campaignIds.length\n ? { campaignIds: FieldValue.arrayUnion(...campaignIds) }\n : {}),\n // The same union rule as the campaigns above it, for the same\n // reason: a tag the merchant put on by hand survives the file.\n ...(tags.length ? { tags: FieldValue.arrayUnion(...tags) } : {}),\n // Present keys only, deep-merged by the merge-set — so the\n // fields this door did not carry keep whatever they held.\n ...profile,\n ...(options.purchaseCents\n ? {\n ltvCents: FieldValue.increment(options.purchaseCents),\n ordersCount: FieldValue.increment(1),\n lastPurchaseAtMs: Date.now(),\n // A contact that EXISTED before their first purchase\n // reached this branch, and it never wrote\n // `firstPurchaseAtMs` — only the create path did. So\n // every converted lead permanently lacked RFM's R anchor\n // while walk-in buyers carried it. Set it on the first\n // purchase only; later purchases must not move it.\n ...(facet.firstPurchaseAtMs\n ? {}\n : { firstPurchaseAtMs: Date.now() }),\n }\n : {}),\n },\n },\n /*\n * ATTRIBUTION GROWS ON THE MERGE BRANCH, which the create-only\n * `hostId` beside it never did — so a person the first site\n * captured and the second site later met read as the first site's\n * alone, forever.\n *\n * `arrayUnion`, so the audience filter \"everyone captured on A, B\n * or C\" answers with the sites that actually met this person.\n */\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(options.hostId),\n ...(formIdToAdd\n ? { [CONTACT_FORM_IDS_FIELD]: FieldValue.arrayUnion(formIdToAdd) }\n : {}),\n /*\n * AND SO DOES VISIBILITY — by the capture, never by the lookup.\n *\n * This site just collected this person: it has its own relationship\n * with them and may see the row. A site that has never captured\n * them gains nothing here, which is what keeps an agency's clients\n * apart on a document all of them share. The per-interaction\n * `hostId` above is what keeps the HISTORY apart on the same row.\n */\n visibleTo: FieldValue.arrayUnion(...consentGroupScope(group)),\n /*\n * RECORDED AGAINST THE CAPTURING SITE, not against the org.\n *\n * The contact document is shared by every site in the org, which is\n * the point of it — one address book behind many brands. Its\n * consent is not shared on the same terms: the checkbox this\n * capture carried was ticked under one brand's name, on one brand's\n * form, and a basis written at the top of this document made the\n * person mailable by every other brand the account holds.\n *\n * A merge writes one key of the map and leaves the rest, so a\n * person who opts in to a second site accumulates two grants rather\n * than replacing the first.\n */\n ...consentFields,\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n await settleCompanyContactsCounts(companiesBeside(contactsRef), link)\n // The merged facet, name and scope are what the Contacts list\n // searches and filters by (AGL-3321): restamped from the stored row.\n await restampCrmListFieldsAt(docSnapshot.ref, 'contacts')\n // The address's domain, checked after the response (AGL-3328).\n scheduleCapturedEmailCheck({\n orgId: contactsRef.parent?.id ?? null,\n hostId: options.hostId,\n email,\n predicted: docSnapshot.get('emailStatus') === 'undeliverable',\n })\n return { contactId: docSnapshot.id, created: false }\n }\n\n /*\n * THE ERASED PERSON DOES NOT COME BACK (AGL-2623).\n *\n * Before the band, on the CREATE branch only — the one read this adds\n * is paid by a capture that would otherwise make a new row, never by\n * the merge above. An erasure wrote a row on this site's suppression\n * list with no address on it; finding that row here is what keeps the\n * next form fill or checkout from rebuilding the record the workspace\n * just erased. The order or booking that triggered the capture still\n * succeeds, exactly as it does when the band refuses: the person bought\n * something, and the merchant's record of the sale is not the CRM's\n * record of the person.\n */\n if (\n batch?.erased(email) ??\n (await hostRefusesCaptureForErasure(options.hostId, email, firestore))\n ) {\n return { refused: 'erased' }\n }\n\n // New contact: records-band check via the aggregate counts (cheap; no\n // doc reads) against the owning org's entitlements (AGL-238/890).\n // Metered plans always pass (overage bills via the report-usage\n // cron); only free's hard band drops the CRM record — visibly, via\n // the counter and the console alert (AGL-891). The signup/order that\n // triggered the capture always succeeds either way.\n //\n // THE RECORDS BAND, not the contacts headcount (AGL-2611): companies\n // and deals share this band, so a capture is refused on a Free org\n // whose hundred records are ninety companies and ten people — the same\n // verdict the company drawer would give the ninety-first company.\n // `contactsRef` is handed in so the contacts aggregate is the one this\n // door already reads; the org reference is its parent.\n //\n // A batch counted once and keeps the tally, in call order, so each of\n // its creates is admitted exactly as it would be here one at a time.\n const orgBilling = batch\n ? batch.orgBilling\n : await getOrgForHost(options.hostId)\n const admitted = batch\n ? batch.admitCreate(email)\n : await (async () => {\n const orgRef =\n contactsRef.parent ??\n firestore.collection('orgs').doc(String(orgBilling?.orgId ?? ''))\n const { crmRecordsCount } = await countCrmRecords(orgRef, contactsRef)\n return checkCrmRecordsQuota(\n (orgBilling?.org as any) ?? null,\n crmRecordsCount,\n ).allowed\n })()\n if (!admitted) {\n await hostRef\n .collection('counters')\n .doc('contactsDropped')\n .set({ total: FieldValue.increment(1) }, { merge: true })\n return { refused: 'band' }\n }\n\n /*\n * The profile on a create, with the door's stage floor applied the same\n * way as on a merge — there is no stored stage yet, so the floor is what\n * a door that named one writes. A `null` address is dropped rather than\n * written: there is nothing on a new document for it to clear.\n */\n const profile = storableProfile(options.facet)\n // A new person holds nothing yet, so the fill is written whole.\n fillProfile(profile, options.facetFill, null)\n const advanced = advanceContactLifecycleStage(\n profile.lifecycleStage,\n options.initialLifecycleStage,\n )\n if (advanced) profile.lifecycleStage = advanced\n if (profile.address === null) delete profile.address\n if (profile.otherAddress === null) delete profile.otherAddress\n // The holder's name is the first and last names' when the door gave\n // either (AGL-3515); the canonical name is the one the door gave, or\n // that composition for a door that gave only the parts.\n const composedName = composeContactName(profile.firstName, profile.lastName)\n const canonicalName = (options.name || composedName).slice(0, 120)\n const holderName = (composedName || options.name || '').slice(0, 120)\n\n const record: Record<string, unknown> = {\n hostId: options.hostId,\n /*\n * WHICH SITES HAVE MET THIS PERSON — attribution, and separate from\n * consent above.\n *\n * The scalar `hostId` beside it names the FIRST capturing site and is\n * never rewritten, which is provenance for the ROW. This array is the\n * one that grows and the one an audience query can filter on.\n */\n [CAPTURED_BY_HOST_FIELD]: [options.hostId],\n // The form mirror's first entry, when this capture came through one —\n // see `HostContact.formIds`. Absent otherwise, like the campaigns.\n ...(interaction.formId\n ? { [CONTACT_FORM_IDS_FIELD]: [interaction.formId] }\n : {}),\n /*\n * THE CAPTURING GROUP, not the whole org.\n *\n * Stamping `['org']` here made every contact readable by every site in\n * the account on the day it was created — so an agency's twelve clients\n * shared one address book by default, and closing the missing-field\n * fail-open would not have touched it, because the field was present\n * and said so.\n *\n * A group of one — the default — is this site alone. A declared group\n * is the sites that already present as one sender. Widening beyond that\n * is available and is an ACT: an org may set its CRM default\n * (`crmDefaultScopeOf`) to `'org'`, or a later capture on a sibling\n * site unions that site in.\n */\n visibleTo:\n crmDefaultScopeOf(\n orgBilling?.org as Record<string, unknown> | null | undefined,\n ) === 'org'\n ? [ORG_SCOPE_TOKEN]\n : consentGroupScope(group),\n email,\n ...(canonicalName ? nameSearchFields(canonicalName) : {}),\n // The search echo of the facet's phone — see `HostContact.phone`.\n ...(profile.phone ? { phone: profile.phone } : {}),\n // The search echo of the facet's company name — see `HostContact.companyName`.\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n // The company mirror the company page queries (AGL-2613) — a create\n // has nothing to union with, so the door's company is the whole list.\n ...(profile.companyId\n ? { [CONTACT_COMPANY_IDS_FIELD]: [profile.companyId] }\n : {}),\n // The facet this capture creates. Everything a holder owns lives under\n // its own group id; the address and the canonical name above are the\n // only shared identity.\n [CONTACT_FACETS_FIELD]: {\n [group.groupId]: {\n sources: { [options.source]: true },\n interactions: [interaction],\n tags,\n // A create has nothing to union with, so the normalized list is the\n // whole membership.\n ...(campaignIds.length ? { campaignIds } : {}),\n ...customFacet,\n ...(holderName ? { name: holderName } : {}),\n ...profile,\n ...(options.purchaseCents\n ? {\n ltvCents: options.purchaseCents,\n ordersCount: 1,\n lastPurchaseAtMs: Date.now(),\n firstPurchaseAtMs: Date.now(),\n }\n : {}),\n },\n },\n ...consentFields,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await contactsRef.add({\n ...record,\n // What the Contacts list searches and filters by (AGL-3321), from the\n // row as written — and nothing scheduled against a new person.\n ...crmNewRecordListFields('contacts', record),\n })\n // The address now resolves to this row (AGL-2625). Its own catch inside\n // the writer, so an index the capture could not reach costs nothing.\n await writeContactEmailIndex(emailIndexBeside(contactsRef), created.id, [email])\n // The company the door named now has one more contact naming it\n // (AGL-2613) — the fresh row's plan is the trivial one, nothing held\n // before and nothing held elsewhere.\n if (profile.companyId) {\n await settleCompanyContactsCounts(\n companiesBeside(contactsRef),\n planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n profile.companyId,\n ),\n )\n }\n /*\n * ATTRIBUTED ON CREATION ONLY, and therefore below the band gate rather\n * than above it — the opposite placement to the order join at the top of\n * this function, deliberately.\n *\n * The order join sits above because it credits MONEY, which is real\n * whether or not a CRM record was kept for the buyer, and a Free org past\n * its included band would otherwise silently drop the revenue with the\n * contact. This credits a contact, which does not exist when the band\n * dropped it: attributing one above the gate would report a campaign as\n * having produced people the customer cannot see anywhere in the console.\n *\n * The existing-contact branch above returns without reaching here, which\n * is the same rule `addHostLead` applies — an interaction appended to\n * somebody the site already held is another visit, not a new person, and\n * crediting it would let the most recent campaign re-earn the whole list.\n */\n if (options.conversionTouch) {\n await creditConversion({\n hostId: options.hostId,\n kind: 'contact',\n refId: created.id,\n touch: options.conversionTouch,\n convertedAtMs: interaction.atMs,\n })\n }\n /*\n * REPORTED ON CREATION ONLY, below the band gate for the reason the\n * attribution above is: a contact the band dropped does not exist, and\n * an automation told about it would act on a person the console cannot\n * show. The merge branch returned long before this line, so a repeat\n * visit by somebody already held is never announced as a new contact.\n */\n if (options.onCreated) {\n await Promise.resolve(\n options.onCreated({\n contactId: created.id,\n hostId: options.hostId,\n email,\n ...(holderName ? { name: holderName } : {}),\n source: options.source,\n campaignIds,\n ...(profile.lifecycleStage\n ? { lifecycleStage: profile.lifecycleStage }\n : {}),\n }),\n ).catch((error) => {\n console.error('upsertHostContact onCreated failed', error)\n })\n }\n // A new person's address, checked after the response (AGL-3328): a\n // domain that takes no mail reads \"Would bounce\" on the record.\n scheduleCapturedEmailCheck({\n orgId: contactsRef.parent?.id ?? null,\n hostId: options.hostId,\n email,\n })\n return { contactId: created.id, created: true }\n } catch (error) {\n console.error('upsertHostContact failed', error)\n return { refused: 'error' }\n }\n}\n\n/*\n * THE LOOKUPS OF MANY CAPTURES, PAID ONCE (AGL-3423).\n *\n * `upsertHostContact` is the one writer of the contacts collection, and for\n * a single capture it resolves everything it decides with on its own: the\n * site's org and consent group, the person the address already belongs to,\n * whether the site erased them, and how full the records band is. For a\n * form submission that is a handful of reads. For a file it was the same\n * handful again for every row, serially — a two-hundred-row chunk of an\n * Apollo export was thousands of round trips and three aggregate counts per\n * new person, and the request ran into the function's sixty seconds before\n * it could answer.\n *\n * A batch is those answers for every address in a request, read in a\n * number of round trips that does not grow with the file. The door is\n * handed it as {@link UpsertHostContactOptions.batch} and consults it in\n * place of each per-capture read; every decision is still the door's own,\n * made by the same code, so an import cannot drift into a second writer\n * with its own ideas about dedupe, consent, scope or the band.\n *\n * ## What a batch answers, and what it leaves to the door\n *\n * - **Who the address already is.** {@link findContactsByEmail} — the index\n * and the `email` query, for every address at once. `claim` hands an\n * address's answer out ONCE: a second capture of the same address in the\n * same batch is asked live, so a create earlier in the batch is found\n * rather than minted twice.\n * - **Whether the site erased them.** {@link hostErasedEmails}, one read.\n * - **Room in the records band.** One count, then a running tally in call\n * order, so N creates admit exactly as N serial door calls would. A\n * caller that creates OTHER records against the same band — the import's\n * companies — spends from the same tally with {@link ContactCaptureBatch.admit},\n * and may {@link ContactCaptureBatch.reserve} an address's room at its\n * place in the file, so the order in which rows are later written does\n * not decide which of them the band keeps.\n *\n * Any answer a batch does not have — a page of the lookup that failed, an\n * address it was not prepared with — is `undefined`, and the door reads for\n * itself exactly as it does without a batch.\n */\n\n/** The resolved answers a batch of captures on one site share. */\nexport interface ContactCaptureBatch {\n /** The site every capture in the batch is on; a door for another site ignores the batch. */\n readonly hostId: string\n readonly contactsRef: FirebaseFirestore.CollectionReference\n readonly group: ConsentGroup\n readonly orgBilling: Awaited<ReturnType<typeof getOrgForHost>>\n /**\n * What an address resolved to when the batch was prepared, without\n * spending it: the record, `null` for nobody, `undefined` for not known.\n */\n peek(email: string): FirebaseFirestore.DocumentSnapshot | null | undefined\n /**\n * The same answer, handed out once. Every later claim of the address is\n * `undefined`, so its door looks it up live.\n */\n claim(email: string): FirebaseFirestore.DocumentSnapshot | null | undefined\n /** Whether the site erased the address; `undefined` when the read failed. */\n erased(email: string): boolean | undefined\n /** Takes room for one more record in the band, now. False when the band refuses. */\n admit(): boolean\n /** Takes the address's room now, at its place in the caller's order. */\n reserve(email: string): boolean\n /** The door's question: the reserved answer when there is one, else {@link admit}. */\n admitCreate(email: string): boolean\n}\n\n/**\n * Reads, once, what every capture of `emails` on `hostId` would read for\n * itself. Throws only when the site or the band cannot be read at all —\n * the reads every capture would fail on — so a caller answers the request\n * rather than refusing every row one at a time.\n */\nexport async function prepareContactCaptureBatch(\n hostId: string,\n emails: readonly unknown[],\n): Promise<ContactCaptureBatch> {\n const firestore = firebaseAdmin.app().firestore()\n const [contactsRef, orgBilling] = await Promise.all([\n orgDataCollectionForHost(hostId, 'contacts'),\n getOrgForHost(hostId),\n ])\n const group = await consentGroupForSite(\n hostId,\n (orgBilling?.org as Record<string, unknown> | undefined) ?? null,\n )\n const orgRef =\n contactsRef.parent ??\n firestore.collection('orgs').doc(String(orgBilling?.orgId ?? ''))\n const addresses = [\n ...new Set(\n emails\n .map((email) => normalizeContactEmail(email))\n .filter((email): email is string => !!email),\n ),\n ]\n const [existing, erased, counted] = await Promise.all([\n findContactsByEmail(contactsRef, addresses),\n hostErasedEmails(hostId, addresses, firestore),\n countCrmRecords(orgRef, contactsRef),\n ])\n\n const org = (orgBilling?.org as never) ?? null\n let used = counted.crmRecordsCount\n const claimed = new Set<string>()\n const tickets = new Map<string, boolean>()\n const admit = (): boolean => {\n if (!checkCrmRecordsQuota(org, used).allowed) return false\n used += 1\n return true\n }\n\n return {\n hostId,\n contactsRef,\n group,\n orgBilling,\n peek: (email) => existing.get(email),\n claim: (email) => {\n if (claimed.has(email)) return undefined\n claimed.add(email)\n return existing.get(email)\n },\n erased: (email) => (erased ? erased.has(email) : undefined),\n admit,\n reserve: (email) => {\n const ticket = tickets.get(email)\n if (ticket !== undefined) return ticket\n const admitted = admit()\n tickets.set(email, admitted)\n return admitted\n },\n admitCreate: (email) => {\n const ticket = tickets.get(email)\n if (ticket === undefined) return admit()\n tickets.delete(email)\n return ticket\n },\n }\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkCrmRecordsQuota","composeContactName","CONTACT_EXTRA_PHONE_FIELDS","consentGroupScope","crmDefaultScopeOf","CONTACT_FACETS_FIELD","CONTACT_FORM_IDS_CAP","CONTACT_FORM_IDS_FIELD","marketingConsentFieldsForGroup","mergeContactInteraction","normalizeContactBirthdate","normalizeContainerIds","readContactFacet","normalizeContactEmail","ORG_SCOPE_TOKEN","FieldValue","firebaseAdmin","countCrmRecords","restampCrmListFieldsAt","hostErasedEmails","hostRefusesCaptureForErasure","scheduleCapturedEmailCheck","creditConversion","creditOrderConversion","nameSearchFields","consentGroupForGrant","declineMarketingConsentFields","MARKETING_CONSENT_SOURCE_FIELD","advanceContactLifecycleStage","CONTACT_COMPANY_IDS_FIELD","CONTACT_FIELD_KEY_PATTERN","CRM_COLLECTIONS","crmNewRecordListFields","isContactLifecycleStage","planContactCompanyLink","readContactCompanyLink","normalizeAddress","normalizePhone","contactCompanyMirrorValue","settleCompanyContactsCounts","emailIndexBeside","findContactByEmail","findContactsByEmail","writeContactEmailIndex","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","storableProfile","input","out","salutation","trim","replace","slice","firstName","undefined","lastName","key","value","phone","birthdate","otherAddress","doNotCall","jobTitle","leadSource","address","companyId","companyName","ownerUid","lifecycleStage","custom","Object","entries","test","keys","length","fillProfile","profile","fill","stored","given","String","companiesBeside","contactsRef","parent","collection","companies","normalizeTags","tags","Set","map","tag","toLowerCase","filter","Boolean","upsertHostContact","options","email","refused","source","interaction","refId","hostId","orderId","amountCents","Number","purchaseCents","purchaseCurrency","currency","orderedAtMs","atMs","Date","now","catch","firestore","app","hostRef","doc","batch","group","consentExtra","marketingConsentSource","consentFields","marketingConsent","disclosedConsentGroup","declineMarketingConsent","type","summary","formId","path","campaignIds","customEntries","facet","customFacet","fromEntries","prefetched","claim","docSnapshot","data","groupId","merged","name","sources","interactions","facetFill","composedName","facetName","advanced","initialLifecycleStage","heldFormIds","Array","isArray","get","formIdToAdd","includes","link","mirror","ref","set","arrayUnion","ltvCents","increment","ordersCount","lastPurchaseAtMs","firstPurchaseAtMs","visibleTo","updatedAt","serverTimestamp","merge","orgId","id","predicted","contactId","created","erased","orgBilling","admitted","admitCreate","orgRef","crmRecordsCount","org","allowed","total","canonicalName","holderName","record","createdAt","add","companyIds","heldElsewhere","conversionTouch","kind","touch","convertedAtMs","onCreated","Promise","resolve","error","console","prepareContactCaptureBatch","emails","all","addresses","existing","counted","used","claimed","tickets","Map","admit","peek","has","reserve","ticket","delete"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,sBAAsB,EACtBC,oBAAoB,EACpBC,kBAAkB,EAClBC,0BAA0B,EAE1BC,iBAAiB,EACjBC,iBAAiB,EACjBC,oBAAoB,EACpBC,oBAAoB,EACpBC,sBAAsB,EAKtBC,8BAA8B,EAC9BC,uBAAuB,EACvBC,yBAAyB,EACzBC,qBAAqB,EACrBC,gBAAgB,EAChBC,qBAAqB,EACrBC,eAAe,QACV,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,eAAe,EAAEC,sBAAsB,QAAQ,mBAAe;AACvE,SAASC,gBAAgB,EAAEC,4BAA4B,QAAQ,yBAAqB;AACpF,SAASC,0BAA0B,QAAQ,2BAAuB;AAClE,SACEC,gBAAgB,EAChBC,qBAAqB,QAEhB,uDAAsD;AAC7D,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,oBAAoB,QAAQ,wCAAuC;AAC5E,SACEC,6BAA6B,EAC7BC,8BAA8B,QAEzB,2CAA0C;AACjD;;;;;;CAMC,GACD,SACEC,4BAA4B,EAC5BC,yBAAyB,EACzBC,yBAA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