@aglyn/aglyn 1.1.0 → 1.2.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 +11 -11
- package/src/lib/app-utils/contacts.d.ts +4 -1
- package/src/lib/app-utils/contacts.js +5 -1
- package/src/lib/app-utils/contacts.js.map +1 -1
- package/src/lib/app-utils/crm.d.ts +11 -0
- package/src/lib/app-utils/crm.js +10 -4
- package/src/lib/app-utils/crm.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +1 -1
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/aglyn",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -37,16 +37,16 @@
|
|
|
37
37
|
"./package.json": "./package.json"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@aglyn/shared-data-enums": "1.
|
|
41
|
-
"@aglyn/shared-data-mdi": "1.
|
|
42
|
-
"@aglyn/shared-data-types": "1.
|
|
43
|
-
"@aglyn/shared-util-email": "1.
|
|
44
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
45
|
-
"@aglyn/shared-util-http": "1.
|
|
46
|
-
"@aglyn/shared-util-logger": "1.
|
|
47
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
48
|
-
"@aglyn/shared-util-tools": "1.
|
|
49
|
-
"@aglyn/shared-util-vendor": "1.
|
|
40
|
+
"@aglyn/shared-data-enums": "1.2.0",
|
|
41
|
+
"@aglyn/shared-data-mdi": "1.2.0",
|
|
42
|
+
"@aglyn/shared-data-types": "1.2.0",
|
|
43
|
+
"@aglyn/shared-util-email": "1.2.0",
|
|
44
|
+
"@aglyn/shared-util-first-touch": "1.2.0",
|
|
45
|
+
"@aglyn/shared-util-http": "1.2.0",
|
|
46
|
+
"@aglyn/shared-util-logger": "1.2.0",
|
|
47
|
+
"@aglyn/shared-util-timestamp": "1.2.0",
|
|
48
|
+
"@aglyn/shared-util-tools": "1.2.0",
|
|
49
|
+
"@aglyn/shared-util-vendor": "1.2.0",
|
|
50
50
|
"@data-driven-forms/react-form-renderer": "^4.2.0",
|
|
51
51
|
"@msgpack/msgpack": "^3.1.3",
|
|
52
52
|
"@types/unist": "^3.0.3",
|
|
@@ -628,7 +628,10 @@ export interface OrgContactRow {
|
|
|
628
628
|
name: string;
|
|
629
629
|
/** Every site that has captured this person, sorted for a stable render. */
|
|
630
630
|
capturedByHostIds: string[];
|
|
631
|
-
/**
|
|
631
|
+
/**
|
|
632
|
+
* One verdict per capturing site, in the same order. For a person no site
|
|
633
|
+
* captured, one per site their consent is recorded on, sorted.
|
|
634
|
+
*/
|
|
632
635
|
consent: OrgContactHostConsent[];
|
|
633
636
|
}
|
|
634
637
|
/**
|
|
@@ -434,12 +434,16 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
434
434
|
*/ export function orgContactRow(contact, contactId, org) {
|
|
435
435
|
const record = contact != null ? contact : {};
|
|
436
436
|
const capturedByHostIds = contactCaptureHostIds(record);
|
|
437
|
+
// A person no site captured was added at the organization level, and their
|
|
438
|
+
// consent is recorded on each site without one having met them.
|
|
439
|
+
const consentByHost = record[MARKETING_CONSENT_BY_HOST_FIELD];
|
|
440
|
+
const consentHostIds = capturedByHostIds.length || !consentByHost || typeof consentByHost !== 'object' ? capturedByHostIds : Object.keys(consentByHost).sort();
|
|
437
441
|
return {
|
|
438
442
|
$id: contactId,
|
|
439
443
|
email: typeof record['email'] === 'string' ? record['email'] : '',
|
|
440
444
|
name: typeof record['name'] === 'string' ? record['name'] : '',
|
|
441
445
|
capturedByHostIds,
|
|
442
|
-
consent:
|
|
446
|
+
consent: consentHostIds.map((hostId)=>{
|
|
443
447
|
/*
|
|
444
448
|
* READ FOR THE SITE, one call per site. `readMarketingBasis` requires
|
|
445
449
|
* the group it is being read for and has no default, so this cannot
|
|
@@ -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 { heldScopeTokens } from './scope-tokens'\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'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\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 `container-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 * SALESFORCE'S STANDARD CONTACT FIELDS (AGL-3515), per holder like the\n * profile above and for the same reason. Every one of them is personal\n * data about the person, so none reaches the org view (see\n * `ORG_CONTACT_FIELDS`) and an erasure takes them with the document.\n */\n /** One of the org's salutation values, by label (`Mr.`, `Dr.` …). */\n salutation?: string\n /**\n * The person's given and family names. While either is set, {@link name}\n * is their composition — see {@link composeContactName} — so every reader\n * of the display name reads the same person the structured fields name. A\n * facet holding only `name` keeps it as typed: nothing splits a stored\n * name into parts after the fact.\n */\n firstName?: string\n lastName?: string\n department?: string\n /** E.164, like {@link phone}. */\n mobilePhone?: string\n /** E.164. */\n homePhone?: string\n /** E.164. */\n otherPhone?: string\n /** E.164. */\n fax?: string\n /** A calendar date, `YYYY-MM-DD`, never in the future — {@link normalizeContactBirthdate}. */\n birthdate?: string\n assistantName?: string\n /** E.164. */\n assistantPhone?: string\n /**\n * Another contact of the org this holder can see — the person's manager.\n * Never the contact itself, and never a contact whose own chain leads\n * back here: `crm/contact-update` refuses both. `null` is \"nobody\" — what\n * a merge leaves where a pointer would have named the person themselves.\n */\n reportsToContactId?: string | null\n /**\n * A second postal address. {@link address} is the MAILING address — the\n * one a letter goes to — and keeps its field name; this is Salesforce's\n * Other Address beside it.\n */\n otherAddress?: AglynPostalAddress | null\n /**\n * The person asked not to be phoned. Stored only as `true`; absent is\n * \"may be called\". A hint beside every number and on the Call button,\n * never a block: the rep decides.\n */\n doNotCall?: boolean\n}\n\n/**\n * The profile's phone fields besides `phone` (AGL-3515), each stored E.164\n * through `normalizePhone`, in the order a record page lists them.\n */\nexport const CONTACT_EXTRA_PHONE_FIELDS = [\n 'mobilePhone',\n 'homePhone',\n 'otherPhone',\n 'fax',\n 'assistantPhone',\n] as const\n\nexport type ContactExtraPhoneField = (typeof CONTACT_EXTRA_PHONE_FIELDS)[number]\n\n/** How each phone field is labeled on screen, in a file and in the docs. */\nexport const CONTACT_PHONE_FIELD_LABELS: Record<'phone' | ContactExtraPhoneField, string> = {\n phone: 'Phone',\n mobilePhone: 'Mobile phone',\n homePhone: 'Home phone',\n otherPhone: 'Other phone',\n fax: 'Fax',\n assistantPhone: 'Assistant phone',\n}\n\n/** The longest first or last name a facet keeps — the composed name stays within 120. */\nexport const CONTACT_NAME_PART_MAX = 59\n\n/**\n * The display name a holder's first and last names make: `\"First Last\"`,\n * either alone, or `''` when neither is set — Salesforce's Name, less the\n * salutation, which is a form of address and not part of who the person is.\n */\nexport function composeContactName(firstName: unknown, lastName: unknown): string {\n const part = (value: unknown) =>\n String(value ?? '')\n .trim()\n .replace(/\\s+/g, ' ')\n .slice(0, CONTACT_NAME_PART_MAX)\n return [part(firstName), part(lastName)].filter(Boolean).join(' ')\n}\n\n/** The sentence a birthdate that cannot be stored is refused with. */\nexport const CONTACT_BIRTHDATE_REFUSAL =\n 'Birthdate must be a past date written YYYY-MM-DD, like 1984-07-21.'\n\n/**\n * A birthdate as stored: `YYYY-MM-DD` for a real calendar date that is not\n * in the future, `''` for a blank (a clear), and `null` for anything else.\n *\n * \"Not in the future\" is judged against the latest calendar day anywhere on\n * Earth (UTC+14), so a person entering today's date where the day has\n * already turned is never refused.\n */\nexport function normalizeContactBirthdate(value: unknown, nowMs = Date.now()): string | null {\n const text = String(value ?? '').trim()\n if (!text) return ''\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return null\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n const date = new Date(Date.UTC(year, month - 1, day))\n if (\n year < 1000 ||\n date.getUTCFullYear() !== year ||\n date.getUTCMonth() !== month - 1 ||\n date.getUTCDate() !== day\n ) {\n return null\n }\n const latestToday = new Date(nowMs + 14 * 60 * 60 * 1000).toISOString().slice(0, 10)\n return text > latestToday ? null : text\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/**\n * The facet of a person the ORGANIZATION holds rather than a site (AGL-4122):\n * someone added by hand at the organization level with no Source site, where\n * the record belongs to the whole org and no site has met them.\n *\n * A key in the same map as a consent group's id and read the same way, so the\n * record page, the update route and every reader of a facet serve this person\n * without knowing the difference. Never a consent group's own id: those are\n * Firestore ids, and `resolveConsentGroup` does not mint this one.\n */\nexport const ORG_CONTACT_HOLDER_ID = 'org'\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 * Who a contact is to ONE holder (AGL-4042): the name and the birthdate that\n * holder keeps, and nothing else. For a plugin that was handed a contact id\n * and must recognize the person — a waiver matched at check-in by name and\n * date of birth — without reading the CRM's record. The birthdate is null\n * unless it is a stored calendar date.\n */\nexport function contactIdentityForGroup(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): { name: string | null; birthdate: string | null } {\n if (!contact) return { name: null, birthdate: null }\n const name = contactDisplayName(contact, groupId).trim()\n return {\n name: name || null,\n // A blank reads as no birthdate, like one that is not a date.\n birthdate: normalizeContactBirthdate(readContactFacet(contact, groupId).birthdate) || null,\n }\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 *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\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 * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\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 * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take 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 grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\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', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${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","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","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_EXTRA_PHONE_FIELDS","CONTACT_PHONE_FIELD_LABELS","phone","mobilePhone","homePhone","otherPhone","fax","assistantPhone","CONTACT_NAME_PART_MAX","composeContactName","firstName","lastName","part","replace","filter","Boolean","join","CONTACT_BIRTHDATE_REFUSAL","normalizeContactBirthdate","nowMs","Date","now","text","match","exec","year","month","day","Number","date","UTC","getUTCFullYear","getUTCMonth","getUTCDate","latestToday","toISOString","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","ORG_CONTACT_HOLDER_ID","contactFacetPath","field","Error","contactDisplayName","canonical","contactIdentityForGroup","birthdate","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","token","action","retained","refused","byHost","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,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,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DzF,MAAM,OAAOyF,MAAM,CAAC,OAAO,KAAK,WAAWA,MAAM,CAAC,OAAO,GAAG;QAC5DC;QACAE,SAASF,kBAAkB5B,GAAG,CAAC,CAACa;YAC9B;;;;;;OAMC,GACD,MAAMjB,QAAQlH,oBAAoBgJ,KAAKb;YACvC,MAAM,EAAEkB,KAAK,EAAE,GAAGhJ,mBAAmB4I,QAAQ/B;YAC7C,OAAO;gBACLiB;gBACA/B,SAASc,MAAMd,OAAO;gBACtBkD,WAAWpC,MAAM1D,IAAI;gBACrB+F,UAAUrC,MAAMqC,QAAQ;gBACxBF;YACF;QACF;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMG,yBAAyD;IACpEC,SAAS;IACTC,UAAU;IACVC,YAAY;AACd,EAAC;AAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,uBACdC,KAA4B,EAC5BC,QAAiB;QAGZD;IADL,MAAME,aAAaF,MAAMN,QAAQ,IAC5BM,mBAAAA,MAAMP,SAAS,YAAfO,mBAAmBA,MAAMzD,OAAO,GACjC0D,YAAYD,MAAM1B,MAAM;IAC5B,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 { heldScopeTokens } from './scope-tokens'\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'\nimport { refusalsOf, type RetainedRefusals } from './retained-refusals'\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 `container-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 * SALESFORCE'S STANDARD CONTACT FIELDS (AGL-3515), per holder like the\n * profile above and for the same reason. Every one of them is personal\n * data about the person, so none reaches the org view (see\n * `ORG_CONTACT_FIELDS`) and an erasure takes them with the document.\n */\n /** One of the org's salutation values, by label (`Mr.`, `Dr.` …). */\n salutation?: string\n /**\n * The person's given and family names. While either is set, {@link name}\n * is their composition — see {@link composeContactName} — so every reader\n * of the display name reads the same person the structured fields name. A\n * facet holding only `name` keeps it as typed: nothing splits a stored\n * name into parts after the fact.\n */\n firstName?: string\n lastName?: string\n department?: string\n /** E.164, like {@link phone}. */\n mobilePhone?: string\n /** E.164. */\n homePhone?: string\n /** E.164. */\n otherPhone?: string\n /** E.164. */\n fax?: string\n /** A calendar date, `YYYY-MM-DD`, never in the future — {@link normalizeContactBirthdate}. */\n birthdate?: string\n assistantName?: string\n /** E.164. */\n assistantPhone?: string\n /**\n * Another contact of the org this holder can see — the person's manager.\n * Never the contact itself, and never a contact whose own chain leads\n * back here: `crm/contact-update` refuses both. `null` is \"nobody\" — what\n * a merge leaves where a pointer would have named the person themselves.\n */\n reportsToContactId?: string | null\n /**\n * A second postal address. {@link address} is the MAILING address — the\n * one a letter goes to — and keeps its field name; this is Salesforce's\n * Other Address beside it.\n */\n otherAddress?: AglynPostalAddress | null\n /**\n * The person asked not to be phoned. Stored only as `true`; absent is\n * \"may be called\". A hint beside every number and on the Call button,\n * never a block: the rep decides.\n */\n doNotCall?: boolean\n}\n\n/**\n * The profile's phone fields besides `phone` (AGL-3515), each stored E.164\n * through `normalizePhone`, in the order a record page lists them.\n */\nexport const CONTACT_EXTRA_PHONE_FIELDS = [\n 'mobilePhone',\n 'homePhone',\n 'otherPhone',\n 'fax',\n 'assistantPhone',\n] as const\n\nexport type ContactExtraPhoneField = (typeof CONTACT_EXTRA_PHONE_FIELDS)[number]\n\n/** How each phone field is labeled on screen, in a file and in the docs. */\nexport const CONTACT_PHONE_FIELD_LABELS: Record<'phone' | ContactExtraPhoneField, string> = {\n phone: 'Phone',\n mobilePhone: 'Mobile phone',\n homePhone: 'Home phone',\n otherPhone: 'Other phone',\n fax: 'Fax',\n assistantPhone: 'Assistant phone',\n}\n\n/** The longest first or last name a facet keeps — the composed name stays within 120. */\nexport const CONTACT_NAME_PART_MAX = 59\n\n/**\n * The display name a holder's first and last names make: `\"First Last\"`,\n * either alone, or `''` when neither is set — Salesforce's Name, less the\n * salutation, which is a form of address and not part of who the person is.\n */\nexport function composeContactName(firstName: unknown, lastName: unknown): string {\n const part = (value: unknown) =>\n String(value ?? '')\n .trim()\n .replace(/\\s+/g, ' ')\n .slice(0, CONTACT_NAME_PART_MAX)\n return [part(firstName), part(lastName)].filter(Boolean).join(' ')\n}\n\n/** The sentence a birthdate that cannot be stored is refused with. */\nexport const CONTACT_BIRTHDATE_REFUSAL =\n 'Birthdate must be a past date written YYYY-MM-DD, like 1984-07-21.'\n\n/**\n * A birthdate as stored: `YYYY-MM-DD` for a real calendar date that is not\n * in the future, `''` for a blank (a clear), and `null` for anything else.\n *\n * \"Not in the future\" is judged against the latest calendar day anywhere on\n * Earth (UTC+14), so a person entering today's date where the day has\n * already turned is never refused.\n */\nexport function normalizeContactBirthdate(value: unknown, nowMs = Date.now()): string | null {\n const text = String(value ?? '').trim()\n if (!text) return ''\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text)\n if (!match) return null\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n const date = new Date(Date.UTC(year, month - 1, day))\n if (\n year < 1000 ||\n date.getUTCFullYear() !== year ||\n date.getUTCMonth() !== month - 1 ||\n date.getUTCDate() !== day\n ) {\n return null\n }\n const latestToday = new Date(nowMs + 14 * 60 * 60 * 1000).toISOString().slice(0, 10)\n return text > latestToday ? null : text\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/**\n * The facet of a person the ORGANIZATION holds rather than a site (AGL-4122):\n * someone added by hand at the organization level with no Source site, where\n * the record belongs to the whole org and no site has met them.\n *\n * A key in the same map as a consent group's id and read the same way, so the\n * record page, the update route and every reader of a facet serve this person\n * without knowing the difference. Never a consent group's own id: those are\n * Firestore ids, and `resolveConsentGroup` does not mint this one.\n */\nexport const ORG_CONTACT_HOLDER_ID = 'org'\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 * Who a contact is to ONE holder (AGL-4042): the name and the birthdate that\n * holder keeps, and nothing else. For a plugin that was handed a contact id\n * and must recognize the person — a waiver matched at check-in by name and\n * date of birth — without reading the CRM's record. The birthdate is null\n * unless it is a stored calendar date.\n */\nexport function contactIdentityForGroup(\n contact: Record<string, unknown> | null | undefined,\n groupId: string,\n): { name: string | null; birthdate: string | null } {\n if (!contact) return { name: null, birthdate: null }\n const name = contactDisplayName(contact, groupId).trim()\n return {\n name: name || null,\n // A blank reads as no birthdate, like one that is not a date.\n birthdate: normalizeContactBirthdate(readContactFacet(contact, groupId).birthdate) || null,\n }\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 *\n * Less the tokens a share ADDED (AGL-3336): a site the record was shared\n * with sees it and holds nothing, so it must not keep the record alive when\n * its last holder lets go — `heldScopeTokens` is `visibleTo` without them.\n */\nexport function contactHolderTokens(\n contact: Record<string, unknown> | null | undefined,\n): string[] {\n return heldScopeTokens(contact)\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 * Every refusal the document holds, every site's and the unscoped one,\n * which the delete keeps in `retainedRefusals` in the same transaction\n * — see `retained-refusals.ts`. `null` when it holds none.\n */\n retained: RetainedRefusals | null\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 * A consent entry that is a REFUSAL is not among them: it stays on the\n * document for the holders that remain, because a person's \"no\" is not\n * the leaving holder's to take 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 grants, its capture attribution and its scope tokens — and the\n * DOCUMENT dies only when the last holder lets go.\n *\n * A REFUSAL IS NOT LET GO (AGL-3338). The list gate reads a stored refusal\n * as the one fact an operator's attestation cannot overrule, so a detach\n * leaves the leaving group's refusal entries on the document, and a delete\n * answers every refusal the document holds for the caller to retain beside\n * the delete. Read off the document's own data: a table row's projection\n * carries neither the consent map nor the unscoped field.\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', retained: refusalsOf(contact) }\n const refused = refusalsOf(contact)?.byHost ?? {}\n return {\n action: 'detach',\n remove: [\n `${CONTACT_FACETS_FIELD}.${group.groupId}`,\n ...group.hostIds\n .filter((id) => !(id in refused))\n .map((id) => `${MARKETING_CONSENT_BY_HOST_FIELD}.${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 /**\n * One verdict per capturing site, in the same order. For a person no site\n * captured, one per site their consent is recorded on, sorted.\n */\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 // A person no site captured was added at the organization level, and their\n // consent is recorded on each site without one having met them.\n const consentByHost = record[MARKETING_CONSENT_BY_HOST_FIELD]\n const consentHostIds =\n capturedByHostIds.length || !consentByHost || typeof consentByHost !== 'object'\n ? capturedByHostIds\n : Object.keys(consentByHost).sort()\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: consentHostIds.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","heldScopeTokens","CAPTURED_BY_HOST_FIELD","MARKETING_CONSENT_BY_HOST_FIELD","MARKETING_CONSENT_FIELD","readMarketingBasis","refusalsOf","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_EXTRA_PHONE_FIELDS","CONTACT_PHONE_FIELD_LABELS","phone","mobilePhone","homePhone","otherPhone","fax","assistantPhone","CONTACT_NAME_PART_MAX","composeContactName","firstName","lastName","part","replace","filter","Boolean","join","CONTACT_BIRTHDATE_REFUSAL","normalizeContactBirthdate","nowMs","Date","now","text","match","exec","year","month","day","Number","date","UTC","getUTCFullYear","getUTCMonth","getUTCDate","latestToday","toISOString","CONTACT_FACETS_FIELD","readContactFacet","groupId","facets","facet","undefined","ORG_CONTACT_HOLDER_ID","contactFacetPath","field","Error","contactDisplayName","canonical","contactIdentityForGroup","birthdate","contactHolderTokens","planContactDetach","group","held","leaving","hostIds","map","id","remaining","token","action","retained","refused","byHost","remove","removeTokens","removeHostIds","interactionsForGroup","reach","hostId","contactMatchesSegment","segment","tags","contactTags","tag","some","ORG_CONTACT_FIELDS","contactCaptureHostIds","raw","sort","orgContactRow","contactId","org","record","capturedByHostIds","consentByHost","consentHostIds","keys","$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,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SACEC,sBAAsB,EACtBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,kBAAkB,QAEb,yBAAqB;AAC5B,SAASC,UAAU,QAA+B,yBAAqB;AA+BvE;;;;;;;;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,iCAAiC,kBAAiB;AAE/D;;;CAGC,GACD,OAAO,MA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B;;;;;;OAMC,GACD,MAAMjB,QAAQlH,oBAAoBgJ,KAAKb;YACvC,MAAM,EAAEqB,KAAK,EAAE,GAAGnJ,mBAAmB4I,QAAQ/B;YAC7C,OAAO;gBACLiB;gBACA/B,SAASc,MAAMd,OAAO;gBACtBqD,WAAWvC,MAAM1D,IAAI;gBACrBkG,UAAUxC,MAAMwC,QAAQ;gBACxBF;YACF;QACF;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMG,yBAAyD;IACpEC,SAAS;IACTC,UAAU;IACVC,YAAY;AACd,EAAC;AAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASC,uBACdC,KAA4B,EAC5BC,QAAiB;QAGZD;IADL,MAAME,aAAaF,MAAMN,QAAQ,IAC5BM,mBAAAA,MAAMP,SAAS,YAAfO,mBAAmBA,MAAM5D,OAAO,GACjC6D,YAAYD,MAAM7B,MAAM;IAC5B,OAAO,GAAG+B,WAAW,GAAG,EAAEP,sBAAsB,CAACK,MAAMR,KAAK,CAAC,EAAE;AACjE"}
|
|
@@ -654,6 +654,12 @@ export interface CrmTask extends Omit<CrmScoped, 'hostId'> {
|
|
|
654
654
|
}
|
|
655
655
|
/** How an activity kind reads on screen — typed so a kind cannot ship unlabeled. */
|
|
656
656
|
export declare const CRM_ACTIVITY_KIND_LABELS: Record<CrmActivityKind, string>;
|
|
657
|
+
/**
|
|
658
|
+
* How a kind reads after a direction — "Inbound call", "Outbound WhatsApp
|
|
659
|
+
* message". Its own map rather than the label lowercased, because a brand
|
|
660
|
+
* keeps its capitals and a channel's name is not the thing that was sent.
|
|
661
|
+
*/
|
|
662
|
+
export declare const CRM_ACTIVITY_KIND_NOUNS: Record<CrmActivityKind, string>;
|
|
657
663
|
/**
|
|
658
664
|
* Whether a kind takes an outcome and a duration.
|
|
659
665
|
*
|
|
@@ -2407,6 +2413,11 @@ export declare const CRM_PICKLIST_DEFINITIONS: readonly [{
|
|
|
2407
2413
|
readonly field: "contactRoles";
|
|
2408
2414
|
readonly arrayKey: "role";
|
|
2409
2415
|
readonly keyField: "contactRoleKeys";
|
|
2416
|
+
}, {
|
|
2417
|
+
readonly object: "company";
|
|
2418
|
+
readonly field: "contactRoles";
|
|
2419
|
+
readonly arrayKey: "role";
|
|
2420
|
+
readonly keyField: "contactRoleKeys";
|
|
2410
2421
|
}];
|
|
2411
2422
|
}, {
|
|
2412
2423
|
readonly id: "taskStatus";
|
package/src/lib/app-utils/crm.js
CHANGED
|
@@ -518,7 +518,7 @@ export const CRM_TASK_KIND_LABELS = {
|
|
|
518
518
|
* How a kind reads after a direction — "Inbound call", "Outbound WhatsApp
|
|
519
519
|
* message". Its own map rather than the label lowercased, because a brand
|
|
520
520
|
* keeps its capitals and a channel's name is not the thing that was sent.
|
|
521
|
-
*/ const CRM_ACTIVITY_KIND_NOUNS = {
|
|
521
|
+
*/ export const CRM_ACTIVITY_KIND_NOUNS = {
|
|
522
522
|
call: 'call',
|
|
523
523
|
email: 'email',
|
|
524
524
|
text: 'text message',
|
|
@@ -2909,9 +2909,9 @@ export function isCrmPicklistObject(value) {
|
|
|
2909
2909
|
};
|
|
2910
2910
|
/**
|
|
2911
2911
|
* Salesforce's Opportunity Contact Role (AGL-3521): the part a contact
|
|
2912
|
-
* plays on a deal. Plain; the label sits in each
|
|
2913
|
-
* `contactRoles`, and `contactRoleKeys` lists their
|
|
2914
|
-
* rename or a delete finds the
|
|
2912
|
+
* plays on a deal, and on a company (AGL-4122). Plain; the label sits in each
|
|
2913
|
+
* entry of the record's `contactRoles`, and `contactRoleKeys` lists their
|
|
2914
|
+
* keys, which is how a rename or a delete finds the records to rewrite.
|
|
2915
2915
|
*/ const OPPORTUNITY_CONTACT_ROLE_DEFINITION = {
|
|
2916
2916
|
id: 'opportunityContactRole',
|
|
2917
2917
|
label: 'Contact role',
|
|
@@ -2962,6 +2962,12 @@ export function isCrmPicklistObject(value) {
|
|
|
2962
2962
|
field: 'contactRoles',
|
|
2963
2963
|
arrayKey: 'role',
|
|
2964
2964
|
keyField: 'contactRoleKeys'
|
|
2965
|
+
},
|
|
2966
|
+
{
|
|
2967
|
+
object: 'company',
|
|
2968
|
+
field: 'contactRoles',
|
|
2969
|
+
arrayKey: 'role',
|
|
2970
|
+
keyField: 'contactRoleKeys'
|
|
2965
2971
|
}
|
|
2966
2972
|
]
|
|
2967
2973
|
};
|