@aglyn/plugins-crm 1.19.0 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/log-activity-dialog.d.ts +2 -0
  3. package/src/lib/components/log-activity-dialog.js +11 -2
  4. package/src/lib/components/log-activity-dialog.js.map +1 -1
  5. package/src/lib/components/record-sharing-card.js +8 -7
  6. package/src/lib/components/record-sharing-card.js.map +1 -1
  7. package/src/lib/components/settings-section.d.ts +10 -3
  8. package/src/lib/components/settings-section.js +286 -35
  9. package/src/lib/components/settings-section.js.map +1 -1
  10. package/src/lib/components/share-records-dialog.d.ts +17 -3
  11. package/src/lib/components/share-records-dialog.js +59 -45
  12. package/src/lib/components/share-records-dialog.js.map +1 -1
  13. package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
  14. package/src/lib/components/sharing-rule-drawer.js +51 -40
  15. package/src/lib/components/sharing-rule-drawer.js.map +1 -1
  16. package/src/lib/components/sharing-rules-card.js +2 -1
  17. package/src/lib/components/sharing-rules-card.js.map +1 -1
  18. package/src/lib/declarations.server.js +10 -1
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/hooks/use-campaign-filing-log.js +10 -2
  21. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
  22. package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
  23. package/src/lib/hooks/use-crm-sharing.js +20 -0
  24. package/src/lib/hooks/use-crm-sharing.js.map +1 -1
  25. package/src/lib/model/crm-sharing-api.d.ts +5 -2
  26. package/src/lib/model/crm-sharing-api.js +3 -0
  27. package/src/lib/model/crm-sharing-api.js.map +1 -1
  28. package/src/lib/model/crm-sharing.d.ts +153 -5
  29. package/src/lib/model/crm-sharing.js +243 -20
  30. package/src/lib/model/crm-sharing.js.map +1 -1
  31. package/src/lib/model/lead-filters.d.ts +1 -1
  32. package/src/lib/server/add-contact-by-hand.js +11 -4
  33. package/src/lib/server/add-contact-by-hand.js.map +1 -1
  34. package/src/lib/server/api-v1/crm-activities.js +2 -2
  35. package/src/lib/server/api-v1/crm-activities.js.map +1 -1
  36. package/src/lib/server/api-v1/crm-companies.js +2 -2
  37. package/src/lib/server/api-v1/crm-companies.js.map +1 -1
  38. package/src/lib/server/api-v1/crm-deals.js +2 -2
  39. package/src/lib/server/api-v1/crm-deals.js.map +1 -1
  40. package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
  41. package/src/lib/server/api-v1/crm-shared.js +12 -1
  42. package/src/lib/server/api-v1/crm-shared.js.map +1 -1
  43. package/src/lib/server/api-v1/crm-tasks.js +2 -2
  44. package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
  45. package/src/lib/server/associate-company-by-domain.d.ts +1 -1
  46. package/src/lib/server/associate-company-by-domain.js +4 -4
  47. package/src/lib/server/associate-company-by-domain.js.map +1 -1
  48. package/src/lib/server/automation-steps.js +24 -12
  49. package/src/lib/server/automation-steps.js.map +1 -1
  50. package/src/lib/server/campaign-filing-activity.js +7 -3
  51. package/src/lib/server/campaign-filing-activity.js.map +1 -1
  52. package/src/lib/server/convert-host-lead.js +13 -4
  53. package/src/lib/server/convert-host-lead.js.map +1 -1
  54. package/src/lib/server/crm-default-sharing.d.ts +86 -0
  55. package/src/lib/server/crm-default-sharing.js +409 -0
  56. package/src/lib/server/crm-default-sharing.js.map +1 -0
  57. package/src/lib/server/crm-inbound-email.js +2 -2
  58. package/src/lib/server/crm-inbound-email.js.map +1 -1
  59. package/src/lib/server/crm-sharing-runs.d.ts +71 -0
  60. package/src/lib/server/crm-sharing-runs.js +221 -0
  61. package/src/lib/server/crm-sharing-runs.js.map +1 -0
  62. package/src/lib/server/crm-sharing.d.ts +24 -1
  63. package/src/lib/server/crm-sharing.js +183 -31
  64. package/src/lib/server/crm-sharing.js.map +1 -1
  65. package/src/lib/server/email-send.js +5 -2
  66. package/src/lib/server/email-send.js.map +1 -1
  67. package/src/lib/server/record-timeline.d.ts +2 -1
  68. package/src/lib/server/record-timeline.js +11 -6
  69. package/src/lib/server/record-timeline.js.map +1 -1
  70. package/src/lib/server/task-routes.js +10 -6
  71. package/src/lib/server/task-routes.js.map +1 -1
  72. package/src/lib/server.js +23 -1
  73. package/src/lib/server.js.map +1 -1
  74. package/src/lib/transfer/common.d.ts +5 -1
  75. package/src/lib/transfer/common.js +8 -5
  76. package/src/lib/transfer/common.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-sharing.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 * CRM SHARING FOR MULTI-BRAND ORGS (AGL-3336).\n *\n * A member holding \"Change CRM settings\" shares a lead, a contact, a company or a deal with other\n * sites — by hand, from the record or a list's bulk bar, or by a SHARING\n * RULE that applies to every record it matches, now and later. The model is\n * Salesforce's three layers:\n *\n * 1. the org-wide default — the consent-group scope a record is captured\n * with (`consentGroupScope`), untouched by anything here;\n * 2. sharing rules — `crm.sharingRules` on the org document;\n * 3. manual shares — per record, per target.\n *\n * ## One field is enforced, so one field is widened\n *\n * Both enforcement layers read `visibleTo`: the rules with `hasAny`, every\n * list with `array-contains-any`. A share therefore ADDS its tokens to\n * `visibleTo`, which is what puts the record on the target site's lists as a\n * real query — no second field, no second index, no loaded-window match.\n * `'org'` is the token for \"all sites\", and it covers a site created later\n * with nothing to recompute, because every site's read set carries it.\n *\n * ## …and the sources stay distinguishable\n *\n * The record keeps its grants under `sharing` (`SCOPE_GRANTS_FIELD` in\n * core): one grant per rule and one per hand-shared target, and `added`,\n * the tokens the grants put on `visibleTo` that were not there already.\n * The record's own scope — its HELD tokens — is `visibleTo` without\n * `added`, so taking a grant away removes only what grants alone\n * contributed, and never a consent-group token. A token a site later\n * captures the person on is held from then on: the capturing sites\n * (`hostId`, `capturedByHostIds`) are never counted as added.\n *\n * ## Visibility is not consent, and not write access\n *\n * Nothing here reads or writes a consent entry. A site a record is shared\n * with sees it; it holds no basis to market to the person, and the\n * audience paths read `heldByHost`, not `visibleTo`. Write access is its\n * own field, `writeTo`, present only on a shared record: the held tokens\n * and the tokens of grants whose access is `edit`. The Firestore rules and\n * the CRM's routes check it; a read-only grant is the default.\n */\n\nimport type { ScopeToken } from '@aglyn/aglyn'\nimport {\n heldScopeTokens,\n hostIdsFromScope,\n hostScopeToken,\n isScopeToken,\n MAX_SCOPE_HOSTS,\n ORG_SCOPE_TOKEN,\n parseScopeToken,\n SCOPE_GRANTS_FIELD,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { CrmPicklist } from '@aglyn/aglyn/app-utils/crm'\nimport {\n isLeadSourceDirection,\n LEAD_SOURCE_DIRECTION_LABELS,\n leadSourceDirectionOf,\n STANDARD_LEAD_SOURCES,\n} from './lead-source-direction'\n\n/*==========================================\n * WHAT IS SHARED.\n *=========================================*/\n\n/** The four record types a share or a rule applies to, by their collection. */\nexport const CRM_SHARING_OBJECTS = ['leads', 'contacts', 'companies', 'deals'] as const\nexport type CrmSharingObject = (typeof CRM_SHARING_OBJECTS)[number]\n\nexport function isCrmSharingObject(value: unknown): value is CrmSharingObject {\n return (\n typeof value === 'string' && (CRM_SHARING_OBJECTS as readonly string[]).includes(value)\n )\n}\n\n/** How each object reads in a sentence. */\nexport const CRM_SHARING_OBJECT_LABELS: Readonly<\n Record<CrmSharingObject, { one: string; many: string }>\n> = {\n leads: { one: 'lead', many: 'Leads' },\n contacts: { one: 'contact', many: 'Contacts' },\n companies: { one: 'company', many: 'Companies' },\n deals: { one: 'deal', many: 'Deals' },\n}\n\n/** What a target site may do with a shared record. Read-only unless a grant says edit. */\nexport type CrmShareAccess = 'read' | 'edit'\n\nexport function isCrmShareAccess(value: unknown): value is CrmShareAccess {\n return value === 'read' || value === 'edit'\n}\n\n/** Where a grant came from. */\nexport type CrmShareSource = 'manual' | 'rule'\n\n/** One grant on one record. */\nexport interface CrmShareGrant {\n source: CrmShareSource\n /** The sites it shares with: `['org']` for all sites, else host tokens. */\n tokens: ScopeToken[]\n access: CrmShareAccess\n /** The rule behind a `rule` grant. */\n ruleId?: string\n /** Who shared it by hand, as they were named at the time. */\n byUid?: string\n byName?: string\n /** When the grant was made. */\n atMs: number\n}\n\n/** `sharing` on a record — see the module note. */\nexport interface CrmRecordSharing {\n /** Keyed by {@link manualGrantKey} or {@link ruleGrantKey}. */\n grants: Record<string, CrmShareGrant>\n /** Every token any grant names — the record's shares, however held. */\n tokens: ScopeToken[]\n /** The tokens the grants ADDED to `visibleTo` — see `heldScopeTokens`. */\n added: ScopeToken[]\n /** The rules holding a grant here, so a rule's removal can find its records. */\n ruleIds: string[]\n /**\n * The held tokens of a record shared with all sites, and nothing\n * otherwise. `array-contains` on it answers \"is this record shared with\n * everyone AND held by site X\" — the one question `added` alone cannot,\n * since a query takes a single array clause.\n */\n orgWideHeldBy: ScopeToken[]\n}\n\n/** The record field its grants live under — the core's name for it. */\nexport const CRM_SHARING_FIELD = SCOPE_GRANTS_FIELD\n\n/** The record field naming who may WRITE it, present only while it is shared. */\nexport const CRM_WRITE_SCOPE_FIELD = 'writeTo'\n\n/** The array field a rule's removal queries. */\nexport const CRM_SHARING_RULE_IDS_PATH = `${CRM_SHARING_FIELD}.ruleIds`\n\n/** A hand share is one grant per target, so each is unshared on its own. */\nexport function manualGrantKey(token: string): string {\n const parsed = parseScopeToken(token)\n if (!parsed) throw new Error(`not a scope token: ${token}`)\n return parsed.kind === 'org' ? 'manual_org' : `manual_${parsed.hostId}`\n}\n\nexport function ruleGrantKey(ruleId: string): string {\n return `rule_${ruleId}`\n}\n\nfunction tokenList(raw: unknown): ScopeToken[] {\n if (!Array.isArray(raw)) return []\n return [...new Set(raw.filter(isScopeToken))]\n}\n\nfunction readGrant(raw: unknown): CrmShareGrant | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const tokens = tokenList(value['tokens'])\n if (!tokens.length) return null\n const source = value['source'] === 'rule' ? 'rule' : value['source'] === 'manual' ? 'manual' : null\n if (!source) return null\n const ruleId = typeof value['ruleId'] === 'string' ? value['ruleId'] : ''\n if (source === 'rule' && !ruleId) return null\n const byUid = typeof value['byUid'] === 'string' ? value['byUid'] : ''\n const byName = typeof value['byName'] === 'string' ? value['byName'] : ''\n const atMs = typeof value['atMs'] === 'number' && Number.isFinite(value['atMs']) ? value['atMs'] : 0\n return {\n source,\n tokens,\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(ruleId ? { ruleId } : {}),\n ...(byUid ? { byUid } : {}),\n ...(byName ? { byName } : {}),\n atMs,\n }\n}\n\n/** A record's grants, cleaned; `{}` for a record never shared. */\nexport function readRecordGrants(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, CrmShareGrant> {\n const sharing = (record ?? {})[CRM_SHARING_FIELD]\n if (!sharing || typeof sharing !== 'object' || Array.isArray(sharing)) return {}\n const grants = (sharing as Record<string, unknown>)['grants']\n if (!grants || typeof grants !== 'object' || Array.isArray(grants)) return {}\n const out: Record<string, CrmShareGrant> = {}\n for (const [key, raw] of Object.entries(grants as Record<string, unknown>)) {\n const grant = readGrant(raw)\n if (grant) out[key] = grant\n }\n return out\n}\n\n/*==========================================\n * THE PLAN: grants in, the three fields out.\n *=========================================*/\n\n/**\n * The sites that captured or created the record. Their tokens are HELD,\n * whatever `added` says: a person shared to site B and later captured on B\n * is B's own from then on, and unsharing must not hide them from B.\n */\nexport function recordHolderHostIds(record: Readonly<Record<string, unknown>>): string[] {\n const ids = new Set<string>()\n const hostId = record['hostId']\n if (typeof hostId === 'string' && hostId) ids.add(hostId)\n const captured = record['capturedByHostIds']\n if (Array.isArray(captured)) {\n for (const id of captured) if (typeof id === 'string' && id) ids.add(id)\n }\n return [...ids]\n}\n\n/**\n * The record's own scope: `visibleTo` less what grants added, its capturing\n * sites kept — the core's `heldScopeTokens`, as scope tokens.\n */\nexport function recordHeldScope(record: Readonly<Record<string, unknown>>): ScopeToken[] {\n return tokenList(heldScopeTokens(record))\n}\n\nexport interface CrmSharingPlan {\n visibleTo: ScopeToken[]\n /** `null` removes the field: an unshared record writes by `visibleTo`. */\n writeTo: ScopeToken[] | null\n /** `null` removes the field. */\n sharing: CrmRecordSharing | null\n}\n\n/**\n * The fields a record carries under `grants`.\n *\n * A grant naming a token the record already holds adds nothing, and a\n * record held org-wide adds nothing at all — every site sees it already, so\n * a share there would only make a later unshare look like it hid something.\n * The token order is the held scope first and the additions after it, so an\n * unchanged record plans the `visibleTo` it has.\n */\nexport function planRecordSharing(\n record: Readonly<Record<string, unknown>>,\n grants: Readonly<Record<string, CrmShareGrant>>,\n): CrmSharingPlan {\n const held = recordHeldScope(record)\n const entries = Object.entries(grants)\n if (!entries.length) return { visibleTo: held, writeTo: null, sharing: null }\n const heldSet = new Set<string>(held)\n const heldOrgWide = heldSet.has(ORG_SCOPE_TOKEN)\n const tokens: ScopeToken[] = []\n const editTokens: ScopeToken[] = []\n const ruleIds: string[] = []\n for (const [, grant] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n for (const token of grant.tokens) {\n if (!tokens.includes(token)) tokens.push(token)\n if (grant.access === 'edit' && !editTokens.includes(token)) editTokens.push(token)\n }\n if (grant.source === 'rule' && grant.ruleId && !ruleIds.includes(grant.ruleId)) {\n ruleIds.push(grant.ruleId)\n }\n }\n const added = heldOrgWide ? [] : tokens.filter((token) => !heldSet.has(token))\n const writeTo = [...held]\n for (const token of editTokens) if (!writeTo.includes(token)) writeTo.push(token)\n return {\n visibleTo: [...held, ...added],\n writeTo,\n sharing: {\n grants: Object.fromEntries(entries),\n tokens,\n added,\n ruleIds,\n orgWideHeldBy: added.includes(ORG_SCOPE_TOKEN) ? [...held] : [],\n },\n }\n}\n\nconst sameList = (a: readonly unknown[] | null | undefined, b: readonly unknown[] | null | undefined) =>\n (a ?? null) === null\n ? (b ?? null) === null\n : (b ?? null) !== null && a!.length === b!.length && a!.every((entry, at) => entry === b![at])\n\nconst sameGrant = (a: CrmShareGrant | undefined, b: CrmShareGrant | undefined) =>\n !!a &&\n !!b &&\n a.source === b.source &&\n a.access === b.access &&\n (a.ruleId ?? '') === (b.ruleId ?? '') &&\n (a.byUid ?? '') === (b.byUid ?? '') &&\n (a.byName ?? '') === (b.byName ?? '') &&\n a.atMs === b.atMs &&\n sameList(a.tokens, b.tokens)\n\n/** Whether writing `plan` would change what the record stores. */\nexport function sharingPlanChanges(\n record: Readonly<Record<string, unknown>>,\n plan: CrmSharingPlan,\n): boolean {\n if (!sameList(tokenList(record['visibleTo']), plan.visibleTo)) return true\n const storedWrite = record[CRM_WRITE_SCOPE_FIELD]\n if (!sameList(Array.isArray(storedWrite) ? tokenList(storedWrite) : null, plan.writeTo)) return true\n const stored = record[CRM_SHARING_FIELD]\n if (!plan.sharing) return stored !== undefined && stored !== null\n const grants = readRecordGrants(record)\n const keys = Object.keys(plan.sharing.grants)\n if (keys.length !== Object.keys(grants).length) return true\n if (!keys.every((key) => sameGrant(grants[key], plan.sharing!.grants[key]))) return true\n const sharing = (stored ?? {}) as Record<string, unknown>\n return (\n !sameList(tokenList(sharing['tokens']), plan.sharing.tokens) ||\n !sameList(tokenList(sharing['added']), plan.sharing.added) ||\n !sameList(\n Array.isArray(sharing['ruleIds']) ? (sharing['ruleIds'] as unknown[]) : [],\n plan.sharing.ruleIds,\n ) ||\n !sameList(tokenList(sharing['orgWideHeldBy']), plan.sharing.orgWideHeldBy)\n )\n}\n\n/*==========================================\n * SHARING RULES: `crm.sharingRules` on the org document.\n *=========================================*/\n\n/** The org document path the rules are stored under. */\nexport const CRM_SHARING_RULES_PATH = 'crm.sharingRules'\n\n/** A workspace keeps at most this many. */\nexport const CRM_SHARING_RULES_MAX = 20\n\n/** At most this many values per criterion. */\nexport const CRM_SHARING_CRITERION_MAX = 20\n\n/**\n * Which records a rule matches, beyond the object and the capturing site.\n * AND across the keys, OR within one; an absent or empty key matches\n * everything.\n */\nexport interface CrmSharingCriteria {\n /** A lead's or a contact's lead source, by label. */\n leadSources?: string[]\n /**\n * A lead's or a contact's lead source DIRECTION — `inbound` or `outbound`,\n * the Lead source picklist's groups (AGL-3511). Expanded through the org's\n * list when the rule is evaluated, so a value moved between groups moves\n * the records that hold it.\n */\n leadSourceGroups?: string[]\n /** Any of these tags (lead, contact, company). */\n tags?: string[]\n /** Filed under any of these campaigns (lead, contact). */\n campaignIds?: string[]\n /** A lead's status, a contact's lifecycle stage, or a deal's stage id. */\n stages?: string[]\n /** Owned by any of these members. */\n ownerUids?: string[]\n}\n\nexport const CRM_SHARING_CRITERIA_KEYS = [\n 'leadSources',\n 'leadSourceGroups',\n 'tags',\n 'campaignIds',\n 'stages',\n 'ownerUids',\n] as const satisfies readonly (keyof CrmSharingCriteria)[]\n\n/** Which criteria an object's records can answer. */\nexport const CRM_SHARING_CRITERIA_FOR: Readonly<\n Record<CrmSharingObject, readonly (keyof CrmSharingCriteria)[]>\n> = {\n leads: ['leadSources', 'leadSourceGroups', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n contacts: ['leadSources', 'leadSourceGroups', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n companies: ['tags', 'ownerUids'],\n deals: ['stages', 'ownerUids'],\n}\n\n/** Where a rule's recompute stands. */\nexport interface CrmSharingRuleRun {\n status: 'running' | 'done' | 'failed'\n /** What the run does: apply the rule everywhere, or take it away. */\n mode: 'apply' | 'remove'\n /** Records examined. */\n processed: number\n /** Records whose sharing changed. */\n changed: number\n /** The last record id an `apply` run examined, to continue after. */\n cursor?: string | null\n startedAtMs: number\n finishedAtMs?: number\n error?: string\n}\n\nexport interface CrmSharingRule {\n id: string\n name: string\n object: CrmSharingObject\n /** Off keeps the rule and takes away what it granted. */\n enabled: boolean\n /** Records captured or created on any of these sites; empty is every site. */\n sourceHostIds: string[]\n criteria: CrmSharingCriteria\n /** `['org']` for all sites, including sites added later; else host tokens. */\n targets: ScopeToken[]\n access: CrmShareAccess\n /** Being deleted: its grants are being removed, and it matches nothing. */\n deleting?: boolean\n createdByUid?: string\n createdAtMs: number\n updatedAtMs: number\n run?: CrmSharingRuleRun\n}\n\nconst RULE_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nfunction stringList(raw: unknown, max = CRM_SHARING_CRITERION_MAX): string[] {\n if (!Array.isArray(raw)) return []\n const out: string[] = []\n for (const entry of raw) {\n const value = String(entry ?? '').trim().slice(0, 200)\n if (value && !out.includes(value)) out.push(value)\n if (out.length >= max) break\n }\n return out\n}\n\n/** One rule as stored, cleaned, or null when it cannot be applied. */\nexport function readCrmSharingRule(raw: unknown): CrmSharingRule | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const id = String(value['id'] ?? '')\n if (!RULE_ID.test(id)) return null\n if (!isCrmSharingObject(value['object'])) return null\n const targets = normalizeShareTargets(tokenList(value['targets']))\n if (!targets) return null\n const rawCriteria = (value['criteria'] ?? {}) as Record<string, unknown>\n const criteria: CrmSharingCriteria = {}\n for (const key of CRM_SHARING_CRITERIA_FOR[value['object']]) {\n let list = stringList(rawCriteria[key])\n // A direction is one of the picklist's groups, never free text.\n if (key === 'leadSourceGroups') list = list.filter(isLeadSourceDirection)\n if (list.length) criteria[key] = key === 'tags' ? list.map((tag) => tag.toLowerCase()) : list\n }\n const run = value['run'] as Record<string, unknown> | undefined\n return {\n id,\n name: String(value['name'] ?? '').trim().slice(0, 120) || 'Sharing rule',\n object: value['object'],\n enabled: value['enabled'] !== false,\n sourceHostIds: stringList(value['sourceHostIds'], MAX_SCOPE_HOSTS),\n criteria,\n targets,\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(value['deleting'] === true ? { deleting: true } : {}),\n ...(typeof value['createdByUid'] === 'string' ? { createdByUid: value['createdByUid'] } : {}),\n createdAtMs: Number(value['createdAtMs']) || 0,\n updatedAtMs: Number(value['updatedAtMs']) || 0,\n ...(run && typeof run === 'object'\n ? {\n run: {\n status:\n run['status'] === 'done' || run['status'] === 'failed' ? run['status'] : 'running',\n mode: run['mode'] === 'remove' ? 'remove' : 'apply',\n processed: Number(run['processed']) || 0,\n changed: Number(run['changed']) || 0,\n cursor: typeof run['cursor'] === 'string' ? run['cursor'] : null,\n startedAtMs: Number(run['startedAtMs']) || 0,\n ...(typeof run['finishedAtMs'] === 'number' ? { finishedAtMs: run['finishedAtMs'] } : {}),\n ...(typeof run['error'] === 'string' ? { error: run['error'] } : {}),\n },\n }\n : {}),\n }\n}\n\n/** The org's sharing rules, in their stored order. */\nexport function readCrmSharingRules(\n org: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingRule[] {\n const crm = (org ?? {})['crm']\n const raw =\n crm && typeof crm === 'object' && !Array.isArray(crm)\n ? (crm as Record<string, unknown>)['sharingRules']\n : undefined\n if (!Array.isArray(raw)) return []\n const out: CrmSharingRule[] = []\n for (const entry of raw) {\n const rule = readCrmSharingRule(entry)\n if (rule && !out.some((existing) => existing.id === rule.id)) out.push(rule)\n }\n return out\n}\n\n/** The rules that grant anything now: enabled, and not being deleted. */\nexport function activeSharingRules(\n rules: readonly CrmSharingRule[],\n object?: CrmSharingObject,\n): CrmSharingRule[] {\n return rules.filter(\n (rule) => rule.enabled && !rule.deleting && (!object || rule.object === object),\n )\n}\n\n/**\n * A share's targets, cleaned for storage: `['org']` when all sites are\n * named, else the host tokens, capped. `null` when nothing is left.\n */\nexport function normalizeShareTargets(tokens: readonly string[]): ScopeToken[] | null {\n const clean = tokenList(tokens)\n if (!clean.length) return null\n if (clean.includes(ORG_SCOPE_TOKEN)) return [ORG_SCOPE_TOKEN]\n if (clean.length > MAX_SCOPE_HOSTS) return null\n return clean\n}\n\n/** Targets from a request: `'all'`, or a list of host ids. */\nexport function shareTargetsFrom(input: unknown): ScopeToken[] | null {\n if (input === 'all') return [ORG_SCOPE_TOKEN]\n if (!Array.isArray(input)) return null\n return normalizeShareTargets(\n input\n .map((id) => String(id ?? '').trim())\n .filter((id) => id && !id.includes('/') && !id.includes(':'))\n .map(hostScopeToken),\n )\n}\n\n/*==========================================\n * WHAT A RULE READS OFF A RECORD.\n *=========================================*/\n\nexport interface CrmSharingFacts {\n hostIds: string[]\n leadSources: string[]\n tags: string[]\n campaignIds: string[]\n stages: string[]\n ownerUids: string[]\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\nconst strs = (value: unknown): string[] =>\n Array.isArray(value) ? value.map(str).filter(Boolean) : []\n\n/**\n * The facts a rule's criteria are matched against. A contact keeps each\n * holder's working fields in its own facet, so a contact answers with the\n * union of its facets: a rule about \"contacts tagged vip\" matches a person\n * any holder tagged.\n */\nexport function crmSharingFacts(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n): CrmSharingFacts {\n const facts: CrmSharingFacts = {\n hostIds: recordHolderHostIds(record),\n leadSources: [],\n tags: [],\n campaignIds: [],\n stages: [],\n ownerUids: [],\n }\n const take = (source: Readonly<Record<string, unknown>>, stageField: string | null) => {\n const leadSource = str(source['leadSource'])\n if (leadSource) facts.leadSources.push(leadSource)\n facts.tags.push(...strs(source['tags']).map((tag) => tag.toLowerCase()))\n facts.campaignIds.push(...strs(source['campaignIds']))\n const stage = stageField ? str(source[stageField]) : ''\n if (stage) facts.stages.push(stage)\n const owner = str(source['ownerUid'])\n if (owner) facts.ownerUids.push(owner)\n }\n if (object === 'leads') take(record, 'status')\n else if (object === 'companies') take(record, null)\n else if (object === 'deals') take(record, 'stageId')\n else {\n const facets = record['facets']\n if (facets && typeof facets === 'object' && !Array.isArray(facets)) {\n for (const facet of Object.values(facets as Record<string, unknown>)) {\n if (facet && typeof facet === 'object' && !Array.isArray(facet)) {\n take(facet as Record<string, unknown>, 'lifecycleStage')\n }\n }\n }\n }\n // A lead with no status is New, as every lead reader answers it.\n if (object === 'leads' && !facts.stages.length) facts.stages.push('new')\n return facts\n}\n\nconst anyOf = (wanted: readonly string[] | undefined, have: readonly string[], fold = false) => {\n if (!wanted?.length) return true\n const set = new Set(fold ? have.map((value) => value.toLowerCase()) : have)\n return wanted.some((value) => set.has(fold ? value.toLowerCase() : value))\n}\n\n/**\n * What a rule is evaluated against beyond the record: the org's Lead source\n * list, which a direction criterion is expanded through (AGL-3511). Absent,\n * the standard values alone answer.\n */\nexport interface CrmSharingContext {\n leadSources?: CrmPicklist\n}\n\n/** Whether any active rule for `object` asks a lead source direction — whether the list must be read. */\nexport function sharingRulesAskLeadSourceDirection(\n rules: readonly CrmSharingRule[],\n object: CrmSharingObject,\n): boolean {\n return activeSharingRules(rules, object).some((rule) => Boolean(rule.criteria.leadSourceGroups?.length))\n}\n\n/** Whether a rule shares this record. */\nexport function crmSharingRuleMatches(\n rule: CrmSharingRule,\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n context: CrmSharingContext = {},\n): boolean {\n if (!rule.enabled || rule.deleting || rule.object !== object) return false\n const facts = crmSharingFacts(object, record)\n if (rule.sourceHostIds.length && !facts.hostIds.some((id) => rule.sourceHostIds.includes(id))) {\n return false\n }\n const { criteria } = rule\n const directions = criteria.leadSourceGroups?.length\n ? facts.leadSources\n .map((label) => leadSourceDirectionOf(context.leadSources ?? STANDARD_LEAD_SOURCES, label))\n .filter((direction): direction is NonNullable<typeof direction> => direction !== null)\n : []\n return (\n anyOf(criteria.leadSources, facts.leadSources, true) &&\n anyOf(criteria.leadSourceGroups, directions) &&\n anyOf(criteria.tags, facts.tags, true) &&\n anyOf(criteria.campaignIds, facts.campaignIds) &&\n anyOf(criteria.stages, facts.stages) &&\n anyOf(criteria.ownerUids, facts.ownerUids)\n )\n}\n\n/**\n * The grants a record should carry: its hand shares as they are, and one\n * grant per active rule that matches it now. A rule grant already present\n * keeps its date, so re-evaluating an unchanged record writes nothing.\n *\n * A rule grant whose rule is not among `rules` is dropped — the caller\n * passes every active rule of the org, so a rule absent from them has been\n * switched off or deleted.\n */\nexport function evaluateRecordGrants(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n rules: readonly CrmSharingRule[],\n atMs: number,\n context: CrmSharingContext = {},\n): Record<string, CrmShareGrant> {\n const current = readRecordGrants(record)\n const next: Record<string, CrmShareGrant> = {}\n for (const [key, grant] of Object.entries(current)) {\n if (grant.source === 'manual') next[key] = grant\n }\n for (const rule of activeSharingRules(rules, object)) {\n if (!crmSharingRuleMatches(rule, object, record, context)) continue\n const key = ruleGrantKey(rule.id)\n const before = current[key]\n next[key] = {\n source: 'rule',\n ruleId: rule.id,\n tokens: [...rule.targets],\n access: rule.access,\n atMs: before && sameList(before.tokens, rule.targets) && before.access === rule.access\n ? before.atMs\n : atMs,\n }\n }\n return next\n}\n\n/** The hand shares after sharing with `targets`, by `by`. */\nexport function withManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly ScopeToken[],\n access: CrmShareAccess,\n by: { uid: string; name?: string | null },\n atMs: number,\n): Record<string, CrmShareGrant> {\n const next = { ...grants }\n for (const token of targets) {\n const name = String(by.name ?? '').trim()\n next[manualGrantKey(token)] = {\n source: 'manual',\n tokens: [token],\n access,\n byUid: by.uid,\n ...(name ? { byName: name } : {}),\n atMs,\n }\n }\n return next\n}\n\n/** The hand shares after unsharing `targets`. Rule grants are the rule's to take away. */\nexport function withoutManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly string[],\n): Record<string, CrmShareGrant> {\n const drop = new Set(targets.filter(isScopeToken).map(manualGrantKey))\n return Object.fromEntries(Object.entries(grants).filter(([key]) => !drop.has(key)))\n}\n\n/*==========================================\n * WHAT A READER SEES.\n *=========================================*/\n\n/**\n * Whether a caller holding `tokens` may write the record: `writeTo` on a\n * shared record, else `visibleTo` — the Firestore rules' own predicate.\n */\nexport function crmRecordWritableBy(\n record: Readonly<Record<string, unknown>>,\n tokens: readonly string[],\n): boolean {\n const writeTo = record[CRM_WRITE_SCOPE_FIELD]\n const scope = Array.isArray(writeTo) ? writeTo : record['visibleTo']\n if (!Array.isArray(scope) || !tokens.length) return false\n return scope.some((token) => tokens.includes(token as string))\n}\n\n/** How a record reached a site that sees it only through a share. */\nexport interface CrmShareChip {\n source: CrmShareSource\n access: CrmShareAccess\n /** The member who shared it by hand. */\n byName?: string\n /** The rule that shared it. */\n ruleId?: string\n /** Shared with every site. */\n allSites: boolean\n}\n\n/**\n * Why a site seeing this record sees it, when the answer is a share — or\n * `null` when the site holds it (or cannot see it at all). `hostIds` are\n * the viewing group's sites; at the organization level there is none.\n */\nexport function crmShareChipFor(\n record: Readonly<Record<string, unknown>> | null | undefined,\n hostIds: readonly string[],\n): CrmShareChip | null {\n if (!record || !hostIds.length) return null\n const held = recordHeldScope(record)\n if (held.includes(ORG_SCOPE_TOKEN)) return null\n const viewing = new Set(hostIds.map(hostScopeToken))\n if (held.some((token) => viewing.has(token))) return null\n const grants = Object.values(readRecordGrants(record))\n const reaching = grants.filter((grant) =>\n grant.tokens.some((token) => token === ORG_SCOPE_TOKEN || viewing.has(token)),\n )\n if (!reaching.length) return null\n // A hand share names a person, so it leads; an edit grant outranks read.\n const pick =\n reaching.find((grant) => grant.source === 'manual' && grant.access === 'edit') ??\n reaching.find((grant) => grant.source === 'manual') ??\n reaching.find((grant) => grant.access === 'edit') ??\n reaching[0]\n return {\n source: pick.source,\n access: reaching.some((grant) => grant.access === 'edit') ? 'edit' : 'read',\n ...(pick.byName ? { byName: pick.byName } : {}),\n ...(pick.ruleId ? { ruleId: pick.ruleId } : {}),\n allSites: pick.tokens.includes(ORG_SCOPE_TOKEN),\n }\n}\n\n/** The chip's words: \"Shared by Dana\", \"Shared by rule Brand A leads\". */\nexport function crmShareChipLabel(\n chip: CrmShareChip,\n rules: readonly Pick<CrmSharingRule, 'id' | 'name'>[] = [],\n): string {\n if (chip.source === 'manual') return chip.byName ? `Shared by ${chip.byName}` : 'Shared by hand'\n const rule = rules.find((entry) => entry.id === chip.ruleId)\n return rule ? `Shared by rule ${rule.name}` : 'Shared by a rule'\n}\n\n/** One line of a record's Sharing card. */\nexport type CrmSharingLine =\n | { kind: 'held'; hostIds: string[]; allSites: boolean }\n | {\n kind: 'manual'\n key: string\n token: ScopeToken\n access: CrmShareAccess\n byName?: string\n atMs: number\n }\n | { kind: 'rule'; key: string; ruleId: string; tokens: ScopeToken[]; access: CrmShareAccess; atMs: number }\n\n/**\n * Where a record is visible and why: the sites that hold it (its consent\n * group or its creating site), then one line per hand share, then one per\n * rule. The held line is never unsharable; a hand share is, in one click.\n */\nexport function describeRecordSharing(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingLine[] {\n if (!record) return []\n const held = recordHeldScope(record)\n const lines: CrmSharingLine[] = [\n { kind: 'held', hostIds: hostIdsFromScope(held), allSites: held.includes(ORG_SCOPE_TOKEN) },\n ]\n const grants = Object.entries(readRecordGrants(record))\n for (const [key, grant] of grants) {\n if (grant.source !== 'manual') continue\n lines.push({\n kind: 'manual',\n key,\n token: grant.tokens[0],\n access: grant.access,\n ...(grant.byName ? { byName: grant.byName } : {}),\n atMs: grant.atMs,\n })\n }\n for (const [key, grant] of grants) {\n if (grant.source !== 'rule' || !grant.ruleId) continue\n lines.push({\n kind: 'rule',\n key,\n ruleId: grant.ruleId,\n tokens: grant.tokens,\n access: grant.access,\n atMs: grant.atMs,\n })\n }\n return lines\n}\n\n/** \"All sites\", a site's name, or \"N sites\". */\nexport function describeShareTargets(\n tokens: readonly string[],\n siteName: (hostId: string) => string,\n): string {\n if (tokens.includes(ORG_SCOPE_TOKEN)) return 'All sites'\n const ids = hostIdsFromScope(tokens)\n if (ids.length === 1) return siteName(ids[0])\n if (ids.length <= 3) return ids.map(siteName).join(', ')\n return `${ids.length} sites`\n}\n\n/** A rule as one sentence of its \"which records\" half. */\nexport function describeSharingRuleScope(\n rule: Pick<CrmSharingRule, 'object' | 'sourceHostIds' | 'criteria'>,\n siteName: (hostId: string) => string,\n labels: { owner?: (uid: string) => string; stage?: (id: string) => string } = {},\n): string {\n const parts: string[] = [CRM_SHARING_OBJECT_LABELS[rule.object].many]\n if (rule.sourceHostIds.length) {\n parts.push(`captured on ${rule.sourceHostIds.map(siteName).join(' or ')}`)\n }\n const { criteria } = rule\n if (criteria.leadSources?.length) parts.push(`from ${criteria.leadSources.join(' or ')}`)\n if (criteria.leadSourceGroups?.length) {\n const directions = criteria.leadSourceGroups.map((group) =>\n isLeadSourceDirection(group) ? LEAD_SOURCE_DIRECTION_LABELS[group] : group,\n )\n parts.push(`${directions.join(' or ')} by lead source`)\n }\n if (criteria.tags?.length) parts.push(`tagged ${criteria.tags.join(' or ')}`)\n if (criteria.campaignIds?.length) {\n parts.push(`in ${criteria.campaignIds.length === 1 ? 'a campaign' : `${criteria.campaignIds.length} campaigns`}`)\n }\n if (criteria.stages?.length) {\n parts.push(`at ${criteria.stages.map((id) => labels.stage?.(id) ?? id).join(' or ')}`)\n }\n if (criteria.ownerUids?.length) {\n parts.push(`owned by ${criteria.ownerUids.map((uid) => labels.owner?.(uid) ?? uid).join(' or ')}`)\n }\n return parts.join(', ')\n}\n\n/*==========================================\n * THE ROUTE.\n *=========================================*/\n\n/** `POST /api/crm/sharing` — every sharing act, by `action`. */\nexport const CRM_SHARING_ROUTE = 'crm/sharing' as const\n\nexport const crmSharingRouteUrl = (): string => `/api/${CRM_SHARING_ROUTE}`\n\n/** Records one share or unshare may name. */\nexport const CRM_SHARING_IDS_MAX = 200\n\nexport type CrmSharingAction =\n | 'sites'\n | 'share'\n | 'unshare'\n | 'evaluate'\n | 'rule-save'\n | 'rule-delete'\n | 'rule-continue'\n\nexport interface CrmSharingSite {\n id: string\n name: string\n}\n\nexport interface CrmSharingResponse {\n ok: true\n /** `sites`: the org's sites, by name. */\n sites?: CrmSharingSite[]\n /** `share`/`unshare`/`evaluate`: records whose sharing changed. */\n changed?: number\n /** Records named that could not be found. */\n missing?: number\n /** The rule a rule action saved or ran. */\n rule?: CrmSharingRule | null\n /** Whether a rule run has more to do (`rule-continue` again). */\n more?: boolean\n}\n"],"names":["heldScopeTokens","hostIdsFromScope","hostScopeToken","isScopeToken","MAX_SCOPE_HOSTS","ORG_SCOPE_TOKEN","parseScopeToken","SCOPE_GRANTS_FIELD","isLeadSourceDirection","LEAD_SOURCE_DIRECTION_LABELS","leadSourceDirectionOf","STANDARD_LEAD_SOURCES","CRM_SHARING_OBJECTS","isCrmSharingObject","value","includes","CRM_SHARING_OBJECT_LABELS","leads","one","many","contacts","companies","deals","isCrmShareAccess","CRM_SHARING_FIELD","CRM_WRITE_SCOPE_FIELD","CRM_SHARING_RULE_IDS_PATH","manualGrantKey","token","parsed","Error","kind","hostId","ruleGrantKey","ruleId","tokenList","raw","Array","isArray","Set","filter","readGrant","tokens","length","source","byUid","byName","atMs","Number","isFinite","access","readRecordGrants","record","sharing","grants","out","key","Object","entries","grant","recordHolderHostIds","ids","add","captured","id","recordHeldScope","planRecordSharing","held","visibleTo","writeTo","heldSet","heldOrgWide","has","editTokens","ruleIds","sort","a","b","push","added","fromEntries","orgWideHeldBy","sameList","every","entry","at","sameGrant","sharingPlanChanges","plan","storedWrite","stored","undefined","keys","CRM_SHARING_RULES_PATH","CRM_SHARING_RULES_MAX","CRM_SHARING_CRITERION_MAX","CRM_SHARING_CRITERIA_KEYS","CRM_SHARING_CRITERIA_FOR","RULE_ID","stringList","max","String","trim","slice","readCrmSharingRule","test","targets","normalizeShareTargets","rawCriteria","criteria","list","map","tag","toLowerCase","run","name","object","enabled","sourceHostIds","deleting","createdByUid","createdAtMs","updatedAtMs","status","mode","processed","changed","cursor","startedAtMs","finishedAtMs","error","readCrmSharingRules","org","crm","rule","some","existing","activeSharingRules","rules","clean","shareTargetsFrom","input","str","strs","Boolean","crmSharingFacts","facts","hostIds","leadSources","tags","campaignIds","stages","ownerUids","take","stageField","leadSource","stage","owner","facets","facet","values","anyOf","wanted","have","fold","set","sharingRulesAskLeadSourceDirection","leadSourceGroups","crmSharingRuleMatches","context","directions","label","direction","evaluateRecordGrants","current","next","before","withManualShares","by","uid","withoutManualShares","drop","crmRecordWritableBy","scope","crmShareChipFor","reaching","viewing","pick","find","allSites","crmShareChipLabel","chip","describeRecordSharing","lines","describeShareTargets","siteName","join","describeSharingRuleScope","labels","parts","group","CRM_SHARING_ROUTE","crmSharingRouteUrl","CRM_SHARING_IDS_MAX"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC;AAGD,SACEA,eAAe,EACfC,gBAAgB,EAChBC,cAAc,EACdC,YAAY,EACZC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,kBAAkB,QACb,sCAAqC;AAE5C,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,qBAAqB,QAChB,6BAAyB;AAEhC;;2CAE2C,GAE3C,6EAA6E,GAC7E,OAAO,MAAMC,sBAAsB;IAAC;IAAS;IAAY;IAAa;CAAQ,CAAS;AAGvF,OAAO,SAASC,mBAAmBC,KAAc;IAC/C,OACE,OAAOA,UAAU,YAAY,AAACF,oBAA0CG,QAAQ,CAACD;AAErF;AAEA,yCAAyC,GACzC,OAAO,MAAME,4BAET;IACFC,OAAO;QAAEC,KAAK;QAAQC,MAAM;IAAQ;IACpCC,UAAU;QAAEF,KAAK;QAAWC,MAAM;IAAW;IAC7CE,WAAW;QAAEH,KAAK;QAAWC,MAAM;IAAY;IAC/CG,OAAO;QAAEJ,KAAK;QAAQC,MAAM;IAAQ;AACtC,EAAC;AAKD,OAAO,SAASI,iBAAiBT,KAAc;IAC7C,OAAOA,UAAU,UAAUA,UAAU;AACvC;AAuCA,qEAAqE,GACrE,OAAO,MAAMU,oBAAoBjB,mBAAkB;AAEnD,+EAA+E,GAC/E,OAAO,MAAMkB,wBAAwB,U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CAAC,EAAE;IAClH;IACA,KAAIkE,mBAAAA,SAAS0C,MAAM,qBAAf1C,iBAAiBlE,MAAM,EAAE;QAC3B4J,MAAMzH,IAAI,CAAC,CAAC,GAAG,EAAE+B,SAAS0C,MAAM,CAACxC,GAAG,CAAC,CAAC/C;;2BAAOsI,OAAO1C,KAAK,oBAAZ0C,OAAO1C,KAAK,MAAZ0C,QAAetI,sBAAOA;WAAIoI,IAAI,CAAC,SAAS;IACvF;IACA,KAAIvF,sBAAAA,SAAS2C,SAAS,qBAAlB3C,oBAAoBlE,MAAM,EAAE;QAC9B4J,MAAMzH,IAAI,CAAC,CAAC,SAAS,EAAE+B,SAAS2C,SAAS,CAACzC,GAAG,CAAC,CAACoE;;2BAAQmB,OAAOzC,KAAK,oBAAZyC,OAAOzC,KAAK,MAAZyC,QAAenB,uBAAQA;WAAKiB,IAAI,CAAC,SAAS;IACnG;IACA,OAAOG,MAAMH,IAAI,CAAC;AACpB;AAEA;;2CAE2C,GAE3C,8DAA8D,GAC9D,OAAO,MAAMK,oBAAoB,cAAsB;AAEvD,OAAO,MAAMC,qBAAqB,IAAc,CAAC,KAAK,EAAED,mBAAmB,CAAA;AAE3E,2CAA2C,GAC3C,OAAO,MAAME,sBAAsB,IAAG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-sharing.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 * CRM SHARING FOR MULTI-BRAND ORGS (AGL-3336).\n *\n * A member holding \"Change CRM settings\" shares a lead, a contact, a company or a deal with other\n * sites — by hand, from the record or a list's bulk bar, or by a SHARING\n * RULE that applies to every record it matches, now and later. The model is\n * Salesforce's three layers:\n *\n * 1. the org-wide default — the consent-group scope a record is captured\n * with (`consentGroupScope`), untouched by anything here;\n * 2. sharing rules — `crm.sharingRules` on the org document;\n * 3. manual shares — per record, per target.\n *\n * ## One field is enforced, so one field is widened\n *\n * Both enforcement layers read `visibleTo`: the rules with `hasAny`, every\n * list with `array-contains-any`. A share therefore ADDS its tokens to\n * `visibleTo`, which is what puts the record on the target site's lists as a\n * real query — no second field, no second index, no loaded-window match.\n * `'org'` is the token for \"all sites\", and it covers a site created later\n * with nothing to recompute, because every site's read set carries it.\n *\n * ## …and the sources stay distinguishable\n *\n * The record keeps its grants under `sharing` (`SCOPE_GRANTS_FIELD` in\n * core): one grant per rule and one per hand-shared target, and `added`,\n * the tokens the grants put on `visibleTo` that were not there already.\n * The record's own scope — its HELD tokens — is `visibleTo` without\n * `added`, so taking a grant away removes only what grants alone\n * contributed, and never a consent-group token. A token a site later\n * captures the person on is held from then on: the capturing sites\n * (`hostId`, `capturedByHostIds`) are never counted as added.\n *\n * ## Visibility is not consent, and not write access\n *\n * Nothing here reads or writes a consent entry. A site a record is shared\n * with sees it; it holds no basis to market to the person, and the\n * audience paths read `heldByHost`, not `visibleTo`. Write access is its\n * own field, `writeTo`, present only on a shared record: the held tokens\n * and the tokens of grants whose access is `edit`. The Firestore rules and\n * the CRM's routes check it; a read-only grant is the default.\n *\n * ## All sites except some (AGL-4047)\n *\n * A grant or a rule can share with every site but the ones it leaves out:\n * `except` beside `tokens` (a rule's `targets`). Readers still enforce one\n * flat list, so the grant's `tokens` are the sites it reaches, worked out\n * from the workspace's sites every time the record's sharing is recomputed,\n * and a site added later joins on the next recompute, which the workspace's\n * own site change starts (`server/crm-sharing-runs.ts`). `planRecordSharing`\n * reads `tokens` as it always has, so `visibleTo`, `added` and `writeTo` come\n * out the same way. A site left out that captured the person still holds\n * them: held tokens are never a grant's to take away. One grant reaches at\n * most {@link CRM_SHARING_MAX_INCLUDED} sites, since a record's search fields\n * grow by site; past that it keeps the sites it has and stops widening.\n */\n\nimport type { ScopeToken } from '@aglyn/aglyn'\nimport {\n heldScopeTokens,\n hostIdsFromScope,\n hostScopeToken,\n isScopeToken,\n MAX_SCOPE_HOSTS,\n ORG_SCOPE_TOKEN,\n parseScopeToken,\n SCOPE_GRANTS_FIELD,\n type ScopeSharingChoice,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { CrmPicklist } from '@aglyn/aglyn/app-utils/crm'\nimport {\n isLeadSourceDirection,\n LEAD_SOURCE_DIRECTION_LABELS,\n leadSourceDirectionOf,\n STANDARD_LEAD_SOURCES,\n} from './lead-source-direction'\n\n/*==========================================\n * WHAT IS SHARED.\n *=========================================*/\n\n/** The four record types a share or a rule applies to, by their collection. */\nexport const CRM_SHARING_OBJECTS = ['leads', 'contacts', 'companies', 'deals'] as const\nexport type CrmSharingObject = (typeof CRM_SHARING_OBJECTS)[number]\n\nexport function isCrmSharingObject(value: unknown): value is CrmSharingObject {\n return (\n typeof value === 'string' && (CRM_SHARING_OBJECTS as readonly string[]).includes(value)\n )\n}\n\n/** How each object reads in a sentence. */\nexport const CRM_SHARING_OBJECT_LABELS: Readonly<\n Record<CrmSharingObject, { one: string; many: string }>\n> = {\n leads: { one: 'lead', many: 'Leads' },\n contacts: { one: 'contact', many: 'Contacts' },\n companies: { one: 'company', many: 'Companies' },\n deals: { one: 'deal', many: 'Deals' },\n}\n\n/** What a target site may do with a shared record. Read-only unless a grant says edit. */\nexport type CrmShareAccess = 'read' | 'edit'\n\nexport function isCrmShareAccess(value: unknown): value is CrmShareAccess {\n return value === 'read' || value === 'edit'\n}\n\n/** Where a grant came from. */\nexport type CrmShareSource = 'manual' | 'rule'\n\n/** One grant on one record. */\nexport interface CrmShareGrant {\n source: CrmShareSource\n /**\n * The sites it shares with: `['org']` for all sites, else host tokens. For\n * a grant with `except`, the sites it reached when last worked out.\n */\n tokens: ScopeToken[]\n /**\n * Present on a grant shared with all sites except some (AGL-4047): the\n * sites it leaves out, as host tokens. `tokens` follows the workspace's\n * sites, so a site added later joins.\n */\n except?: ScopeToken[]\n access: CrmShareAccess\n /** The rule behind a `rule` grant. */\n ruleId?: string\n /** Who shared it by hand, as they were named at the time. */\n byUid?: string\n byName?: string\n /** When the grant was made. */\n atMs: number\n}\n\n/** `sharing` on a record — see the module note. */\nexport interface CrmRecordSharing {\n /** Keyed by {@link manualGrantKey} or {@link ruleGrantKey}. */\n grants: Record<string, CrmShareGrant>\n /** Every token any grant names — the record's shares, however held. */\n tokens: ScopeToken[]\n /** The tokens the grants ADDED to `visibleTo` — see `heldScopeTokens`. */\n added: ScopeToken[]\n /** The rules holding a grant here, so a rule's removal can find its records. */\n ruleIds: string[]\n /**\n * The held tokens of a record shared with all sites, and nothing\n * otherwise. `array-contains` on it answers \"is this record shared with\n * everyone AND held by site X\" — the one question `added` alone cannot,\n * since a query takes a single array clause.\n */\n orgWideHeldBy: ScopeToken[]\n /**\n * `true` while any grant shares with all sites except some (AGL-4047), so\n * a change to the workspace's sites can find the records to bring level\n * ({@link CRM_SHARING_EXCEPT_PATH}). Absent otherwise.\n */\n hasExcept?: true\n}\n\n/** The record field its grants live under — the core's name for it. */\nexport const CRM_SHARING_FIELD = SCOPE_GRANTS_FIELD\n\n/** The record field naming who may WRITE it, present only while it is shared. */\nexport const CRM_WRITE_SCOPE_FIELD = 'writeTo'\n\n/** The array field a rule's removal queries. */\nexport const CRM_SHARING_RULE_IDS_PATH = `${CRM_SHARING_FIELD}.ruleIds`\n\n/** The field a site change queries for records with an all-except grant (AGL-4047). */\nexport const CRM_SHARING_EXCEPT_PATH = `${CRM_SHARING_FIELD}.hasExcept`\n\n/**\n * The most sites one all-except grant reaches (AGL-4047). A record's scoped\n * search fields grow by site (`scopedSearchTokens`), so past this the grant\n * keeps the sites it has and stops widening, and a new share is refused.\n */\nexport const CRM_SHARING_MAX_INCLUDED = MAX_SCOPE_HOSTS\n\n/** The key of a record's one hand share with all sites except some. */\nexport const MANUAL_EXCEPT_GRANT_KEY = 'manual_except'\n\n/** A hand share is one grant per target, so each is unshared on its own. */\nexport function manualGrantKey(token: string): string {\n const parsed = parseScopeToken(token)\n if (!parsed) throw new Error(`not a scope token: ${token}`)\n return parsed.kind === 'org' ? 'manual_org' : `manual_${parsed.hostId}`\n}\n\nexport function ruleGrantKey(ruleId: string): string {\n return `rule_${ruleId}`\n}\n\nfunction tokenList(raw: unknown): ScopeToken[] {\n if (!Array.isArray(raw)) return []\n return [...new Set(raw.filter(isScopeToken))]\n}\n\n/** Host tokens only, de-duplicated: what an `except` list may hold. */\nfunction hostTokenList(raw: unknown): ScopeToken[] {\n return tokenList(raw).filter((token) => parseScopeToken(token)?.kind === 'host')\n}\n\nfunction readGrant(raw: unknown): CrmShareGrant | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const tokens = tokenList(value['tokens'])\n const except = hostTokenList(value['except'])\n // An all-except grant can reach no site for a while, when every site but\n // the ones it leaves out is gone. It still says who it shares with.\n if (!tokens.length && !except.length) return null\n if (except.length && tokens.includes(ORG_SCOPE_TOKEN)) return null\n const source = value['source'] === 'rule' ? 'rule' : value['source'] === 'manual' ? 'manual' : null\n if (!source) return null\n const ruleId = typeof value['ruleId'] === 'string' ? value['ruleId'] : ''\n if (source === 'rule' && !ruleId) return null\n const byUid = typeof value['byUid'] === 'string' ? value['byUid'] : ''\n const byName = typeof value['byName'] === 'string' ? value['byName'] : ''\n const atMs = typeof value['atMs'] === 'number' && Number.isFinite(value['atMs']) ? value['atMs'] : 0\n return {\n source,\n tokens,\n ...(except.length ? { except } : {}),\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(ruleId ? { ruleId } : {}),\n ...(byUid ? { byUid } : {}),\n ...(byName ? { byName } : {}),\n atMs,\n }\n}\n\n/** A record's grants, cleaned; `{}` for a record never shared. */\nexport function readRecordGrants(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, CrmShareGrant> {\n const sharing = (record ?? {})[CRM_SHARING_FIELD]\n if (!sharing || typeof sharing !== 'object' || Array.isArray(sharing)) return {}\n const grants = (sharing as Record<string, unknown>)['grants']\n if (!grants || typeof grants !== 'object' || Array.isArray(grants)) return {}\n const out: Record<string, CrmShareGrant> = {}\n for (const [key, raw] of Object.entries(grants as Record<string, unknown>)) {\n const grant = readGrant(raw)\n if (grant) out[key] = grant\n }\n return out\n}\n\n/*==========================================\n * THE PLAN: grants in, the three fields out.\n *=========================================*/\n\n/**\n * The sites that captured or created the record. Their tokens are HELD,\n * whatever `added` says: a person shared to site B and later captured on B\n * is B's own from then on, and unsharing must not hide them from B.\n */\nexport function recordHolderHostIds(record: Readonly<Record<string, unknown>>): string[] {\n const ids = new Set<string>()\n const hostId = record['hostId']\n if (typeof hostId === 'string' && hostId) ids.add(hostId)\n const captured = record['capturedByHostIds']\n if (Array.isArray(captured)) {\n for (const id of captured) if (typeof id === 'string' && id) ids.add(id)\n }\n return [...ids]\n}\n\n/**\n * The record's own scope: `visibleTo` less what grants added, its capturing\n * sites kept — the core's `heldScopeTokens`, as scope tokens.\n */\nexport function recordHeldScope(record: Readonly<Record<string, unknown>>): ScopeToken[] {\n return tokenList(heldScopeTokens(record))\n}\n\nexport interface CrmSharingPlan {\n visibleTo: ScopeToken[]\n /** `null` removes the field: an unshared record writes by `visibleTo`. */\n writeTo: ScopeToken[] | null\n /** `null` removes the field. */\n sharing: CrmRecordSharing | null\n}\n\n/**\n * The fields a record carries under `grants`.\n *\n * A grant naming a token the record already holds adds nothing, and a\n * record held org-wide adds nothing at all — every site sees it already, so\n * a share there would only make a later unshare look like it hid something.\n * The token order is the held scope first and the additions after it, so an\n * unchanged record plans the `visibleTo` it has.\n */\nexport function planRecordSharing(\n record: Readonly<Record<string, unknown>>,\n grants: Readonly<Record<string, CrmShareGrant>>,\n): CrmSharingPlan {\n const held = recordHeldScope(record)\n const entries = Object.entries(grants)\n if (!entries.length) return { visibleTo: held, writeTo: null, sharing: null }\n const heldSet = new Set<string>(held)\n const heldOrgWide = heldSet.has(ORG_SCOPE_TOKEN)\n const tokens: ScopeToken[] = []\n const editTokens: ScopeToken[] = []\n const ruleIds: string[] = []\n for (const [, grant] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n for (const token of grant.tokens) {\n if (!tokens.includes(token)) tokens.push(token)\n if (grant.access === 'edit' && !editTokens.includes(token)) editTokens.push(token)\n }\n if (grant.source === 'rule' && grant.ruleId && !ruleIds.includes(grant.ruleId)) {\n ruleIds.push(grant.ruleId)\n }\n }\n const added = heldOrgWide ? [] : tokens.filter((token) => !heldSet.has(token))\n const writeTo = [...held]\n for (const token of editTokens) if (!writeTo.includes(token)) writeTo.push(token)\n return {\n visibleTo: [...held, ...added],\n writeTo,\n sharing: {\n grants: Object.fromEntries(entries),\n tokens,\n added,\n ruleIds,\n orgWideHeldBy: added.includes(ORG_SCOPE_TOKEN) ? [...held] : [],\n ...(entries.some(([, grant]) => grant.except?.length) ? { hasExcept: true as const } : {}),\n },\n }\n}\n\nconst sameList = (a: readonly unknown[] | null | undefined, b: readonly unknown[] | null | undefined) =>\n (a ?? null) === null\n ? (b ?? null) === null\n : (b ?? null) !== null && a!.length === b!.length && a!.every((entry, at) => entry === b![at])\n\nconst sameGrant = (a: CrmShareGrant | undefined, b: CrmShareGrant | undefined) =>\n !!a &&\n !!b &&\n a.source === b.source &&\n a.access === b.access &&\n (a.ruleId ?? '') === (b.ruleId ?? '') &&\n (a.byUid ?? '') === (b.byUid ?? '') &&\n (a.byName ?? '') === (b.byName ?? '') &&\n a.atMs === b.atMs &&\n sameList(a.tokens, b.tokens) &&\n sameList(a.except ?? [], b.except ?? [])\n\n/** Whether writing `plan` would change what the record stores. */\nexport function sharingPlanChanges(\n record: Readonly<Record<string, unknown>>,\n plan: CrmSharingPlan,\n): boolean {\n if (!sameList(tokenList(record['visibleTo']), plan.visibleTo)) return true\n const storedWrite = record[CRM_WRITE_SCOPE_FIELD]\n if (!sameList(Array.isArray(storedWrite) ? tokenList(storedWrite) : null, plan.writeTo)) return true\n const stored = record[CRM_SHARING_FIELD]\n if (!plan.sharing) return stored !== undefined && stored !== null\n const grants = readRecordGrants(record)\n const keys = Object.keys(plan.sharing.grants)\n if (keys.length !== Object.keys(grants).length) return true\n if (!keys.every((key) => sameGrant(grants[key], plan.sharing!.grants[key]))) return true\n const sharing = (stored ?? {}) as Record<string, unknown>\n return (\n !sameList(tokenList(sharing['tokens']), plan.sharing.tokens) ||\n !sameList(tokenList(sharing['added']), plan.sharing.added) ||\n !sameList(\n Array.isArray(sharing['ruleIds']) ? (sharing['ruleIds'] as unknown[]) : [],\n plan.sharing.ruleIds,\n ) ||\n !sameList(tokenList(sharing['orgWideHeldBy']), plan.sharing.orgWideHeldBy) ||\n (sharing['hasExcept'] === true) !== (plan.sharing.hasExcept === true)\n )\n}\n\n/*==========================================\n * SHARING RULES: `crm.sharingRules` on the org document.\n *=========================================*/\n\n/** The org document path the rules are stored under. */\nexport const CRM_SHARING_RULES_PATH = 'crm.sharingRules'\n\n/** A workspace keeps at most this many. */\nexport const CRM_SHARING_RULES_MAX = 20\n\n/** At most this many values per criterion. */\nexport const CRM_SHARING_CRITERION_MAX = 20\n\n/**\n * Which records a rule matches, beyond the object and the capturing site.\n * AND across the keys, OR within one; an absent or empty key matches\n * everything.\n */\nexport interface CrmSharingCriteria {\n /** A lead's or a contact's lead source, by label. */\n leadSources?: string[]\n /**\n * A lead's or a contact's lead source DIRECTION — `inbound` or `outbound`,\n * the Lead source picklist's groups (AGL-3511). Expanded through the org's\n * list when the rule is evaluated, so a value moved between groups moves\n * the records that hold it.\n */\n leadSourceGroups?: string[]\n /** Any of these tags (lead, contact, company). */\n tags?: string[]\n /** Filed under any of these campaigns (lead, contact). */\n campaignIds?: string[]\n /** A lead's status, a contact's lifecycle stage, or a deal's stage id. */\n stages?: string[]\n /** Owned by any of these members. */\n ownerUids?: string[]\n}\n\nexport const CRM_SHARING_CRITERIA_KEYS = [\n 'leadSources',\n 'leadSourceGroups',\n 'tags',\n 'campaignIds',\n 'stages',\n 'ownerUids',\n] as const satisfies readonly (keyof CrmSharingCriteria)[]\n\n/** Which criteria an object's records can answer. */\nexport const CRM_SHARING_CRITERIA_FOR: Readonly<\n Record<CrmSharingObject, readonly (keyof CrmSharingCriteria)[]>\n> = {\n leads: ['leadSources', 'leadSourceGroups', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n contacts: ['leadSources', 'leadSourceGroups', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n companies: ['tags', 'ownerUids'],\n deals: ['stages', 'ownerUids'],\n}\n\n/** Where a rule's recompute stands. */\nexport interface CrmSharingRuleRun {\n status: 'running' | 'done' | 'failed'\n /** What the run does: apply the rule everywhere, or take it away. */\n mode: 'apply' | 'remove'\n /** Records examined. */\n processed: number\n /** Records whose sharing changed. */\n changed: number\n /** The last record id an `apply` run examined, to continue after. */\n cursor?: string | null\n startedAtMs: number\n finishedAtMs?: number\n error?: string\n}\n\nexport interface CrmSharingRule {\n id: string\n name: string\n object: CrmSharingObject\n /** Off keeps the rule and takes away what it granted. */\n enabled: boolean\n /** Records captured or created on any of these sites; empty is every site. */\n sourceHostIds: string[]\n criteria: CrmSharingCriteria\n /**\n * `['org']` for all sites, including sites added later; else host tokens.\n * For a rule with `except`, the sites it reached when it was saved.\n */\n targets: ScopeToken[]\n /**\n * Present on a rule that shares with all sites except some (AGL-4047): the\n * sites it leaves out, as host tokens. Its grants follow the workspace's\n * sites, so a site added later joins.\n */\n except?: ScopeToken[]\n access: CrmShareAccess\n /** Being deleted: its grants are being removed, and it matches nothing. */\n deleting?: boolean\n createdByUid?: string\n createdAtMs: number\n updatedAtMs: number\n run?: CrmSharingRuleRun\n}\n\nconst RULE_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nfunction stringList(raw: unknown, max = CRM_SHARING_CRITERION_MAX): string[] {\n if (!Array.isArray(raw)) return []\n const out: string[] = []\n for (const entry of raw) {\n const value = String(entry ?? '').trim().slice(0, 200)\n if (value && !out.includes(value)) out.push(value)\n if (out.length >= max) break\n }\n return out\n}\n\n/** One rule as stored, cleaned, or null when it cannot be applied. */\nexport function readCrmSharingRule(raw: unknown): CrmSharingRule | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const id = String(value['id'] ?? '')\n if (!RULE_ID.test(id)) return null\n if (!isCrmSharingObject(value['object'])) return null\n const except = hostTokenList(value['except'])\n const targets = except.length\n ? hostTokenList(value['targets'])\n : normalizeShareTargets(tokenList(value['targets']))\n if (!targets) return null\n const rawCriteria = (value['criteria'] ?? {}) as Record<string, unknown>\n const criteria: CrmSharingCriteria = {}\n for (const key of CRM_SHARING_CRITERIA_FOR[value['object']]) {\n let list = stringList(rawCriteria[key])\n // A direction is one of the picklist's groups, never free text.\n if (key === 'leadSourceGroups') list = list.filter(isLeadSourceDirection)\n if (list.length) criteria[key] = key === 'tags' ? list.map((tag) => tag.toLowerCase()) : list\n }\n const run = value['run'] as Record<string, unknown> | undefined\n return {\n id,\n name: String(value['name'] ?? '').trim().slice(0, 120) || 'Sharing rule',\n object: value['object'],\n enabled: value['enabled'] !== false,\n sourceHostIds: stringList(value['sourceHostIds'], MAX_SCOPE_HOSTS),\n criteria,\n targets,\n ...(except.length ? { except } : {}),\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(value['deleting'] === true ? { deleting: true } : {}),\n ...(typeof value['createdByUid'] === 'string' ? { createdByUid: value['createdByUid'] } : {}),\n createdAtMs: Number(value['createdAtMs']) || 0,\n updatedAtMs: Number(value['updatedAtMs']) || 0,\n ...(run && typeof run === 'object'\n ? {\n run: {\n status:\n run['status'] === 'done' || run['status'] === 'failed' ? run['status'] : 'running',\n mode: run['mode'] === 'remove' ? 'remove' : 'apply',\n processed: Number(run['processed']) || 0,\n changed: Number(run['changed']) || 0,\n cursor: typeof run['cursor'] === 'string' ? run['cursor'] : null,\n startedAtMs: Number(run['startedAtMs']) || 0,\n ...(typeof run['finishedAtMs'] === 'number' ? { finishedAtMs: run['finishedAtMs'] } : {}),\n ...(typeof run['error'] === 'string' ? { error: run['error'] } : {}),\n },\n }\n : {}),\n }\n}\n\n/** The org's sharing rules, in their stored order. */\nexport function readCrmSharingRules(\n org: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingRule[] {\n const crm = (org ?? {})['crm']\n const raw =\n crm && typeof crm === 'object' && !Array.isArray(crm)\n ? (crm as Record<string, unknown>)['sharingRules']\n : undefined\n if (!Array.isArray(raw)) return []\n const out: CrmSharingRule[] = []\n for (const entry of raw) {\n const rule = readCrmSharingRule(entry)\n if (rule && !out.some((existing) => existing.id === rule.id)) out.push(rule)\n }\n return out\n}\n\n/** The rules that grant anything now: enabled, and not being deleted. */\nexport function activeSharingRules(\n rules: readonly CrmSharingRule[],\n object?: CrmSharingObject,\n): CrmSharingRule[] {\n return rules.filter(\n (rule) => rule.enabled && !rule.deleting && (!object || rule.object === object),\n )\n}\n\n/**\n * A share's targets, cleaned for storage: `['org']` when all sites are\n * named, else the host tokens, capped. `null` when nothing is left.\n */\nexport function normalizeShareTargets(tokens: readonly string[]): ScopeToken[] | null {\n const clean = tokenList(tokens)\n if (!clean.length) return null\n if (clean.includes(ORG_SCOPE_TOKEN)) return [ORG_SCOPE_TOKEN]\n if (clean.length > MAX_SCOPE_HOSTS) return null\n return clean\n}\n\n/** Targets from a request: `'all'`, or a list of host ids. */\nexport function shareTargetsFrom(input: unknown): ScopeToken[] | null {\n if (input === 'all') return [ORG_SCOPE_TOKEN]\n if (!Array.isArray(input)) return null\n return normalizeShareTargets(\n input\n .map((id) => String(id ?? '').trim())\n .filter((id) => id && !id.includes('/') && !id.includes(':'))\n .map(hostScopeToken),\n )\n}\n\n/**\n * All sites except some, from a request (AGL-4047):\n * `{ mode: 'allExcept', exceptHostIds }`, or null when the input is not that\n * choice. Whether the sites are the workspace's, and what the choice reaches,\n * is `sharingFromChoice`'s to answer against the workspace's sites.\n */\nexport function shareExceptChoiceFrom(\n input: unknown,\n): Extract<ScopeSharingChoice, { mode: 'allExcept' }> | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null\n const value = input as Record<string, unknown>\n if (value['mode'] !== 'allExcept' || !Array.isArray(value['exceptHostIds'])) return null\n const exceptHostIds = [\n ...new Set(\n (value['exceptHostIds'] as unknown[])\n .map((id) => String(id ?? '').trim())\n .filter((id) => id && !id.includes('/') && !id.includes(':')),\n ),\n ].slice(0, 1000)\n return { mode: 'allExcept', exceptHostIds }\n}\n\n/**\n * The sites `orgs/{orgId}.hosts` names: the list the sweep keeps every\n * all-except document level with (`orgHostIdsFromDoc`), read the same way\n * here so the CRM's grants and the sweep never disagree about a site.\n */\nexport function crmOrgHostIds(org: Readonly<Record<string, unknown>> | null | undefined): string[] {\n const hosts = org?.['hosts']\n if (!hosts || typeof hosts !== 'object' || Array.isArray(hosts)) return []\n return Object.entries(hosts as Record<string, unknown>)\n .filter(([, on]) => Boolean(on))\n .map(([hostId]) => hostId)\n}\n\n/**\n * The sites an all-except grant reaches (AGL-4047): the workspace's sites\n * less the ones it leaves out, sorted. `orgHostIds` unknown keeps what the\n * grant reached last. Past {@link CRM_SHARING_MAX_INCLUDED} it stops\n * widening: it keeps the sites it reached that are still the workspace's.\n */\nexport function sitesAllExcept(\n except: readonly string[],\n orgHostIds: readonly string[] | null | undefined,\n previous: readonly string[],\n): ScopeToken[] {\n const left = new Set(hostIdsFromScope(except))\n const before = hostIdsFromScope(hostTokenList(previous)).filter((id) => !left.has(id))\n if (!orgHostIds) return before.map(hostScopeToken)\n const org = [...new Set(orgHostIds.filter(Boolean))]\n const included = org.filter((id) => !left.has(id)).sort()\n if (included.length <= CRM_SHARING_MAX_INCLUDED) return included.map(hostScopeToken)\n const now = new Set(org)\n return before.filter((id) => now.has(id)).map(hostScopeToken)\n}\n\n/*==========================================\n * WHAT A RULE READS OFF A RECORD.\n *=========================================*/\n\nexport interface CrmSharingFacts {\n hostIds: string[]\n leadSources: string[]\n tags: string[]\n campaignIds: string[]\n stages: string[]\n ownerUids: string[]\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\nconst strs = (value: unknown): string[] =>\n Array.isArray(value) ? value.map(str).filter(Boolean) : []\n\n/**\n * The facts a rule's criteria are matched against. A contact keeps each\n * holder's working fields in its own facet, so a contact answers with the\n * union of its facets: a rule about \"contacts tagged vip\" matches a person\n * any holder tagged.\n */\nexport function crmSharingFacts(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n): CrmSharingFacts {\n const facts: CrmSharingFacts = {\n hostIds: recordHolderHostIds(record),\n leadSources: [],\n tags: [],\n campaignIds: [],\n stages: [],\n ownerUids: [],\n }\n const take = (source: Readonly<Record<string, unknown>>, stageField: string | null) => {\n const leadSource = str(source['leadSource'])\n if (leadSource) facts.leadSources.push(leadSource)\n facts.tags.push(...strs(source['tags']).map((tag) => tag.toLowerCase()))\n facts.campaignIds.push(...strs(source['campaignIds']))\n const stage = stageField ? str(source[stageField]) : ''\n if (stage) facts.stages.push(stage)\n const owner = str(source['ownerUid'])\n if (owner) facts.ownerUids.push(owner)\n }\n if (object === 'leads') take(record, 'status')\n else if (object === 'companies') take(record, null)\n else if (object === 'deals') take(record, 'stageId')\n else {\n const facets = record['facets']\n if (facets && typeof facets === 'object' && !Array.isArray(facets)) {\n for (const facet of Object.values(facets as Record<string, unknown>)) {\n if (facet && typeof facet === 'object' && !Array.isArray(facet)) {\n take(facet as Record<string, unknown>, 'lifecycleStage')\n }\n }\n }\n }\n // A lead with no status is New, as every lead reader answers it.\n if (object === 'leads' && !facts.stages.length) facts.stages.push('new')\n return facts\n}\n\nconst anyOf = (wanted: readonly string[] | undefined, have: readonly string[], fold = false) => {\n if (!wanted?.length) return true\n const set = new Set(fold ? have.map((value) => value.toLowerCase()) : have)\n return wanted.some((value) => set.has(fold ? value.toLowerCase() : value))\n}\n\n/**\n * What a rule is evaluated against beyond the record: the org's Lead source\n * list, which a direction criterion is expanded through (AGL-3511). Absent,\n * the standard values alone answer.\n */\nexport interface CrmSharingContext {\n leadSources?: CrmPicklist\n /**\n * The workspace's sites (`orgs/{orgId}.hosts`), which an all-except grant\n * reaches less the ones it leaves out (AGL-4047). Absent, such a grant keeps\n * the sites it reached last.\n */\n orgHostIds?: readonly string[]\n}\n\n/** Whether any active rule for `object` asks a lead source direction — whether the list must be read. */\nexport function sharingRulesAskLeadSourceDirection(\n rules: readonly CrmSharingRule[],\n object: CrmSharingObject,\n): boolean {\n return activeSharingRules(rules, object).some((rule) => Boolean(rule.criteria.leadSourceGroups?.length))\n}\n\n/** Whether a rule shares this record. */\nexport function crmSharingRuleMatches(\n rule: CrmSharingRule,\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n context: CrmSharingContext = {},\n): boolean {\n if (!rule.enabled || rule.deleting || rule.object !== object) return false\n const facts = crmSharingFacts(object, record)\n if (rule.sourceHostIds.length && !facts.hostIds.some((id) => rule.sourceHostIds.includes(id))) {\n return false\n }\n const { criteria } = rule\n const directions = criteria.leadSourceGroups?.length\n ? facts.leadSources\n .map((label) => leadSourceDirectionOf(context.leadSources ?? STANDARD_LEAD_SOURCES, label))\n .filter((direction): direction is NonNullable<typeof direction> => direction !== null)\n : []\n return (\n anyOf(criteria.leadSources, facts.leadSources, true) &&\n anyOf(criteria.leadSourceGroups, directions) &&\n anyOf(criteria.tags, facts.tags, true) &&\n anyOf(criteria.campaignIds, facts.campaignIds) &&\n anyOf(criteria.stages, facts.stages) &&\n anyOf(criteria.ownerUids, facts.ownerUids)\n )\n}\n\n/**\n * The grants a record should carry: its hand shares as they are, and one\n * grant per active rule that matches it now. A rule grant already present\n * keeps its date, so re-evaluating an unchanged record writes nothing.\n *\n * A rule grant whose rule is not among `rules` is dropped — the caller\n * passes every active rule of the org, so a rule absent from them has been\n * switched off or deleted.\n */\nexport function evaluateRecordGrants(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n rules: readonly CrmSharingRule[],\n atMs: number,\n context: CrmSharingContext = {},\n): Record<string, CrmShareGrant> {\n const current = readRecordGrants(record)\n const next: Record<string, CrmShareGrant> = {}\n for (const [key, grant] of Object.entries(current)) {\n if (grant.source !== 'manual') continue\n // A hand share with all sites except some follows the workspace's sites.\n next[key] = grant.except?.length\n ? { ...grant, tokens: sitesAllExcept(grant.except, context.orgHostIds, grant.tokens) }\n : grant\n }\n for (const rule of activeSharingRules(rules, object)) {\n if (!crmSharingRuleMatches(rule, object, record, context)) continue\n const key = ruleGrantKey(rule.id)\n const before = current[key]\n const except = rule.except ?? []\n const tokens = except.length\n ? sitesAllExcept(except, context.orgHostIds, before?.except?.length ? before.tokens : rule.targets)\n : [...rule.targets]\n next[key] = {\n source: 'rule',\n ruleId: rule.id,\n tokens,\n ...(except.length ? { except: [...except] } : {}),\n access: rule.access,\n atMs:\n before &&\n sameList(before.tokens, tokens) &&\n sameList(before.except ?? [], except) &&\n before.access === rule.access\n ? before.atMs\n : atMs,\n }\n }\n return next\n}\n\n/**\n * Whether working out this record's sharing needs the workspace's sites: a\n * grant on it, or an active rule for its kind, leaves sites out (AGL-4047).\n * Everything else plans from the record and the rules alone.\n */\nexport function sharingAsksOrgSites(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n rules: readonly CrmSharingRule[],\n): boolean {\n return (\n Object.values(readRecordGrants(record)).some((grant) => Boolean(grant.except?.length)) ||\n activeSharingRules(rules, object).some((rule) => Boolean(rule.except?.length))\n )\n}\n\n/** The hand shares after sharing with `targets`, by `by`. */\nexport function withManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly ScopeToken[],\n access: CrmShareAccess,\n by: { uid: string; name?: string | null },\n atMs: number,\n): Record<string, CrmShareGrant> {\n const next = { ...grants }\n for (const token of targets) {\n const name = String(by.name ?? '').trim()\n next[manualGrantKey(token)] = {\n source: 'manual',\n tokens: [token],\n access,\n byUid: by.uid,\n ...(name ? { byName: name } : {}),\n atMs,\n }\n }\n return next\n}\n\n/**\n * The hand shares after sharing with all sites except some (AGL-4047): one\n * grant, {@link MANUAL_EXCEPT_GRANT_KEY}, replacing any earlier one. `tokens`\n * are the sites it reaches today.\n */\nexport function withManualExceptShare(\n grants: Readonly<Record<string, CrmShareGrant>>,\n share: { tokens: readonly ScopeToken[]; except: readonly ScopeToken[] },\n access: CrmShareAccess,\n by: { uid: string; name?: string | null },\n atMs: number,\n): Record<string, CrmShareGrant> {\n const name = String(by.name ?? '').trim()\n return {\n ...grants,\n [MANUAL_EXCEPT_GRANT_KEY]: {\n source: 'manual',\n tokens: [...share.tokens],\n except: [...share.except],\n access,\n byUid: by.uid,\n ...(name ? { byName: name } : {}),\n atMs,\n },\n }\n}\n\n/** The hand shares after taking away the share with all sites except some. */\nexport function withoutManualExceptShare(\n grants: Readonly<Record<string, CrmShareGrant>>,\n): Record<string, CrmShareGrant> {\n return Object.fromEntries(\n Object.entries(grants).filter(([key]) => key !== MANUAL_EXCEPT_GRANT_KEY),\n )\n}\n\n/** The hand shares after unsharing `targets`. Rule grants are the rule's to take away. */\nexport function withoutManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly string[],\n): Record<string, CrmShareGrant> {\n const drop = new Set(targets.filter(isScopeToken).map(manualGrantKey))\n return Object.fromEntries(Object.entries(grants).filter(([key]) => !drop.has(key)))\n}\n\n/*==========================================\n * WHAT A READER SEES.\n *=========================================*/\n\n/**\n * Whether a caller holding `tokens` may write the record: `writeTo` on a\n * shared record, else `visibleTo` — the Firestore rules' own predicate.\n */\nexport function crmRecordWritableBy(\n record: Readonly<Record<string, unknown>>,\n tokens: readonly string[],\n): boolean {\n const writeTo = record[CRM_WRITE_SCOPE_FIELD]\n const scope = Array.isArray(writeTo) ? writeTo : record['visibleTo']\n if (!Array.isArray(scope) || !tokens.length) return false\n return scope.some((token) => tokens.includes(token as string))\n}\n\n/** How a record reached a site that sees it only through a share. */\nexport interface CrmShareChip {\n source: CrmShareSource\n access: CrmShareAccess\n /** The member who shared it by hand. */\n byName?: string\n /** The rule that shared it. */\n ruleId?: string\n /** Shared with every site. */\n allSites: boolean\n}\n\n/**\n * Why a site seeing this record sees it, when the answer is a share — or\n * `null` when the site holds it (or cannot see it at all). `hostIds` are\n * the viewing group's sites; at the organization level there is none.\n */\nexport function crmShareChipFor(\n record: Readonly<Record<string, unknown>> | null | undefined,\n hostIds: readonly string[],\n): CrmShareChip | null {\n if (!record || !hostIds.length) return null\n const held = recordHeldScope(record)\n if (held.includes(ORG_SCOPE_TOKEN)) return null\n const viewing = new Set(hostIds.map(hostScopeToken))\n if (held.some((token) => viewing.has(token))) return null\n const grants = Object.values(readRecordGrants(record))\n const reaching = grants.filter((grant) =>\n grant.tokens.some((token) => token === ORG_SCOPE_TOKEN || viewing.has(token)),\n )\n if (!reaching.length) return null\n // A hand share names a person, so it leads; an edit grant outranks read.\n const pick =\n reaching.find((grant) => grant.source === 'manual' && grant.access === 'edit') ??\n reaching.find((grant) => grant.source === 'manual') ??\n reaching.find((grant) => grant.access === 'edit') ??\n reaching[0]\n return {\n source: pick.source,\n access: reaching.some((grant) => grant.access === 'edit') ? 'edit' : 'read',\n ...(pick.byName ? { byName: pick.byName } : {}),\n ...(pick.ruleId ? { ruleId: pick.ruleId } : {}),\n allSites: pick.tokens.includes(ORG_SCOPE_TOKEN),\n }\n}\n\n/** The chip's words: \"Shared by Dana\", \"Shared by rule Brand A leads\". */\nexport function crmShareChipLabel(\n chip: CrmShareChip,\n rules: readonly Pick<CrmSharingRule, 'id' | 'name'>[] = [],\n): string {\n if (chip.source === 'manual') return chip.byName ? `Shared by ${chip.byName}` : 'Shared by hand'\n const rule = rules.find((entry) => entry.id === chip.ruleId)\n return rule ? `Shared by rule ${rule.name}` : 'Shared by a rule'\n}\n\n/** One line of a record's Sharing card. */\nexport type CrmSharingLine =\n | { kind: 'held'; hostIds: string[]; allSites: boolean }\n | {\n kind: 'manual'\n key: string\n token: ScopeToken\n access: CrmShareAccess\n byName?: string\n atMs: number\n }\n | {\n /** A hand share with all sites except some (AGL-4047). */\n kind: 'manualExcept'\n key: string\n tokens: ScopeToken[]\n except: ScopeToken[]\n access: CrmShareAccess\n byName?: string\n atMs: number\n }\n | {\n kind: 'rule'\n key: string\n ruleId: string\n tokens: ScopeToken[]\n /** The sites a rule shares with all but (AGL-4047). */\n except?: ScopeToken[]\n access: CrmShareAccess\n atMs: number\n }\n\n/**\n * Where a record is visible and why: the sites that hold it (its consent\n * group or its creating site), then one line per hand share, then one per\n * rule. The held line is never unsharable; a hand share is, in one click.\n */\nexport function describeRecordSharing(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingLine[] {\n if (!record) return []\n const held = recordHeldScope(record)\n const lines: CrmSharingLine[] = [\n { kind: 'held', hostIds: hostIdsFromScope(held), allSites: held.includes(ORG_SCOPE_TOKEN) },\n ]\n const grants = Object.entries(readRecordGrants(record))\n for (const [key, grant] of grants) {\n if (grant.source !== 'manual') continue\n if (grant.except?.length) {\n lines.push({\n kind: 'manualExcept',\n key,\n tokens: grant.tokens,\n except: grant.except,\n access: grant.access,\n ...(grant.byName ? { byName: grant.byName } : {}),\n atMs: grant.atMs,\n })\n continue\n }\n lines.push({\n kind: 'manual',\n key,\n token: grant.tokens[0],\n access: grant.access,\n ...(grant.byName ? { byName: grant.byName } : {}),\n atMs: grant.atMs,\n })\n }\n for (const [key, grant] of grants) {\n if (grant.source !== 'rule' || !grant.ruleId) continue\n lines.push({\n kind: 'rule',\n key,\n ruleId: grant.ruleId,\n tokens: grant.tokens,\n ...(grant.except?.length ? { except: grant.except } : {}),\n access: grant.access,\n atMs: grant.atMs,\n })\n }\n return lines\n}\n\n/**\n * \"All sites\", a site's name, or \"N sites\"; for a share with all sites except\n * some (AGL-4047), \"All sites except Blog\", \"All sites except Blog and Shop\"\n * or \"All sites except 3 sites\".\n */\nexport function describeShareTargets(\n tokens: readonly string[],\n siteName: (hostId: string) => string,\n except?: readonly string[] | null,\n): string {\n const left = except ? hostIdsFromScope(except) : []\n if (left.length === 1) return `All sites except ${siteName(left[0])}`\n if (left.length === 2) return `All sites except ${siteName(left[0])} and ${siteName(left[1])}`\n if (left.length > 2) return `All sites except ${left.length} sites`\n if (tokens.includes(ORG_SCOPE_TOKEN)) return 'All sites'\n const ids = hostIdsFromScope(tokens)\n if (ids.length === 1) return siteName(ids[0])\n if (ids.length <= 3) return ids.map(siteName).join(', ')\n return `${ids.length} sites`\n}\n\n/** A rule as one sentence of its \"which records\" half. */\nexport function describeSharingRuleScope(\n rule: Pick<CrmSharingRule, 'object' | 'sourceHostIds' | 'criteria'>,\n siteName: (hostId: string) => string,\n labels: { owner?: (uid: string) => string; stage?: (id: string) => string } = {},\n): string {\n const parts: string[] = [CRM_SHARING_OBJECT_LABELS[rule.object].many]\n if (rule.sourceHostIds.length) {\n parts.push(`captured on ${rule.sourceHostIds.map(siteName).join(' or ')}`)\n }\n const { criteria } = rule\n if (criteria.leadSources?.length) parts.push(`from ${criteria.leadSources.join(' or ')}`)\n if (criteria.leadSourceGroups?.length) {\n const directions = criteria.leadSourceGroups.map((group) =>\n isLeadSourceDirection(group) ? LEAD_SOURCE_DIRECTION_LABELS[group] : group,\n )\n parts.push(`${directions.join(' or ')} by lead source`)\n }\n if (criteria.tags?.length) parts.push(`tagged ${criteria.tags.join(' or ')}`)\n if (criteria.campaignIds?.length) {\n parts.push(`in ${criteria.campaignIds.length === 1 ? 'a campaign' : `${criteria.campaignIds.length} campaigns`}`)\n }\n if (criteria.stages?.length) {\n parts.push(`at ${criteria.stages.map((id) => labels.stage?.(id) ?? id).join(' or ')}`)\n }\n if (criteria.ownerUids?.length) {\n parts.push(`owned by ${criteria.ownerUids.map((uid) => labels.owner?.(uid) ?? uid).join(' or ')}`)\n }\n return parts.join(', ')\n}\n\n/*==========================================\n * THE ROUTE.\n *=========================================*/\n\n/** `POST /api/crm/sharing` — every sharing act, by `action`. */\nexport const CRM_SHARING_ROUTE = 'crm/sharing' as const\n\nexport const crmSharingRouteUrl = (): string => `/api/${CRM_SHARING_ROUTE}`\n\n/** Records one share or unshare may name. */\nexport const CRM_SHARING_IDS_MAX = 200\n\nexport type CrmSharingAction =\n | 'sites'\n | 'share'\n | 'unshare'\n | 'evaluate'\n | 'rule-save'\n | 'rule-delete'\n | 'rule-continue'\n | 'default-apply'\n | 'default-apply-continue'\n\nexport interface CrmSharingSite {\n id: string\n name: string\n}\n\nexport interface CrmSharingResponse {\n ok: true\n /** `sites`: the org's sites, by name. */\n sites?: CrmSharingSite[]\n /** `share`/`unshare`/`evaluate`: records whose sharing changed. */\n changed?: number\n /** Records named that could not be found. */\n missing?: number\n /** The rule a rule action saved or ran. */\n rule?: CrmSharingRule | null\n /** Whether a rule run has more to do (`rule-continue` again). */\n more?: boolean\n /** `default-apply`: where the \"Apply to existing records\" run stands. */\n applyRun?: CrmDefaultApplyRun | null\n}\n\n/*==========================================\n * \"APPLY TO EXISTING RECORDS\" (AGL-4047).\n *\n * The CRM default stamps NEW records. Under \"All sites except…\" a member\n * holding \"Change CRM settings\" can bring the records the workspace already\n * has to it: every contact, lead, company, deal, task and logged activity is\n * shared with every site but the ones left out, and the sites that captured\n * a person keep them. Only that explicit run changes an existing record,\n * never the setting itself. It walks each collection by a cursor in budgeted\n * passes, its progress mirrored here on the org document.\n *=========================================*/\n\n/** The collections the run walks, in order: the cursor names a place in this list. */\nexport const CRM_DEFAULT_APPLY_COLLECTIONS = [\n 'contacts',\n 'leads',\n 'companies',\n 'deals',\n 'crmTasks',\n 'crmActivities',\n] as const\nexport type CrmDefaultApplyCollection = (typeof CRM_DEFAULT_APPLY_COLLECTIONS)[number]\n\nexport function isCrmDefaultApplyCollection(value: unknown): value is CrmDefaultApplyCollection {\n return (\n typeof value === 'string' &&\n (CRM_DEFAULT_APPLY_COLLECTIONS as readonly string[]).includes(value)\n )\n}\n\n/**\n * What a browser writes itself that no sharing rule applies to, yet the CRM\n * default \"All sites except…\" stamps: a logged activity. Its `evaluate`\n * follow-up only marks it, when its sites are exactly the default's, so a\n * site added later sees it (AGL-4047).\n */\nexport const CRM_DEFAULT_MARK_ONLY_COLLECTIONS = ['crmActivities'] as const\nexport type CrmDefaultMarkOnlyCollection = (typeof CRM_DEFAULT_MARK_ONLY_COLLECTIONS)[number]\n\nexport function isCrmDefaultMarkOnlyCollection(value: unknown): value is CrmDefaultMarkOnlyCollection {\n return (\n typeof value === 'string' &&\n (CRM_DEFAULT_MARK_ONLY_COLLECTIONS as readonly string[]).includes(value)\n )\n}\n\n/** Where the run's progress is mirrored on the org document, for the settings card. */\nexport const CRM_DEFAULT_APPLY_RUN_PATH = 'crm.defaultApplyRun'\n\nexport interface CrmDefaultApplyRun {\n status: 'running' | 'done' | 'failed'\n /** Records read. */\n processed: number\n /** Records whose sites moved. */\n changed: number\n /** Records it would take past the site limit, left as they were. */\n capped: number\n /** Where it carries on from. */\n cursor: { collection: CrmDefaultApplyCollection; afterId: string | null } | null\n startedAtMs: number\n finishedAtMs?: number\n error?: string\n}\n\n/** The run as the org document mirrors it, cleaned; null when none was ever started. */\nexport function readCrmDefaultApplyRun(\n org: Readonly<Record<string, unknown>> | null | undefined,\n): CrmDefaultApplyRun | null {\n const crm = (org ?? {})['crm']\n const raw =\n crm && typeof crm === 'object' && !Array.isArray(crm)\n ? (crm as Record<string, unknown>)['defaultApplyRun']\n : undefined\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const cursor = value['cursor'] as Record<string, unknown> | null | undefined\n return {\n status: value['status'] === 'done' || value['status'] === 'failed' ? value['status'] : 'running',\n processed: Number(value['processed']) || 0,\n changed: Number(value['changed']) || 0,\n capped: Number(value['capped']) || 0,\n cursor:\n cursor && isCrmDefaultApplyCollection(cursor['collection'])\n ? {\n collection: cursor['collection'],\n afterId: typeof cursor['afterId'] === 'string' ? cursor['afterId'] : null,\n }\n : null,\n startedAtMs: Number(value['startedAtMs']) || 0,\n ...(typeof value['finishedAtMs'] === 'number' ? { finishedAtMs: value['finishedAtMs'] } : {}),\n ...(typeof value['error'] === 'string' ? { error: value['error'] } : {}),\n }\n}\n"],"names":["heldScopeTokens","hostIdsFromScope","hostScopeToken","isScopeToken","MAX_SCOPE_HOSTS","ORG_SCOPE_TOKEN","parseScopeToken","SCOPE_GRANTS_FIELD","isLeadSourceDirection","LEAD_SOURCE_DIRECTION_LABELS","leadSourceDirectionOf","STANDARD_LEAD_SOURCES","CRM_SHARING_OBJECTS","isCrmSharingObject","value","includes","CRM_SHARING_OBJECT_LABELS","leads","one","many","contacts","companies","deals","isCrmShareAccess","CRM_SHARING_FIELD","CRM_WRITE_SCOPE_FIELD","CRM_SHARING_RULE_IDS_PATH","CRM_SHARING_EXCEPT_PATH","CRM_SHARING_MAX_INCLUDED","MANUAL_EXCEPT_GRANT_KEY","manualGrantKey","token","parsed","Error","kind","hostId","ruleGrantKey","ruleId","tokenList","raw","Array","isArray","Set","filter","hostTokenList","readGrant","tokens","except","length","source","byUid","byName","atMs","Number","isFinite","access","readRecordGrants","record","sharing","grants","out","key","Object","entries","grant","recordHolderHostIds","ids","add","captured","id","recordHeldScope","planRecordSharing","held","visibleTo","writeTo","heldSet","heldOrgWide","has","editTokens","ruleIds","sort","a","b","push","added","fromEntries","orgWideHeldBy","some","hasExcept","sameList","every","entry","at","sameGrant","sharingPlanChanges","plan","storedWrite","stored","undefined","keys","CRM_SHARING_RULES_PATH","CRM_SHARING_RULES_MAX","CRM_SHARING_CRITERION_MAX","CRM_SHARING_CRITERIA_KEYS","CRM_SHARING_CRITERIA_FOR","RULE_ID","stringList","max","String","trim","slice","readCrmSharingRule","test","targets","normalizeShareTargets","rawCriteria","criteria","list","map","tag","toLowerCase","run","name","object","enabled","sourceHostIds","deleting","createdByUid","createdAtMs","updatedAtMs","status","mode","processed","changed","cursor","startedAtMs","finishedAtMs","error","readCrmSharingRules","org","crm","rule","existing","activeSharingRules","rules","clean","shareTargetsFrom","input","shareExceptChoiceFrom","exceptHostIds","crmOrgHostIds","hosts","on","Boolean","sitesAllExcept","orgHostIds","previous","left","before","included","now","str","strs","crmSharingFacts","facts","hostIds","leadSources","tags","campaignIds","stages","ownerUids","take","stageField","leadSource","stage","owner","facets","facet","values","anyOf","wanted","have","fold","set","sharingRulesAskLeadSourceDirection","leadSourceGroups","crmSharingRuleMatches","context","directions","label","direction","evaluateRecordGrants","current","next","sharingAsksOrgSites","withManualShares","by","uid","withManualExceptShare","share","withoutManualExceptShare","withoutManualShares","drop","crmRecordWritableBy","scope","crmShareChipFor","reaching","viewing","pick","find","allSites","crmShareChipLabel","chip","describeRecordSharing","lines","describeShareTargets","siteName","join","describeSharingRuleScope","labels","parts","group","CRM_SHARING_ROUTE","crmSharingRouteUrl","CRM_SHARING_IDS_MAX","CRM_DEFAULT_APPLY_COLLECTIONS","isCrmDefaultApplyCollection","CRM_DEFAULT_MARK_ONLY_COLLECTIONS","isCrmDefaultMarkOnlyCollection","CRM_DEFAULT_APPLY_RUN_PATH","readCrmDefaultApplyRun","capped","collection","afterId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC;AAGD,SACEA,eAAe,EACfC,gBAAgB,EAChBC,cAAc,EACdC,YAAY,EACZC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,kBAAkB,QAEb,sCAAqC;AAE5C,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,qBAAqB,EACrBC,qBAAqB,QAChB,6BAAyB;AAEhC;;2CAE2C,GAE3C,6EAA6E,GAC7E,OAAO,MAAMC,sBAAsB;IAAC;IAAS;IAAY;IAAa;CAAQ,CAAS;AAGvF,OAAO,SAASC,mBAAmBC,KAAc;IAC/C,OACE,OAAOA,UAAU,YAAY,AAACF,oBAA0CG,QAAQ,CAACD;AAErF;AAEA,yCAAyC,GACzC,OAAO,MAAME,4BAET;IACFC,OAAO;QAAEC,KAAK;QAAQC,MAAM;IAAQ;IACp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ChCmG,SAAS,OAAOnG,MAAM,CAAC,UAAU,KAAK,WAAWA,MAAM,CAAC,UAAU,GAAG;QACvE,IACA;QACNC,aAAalF,OAAOvC,KAAK,CAAC,cAAc,KAAK;OACzC,OAAOA,KAAK,CAAC,eAAe,KAAK,WAAW;QAAE0H,cAAc1H,KAAK,CAAC,eAAe;IAAC,IAAI,CAAC,GACvF,OAAOA,KAAK,CAAC,QAAQ,KAAK,WAAW;QAAE2H,OAAO3H,KAAK,CAAC,QAAQ;IAAC,IAAI,CAAC;AAE1E"}
@@ -73,7 +73,7 @@ export declare const LEAD_STATUS_FILTER_OPTIONS: {
73
73
  }[];
74
74
  /** The choices for Email: every verdict, plus the two aggregates. */
75
75
  export declare const LEAD_EMAIL_FILTER_OPTIONS: {
76
- value: "none" | "ok" | "bounced" | "complained" | "blocked" | "undeliverable" | "unsubscribed" | "do_not_contact" | "problem";
76
+ value: "none" | "ok" | "bounced" | "complained" | "problem" | "blocked" | "undeliverable" | "unsubscribed" | "do_not_contact";
77
77
  label: string;
78
78
  }[];
79
79
  /** The choices for Lead source direction: each group of the Lead source picklist. */
@@ -15,7 +15,7 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
15
15
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
- */ import { CAPTURED_BY_HOST_FIELD, checkCrmRecordsQuota, composeContactName, consentGroupForGrant, consentGroupForHost, consentGroupScope, CONTACT_COMPANY_IDS_FIELD, CONTACT_FACETS_FIELD, contactFacetPath, crmDefaultScopeOf, crmNewRecordListFields, crmReadTokens, createResourceUid, MARKETING_CONSENT_BY_HOST_FIELD, marketingConsentFieldsForGroup, marketingConsentFieldsForHost, nameSearchFields, ORG_CONTACT_HOLDER_ID, ORG_SCOPE_TOKEN, planContactCompanyLink, readContactCompanyLink } from "@aglyn/aglyn/server";
18
+ */ import { CAPTURED_BY_HOST_FIELD, checkCrmRecordsQuota, composeContactName, consentGroupForGrant, consentGroupForHost, consentGroupScope, CONTACT_COMPANY_IDS_FIELD, CONTACT_FACETS_FIELD, contactFacetPath, crmDefaultScopeOf, crmDefaultSharingOf, crmScopeFields, crmNewRecordListFields, crmReadTokens, createResourceUid, MARKETING_CONSENT_BY_HOST_FIELD, marketingConsentFieldsForGroup, marketingConsentFieldsForHost, nameSearchFields, ORG_CONTACT_HOLDER_ID, ORG_SCOPE_TOKEN, planContactCompanyLink, readContactCompanyLink } from "@aglyn/aglyn/server";
19
19
  import { contactCompanyLinkFields, firebaseAdmin, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
20
20
  import { scheduleCapturedEmailCheck } from "@aglyn/tenant-data-admin/server/capture-email-check";
21
21
  import { settleCompanyContactsCounts } from "@aglyn/tenant-data-admin/server/contact-company-link";
@@ -77,9 +77,16 @@ import { orgHostIds } from "./org-caller.js";
77
77
  // The one number the record can be found by; a person who gave only a
78
78
  // mobile is found by that.
79
79
  const phone = profile.phone || profile.mobilePhone || '';
80
+ /*
81
+ * A new person is stamped by the org's CRM default, with the marker under
82
+ * "All sites except…" (AGL-4047). A person the workspace already has
83
+ * gains this site's group as before; under all sites except some only the
84
+ * group, since widening a record that exists is the explicit "Apply to
85
+ * existing records" run's to do, never a capture's.
86
+ */ const stamped = crmScopeFields(org, group);
80
87
  const scope = crmDefaultScopeOf(org) === 'org' ? [
81
88
  ORG_SCOPE_TOKEN
82
- ] : consentGroupScope(group);
89
+ ] : crmDefaultSharingOf(org) === 'allExcept' ? consentGroupScope(group) : stamped.visibleTo;
83
90
  const existing = email ? await findContactByEmail(contacts, email) : phone ? await findVisibleContactByPhone(contacts, phone, sourceHostId && crmDefaultScopeOf(org) !== 'org' ? crmReadTokens(group) : null) : null;
84
91
  if (existing) {
85
92
  var _existing_data;
@@ -149,8 +156,8 @@ import { orgHostIds } from "./org-caller.js";
149
156
  hostId: sourceHostId,
150
157
  [CAPTURED_BY_HOST_FIELD]: sourceHostId ? [
151
158
  sourceHostId
152
- ] : [],
153
- visibleTo: scope,
159
+ ] : []
160
+ }, stamped, {
154
161
  /*
155
162
  * BLANK RATHER THAN ABSENT. The Contacts table sorts by every column, and
156
163
  * a Firestore `orderBy` drops a document that lacks the field, so a person
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/add-contact-by-hand.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkCrmRecordsQuota,\n composeContactName,\n type ConsentGroup,\n consentGroupForGrant,\n consentGroupForHost,\n consentGroupScope,\n CONTACT_COMPANY_IDS_FIELD,\n CONTACT_FACETS_FIELD,\n type ContactFacet,\n contactFacetPath,\n crmDefaultScopeOf,\n crmNewRecordListFields,\n crmReadTokens,\n createResourceUid,\n MARKETING_CONSENT_BY_HOST_FIELD,\n marketingConsentFieldsForGroup,\n marketingConsentFieldsForHost,\n nameSearchFields,\n ORG_CONTACT_HOLDER_ID,\n ORG_SCOPE_TOKEN,\n planContactCompanyLink,\n readContactCompanyLink,\n} from '@aglyn/aglyn/server'\nimport {\n contactCompanyLinkFields,\n firebaseAdmin,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { scheduleCapturedEmailCheck } from '@aglyn/tenant-data-admin/server/capture-email-check'\nimport { settleCompanyContactsCounts } from '@aglyn/tenant-data-admin/server/contact-company-link'\nimport {\n emailIndexBeside,\n findContactByEmail,\n writeContactEmailIndex,\n} from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { countCrmRecords } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { hostRefusesCaptureForErasure } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n type ContactProfileInput,\n storableProfile,\n} from '@aglyn/tenant-data-admin/server/upsert-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { ORG_HOLDER_GROUP, contactPrimaryGroup } from '../model/contact-holder'\nimport { orgHostIds } from './org-caller'\n\n/**\n * A PERSON THE TEAM ADDS WHO DID NOT COME THROUGH A SITE'S CAPTURE (AGL-4122).\n *\n * `upsertHostContact` is the door for somebody a site met, and it needs what a\n * site's capture always has: a site and an address. A person typed in by the\n * team may have neither. They may be a name and a phone number, added at the\n * organization level, because the team is working a deal with someone whose\n * email comes later. That is this path, and only that: a site AND an address\n * still go through the capture door, which is why the route asks.\n *\n * ## Who the person already is\n *\n * The address when there is one, through the same index the capture reads. With\n * none, the phone number. With neither, nobody: two blank emails are not the\n * same person, and a name is not an identity.\n *\n * The phone lookup is the one narrowing the capture's address lookup refuses,\n * deliberately. An address names one human, so the capture recognizes them\n * across every site. A phone number can be a shared office line, so it only\n * matches somebody this caller's view already holds, and an agency's two\n * clients who share a switchboard stay two records.\n *\n * ## The facet, and what names no site\n *\n * With a Source site the profile lives in that site's group's facet, as a\n * capture's would. With none it lives in `ORG_CONTACT_HOLDER_ID`, and the row\n * has no capturing site: `hostId` is `null`, `capturedByHostIds` is empty, and\n * the record says so instead of guessing a brand that never met the person.\n *\n * ## Consent\n *\n * Only with an address, since a basis for mail needs somewhere to send it. With\n * a site, for that site or the group it disclosed. With none, the person told\n * the organization yes, so the grant is written on every site it has. One entry\n * per site, each a group of one: `byHost[hostId]` stays a lookup, and a site\n * added next month inherits nothing.\n *\n * ## What is not announced\n *\n * A created person with no site or no address fires no `contactCreated`: the\n * event belongs to a site, and what listens for it is mostly mail. The team\n * added them on purpose, so owner rules and domain matching have nothing to add\n * either.\n */\n\nexport interface AddContactByHandInput {\n orgId: string\n org: Record<string, unknown> | null | undefined\n /** The site they came from, or `null` for none. */\n sourceHostId: string | null\n /** Normalized, or `null` for a person with no address yet. */\n email: string | null\n name?: string\n facet?: ContactProfileInput\n tags?: readonly string[]\n /** An opt-in the person gave. Ignored with no address. */\n marketingConsent?: boolean\n /** The consent-group sentence shown beside the box, with a Source site. */\n disclosedConsentGroup?: string\n}\n\nexport type AddContactByHandVerdict =\n | { contactId: string; created: boolean }\n | { refused: 'band' | 'erased' | 'error' }\n\n/** The Consent entries for the opt-in, keyed `byHost[hostId]`. */\nfunction consentEntries(\n input: AddContactByHandInput,\n group: ConsentGroup,\n hostIds: readonly string[],\n): Record<string, unknown> {\n if (!input.marketingConsent || !input.email) return {}\n const now = Date.now()\n const fields = input.sourceHostId\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, input.disclosedConsentGroup),\n now,\n )\n : Object.assign(\n {},\n ...hostIds.map(\n (hostId) =>\n marketingConsentFieldsForHost(hostId, now)[MARKETING_CONSENT_BY_HOST_FIELD],\n ),\n )\n return input.sourceHostId\n ? (fields[MARKETING_CONSENT_BY_HOST_FIELD] as Record<string, unknown>)\n : fields\n}\n\n/** Who a person with this number already is, among those the caller can see. */\nasync function findVisibleContactByPhone(\n contacts: FirebaseFirestore.CollectionReference,\n phone: string,\n readable: readonly string[] | null,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const matches = await contacts.where('phone', '==', phone).limit(10).get()\n const visible = matches.docs.find((doc) => {\n if (!readable) return true\n const tokens = doc.get('visibleTo')\n return Array.isArray(tokens) && tokens.some((token) => readable.includes(String(token)))\n })\n return visible ?? null\n}\n\n/** The profile written into a holder's existing facet, one dotted path per field. */\nfunction facetUpdate(\n groupId: string,\n profile: ReturnType<typeof storableProfile>,\n name: string,\n tags: readonly string[],\n): Record<string, unknown> {\n const { custom, ...fields } = profile\n const update: Record<string, unknown> = {}\n for (const [field, value] of Object.entries(fields)) {\n if (value !== undefined) update[contactFacetPath(groupId, field)] = value\n }\n for (const [key, value] of Object.entries(custom ?? {})) {\n update[contactFacetPath(groupId, `custom.${key}`)] = value\n }\n if (name) update[contactFacetPath(groupId, 'name')] = name\n if (tags.length) update[contactFacetPath(groupId, 'tags')] = FieldValue.arrayUnion(...tags)\n return update\n}\n\n/** Adds the person, or merges into who they already are. Never rejects. */\nexport async function addContactByHand(\n input: AddContactByHandInput,\n): Promise<AddContactByHandVerdict> {\n try {\n const { orgId, org, sourceHostId, email } = input\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contacts = orgRef.collection('contacts')\n const group = sourceHostId ? consentGroupForHost(org, sourceHostId) : ORG_HOLDER_GROUP\n const hostIds = sourceHostId ? [sourceHostId] : await orgHostIds(firestore, orgId)\n const tags = input.tags ?? []\n\n const profile = storableProfile(input.facet)\n if (profile.address === null) delete profile.address\n if (profile.otherAddress === null) delete profile.otherAddress\n const composedName = composeContactName(profile.firstName, profile.lastName)\n const canonicalName = (input.name || composedName || '').slice(0, 120)\n const holderName = (composedName || input.name || '').slice(0, 120)\n // The one number the record can be found by; a person who gave only a\n // mobile is found by that.\n const phone = profile.phone || profile.mobilePhone || ''\n const scope = crmDefaultScopeOf(org) === 'org' ? [ORG_SCOPE_TOKEN] : consentGroupScope(group)\n\n const existing = email\n ? await findContactByEmail(contacts, email)\n : phone\n ? await findVisibleContactByPhone(\n contacts,\n phone,\n sourceHostId && crmDefaultScopeOf(org) !== 'org' ? crmReadTokens(group) : null,\n )\n : null\n\n if (existing) {\n const data = (existing.data() ?? {}) as Record<string, unknown>\n const groupId = sourceHostId\n ? group.groupId\n : contactPrimaryGroup(data, org).groupId || ORG_CONTACT_HOLDER_ID\n const { companyId, ...withoutCompany } = profile\n const link = companyId\n ? planContactCompanyLink(readContactCompanyLink(data, groupId), companyId)\n : null\n const consent = consentEntries(input, group, hostIds)\n await existing.ref.update({\n ...facetUpdate(groupId, withoutCompany, holderName, tags),\n ...(link ? contactCompanyLinkFields(link, groupId) : {}),\n ...(phone && !data['phone'] ? { phone } : {}),\n ...Object.fromEntries(\n Object.entries(consent).map(([hostId, entry]) => [\n `${MARKETING_CONSENT_BY_HOST_FIELD}.${hostId}`,\n entry,\n ]),\n ),\n ...(sourceHostId\n ? {\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(sourceHostId),\n visibleTo: FieldValue.arrayUnion(...scope),\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n if (link) await settleCompanyContactsCounts(orgRef.collection('companies'), link)\n await restampCrmListFieldsAt(existing.ref, 'contacts')\n return { contactId: existing.id, created: false }\n }\n\n // An erased person stays erased, whichever door they come back through.\n if (email) {\n for (const hostId of hostIds) {\n if (await hostRefusesCaptureForErasure(hostId, email, firestore)) {\n return { refused: 'erased' }\n }\n }\n }\n\n const { crmRecordsCount } = await countCrmRecords(orgRef, contacts)\n if (!checkCrmRecordsQuota((org as never) ?? null, crmRecordsCount).allowed) {\n return { refused: 'band' }\n }\n\n const facet: Partial<ContactFacet> & Record<string, unknown> = {\n sources: { manual: true },\n interactions: [\n {\n type: 'manual',\n atMs: Date.now(),\n ...(sourceHostId ? { hostId: sourceHostId } : {}),\n summary: 'Added by hand',\n },\n ],\n tags: [...tags],\n ...(holderName ? { name: holderName } : {}),\n ...profile,\n }\n const consent = consentEntries(input, group, hostIds)\n const record: Record<string, unknown> = {\n hostId: sourceHostId,\n [CAPTURED_BY_HOST_FIELD]: sourceHostId ? [sourceHostId] : [],\n visibleTo: scope,\n /*\n * BLANK RATHER THAN ABSENT. The Contacts table sorts by every column, and\n * a Firestore `orderBy` drops a document that lacks the field, so a person\n * with no address would vanish from the list the moment someone sorted it\n * by email. Blank sorts first and reads as nothing, and no reader treats\n * it as an address: `normalizeContactEmail` answers `null`.\n */\n email: email ?? '',\n ...(canonicalName ? nameSearchFields(canonicalName) : {}),\n ...(phone ? { phone } : {}),\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n ...(profile.companyId ? { [CONTACT_COMPANY_IDS_FIELD]: [profile.companyId] } : {}),\n [CONTACT_FACETS_FIELD]: { [group.groupId]: facet },\n ...(Object.keys(consent).length ? { [MARKETING_CONSENT_BY_HOST_FIELD]: consent } : {}),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = contacts.doc(createResourceUid())\n await created.set({\n ...record,\n ...crmNewRecordListFields('contacts', record),\n })\n if (email) {\n await writeContactEmailIndex(emailIndexBeside(contacts), created.id, [email])\n scheduleCapturedEmailCheck({ orgId, ...(sourceHostId ? { hostId: sourceHostId } : {}), email })\n }\n if (profile.companyId) {\n await settleCompanyContactsCounts(\n orgRef.collection('companies'),\n planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n profile.companyId,\n ),\n )\n }\n return { contactId: created.id, created: true }\n } catch (error) {\n console.error('[crm] addContactByHand failed', error)\n return { refused: 'error' }\n }\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkCrmRecordsQuota","composeContactName","consentGroupForGrant","consentGroupForHost","consentGroupScope","CONTACT_COMPANY_IDS_FIELD","CONTACT_FACETS_FIELD","contactFacetPath","crmDefaultScopeOf","crmNewRecordListFields","crmReadTokens","createResourceUid","MARKETING_CONSENT_BY_HOST_FIELD","marketingConsentFieldsForGroup","marketingConsentFieldsForHost","nameSearchFields","ORG_CONTACT_HOLDER_ID","ORG_SCOPE_TOKEN","planContactCompanyLink","readContactCompanyLink","contactCompanyLinkFields","firebaseAdmin","restampCrmListFieldsAt","scheduleCapturedEmailCheck","settleCompanyContactsCounts","emailIndexBeside","findContactByEmail","writeContactEmailIndex","countCrmRecords","hostRefusesCaptureForErasure","storableProfile","FieldValue","ORG_HOLDER_GROUP","contactPrimaryGroup","orgHostIds","consentEntries","input","group","hostIds","marketingConsent","email","now","Date","fields","sourceHostId","disclosedConsentGroup","Object","assign","map","hostId","findVisibleContactByPhone","contacts","phone","readable","matches","where","limit","get","visible","docs","find","doc","tokens","Array","isArray","some","token","includes","String","facetUpdate","groupId","profile","name","tags","custom","update","field","value","entries","undefined","key","length","arrayUnion","addContactByHand","orgId","org","firestore","app","orgRef","collection","facet","address","otherAddress","composedName","firstName","lastName","canonicalName","slice","holderName","mobilePhone","scope","existing","data","companyId","withoutCompany","link","consent","ref","fromEntries","entry","visibleTo","updatedAt","serverTimestamp","contactId","id","created","refused","crmRecordsCount","allowed","sources","manual","interactions","type","atMs","summary","record","companyName","keys","createdAt","set","companyIds","heldElsewhere","error","console"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,oBAAoB,EACpBC,kBAAkB,EAElBC,oBAAoB,EACpBC,mBAAmB,EACnBC,iBAAiB,EACjBC,yBAAyB,EACzBC,oBAAoB,EAEpBC,gBAAgB,EAChBC,iBAAiB,EACjBC,sBAAsB,EACtBC,aAAa,EACbC,iBAAiB,EACjBC,+BAA+B,EAC/BC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,gBAAgB,EAChBC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,wBAAwB,EACxBC,aAAa,EACbC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,0BAA0B,QAAQ,sDAAqD;AAChG,SAASC,2BAA2B,QAAQ,uDAAsD;AAClG,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,sBAAsB,QACjB,sDAAqD;AAC5D,SAASC,eAAe,QAAQ,8CAA6C;AAC7E,SAASC,4BAA4B,QAAQ,oDAAmD;AAChG,SAEEC,eAAe,QACV,iDAAgD;AACvD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,6BAAyB;AAC/E,SAASC,UAAU,QAAQ,kBAAc;AAmEzC,gEAAgE,GAChE,SAASC,eACPC,KAA4B,EAC5BC,KAAmB,EACnBC,OAA0B;IAE1B,IAAI,CAACF,MAAMG,gBAAgB,IAAI,CAACH,MAAMI,KAAK,EAAE,O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,MAAMiC,OAAO,CAAC,EAAEoB;YAAM;WAC7C5C,OAAOiF,IAAI,CAACrB,SAASzB,MAAM,GAAG;YAAE,CAACrE,gCAAgC,EAAE8F;QAAQ,IAAI,CAAC;YACpFsB,WAAWjG,WAAWiF,eAAe;YACrCD,WAAWhF,WAAWiF,eAAe;;QAEvC,MAAMG,UAAUhE,SAASU,GAAG,CAAClD;QAC7B,MAAMwG,QAAQc,GAAG,CAAC,aACbJ,QACApH,uBAAuB,YAAYoH;QAExC,IAAIrF,OAAO;YACT,MAAMb,uBAAuBF,iBAAiB0B,WAAWgE,QAAQD,EAAE,EAAE;gBAAC1E;aAAM;YAC5EjB,2BAA2B;gBAAE6D;eAAWxC,eAAe;gBAAEK,QAAQL;YAAa,IAAI,CAAC;gBAAIJ;;QACzF;QACA,IAAI+B,QAAQgC,SAAS,EAAE;YACrB,MAAM/E,4BACJgE,OAAOC,UAAU,CAAC,cAClBvE,uBACE;gBAAEqF,WAAW;gBAAM2B,YAAY,EAAE;gBAAEC,eAAe,EAAE;YAAC,GACrD5D,QAAQgC,SAAS;QAGvB;QACA,OAAO;YAAEU,WAAWE,QAAQD,EAAE;YAAEC,SAAS;QAAK;IAChD,EAAE,OAAOiB,OAAO;QACdC,QAAQD,KAAK,CAAC,iCAAiCA;QAC/C,OAAO;YAAEhB,SAAS;QAAQ;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/add-contact-by-hand.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CAPTURED_BY_HOST_FIELD,\n checkCrmRecordsQuota,\n composeContactName,\n type ConsentGroup,\n consentGroupForGrant,\n consentGroupForHost,\n consentGroupScope,\n CONTACT_COMPANY_IDS_FIELD,\n CONTACT_FACETS_FIELD,\n type ContactFacet,\n contactFacetPath,\n crmDefaultScopeOf,\n crmDefaultSharingOf,\n crmScopeFields,\n crmNewRecordListFields,\n crmReadTokens,\n createResourceUid,\n MARKETING_CONSENT_BY_HOST_FIELD,\n marketingConsentFieldsForGroup,\n marketingConsentFieldsForHost,\n nameSearchFields,\n ORG_CONTACT_HOLDER_ID,\n ORG_SCOPE_TOKEN,\n planContactCompanyLink,\n readContactCompanyLink,\n} from '@aglyn/aglyn/server'\nimport {\n contactCompanyLinkFields,\n firebaseAdmin,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { scheduleCapturedEmailCheck } from '@aglyn/tenant-data-admin/server/capture-email-check'\nimport { settleCompanyContactsCounts } from '@aglyn/tenant-data-admin/server/contact-company-link'\nimport {\n emailIndexBeside,\n findContactByEmail,\n writeContactEmailIndex,\n} from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { countCrmRecords } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { hostRefusesCaptureForErasure } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n type ContactProfileInput,\n storableProfile,\n} from '@aglyn/tenant-data-admin/server/upsert-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { ORG_HOLDER_GROUP, contactPrimaryGroup } from '../model/contact-holder'\nimport { orgHostIds } from './org-caller'\n\n/**\n * A PERSON THE TEAM ADDS WHO DID NOT COME THROUGH A SITE'S CAPTURE (AGL-4122).\n *\n * `upsertHostContact` is the door for somebody a site met, and it needs what a\n * site's capture always has: a site and an address. A person typed in by the\n * team may have neither. They may be a name and a phone number, added at the\n * organization level, because the team is working a deal with someone whose\n * email comes later. That is this path, and only that: a site AND an address\n * still go through the capture door, which is why the route asks.\n *\n * ## Who the person already is\n *\n * The address when there is one, through the same index the capture reads. With\n * none, the phone number. With neither, nobody: two blank emails are not the\n * same person, and a name is not an identity.\n *\n * The phone lookup is the one narrowing the capture's address lookup refuses,\n * deliberately. An address names one human, so the capture recognizes them\n * across every site. A phone number can be a shared office line, so it only\n * matches somebody this caller's view already holds, and an agency's two\n * clients who share a switchboard stay two records.\n *\n * ## The facet, and what names no site\n *\n * With a Source site the profile lives in that site's group's facet, as a\n * capture's would. With none it lives in `ORG_CONTACT_HOLDER_ID`, and the row\n * has no capturing site: `hostId` is `null`, `capturedByHostIds` is empty, and\n * the record says so instead of guessing a brand that never met the person.\n *\n * ## Consent\n *\n * Only with an address, since a basis for mail needs somewhere to send it. With\n * a site, for that site or the group it disclosed. With none, the person told\n * the organization yes, so the grant is written on every site it has. One entry\n * per site, each a group of one: `byHost[hostId]` stays a lookup, and a site\n * added next month inherits nothing.\n *\n * ## What is not announced\n *\n * A created person with no site or no address fires no `contactCreated`: the\n * event belongs to a site, and what listens for it is mostly mail. The team\n * added them on purpose, so owner rules and domain matching have nothing to add\n * either.\n */\n\nexport interface AddContactByHandInput {\n orgId: string\n org: Record<string, unknown> | null | undefined\n /** The site they came from, or `null` for none. */\n sourceHostId: string | null\n /** Normalized, or `null` for a person with no address yet. */\n email: string | null\n name?: string\n facet?: ContactProfileInput\n tags?: readonly string[]\n /** An opt-in the person gave. Ignored with no address. */\n marketingConsent?: boolean\n /** The consent-group sentence shown beside the box, with a Source site. */\n disclosedConsentGroup?: string\n}\n\nexport type AddContactByHandVerdict =\n | { contactId: string; created: boolean }\n | { refused: 'band' | 'erased' | 'error' }\n\n/** The Consent entries for the opt-in, keyed `byHost[hostId]`. */\nfunction consentEntries(\n input: AddContactByHandInput,\n group: ConsentGroup,\n hostIds: readonly string[],\n): Record<string, unknown> {\n if (!input.marketingConsent || !input.email) return {}\n const now = Date.now()\n const fields = input.sourceHostId\n ? marketingConsentFieldsForGroup(\n consentGroupForGrant(group, input.disclosedConsentGroup),\n now,\n )\n : Object.assign(\n {},\n ...hostIds.map(\n (hostId) =>\n marketingConsentFieldsForHost(hostId, now)[MARKETING_CONSENT_BY_HOST_FIELD],\n ),\n )\n return input.sourceHostId\n ? (fields[MARKETING_CONSENT_BY_HOST_FIELD] as Record<string, unknown>)\n : fields\n}\n\n/** Who a person with this number already is, among those the caller can see. */\nasync function findVisibleContactByPhone(\n contacts: FirebaseFirestore.CollectionReference,\n phone: string,\n readable: readonly string[] | null,\n): Promise<FirebaseFirestore.DocumentSnapshot | null> {\n const matches = await contacts.where('phone', '==', phone).limit(10).get()\n const visible = matches.docs.find((doc) => {\n if (!readable) return true\n const tokens = doc.get('visibleTo')\n return Array.isArray(tokens) && tokens.some((token) => readable.includes(String(token)))\n })\n return visible ?? null\n}\n\n/** The profile written into a holder's existing facet, one dotted path per field. */\nfunction facetUpdate(\n groupId: string,\n profile: ReturnType<typeof storableProfile>,\n name: string,\n tags: readonly string[],\n): Record<string, unknown> {\n const { custom, ...fields } = profile\n const update: Record<string, unknown> = {}\n for (const [field, value] of Object.entries(fields)) {\n if (value !== undefined) update[contactFacetPath(groupId, field)] = value\n }\n for (const [key, value] of Object.entries(custom ?? {})) {\n update[contactFacetPath(groupId, `custom.${key}`)] = value\n }\n if (name) update[contactFacetPath(groupId, 'name')] = name\n if (tags.length) update[contactFacetPath(groupId, 'tags')] = FieldValue.arrayUnion(...tags)\n return update\n}\n\n/** Adds the person, or merges into who they already are. Never rejects. */\nexport async function addContactByHand(\n input: AddContactByHandInput,\n): Promise<AddContactByHandVerdict> {\n try {\n const { orgId, org, sourceHostId, email } = input\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contacts = orgRef.collection('contacts')\n const group = sourceHostId ? consentGroupForHost(org, sourceHostId) : ORG_HOLDER_GROUP\n const hostIds = sourceHostId ? [sourceHostId] : await orgHostIds(firestore, orgId)\n const tags = input.tags ?? []\n\n const profile = storableProfile(input.facet)\n if (profile.address === null) delete profile.address\n if (profile.otherAddress === null) delete profile.otherAddress\n const composedName = composeContactName(profile.firstName, profile.lastName)\n const canonicalName = (input.name || composedName || '').slice(0, 120)\n const holderName = (composedName || input.name || '').slice(0, 120)\n // The one number the record can be found by; a person who gave only a\n // mobile is found by that.\n const phone = profile.phone || profile.mobilePhone || ''\n /*\n * A new person is stamped by the org's CRM default, with the marker under\n * \"All sites except…\" (AGL-4047). A person the workspace already has\n * gains this site's group as before; under all sites except some only the\n * group, since widening a record that exists is the explicit \"Apply to\n * existing records\" run's to do, never a capture's.\n */\n const stamped = crmScopeFields(org, group)\n const scope =\n crmDefaultScopeOf(org) === 'org'\n ? [ORG_SCOPE_TOKEN]\n : crmDefaultSharingOf(org) === 'allExcept'\n ? consentGroupScope(group)\n : stamped.visibleTo\n\n const existing = email\n ? await findContactByEmail(contacts, email)\n : phone\n ? await findVisibleContactByPhone(\n contacts,\n phone,\n sourceHostId && crmDefaultScopeOf(org) !== 'org' ? crmReadTokens(group) : null,\n )\n : null\n\n if (existing) {\n const data = (existing.data() ?? {}) as Record<string, unknown>\n const groupId = sourceHostId\n ? group.groupId\n : contactPrimaryGroup(data, org).groupId || ORG_CONTACT_HOLDER_ID\n const { companyId, ...withoutCompany } = profile\n const link = companyId\n ? planContactCompanyLink(readContactCompanyLink(data, groupId), companyId)\n : null\n const consent = consentEntries(input, group, hostIds)\n await existing.ref.update({\n ...facetUpdate(groupId, withoutCompany, holderName, tags),\n ...(link ? contactCompanyLinkFields(link, groupId) : {}),\n ...(phone && !data['phone'] ? { phone } : {}),\n ...Object.fromEntries(\n Object.entries(consent).map(([hostId, entry]) => [\n `${MARKETING_CONSENT_BY_HOST_FIELD}.${hostId}`,\n entry,\n ]),\n ),\n ...(sourceHostId\n ? {\n [CAPTURED_BY_HOST_FIELD]: FieldValue.arrayUnion(sourceHostId),\n visibleTo: FieldValue.arrayUnion(...scope),\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n if (link) await settleCompanyContactsCounts(orgRef.collection('companies'), link)\n await restampCrmListFieldsAt(existing.ref, 'contacts')\n return { contactId: existing.id, created: false }\n }\n\n // An erased person stays erased, whichever door they come back through.\n if (email) {\n for (const hostId of hostIds) {\n if (await hostRefusesCaptureForErasure(hostId, email, firestore)) {\n return { refused: 'erased' }\n }\n }\n }\n\n const { crmRecordsCount } = await countCrmRecords(orgRef, contacts)\n if (!checkCrmRecordsQuota((org as never) ?? null, crmRecordsCount).allowed) {\n return { refused: 'band' }\n }\n\n const facet: Partial<ContactFacet> & Record<string, unknown> = {\n sources: { manual: true },\n interactions: [\n {\n type: 'manual',\n atMs: Date.now(),\n ...(sourceHostId ? { hostId: sourceHostId } : {}),\n summary: 'Added by hand',\n },\n ],\n tags: [...tags],\n ...(holderName ? { name: holderName } : {}),\n ...profile,\n }\n const consent = consentEntries(input, group, hostIds)\n const record: Record<string, unknown> = {\n hostId: sourceHostId,\n [CAPTURED_BY_HOST_FIELD]: sourceHostId ? [sourceHostId] : [],\n ...stamped,\n /*\n * BLANK RATHER THAN ABSENT. The Contacts table sorts by every column, and\n * a Firestore `orderBy` drops a document that lacks the field, so a person\n * with no address would vanish from the list the moment someone sorted it\n * by email. Blank sorts first and reads as nothing, and no reader treats\n * it as an address: `normalizeContactEmail` answers `null`.\n */\n email: email ?? '',\n ...(canonicalName ? nameSearchFields(canonicalName) : {}),\n ...(phone ? { phone } : {}),\n ...(profile.companyName ? { companyName: profile.companyName } : {}),\n ...(profile.companyId ? { [CONTACT_COMPANY_IDS_FIELD]: [profile.companyId] } : {}),\n [CONTACT_FACETS_FIELD]: { [group.groupId]: facet },\n ...(Object.keys(consent).length ? { [MARKETING_CONSENT_BY_HOST_FIELD]: consent } : {}),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = contacts.doc(createResourceUid())\n await created.set({\n ...record,\n ...crmNewRecordListFields('contacts', record),\n })\n if (email) {\n await writeContactEmailIndex(emailIndexBeside(contacts), created.id, [email])\n scheduleCapturedEmailCheck({ orgId, ...(sourceHostId ? { hostId: sourceHostId } : {}), email })\n }\n if (profile.companyId) {\n await settleCompanyContactsCounts(\n orgRef.collection('companies'),\n planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n profile.companyId,\n ),\n )\n }\n return { contactId: created.id, created: true }\n } catch (error) {\n console.error('[crm] addContactByHand failed', error)\n return { refused: 'error' }\n }\n}\n"],"names":["CAPTURED_BY_HOST_FIELD","checkCrmRecordsQuota","composeContactName","consentGroupForGrant","consentGroupForHost","consentGroupScope","CONTACT_COMPANY_IDS_FIELD","CONTACT_FACETS_FIELD","contactFacetPath","crmDefaultScopeOf","crmDefaultSharingOf","crmScopeFields","crmNewRecordListFields","crmReadTokens","createResourceUid","MARKETING_CONSENT_BY_HOST_FIELD","marketingConsentFieldsForGroup","marketingConsentFieldsForHost","nameSearchFields","ORG_CONTACT_HOLDER_ID","ORG_SCOPE_TOKEN","planContactCompanyLink","readContactCompanyLink","contactCompanyLinkFields","firebaseAdmin","restampCrmListFieldsAt","scheduleCapturedEmailCheck","settleCompanyContactsCounts","emailIndexBeside","findContactByEmail","writeContactEmailIndex","countCrmRecords","hostRefusesCaptureForErasure","storableProfile","FieldValue","ORG_HOLDER_GROUP","contactPrimaryGroup","orgHostIds","consentEntries","input","group","hostIds","marketingConsent","email","now","Date","fields","sourceHostId","disclosedConsentGroup","Object","assign","map","hostId","findVisibleContactByPhone","contacts","phone","readable","matches","where","limit","get","visible","docs","find","doc","tokens","Array","isArray","some","token","includes","String","facetUpdate","groupId","profile","name","tags","custom","update","field","value","entries","undefined","key","length","arrayUnion","addContactByHand","orgId","org","firestore","app","orgRef","collection","facet","address","otherAddress","composedName","firstName","lastName","canonicalName","slice","holderName","mobilePhone","stamped","scope","visibleTo","existing","data","companyId","withoutCompany","link","consent","ref","fromEntries","entry","updatedAt","serverTimestamp","contactId","id","created","refused","crmRecordsCount","allowed","sources","manual","interactions","type","atMs","summary","record","companyName","keys","createdAt","set","companyIds","heldElsewhere","error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,eAAe;YACrCD,WAAWjF,WAAWkF,eAAe;;QAEvC,MAAMG,UAAUjE,SAASU,GAAG,CAAClD;QAC7B,MAAMyG,QAAQc,GAAG,CAAC,aACbJ,QACArH,uBAAuB,YAAYqH;QAExC,IAAItF,OAAO;YACT,MAAMb,uBAAuBF,iBAAiB0B,WAAWiE,QAAQD,EAAE,EAAE;gBAAC3E;aAAM;YAC5EjB,2BAA2B;gBAAE6D;eAAWxC,eAAe;gBAAEK,QAAQL;YAAa,IAAI,CAAC;gBAAIJ;;QACzF;QACA,IAAI+B,QAAQkC,SAAS,EAAE;YACrB,MAAMjF,4BACJgE,OAAOC,UAAU,CAAC,cAClBvE,uBACE;gBAAEuF,WAAW;gBAAM0B,YAAY,EAAE;gBAAEC,eAAe,EAAE;YAAC,GACrD7D,QAAQkC,SAAS;QAGvB;QACA,OAAO;YAAES,WAAWE,QAAQD,EAAE;YAAEC,SAAS;QAAK;IAChD,EAAE,OAAOiB,OAAO;QACdC,QAAQD,KAAK,CAAC,iCAAiCA;QAC/C,OAAO;YAAEhB,SAAS;QAAQ;IAC5B;AACF"}
@@ -28,7 +28,7 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
28
28
  */ import { CRM_COLLECTIONS, CRM_ACTIVITY_DIRECTIONS, CRM_ACTIVITY_KINDS, CRM_ACTIVITY_LOG_FULL_MESSAGE, consentGroupForHost, createResourceUid, crmActivityDirection, crmActivityLogHasRoom } from "@aglyn/aglyn/server";
29
29
  import { apiJson, ApiErrors, countCrmActivitiesForRecord } from "@aglyn/tenant-data-admin";
30
30
  import { claimWrite, readJsonBody, requireScope } from "@aglyn/tenant-data-admin/server/api-v1-kit";
31
- import { CRM_LABEL_MAX, CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmCreateStamp, crmRefErrors, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, parseIsoInstant, readChoice, readCrmSite, readEqualityFilters, readOptionalText, readRefId, refuseUnknownKeys } from "./crm-shared.js";
31
+ import { CRM_LABEL_MAX, CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmScopedCreateStamp, crmRefErrors, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, parseIsoInstant, readChoice, readCrmSite, readEqualityFilters, readOptionalText, readRefId, refuseUnknownKeys } from "./crm-shared.js";
32
32
  import { crmActivityLinkWithCompany } from "../crm-activity-company.js";
33
33
  /** The kinds the API accepts: the CRM's own list, so a kind the console logs is one the API takes. */ const ACTIVITY_KINDS = CRM_ACTIVITY_KINDS;
34
34
  /** The activity object as published. */ function activityView(doc) {
@@ -166,7 +166,7 @@ function readActivityInput(body) {
166
166
  });
167
167
  }
168
168
  const id = createResourceUid();
169
- const stamp = crmCreateStamp(ctx, site.siteId);
169
+ const stamp = crmScopedCreateStamp(ctx, site.siteId);
170
170
  const { companyId } = await crmActivityLinkWithCompany(ctx.firestore.collection('orgs').doc(ctx.orgId), parsed.values, {
171
171
  groupId: site.siteId ? consentGroupForHost(org, site.siteId).groupId : null,
172
172
  org