@aglyn/aglyn 1.0.0-beta.178 → 1.0.0-beta.180

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/aglyn",
3
- "version": "1.0.0-beta.178",
3
+ "version": "1.0.0-beta.180",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -33,16 +33,16 @@
33
33
  "./package.json": "./package.json"
34
34
  },
35
35
  "dependencies": {
36
- "@aglyn/shared-data-enums": "1.0.0-beta.178",
37
- "@aglyn/shared-data-mdi": "1.0.0-beta.178",
38
- "@aglyn/shared-data-types": "1.0.0-beta.178",
39
- "@aglyn/shared-util-email": "1.0.0-beta.178",
40
- "@aglyn/shared-util-first-touch": "1.0.0-beta.178",
41
- "@aglyn/shared-util-http": "1.0.0-beta.178",
42
- "@aglyn/shared-util-logger": "1.0.0-beta.178",
43
- "@aglyn/shared-util-timestamp": "1.0.0-beta.178",
44
- "@aglyn/shared-util-tools": "1.0.0-beta.178",
45
- "@aglyn/shared-util-vendor": "1.0.0-beta.178",
36
+ "@aglyn/shared-data-enums": "1.0.0-beta.180",
37
+ "@aglyn/shared-data-mdi": "1.0.0-beta.180",
38
+ "@aglyn/shared-data-types": "1.0.0-beta.180",
39
+ "@aglyn/shared-util-email": "1.0.0-beta.180",
40
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.180",
41
+ "@aglyn/shared-util-http": "1.0.0-beta.180",
42
+ "@aglyn/shared-util-logger": "1.0.0-beta.180",
43
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.180",
44
+ "@aglyn/shared-util-tools": "1.0.0-beta.180",
45
+ "@aglyn/shared-util-vendor": "1.0.0-beta.180",
46
46
  "@data-driven-forms/react-form-renderer": "^4.2.0",
47
47
  "@msgpack/msgpack": "^3.1.3",
48
48
  "@types/unist": "^3.0.3",
@@ -319,6 +319,12 @@ export interface ContactFacet {
319
319
  /** E.164 — `normalizePhone` before writing. */
320
320
  phone?: string;
321
321
  jobTitle?: string;
322
+ /**
323
+ * Where this holder met the person — Salesforce's Lead Source, carried
324
+ * from the lead on conversion and picked from the org's lead source
325
+ * values after it (AGL-3298). The value's label, as the lead stores it.
326
+ */
327
+ leadSource?: string;
322
328
  /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */
323
329
  companyId?: string;
324
330
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `campaign-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const visibleTo = (contact ?? {})['visibleTo']\n return Array.isArray(visibleTo)\n ? visibleTo.filter((token): token is string => typeof token === 'string')\n : []\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent entries, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete' }\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds.map((id) => `marketingConsentByHost.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","visibleTo","filter","token","planContactDetach","group","held","leaving","hostIds","map","id","remaining","action","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AA+B5B;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAA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OAAO,GAAG4B,WAAW,GAAG,EAAEP,sBAAsB,CAACK,MAAMR,KAAK,CAAC,EAAE;AACjE"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/contacts.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 * Contacts CRM v1 (AGL-197): one contact per normalized email per host,\n * fed by the four existing capture silos (forms, members, orders,\n * bookings). Pure data module — the admin-SDK upsert lives in\n * `@aglyn/tenant-data-admin` (`upsertHostContact`) and the console reads\n * client-side under the host-admin rules.\n */\n\nimport type { AglynPostalAddress } from '../foundation'\nimport { consentGroupForHost } from './consent-groups'\nimport type { ContactCustomValue, ContactLifecycleStage } from './crm'\nimport type { EmailState } from './email-state'\nimport {\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n readMarketingBasis,\n type MarketingBasis,\n} from './marketing-consent'\n\nexport type ContactSource =\n | 'form'\n | 'member'\n | 'order'\n | 'booking'\n | 'newsletter'\n // AGL-2276: `POST /v1/contacts`. A first-class source rather than a blank\n // one, because \"where did this person come from\" is the question the\n // console's source filter exists to answer, and an integration importing a\n // CRM is a different answer from a visitor filling in a form. Adding it to\n // the union is what makes `SOURCE_LABELS` and the filter cover it — a raw\n // string written past the type would render as `api` and match no filter.\n | 'api'\n // CRM v2 (AGL-2595): the two doors that are not a capture at all. A person\n // typed into the console by a member of the team, and a person who arrived\n // in a file. Both are first-class for the reason `api` is — a merchant\n // asking \"who did we add ourselves\" and \"who came from the spreadsheet\" is\n // asking the source filter, and a source the union does not name is one it\n // cannot answer for.\n | 'manual'\n | 'import'\n // AGL-3185: the platform's own console — an account created there, and\n // the product-updates decision that account makes at sign-up, in its\n // preferences or at the one-time prompt. First-class for the reason `api`\n // is: the operator's CRM asks \"who signed up for the product\", and\n // `member` is a SITE's member, which an account holder of the platform\n // is not.\n | 'account'\n\n/**\n * How a capture source reads on screen.\n *\n * Typed `Record<ContactSource, string>` so a source added to the union cannot\n * ship without a label, and kept beside the union rather than in the console\n * that first needed it: the contacts filter, the campaign audience and the\n * dynamic-list rule editor all name the same six sources, and three copies of\n * this map is three places for `order` to stop reading as \"Customer\".\n */\nexport const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {\n form: 'Form',\n member: 'Member',\n order: 'Customer',\n booking: 'Booking',\n newsletter: 'Newsletter',\n api: 'API',\n manual: 'Added by hand',\n import: 'Import',\n account: 'Account',\n}\n\nexport interface ContactInteraction {\n type: ContactSource\n /** Source doc id (formSubmissions/siteMembers/orders/bookings). */\n refId?: string\n /** Epoch millis — Timestamps don't serialize into arrays cleanly. */\n atMs: number\n summary?: string\n /**\n * WHICH SITE this interaction happened on.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one person, and splitting them into two rows would\n * bill the org twice for the same address and lose the dedupe that makes a\n * multi-brand account worth having. But the HISTORY on that shared row is\n * not shared: a booking made on one client's site is that client's, and a\n * timeline that cannot be split by site shows an agency's client the other\n * clients' activity.\n *\n * Optional because a row written before this field existed carries none,\n * and an interaction whose site is unknown must read as unattributed rather\n * than be assigned to whoever is looking. Nothing may infer it from the\n * contact's own capture attribution: `capturedByHostIds` says which sites\n * met this person, not which of them produced any particular visit.\n */\n hostId?: string\n /**\n * THE ENTRY POINT: the form this capture came in through.\n *\n * `sources` answers \"what KIND of surface met this person\" and is what the\n * console's capture filter reads; it cannot answer \"which form\", because\n * every form on the site sets the same `form` flag. The id rather than the\n * name, for the reason the submission carries the id: a form's caption is\n * editable and a stored name splits the moment somebody renames it.\n *\n * Beside {@link refId} rather than derived from it. The submission the\n * interaction names does carry the form, but reading it back would be a\n * document read per row of a timeline the console renders straight out of\n * the contact.\n */\n formId?: string\n /**\n * THE ENTRY POINT: the page the person was on when this happened.\n *\n * The same `path` the submission stores. It belongs on the interaction and\n * not on the contact, because a person who came in through the pricing page\n * and returned through a blog post has two entry points and one row —\n * a single field at the top would keep whichever capture wrote last.\n */\n path?: string\n}\n\n/** `orgs/{orgId}/contacts/{contactId}` doc shape. */\nexport interface HostContact {\n /** Normalized (trimmed, lowercased) email — the dedupe key. */\n email: string\n name?: string\n sources: Partial<Record<ContactSource, true>>\n /** Newest-first, capped — the profile timeline. */\n interactions: ContactInteraction[]\n tags?: string[]\n notes?: string\n /**\n * Every site that has captured this person, in no order.\n *\n * An ARRAY and a top-level field, because this is the one attribution that\n * has to survive being a QUERY: \"everyone captured on A, B or C\" is an\n * audience, and `array-contains-any` is what answers it. The per-interaction\n * host says which visit belonged to whom; this says which sites have a\n * relationship at all, and only the second shape can be filtered on in\n * Firestore.\n *\n * Grows by `arrayUnion` on every capture, including the ones that merge\n * onto an existing row — which is exactly what the create-only `hostId`\n * beside it could never do.\n */\n capturedByHostIds?: string[]\n /**\n * Every form this person has come in through, in no order (AGL-2612).\n *\n * The entry point proper is `interactions[].formId` inside the capturing\n * holder's facet, and that stays the record: which form produced which\n * visit is one holder's business. But Firestore cannot select documents\n * by a field of an array ELEMENT, and a facet path is per group, so\n * \"everyone who filled in this form\" — the question the form's own page\n * asks of the Contacts list — has to be a top-level array an\n * `array-contains` can hit, exactly as `capturedByHostIds` is for sites\n * and `companyIds` is for companies. A form id is minted under one site,\n * so a query on it is one site's captures by construction.\n *\n * Grows by `arrayUnion` on every form capture, create or merge, bounded at\n * {@link CONTACT_FORM_IDS_CAP}: a person who has filled in more forms than\n * that keeps the first twenty and the timeline keeps the rest. The facet is\n * the truth and this is its index — a reader answering \"which form\" reads\n * the interaction; only a QUERY reads this.\n */\n formIds?: string[]\n /*\n * SEARCH KEYS (AGL-2596), and nothing more.\n *\n * The console's global search reads a window of contact documents and\n * matches over their top-level fields; it never resolves a holder's facet,\n * because it is one search over a dozen collections and a facet read is a\n * contacts-only idea. So the two profile values a person is looked up BY —\n * their phone number and the company they work for — are mirrored here by\n * every writer that sets them on a facet, as plain values a query can hit.\n *\n * The FACET is the record. These are a last-writer-wins echo of it: two\n * holders who keep different numbers for one person each overwrite the\n * echo and each keep their own facet value, and nothing renders these to a\n * reader — the list, the record page and the export all read through the\n * viewing group's facet. `ORG_CONTACT_FIELDS` below is an allow-list, so\n * neither reaches the org view either.\n */\n /** E.164, mirrored from the last facet write that set one. */\n phone?: string\n /** The company name as typed, mirrored the same way. */\n companyName?: string\n /**\n * The OTHER addresses this person answers to (AGL-2625).\n *\n * A contact is keyed on one email, so one human with a work address and a\n * personal one is two documents until somebody merges them. The merge keeps\n * the survivor's `email` as the identity and records the merged record's\n * address here, so a later capture on it — a form filled in from the\n * personal account — resolves to this row rather than minting the second\n * document again. `emailIndex` (see {@link CONTACT_EMAIL_INDEX_COLLECTION})\n * is the lookup; this array is the record of why an entry there points\n * where it does, and what the record page shows as \"also\".\n *\n * Shared identity like `email`, not a facet field: which addresses are one\n * person is a fact about the person, and a holder that did not perform the\n * merge still needs its capture on the alternate address to land on the\n * shared row. Bounded at {@link CONTACT_ALTERNATE_EMAILS_CAP}.\n */\n alternateEmails?: string[]\n /**\n * When the earliest OPEN task filed against this person is due, epoch\n * ms, or `null` when none is (AGL-2661) — see `CrmDeal.nextTaskAtMs` in\n * `crm.ts` for the rule. On the SHARED row rather than a facet, because a\n * task lives at the organization level and names the contact, not a\n * holder's view of them.\n */\n nextTaskAtMs?: number | null\n /**\n * The last verdict on the address (AGL-3245) — bounced, blocked,\n * unsubscribed, do-not-contact — written by the platform's senders only,\n * on the SHARED row because the address is shared. Absent means nothing\n * is known. See `email-state.ts`.\n */\n emailState?: EmailState\n}\n\n/** Timeline cap: keeps the doc small; older interactions age out. */\nexport const CONTACT_INTERACTIONS_CAP = 50\n\n/** The field holding {@link HostContact.alternateEmails}. */\nexport const CONTACT_ALTERNATE_EMAILS_FIELD = 'alternateEmails'\n\n/**\n * The most alternate addresses one contact carries. Ten is past any real\n * person's mailbox count, and it bounds the index writes one merge fans out.\n */\nexport const CONTACT_ALTERNATE_EMAILS_CAP = 10\n\n/**\n * `orgs/{orgId}/emailIndex/{personKey}` → `{ email, contactId }` (AGL-2625).\n *\n * The address-to-contact lookup the capture door consults BEFORE the\n * per-document `email ==` query, so an address recorded as an alternate on a\n * merged row resolves to the survivor. Keyed by `personKey` — the sha256 of\n * the normalized address — so a document id never carries the address\n * itself, the same derivation a lead and a list membership use.\n *\n * WRITTEN LAZILY, never backfilled: the query on `email` stays as the\n * fallback, and a contact that has no entry gets one on the next write that\n * finds it. A row the index has never seen therefore costs one extra read\n * once, and nothing needs to run over the existing collection.\n *\n * Server-written only; the rules close it to every client.\n */\nexport const CONTACT_EMAIL_INDEX_COLLECTION = 'emailIndex'\n\n/**\n * Every address a contact answers to — the primary first, then the\n * alternates — normalized and deduplicated, so an index writer and a lead\n * lookup walk one list.\n */\nexport function contactEmails(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (value: unknown) => {\n const email = normalizeContactEmail(value)\n if (email && !seen.has(email)) {\n seen.add(email)\n out.push(email)\n }\n }\n push((contact ?? {})['email'])\n const alternates = (contact ?? {})[CONTACT_ALTERNATE_EMAILS_FIELD]\n if (Array.isArray(alternates)) alternates.forEach(push)\n return out\n}\n\n/** The top-level field naming every form a contact came in through — see `HostContact.formIds`. */\nexport const CONTACT_FORM_IDS_FIELD = 'formIds'\n\n/**\n * How many forms the {@link CONTACT_FORM_IDS_FIELD} mirror holds.\n *\n * The same figure as the tag cap: enough that no real person reaches it,\n * small enough that the array never becomes the document. Past it the\n * capture stops adding rather than dropping the oldest, because the mirror\n * is an index of the facet's timeline and an index that silently forgets an\n * entry the timeline still holds would answer a form's contact list wrongly\n * in the one direction nobody would notice.\n */\nexport const CONTACT_FORM_IDS_CAP = 20\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Normalized dedupe key, or null when the input isn't a usable email. */\nexport function normalizeContactEmail(input: unknown): string | null {\n const email = String(input ?? '')\n .trim()\n .toLowerCase()\n return EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null\n}\n\n/**\n * First usable email in a free-form form-submission fields map — forms\n * don't guarantee a canonical email field, so prefer keys that look like\n * email fields before falling back to any email-shaped value.\n */\nexport function extractEmailFromFields(\n fields: Record<string, unknown> | null | undefined,\n): string | null {\n const entries = Object.entries(fields ?? {})\n const preferred = entries.find(([key]) => /email/i.test(key))\n const fromPreferred = normalizeContactEmail(preferred?.[1])\n if (fromPreferred) return fromPreferred\n for (const [, value] of entries) {\n const email = normalizeContactEmail(value)\n if (email) return email\n }\n return null\n}\n\n/**\n * Merges a new interaction into a contact: source flag set, interaction\n * prepended, timeline capped. Pure — the caller persists the result.\n */\nexport function mergeContactInteraction(\n existing: Pick<HostContact, 'sources' | 'interactions'> & {\n name?: string\n },\n update: { source: ContactSource; interaction: ContactInteraction; name?: string },\n): Pick<HostContact, 'sources' | 'interactions'> & { name?: string } {\n return {\n // Existing names win — a later anonymous form shouldn't blank a name.\n name: existing.name || update.name,\n sources: { ...existing.sources, [update.source]: true as const },\n interactions: [update.interaction, ...(existing.interactions ?? [])].slice(\n 0,\n CONTACT_INTERACTIONS_CAP,\n ),\n }\n}\n\n/**\n * THE PER-HOLDER FACET on a shared contact document.\n *\n * ## What is shared and what is not\n *\n * One human who touched two sites is ONE document. That is not a compromise:\n * it is the dedupe the shared address book exists for, it is what keeps a\n * bounce and a suppression describing one person, and it is what makes a\n * multi-brand account bill once for one human instead of once per site. A\n * document per host would push an agency toward twelve separate accounts and\n * throw the whole advantage away.\n *\n * But almost nothing ON that document is legitimately shared.\n *\n * - **SHARED IDENTITY** — `email`, and the canonical `name`. One human, one\n * identity. This is the only part two unrelated businesses may both see,\n * and it is the minimum that makes them one row.\n * - **PER-HOLDER FACET** — everything in this interface. A note, a tag, a\n * call log and a lifetime value are the HOLDER's own business records.\n * Host A's note about a customer is Host A's; a competitor sharing the\n * platform must not read it, and while these lived at the top of the\n * document every site in the org could.\n * - **CONSENT AND VISIBILITY** — per declared group, decided by\n * `marketing-consent.ts` and by `visibleTo`.\n *\n * ## Keyed by GROUP, not by host\n *\n * A business that declared three sites to be one sender is one CRM: a note\n * written on the shop belongs beside the booking made on the booking page,\n * because one team keeps both. Across groups, never — and an undeclared site\n * is a group of one, so the agency case is isolated with nothing configured.\n *\n * ## Commercial figures are per-facet, and that is not a billing change\n *\n * `ltvCents` and `ordersCount` answer \"what is this person worth to ME\". Two\n * unrelated merchants who both sell to one person have two different answers\n * and neither is entitled to the other's. Billing counts DOCUMENTS, and there\n * is still one document, so a person held by two hosts stays one billable\n * contact.\n */\nexport interface ContactFacet {\n /**\n * This holder's display name for the person, overriding the canonical one.\n *\n * The canonical `name` is shared and mutable, so without this a rename on\n * one site changes what an unrelated business sees in its own CRM — two\n * companies that do not know each other exist editing each other's records.\n * The override is written by whoever edits the name from their own console;\n * the canonical field stays as the identity of last resort, for a holder\n * that has never set one.\n */\n name?: string\n /** Which capture surfaces THIS holder saw the person through. */\n sources: Partial<Record<ContactSource, true>>\n /** THIS holder's timeline, newest-first and capped. */\n interactions: ContactInteraction[]\n /** THIS holder's tags. */\n tags?: string[]\n /** THIS holder's notes. */\n notes?: string\n /**\n * The campaigns THIS holder has filed the person under.\n *\n * A label on the CRM record, not an audience: who a campaign's mail reaches\n * is decided by the campaign's lists and by each send's own picker, and\n * nothing in the send path reads this. It answers \"who did we put in the\n * spring push\", which is a question about the holder's own working set.\n *\n * Per-holder for the reason the notes are: two unrelated businesses sharing\n * one row must not read each other's segmentation of a person they both\n * know. See `campaign-membership.ts` for the field and the path.\n */\n campaignIds?: string[]\n /** Gross of fees and refunds — see `upsertHostContact`. */\n ltvCents?: number\n ordersCount?: number\n lastPurchaseAtMs?: number\n firstPurchaseAtMs?: number\n refundedCents?: number\n refundedOrdersCount?: number\n lastRefundAtMs?: number\n /*\n * CRM v2 (AGL-2595): the profile a sales team keeps on a person.\n *\n * Per-holder like everything above them, and for the same reason: a phone\n * number, a job title, an owner and a lifecycle stage are one business's\n * knowledge of a person, and two unrelated businesses sharing the row must\n * not read each other's. `companyId` points at a company document in the\n * same scope, never at the org's whole company list. `custom` is keyed by\n * `ContactFieldDefinition.key`, so a holder's field definitions and a\n * holder's values live under the same group and cannot be joined across\n * one.\n *\n * ⛔ None of these reach the org view. `ORG_CONTACT_FIELDS` is an\n * allow-list, and the org-view spec seeds every one of these with a\n * sentinel and proves it never surfaces.\n */\n /** E.164 — `normalizePhone` before writing. */\n phone?: string\n jobTitle?: string\n /**\n * Where this holder met the person — Salesforce's Lead Source, carried\n * from the lead on conversion and picked from the org's lead source\n * values after it (AGL-3298). The value's label, as the lead stores it.\n */\n leadSource?: string\n /** `orgs/{orgId}/companies/{companyId}`, in this holder's scope. */\n companyId?: string\n /**\n * The company's name as this holder knows it.\n *\n * Free text, so a person can be filed under a company before one exists\n * as a record; the company picker that later sets `companyId` writes the\n * picked company's name here too, so the row reads the same whether the\n * link was made or the name typed. The top-level `companyName` on the\n * document is the search echo of this value — see `HostContact`.\n */\n companyName?: string\n address?: AglynPostalAddress | null\n /** The team member responsible for the relationship. */\n ownerUid?: string\n lifecycleStage?: ContactLifecycleStage\n /** Custom field values, keyed by `ContactFieldDefinition.key`. */\n custom?: Record<string, ContactCustomValue>\n /**\n * When this person last OPENED or CLICKED a campaign sent by one of this\n * holder's sites, epoch ms (AGL-2616).\n *\n * Stamped by the delivery webhook, forward-only, on the first open and the\n * first click of each message — the same bound the per-person rollup on\n * `emailDeliveries/{key}` keeps, so a reader opening one newsletter six\n * times is one write. Per-holder because it answers \"is this person still\n * reading OUR mail\": the address-level rollup counts every sender's mail\n * and a sibling business's, and a re-engagement audience built on that\n * would mail people who are reading somebody else.\n *\n * Absent until the first engagement after the stamp shipped; a message\n * opened before then advanced the address-level rollup and nothing here.\n */\n lastEmailEngagementAtMs?: number\n /**\n * The org-library files THIS holder has attached to the person\n * (AGL-2662), by media document id.\n *\n * Per-holder for the reason every other field here is: an agency running\n * two client brands has one contact document between them, and a signed\n * contract one client filed is not the other client's to see. Ids rather\n * than URLs so a file moved between folders keeps its attachment, and so\n * a private asset is still served through the signed CDN door.\n */\n mediaIds?: string[]\n}\n\n/** The map field holding the facets: `{ [groupId]: ContactFacet }`. */\nexport const CONTACT_FACETS_FIELD = 'facets'\n\n/**\n * The facet one group holds, or an empty one.\n *\n * `map[groupId]` — a lookup, not a search, for the reason the consent map is\n * shaped the same way: there is no expression of this form that returns\n * another holder's notes.\n *\n * An absent facet reads EMPTY rather than falling back to the top-level\n * fields. A fallback would hand every holder in the org the fields the\n * pre-facet document carried at its top, which is the disclosure this shape\n * exists to end; the migration moves them into the capturing group's facet\n * instead.\n */\nexport function readContactFacet(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): ContactFacet {\n const facets = (contact ?? {})[CONTACT_FACETS_FIELD]\n const facet =\n facets && typeof facets === 'object' && !Array.isArray(facets)\n ? (facets as Record<string, unknown>)[groupId]\n : undefined\n if (!facet || typeof facet !== 'object' || Array.isArray(facet)) {\n return { sources: {}, interactions: [] }\n }\n const value = facet as Record<string, unknown>\n return {\n ...(value as unknown as ContactFacet),\n sources: (value['sources'] ?? {}) as ContactFacet['sources'],\n interactions: Array.isArray(value['interactions'])\n ? (value['interactions'] as ContactInteraction[])\n : [],\n }\n}\n\n/** The dotted Firestore path to one field of one holder's facet. */\nexport function contactFacetPath(groupId: string, field: string): string {\n if (!groupId) throw new Error('a contact facet must name a holder')\n return `${CONTACT_FACETS_FIELD}.${groupId}.${field}`\n}\n\n/**\n * The name a given holder should SEE for this person.\n *\n * Their own override first, the canonical identity second. Nothing falls\n * through to another holder's override: that would be one business's edit\n * showing up in another's CRM, which is the thing the override exists to\n * prevent.\n */\nexport function contactDisplayName(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): string {\n const facet = readContactFacet(contact, groupId)\n if (facet.name) return facet.name\n const canonical = (contact ?? {})['name']\n return typeof canonical === 'string' ? canonical : ''\n}\n\n/**\n * Every group that holds this contact — the reference count behind a detach.\n *\n * Read from `visibleTo` rather than from the facet map, because `visibleTo`\n * is what both enforcement layers actually evaluate: a holder that can still\n * READ the row is still holding it whether or not they ever wrote a note. A\n * count taken from the facets would drop a holder who has one and no facet\n * and leave them able to see a document nothing believes they hold.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const visibleTo = (contact ?? {})['visibleTo']\n return Array.isArray(visibleTo)\n ? visibleTo.filter((token): token is string => typeof token === 'string')\n : []\n}\n\n/** What a holder letting go of a contact should do to the document. */\nexport type ContactDetach =\n | {\n /** Nobody else holds it. Delete the document. */\n action: 'delete'\n }\n | {\n /** Other holders remain. Drop this one's half. */\n action: 'detach'\n /**\n * Field-level removals, as a patch. Dotted paths so the OTHER holders'\n * facets and consent entries are untouched — a nested write would\n * replace the whole map and take every other holder's records with it.\n */\n remove: string[]\n /** Scope tokens to pull out of `visibleTo`. */\n removeTokens: string[]\n /** Host ids to pull out of the capture attribution. */\n removeHostIds: string[]\n }\n\n/**\n * DELETE IS A DETACH.\n *\n * One holder removing a contact from their own CRM must not destroy another\n * holder's relationship with that person: they have their own notes, their\n * own order history and their own consent, none of which the deleting holder\n * ever had a claim on. So a delete drops the deleting group's facet, its\n * consent entries, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * ⛔ This is NOT the erasure path. A privacy erasure removes the person\n * everywhere regardless of how many holders remain, and routing it through\n * reference counting would turn a lawful erasure into a partial one — the same\n * absent-versus-invisible defect this area keeps hitting, in the one place\n * where getting it wrong is a legal failure rather than a bug. Erasure calls\n * the document delete directly and must never consult this function.\n *\n * @param group the holder letting go, with every site it covers.\n */\nexport function planContactDetach(\n contact: Record<string, unknown> | null | undefined,\n group: { groupId: string; hostIds: readonly string[] },\n): ContactDetach {\n const held = contactHolderTokens(contact)\n const leaving = new Set(group.hostIds.map((id) => `host:${id}`))\n /*\n * A remaining holder is a token naming somebody else. `'org'` counts as one\n * and blocks the delete on purpose: an org-wide row is held by every site\n * in the account, so one site letting go leaves it held. Narrowing it would\n * be a scope decision, and a delete button is not where that belongs.\n */\n const remaining = held.filter((token) => !leaving.has(token))\n if (!remaining.length) return { action: 'delete' }\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds.map((id) => `marketingConsentByHost.${id}`),\n ],\n removeTokens: [...leaving],\n removeHostIds: [...group.hostIds],\n }\n}\n\n/**\n * The interactions one group of sites may see on a shared contact.\n *\n * An interaction with NO host is shown to everyone: it predates the\n * attribution, so hiding it would empty every existing timeline, and it is\n * already visible to anyone who can read the row. An interaction that names a\n * site is shown only to that site's own group — the agency case, where one\n * client must not read another client's bookings off a person they both know.\n */\nexport function interactionsForGroup(\n interactions: readonly ContactInteraction[] | undefined,\n hostIds: readonly string[],\n): ContactInteraction[] {\n const reach = new Set(hostIds)\n return (interactions ?? []).filter(\n (interaction) => !interaction.hostId || reach.has(interaction.hostId),\n )\n}\n\n/** `orgs/{orgId}/contactSegments/{id}` — a saved audience filter. */\nexport interface ContactSegment {\n name: string\n /** Match contacts sharing at least one tag (empty = any). */\n tags?: string[]\n /** Match contacts with at least one of these sources (empty = any). */\n sources?: ContactSource[]\n}\n\n/** Segment matching (AGL-199): AND across filter kinds, OR within one. */\nexport function contactMatchesSegment(\n contact: Pick<HostContact, 'tags' | 'sources'>,\n segment: Pick<ContactSegment, 'tags' | 'sources'>,\n): boolean {\n if (segment.tags?.length) {\n const contactTags = new Set(\n (contact.tags ?? []).map((tag) => tag.toLowerCase()),\n )\n if (!segment.tags.some((tag) => contactTags.has(tag.toLowerCase()))) {\n return false\n }\n }\n if (segment.sources?.length) {\n if (!segment.sources.some((source) => contact.sources?.[source])) {\n return false\n }\n }\n return true\n}\n\n/*==========================================\n * THE ORG-LEVEL VIEW: the complement of the facet reader above.\n *\n * {@link readContactFacet} answers \"what does THIS holder know about this\n * person\". Everything below answers the question no host page can:\n *\n * who does this ORGANIZATION know, and which of its sites know them.\n *\n * That question is the entire justification for one shared document. Dedupe,\n * suppression and honest billing all rest on one human being one row, and\n * with no surface that shows the deduped person the model's benefit is\n * invisible and the billing unit — unique people per org — looks arbitrary.\n *\n * ## The org view crosses the host boundary, so it carries LESS, not more\n *\n * It is the one place in the product designed to read across holders, which\n * makes it the one place where a careless field re-creates the disclosure the\n * facets exist to end. So the projection is an ALLOW-LIST\n * ({@link ORG_CONTACT_FIELDS}) rather than an omission: identity, capture\n * attribution and consent state. Notes, tags, timelines, call logs and\n * commercial figures are the holder's own business records and are not read\n * here at all — not summarized, not counted, not indicated by their absence.\n *\n * An allow-list rather than a `delete facets` is the load-bearing choice. A\n * subtraction is correct only for as long as somebody remembers to extend it,\n * and a field added to {@link ContactFacet} tomorrow would ride out through a\n * subtraction and be caught by an allow-list.\n *\n * ## The NAME is the canonical one, never a holder's override\n *\n * {@link contactDisplayName} prefers the viewing group's own override, which\n * is right on a host page and wrong here: an override is a name ONE business\n * chose, and rendering it at org level shows an agency the label its client\n * picked. The shared identity is what every holder already sees, so it is the\n * only name that belongs to the org.\n *=========================================*/\n\n/**\n * Every field of a contact document the org view may read.\n *\n * Stated as a value so it can be asserted against — see the org-view spec,\n * which seeds each facet field with a sentinel and proves none of them\n * reaches a row.\n */\nexport const ORG_CONTACT_FIELDS = [\n 'email',\n 'name',\n CAPTURED_BY_HOST_FIELD,\n MARKETING_CONSENT_BY_HOST_FIELD,\n MARKETING_CONSENT_FIELD,\n] as const\n\n/**\n * What one site's relationship with one person amounts to, at org level.\n *\n * Consent is per (contact, host-or-group) and there is no expression that\n * returns another controller's grant, so a row cannot carry one consent\n * verdict. It carries one PER CAPTURING SITE, each naming the controller it\n * was read for — a bare \"consented\" with nobody attached would be exactly the\n * confusion the per-brand model was built to prevent.\n */\nexport interface OrgContactHostConsent {\n /** The site this verdict answers about, and no other. */\n hostId: string\n /** The controller the basis runs to — the declared group, or the site. */\n groupId: string\n /**\n * The group's disclosed name, or `null` for a site that pools with nobody.\n *\n * `null` is not \"unknown\": it is the group of one, where the site's own\n * name is the disclosure and inventing a second would put a label in front\n * of a reader that nothing else uses.\n */\n groupName: string | null\n /** Whether the controller is a DECLARED group rather than the site alone. */\n declared: boolean\n /** `granted` | `declined` | `unrecorded` — never collapsed to a boolean. */\n basis: MarketingBasis\n}\n\n/** One person, as the organization may see them across all of its sites. */\nexport interface OrgContactRow {\n $id: string\n /** The dedupe key, and the reason two captures are one row. */\n email: string\n /** The SHARED identity. Never a holder's own override. */\n name: string\n /** Every site that has captured this person, sorted for a stable render. */\n capturedByHostIds: string[]\n /** One verdict per capturing site, in the same order. */\n consent: OrgContactHostConsent[]\n}\n\n/**\n * Every site that has captured this person.\n *\n * Sorted, because the array is maintained by `arrayUnion` and therefore\n * carries capture order, which is not an order anything should render: two\n * readers of the same row would see the sites in different places on the\n * screen depending on which site met the person first.\n */\nexport function contactCaptureHostIds(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n const raw = (contact ?? {})[CAPTURED_BY_HOST_FIELD]\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw\n .map((id) => String(id ?? '').trim())\n .filter((id): id is string => id !== ''),\n ),\n ].sort()\n}\n\n/**\n * One contact document, projected to what an ORG may see.\n *\n * @param org - the org document — the only input that can resolve a declared\n * consent group, and required for that reason. Without it every site reads\n * as a group of one, which understates the disclosure a person was given\n * and is the safe direction to be wrong in.\n */\nexport function orgContactRow(\n contact: Record<string, unknown> | null | undefined,\n contactId: string,\n org: Record<string, unknown> | null | undefined,\n): OrgContactRow {\n const record = contact ?? {}\n const capturedByHostIds = contactCaptureHostIds(record)\n return {\n $id: contactId,\n email: typeof record['email'] === 'string' ? record['email'] : '',\n name: typeof record['name'] === 'string' ? record['name'] : '',\n capturedByHostIds,\n consent: capturedByHostIds.map((hostId) => {\n /*\n * READ FOR THE SITE, one call per site. `readMarketingBasis` requires\n * the group it is being read for and has no default, so this cannot\n * accidentally report a grant that belongs to somebody else — the\n * argument is the guarantee, and passing the whole row through one\n * call would have had to invent a controller to ask about.\n */\n const group = consentGroupForHost(org, hostId)\n const { basis } = readMarketingBasis(record, group)\n return {\n hostId,\n groupId: group.groupId,\n groupName: group.name,\n declared: group.declared,\n basis,\n }\n }),\n }\n}\n\n/**\n * How a basis reads on screen.\n *\n * Three labels because there are three states. \"Opted in\" and \"No record\" are\n * not opposites and must never collapse into one negative: absence is the\n * commonest case by far — a record captured before the checkbox existed — and\n * showing it as a refusal would tell a merchant they may not mail somebody\n * who never said so.\n */\nexport const MARKETING_BASIS_LABELS: Record<MarketingBasis, string> = {\n granted: 'Opted in',\n declined: 'Opted out',\n unrecorded: 'No record',\n}\n\n/**\n * One consent verdict, WITH THE CONTROLLER IT RUNS TO, as one string.\n *\n * ⛔ There is no function here that returns a basis on its own, and that is\n * the point. A basis is per (person, controller): the same person can be\n * opted in to one brand in an org and opted out of another, so \"consented\"\n * with nobody attached is not a shortened truth, it is a different and false\n * claim — precisely the confusion the per-brand model was built to prevent.\n * Joining the two into a single value is what stops a caller rendering half\n * of it.\n *\n * The controller is the DECLARED GROUP when there is one, because that is who\n * the person was told they would hear from, and the site otherwise. A group\n * of one is named by the site, which is what the capture surface already\n * showed them.\n *\n * @param siteName - how this site reads — the caller resolves it, since the\n * contact document holds ids and not names. An empty one falls back to the\n * id: a site whose name cannot be resolved must still be NAMED, because\n * dropping it would understate which brands hold a relationship.\n */\nexport function orgContactConsentLabel(\n entry: OrgContactHostConsent,\n siteName?: string,\n): string {\n const controller = entry.declared\n ? (entry.groupName ?? entry.groupId)\n : siteName || entry.hostId\n return `${controller} · ${MARKETING_BASIS_LABELS[entry.basis]}`\n}\n"],"names":["consentGroupForHost","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","CONTACT_SOURCE_LABELS","form","member","order","booking","newsletter","api","manual","import","account","CONTACT_INTERACTIONS_CAP","CONTACT_ALTERNATE_EMAILS_FIELD","CONTACT_ALTERNATE_EMAILS_CAP","CONTACT_EMAIL_INDEX_COLLECTION","contactEmails","contact","out","seen","Set","push","value","email","normalizeContactEmail","has","add","alternates","Array","isArray","forEach","CONTACT_FORM_IDS_FIELD","CONTACT_FORM_IDS_CAP","EMAIL_PATTERN","input","String","trim","toLowerCase","test","length","extractEmailFromFields","fields","entries","Object","preferred","find","key","fromPreferred","mergeContactInteraction","existing","update","name","sources","source","interactions","interaction","slice","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","contactFacetPath","field","Error","contactDisplayName","canonical","contactHolderTokens","visibleTo","filter","token","planContactDetach","group","held","leaving","hostIds","map","id","remaining","action","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","$id","consent","basis","groupName","declared","MARKETING_BASIS_LABELS","granted","declined","unrecorded","orgContactConsentLabel","entry","siteName","controller"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC;AAGD,SAASA,mBAAmB,QAAQ,sBAAkB;AAGtD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AA+B5B;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAuD;IAClEC,MAAM;IACNC,QAAQ;IACRC,OAAO;IACPC,SAAS;IACTC,YAAY;IACZC,KAAK;IACLC,QAAQ;IACRC,QAAQ;IACRC,SAAS;AACX,EAAC;AA0JD,mEAAmE,GACnE,OAAO,MAAMC,2BAA2B,GAAE;AAE1C,2DAA2D,GAC3D,OAAO,MAAMC,i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LECTIONS: {
68
68
  readonly contactFields: "contactFields";
69
69
  readonly views: "crmViews";
70
70
  readonly emailTemplates: "crmEmailTemplates";
71
+ /** An org's value sets for its standard picklist fields (AGL-3298). */
72
+ readonly picklists: "crmPicklists";
71
73
  };
72
74
  export type CrmCollection = (typeof CRM_COLLECTIONS)[keyof typeof CRM_COLLECTIONS];
73
75
  /**
@@ -1417,7 +1419,10 @@ export interface CrmLeadProfile {
1417
1419
  address?: AglynPostalAddress | null;
1418
1420
  /** Lower-cased, deduplicated, at most {@link CRM_LEAD_TAGS_MAX}. */
1419
1421
  tags?: string[];
1420
- /** Free text naming where the lead came from — Salesforce's Lead Source. */
1422
+ /**
1423
+ * Where the lead came from — Salesforce's Lead Source: the LABEL of one
1424
+ * of the org's lead source values (see {@link CrmPicklist}).
1425
+ */
1421
1426
  leadSource?: string;
1422
1427
  }
1423
1428
  /** The profile's keys, in the order a card lists them. */
@@ -1458,6 +1463,103 @@ export declare function normalizeCrmLeadProfile(input: Record<string, unknown> |
1458
1463
  patch: CrmLeadProfilePatch;
1459
1464
  errors: CrmLeadProfileErrors;
1460
1465
  };
1466
+ /** The picklists an org keeps, by document id — one per standard field. */
1467
+ export declare const CRM_PICKLIST_IDS: readonly ["leadSource"];
1468
+ export type CrmPicklistId = (typeof CRM_PICKLIST_IDS)[number];
1469
+ /** The lead source value set's document id. */
1470
+ export declare const CRM_LEAD_SOURCE_PICKLIST: CrmPicklistId;
1471
+ /** The most values one picklist holds — a menu, not a table. */
1472
+ export declare const CRM_PICKLIST_VALUES_MAX = 200;
1473
+ /** One value of a picklist. `id` never changes; `label` is what records store. */
1474
+ export interface CrmPicklistValue {
1475
+ id: string;
1476
+ label: string;
1477
+ active: boolean;
1478
+ }
1479
+ /** A picklist as stored and as every reader takes it. */
1480
+ export interface CrmPicklist {
1481
+ /** In the order every picker lists them. */
1482
+ values: CrmPicklistValue[];
1483
+ /** The value a new record starts with, by id — `null` for none. */
1484
+ defaultValueId: string | null;
1485
+ }
1486
+ /**
1487
+ * The values an org that has never edited its list reads — see the block
1488
+ * header. Salesforce's own standard set, trimmed to what a small team
1489
+ * recognizes.
1490
+ */
1491
+ export declare const CRM_LEAD_SOURCE_STARTER_LABELS: readonly string[];
1492
+ /** A label as a picklist stores it: trimmed, single-spaced, capped. */
1493
+ export declare function normalizeCrmPicklistLabel(value: unknown): string;
1494
+ /**
1495
+ * A new value's id: the label as a slug, suffixed until it is not one of
1496
+ * `taken`. Derived rather than random so a seeded list reads the same in
1497
+ * every org, and never reused, because a default names a value by it.
1498
+ */
1499
+ export declare function crmPicklistValueId(label: string, taken: Iterable<string>): string;
1500
+ /** A picklist of active values from labels, in order, with no default. */
1501
+ export declare function crmPicklistFromLabels(labels: readonly string[]): CrmPicklist;
1502
+ /**
1503
+ * A stored document as a picklist, or `null` for one that holds none.
1504
+ *
1505
+ * Tolerant, because the document is client-written: a value with no label
1506
+ * is dropped, a second value with the same label (in any case) or the same
1507
+ * id is dropped, `active` is true unless it is `false`, and a default that
1508
+ * names no value is no default.
1509
+ */
1510
+ export declare function normalizeCrmPicklist(raw: unknown): CrmPicklist | null;
1511
+ /** The org's lead source list as every reader should take it — see the block header. */
1512
+ export declare function effectiveCrmLeadSourcePicklist(raw: unknown): CrmPicklist;
1513
+ /** The value a label names, in any case or spacing — `null` for none. */
1514
+ export declare function crmPicklistValueByLabel(picklist: CrmPicklist, label: unknown): CrmPicklistValue | null;
1515
+ /** The values a picker offers. */
1516
+ export declare function crmPicklistActiveValues(picklist: CrmPicklist): CrmPicklistValue[];
1517
+ /** The label a new record starts with — only while the default value is active. */
1518
+ export declare function crmPicklistDefaultLabel(picklist: CrmPicklist): string | null;
1519
+ /**
1520
+ * The sentence a lead source outside the list is refused with, naming what
1521
+ * the list allows. A long list is cut at twenty names so the sentence stays
1522
+ * one a person can read.
1523
+ */
1524
+ export declare function crmLeadSourceRefusal(picklist: CrmPicklist): string;
1525
+ /**
1526
+ * Whether a write may store `value` as a record's lead source, and the
1527
+ * label it stores.
1528
+ *
1529
+ * - Blank or `null` clears the field — lead source is never required.
1530
+ * - An ACTIVE value, in any case or spacing, stores that value's label.
1531
+ * - The record's `current` value is kept even when it is inactive or no
1532
+ * longer listed: re-saving a record must never be refused for a value
1533
+ * somebody else deactivated.
1534
+ * - Anything else is refused with {@link crmLeadSourceRefusal}.
1535
+ */
1536
+ export declare function judgeCrmLeadSource(picklist: CrmPicklist, value: unknown, current?: unknown): {
1537
+ ok: true;
1538
+ value: string | null;
1539
+ } | {
1540
+ ok: false;
1541
+ error: string;
1542
+ };
1543
+ /** One option of a lead source select. */
1544
+ export interface CrmPicklistOption {
1545
+ label: string;
1546
+ /** Listed but deactivated — shown with an "(inactive)" hint. */
1547
+ inactive: boolean;
1548
+ /** Not in the list at all — a value written before the list existed. */
1549
+ unlisted: boolean;
1550
+ }
1551
+ /**
1552
+ * What a select offers for a record holding `current`: every active value
1553
+ * in order, then the record's own value when the list would not otherwise
1554
+ * show it, so the select keeps what the record holds until it is changed.
1555
+ */
1556
+ export declare function crmPicklistOptions(picklist: CrmPicklist, current?: unknown): CrmPicklistOption[];
1557
+ /**
1558
+ * Where a label sorts: its value's position in the list, unlisted values
1559
+ * after every listed one, and a record with none last. The order the admin
1560
+ * chose is the order a sort by the field reads in, as Salesforce's does.
1561
+ */
1562
+ export declare function crmPicklistRank(picklist: CrmPicklist, label: unknown): number;
1461
1563
  /** The name a lead is listed under: the name it carries, else its address. */
1462
1564
  export declare function crmLeadDisplayName(lead: Record<string, unknown> | null | undefined): string;
1463
1565
  /**