@aglyn/plugins-crm 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/contact-list-columns.js +4 -3
  3. package/src/lib/components/contact-list-columns.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.js +6 -2
  5. package/src/lib/components/contact-properties-card.js.map +1 -1
  6. package/src/lib/components/contacts-bulk-bar.js +16 -5
  7. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  8. package/src/lib/components/contacts-section.js +6 -13
  9. package/src/lib/components/contacts-section.js.map +1 -1
  10. package/src/lib/components/crm-record-insights-zone.js +7 -0
  11. package/src/lib/components/crm-record-insights-zone.js.map +1 -1
  12. package/src/lib/components/crm-send-email-dialog.js +1 -1
  13. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  14. package/src/lib/components/deal-board.d.ts +2 -0
  15. package/src/lib/components/deal-board.js +20 -11
  16. package/src/lib/components/deal-board.js.map +1 -1
  17. package/src/lib/components/deal-stage-card.js +41 -28
  18. package/src/lib/components/deal-stage-card.js.map +1 -1
  19. package/src/lib/components/deals-bulk-bar.js +20 -10
  20. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  21. package/src/lib/components/deals-section.js +1 -0
  22. package/src/lib/components/deals-section.js.map +1 -1
  23. package/src/lib/components/email-capture-card.d.ts +1 -1
  24. package/src/lib/components/email-capture-card.js +2 -1
  25. package/src/lib/components/email-capture-card.js.map +1 -1
  26. package/src/lib/components/record-sharing-card.d.ts +6 -5
  27. package/src/lib/components/record-sharing-card.js +45 -30
  28. package/src/lib/components/record-sharing-card.js.map +1 -1
  29. package/src/lib/components/settings-section.d.ts +18 -11
  30. package/src/lib/components/settings-section.js +36 -19
  31. package/src/lib/components/settings-section.js.map +1 -1
  32. package/src/lib/components/sharing-rules-card.js +2 -1
  33. package/src/lib/components/sharing-rules-card.js.map +1 -1
  34. package/src/lib/components/use-org-members.d.ts +17 -10
  35. package/src/lib/components/use-org-members.js +31 -66
  36. package/src/lib/components/use-org-members.js.map +1 -1
  37. package/src/lib/declarations.d.ts +6 -2
  38. package/src/lib/declarations.js +14 -2
  39. package/src/lib/declarations.js.map +1 -1
  40. package/src/lib/declarations.server.js +16 -0
  41. package/src/lib/declarations.server.js.map +1 -1
  42. package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
  43. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  44. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  45. package/src/lib/hooks/use-crm-record-names.js +59 -6
  46. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  47. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  48. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  49. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  50. package/src/lib/hooks/use-org-member-directory.js +49 -12
  51. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  52. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  53. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  54. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  55. package/src/lib/model/crm-api.d.ts +1 -1
  56. package/src/lib/model/crm-api.js +1 -1
  57. package/src/lib/model/crm-api.js.map +1 -1
  58. package/src/lib/model/crm-permissions.d.ts +35 -0
  59. package/src/lib/model/crm-permissions.js +87 -0
  60. package/src/lib/model/crm-permissions.js.map +1 -0
  61. package/src/lib/model/crm-sharing.d.ts +1 -1
  62. package/src/lib/model/crm-sharing.js +1 -1
  63. package/src/lib/model/crm-sharing.js.map +1 -1
  64. package/src/lib/plugin.js +4 -5
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/capture-contact.d.ts +3 -3
  67. package/src/lib/server/capture-contact.js +3 -3
  68. package/src/lib/server/capture-contact.js.map +1 -1
  69. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  70. package/src/lib/server/crm-setup-writers.server.js +4 -16
  71. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  72. package/src/lib/server/crm-sharing.d.ts +5 -4
  73. package/src/lib/server/crm-sharing.js +8 -6
  74. package/src/lib/server/crm-sharing.js.map +1 -1
  75. package/src/lib/server/email-template-duplicate.js +7 -7
  76. package/src/lib/server/email-template-duplicate.js.map +1 -1
  77. package/src/lib/server/inbound-address.d.ts +9 -7
  78. package/src/lib/server/inbound-address.js +18 -15
  79. package/src/lib/server/inbound-address.js.map +1 -1
  80. package/src/lib/server/org-caller.d.ts +19 -5
  81. package/src/lib/server/org-caller.js +25 -5
  82. package/src/lib/server/org-caller.js.map +1 -1
  83. package/src/lib/server/recipe-routes.d.ts +0 -34
  84. package/src/lib/server/recipe-routes.js +11 -10
  85. package/src/lib/server/recipe-routes.js.map +1 -1
  86. package/src/lib/server/scope-sharing-patch.d.ts +22 -0
  87. package/src/lib/server/scope-sharing-patch.js +25 -0
  88. package/src/lib/server/scope-sharing-patch.js.map +1 -0
  89. package/src/lib/server/task-routes.d.ts +6 -5
  90. package/src/lib/server/task-routes.js +11 -13
  91. package/src/lib/server/task-routes.js.map +1 -1
  92. package/src/lib/server-deal-stage.d.ts +11 -6
  93. package/src/lib/server-deal-stage.js +18 -16
  94. package/src/lib/server-deal-stage.js.map +1 -1
  95. package/src/lib/server.js +16 -18
  96. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-contact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginContactSource,\n type PluginContactCaptureRequest,\n type PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport { formLeadSource } from '@aglyn/aglyn/app-utils/forms'\nimport { normalizePhone } from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from './capture-host-contact'\nimport { contactCaptureActor } from '@aglyn/tenant-runtime/capture-actor'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLeadOutcome,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n readLeadForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport {\n CONVERSION_TOUCH_DETAIL,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\nimport { crmRecordOriginWriter } from './record-origin'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await stampedAfter(request, fileLead(request))\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await stampedAfter(request, fileLead(request))\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok) await stampOrigin(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n // Money changing hands is a purchase whichever door took it — a paid\n // booking or a stay is one as much as an order is.\n by:\n request.interaction.source === 'order' || (request.purchaseCents ?? 0) > 0\n ? 'purchase'\n : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * WHERE THE PERSON CAME FROM (AGL-3519): the door's word — a form, a\n * booking, a newsletter, a member, an order — as the built-in Lead source\n * it names, on a record the capture just started and that names none. A\n * person met before keeps whatever lead source they hold, or the lack of one.\n * Never fails the capture: the writer swallows its own errors.\n */\nasync function stampOrigin(request: PluginContactCaptureRequest): Promise<void> {\n await crmRecordOriginWriter.stamp({\n hostId: request.hostId,\n email: normalizeContactEmail(request.identity.email) ?? '',\n origin: request.interaction.source,\n firstTouchOnly: true,\n })\n}\n\n/** A filed lead's verdict, after its origin is stamped when the filing took. */\nasync function stampedAfter(\n request: PluginContactCaptureRequest,\n filed: Promise<PluginContactCaptured>,\n): Promise<PluginContactCaptured> {\n const verdict = await filed\n if (verdict.ok) await stampOrigin(request)\n return verdict\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n /*\n * Through the seam, which reads the org row and falls back to a lead the\n * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand\n * in the same consent group has to find this person, or its door concludes\n * there is no lead and files the duplicate this migration exists to end.\n */\n const snapshot = await readLeadForHost(request.hostId, key)\n if (!snapshot) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n // `addHostLead` resolves and writes the org collection itself (AGL-3275);\n // this only needs to know whether the person is new, which decides the event.\n const created = !(await readLeadForHost(request.hostId, key))\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? formLeadSource(formId)\n : request.interaction.source\n const outcome = await addHostLeadOutcome({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n ...disclosureOf(request),\n // Filed under the surface's campaigns, as the contact door files a\n // contact (AGL-3458): a lead-routed form in a campaign makes a lead\n // in that campaign.\n ...campaignsFiledUnder(request),\n ...phoneFillOf(request),\n },\n ...(conversionTouchOf(request.detail).conversionTouch\n ? { touch: conversionTouchOf(request.detail).conversionTouch }\n : {}),\n })\n if (!outcome.stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n const cause = contactCaptureActor(\n request.interaction.source,\n email,\n request.actor,\n )\n await emitHostEvent(\n request.hostId,\n 'lead',\n leadCreatedPayload({\n leadId: key,\n email,\n name: request.identity.name,\n source,\n hostId: request.hostId,\n formId,\n campaignIds: campaignsFiledUnder(request).campaignIds,\n }),\n cause ? { actor: cause } : {},\n )\n }\n return { ok: true, record: 'lead', leadId: key, created, sourceAdded: outcome.sourceAdded }\n}\n\n/**\n * The `lead` payload (AGL-3458), as the scalars an event may carry — the\n * shape `contactCreatedPayload` gives a new contact, so one condition reads\n * the same on either event: `name` always present, empty when the door had\n * none; `formId` only when a form filed the lead, so `notEmpty` on it reads\n * as \"came in through a form\" and `equals` picks one form's people out; and\n * `campaignIds` comma-joined, only when the surface is filed under any.\n */\nexport function leadCreatedPayload(lead: {\n leadId: string\n email: string\n name?: string | null\n source: string\n hostId: string\n formId?: string | null\n campaignIds?: readonly string[]\n}): Record<string, string> {\n const formId = String(lead.formId ?? '').trim()\n return {\n leadId: lead.leadId,\n email: lead.email,\n name: String(lead.name ?? '').trim(),\n source: lead.source,\n hostId: lead.hostId,\n ...(formId ? { formId } : {}),\n ...(lead.campaignIds?.length ? { campaignIds: lead.campaignIds.join(',') } : {}),\n }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n ...(request.actor ? { actor: request.actor } : {}),\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...conversionTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...disclosureOf(request),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...campaignsFiledUnder(request),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n ...(phoneFillOf(request).phoneFill\n ? { facetFill: { phone: phoneFillOf(request).phoneFill } }\n : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE DISCLOSURE the capture surface rendered, handed to whichever record the\n * capture lands on (AGL-3320).\n *\n * Passed through unread: both writers resolve the site's group themselves and\n * pool the opt-in only when this is its current key, so a lead and a contact\n * written by one capture record the same sites. A string or nothing, since\n * the writers compare it exactly and anything else could only fail to match.\n */\nfunction disclosureOf(\n request: PluginContactCaptureRequest,\n): { disclosedConsentGroup?: string } {\n const key = request.disclosedConsentGroup\n return typeof key === 'string' && key ? { disclosedConsentGroup: key } : {}\n}\n\n/**\n * THE PHONE A CAPTURE LEARNED IN PASSING (AGL-3493), off `profileFill`.\n *\n * Normalized here so a lead and a contact written by one capture keep the\n * same E.164 string, and dropped when it will not normalize: a fill is an\n * enrichment, and a number in some other shape on the record is the\n * \"stored three ways\" failure `normalizePhone` exists to end. Both writers\n * put it only where the record holds no phone.\n */\nfunction phoneFillOf(request: PluginContactCaptureRequest): { phoneFill?: string } {\n const raw = request.profileFill?.['phone']\n const phone = typeof raw === 'string' ? normalizePhone(raw) : null\n return phone ? { phoneFill: phone } : {}\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * The campaigns the capture surface is filed under, as the contact writer\n * records them. A capture names what its surface is filed under by container\n * kind; the CRM keeps the `campaign` kind on the person's site facet, and a\n * kind it does not keep is the capture's to name and the CRM's to ignore.\n */\nfunction campaignsFiledUnder(\n request: PluginContactCaptureRequest,\n): Pick<UpsertHostContactOptions, 'campaignIds'> {\n const ids = request.containers?.['campaign'] ?? []\n return ids.length ? { campaignIds: ids } : {}\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved by the plugin that\n * credits outcomes (`plugin-conversion-credit`) at the silo's door;\n * `campaignIds` is which campaigns the merchant filed the capture SURFACE\n * under, which is true of everybody who fills that form in. Folding them\n * would credit a campaign for a visitor who typed the address.\n *\n * Passed through as the silo handed it, unread: the touch's shape belongs\n * to the creditor that resolved it, and the creditor checks it again when\n * the contact or the lead is credited. Only its presence is decided here,\n * because `null` and absent mean the same thing to the writer and a caller\n * should not have to know which one it sends.\n */\nfunction conversionTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'conversionTouch'> {\n const touch = detail?.[CONVERSION_TOUCH_DETAIL]\n return touch && typeof touch === 'object'\n ? { conversionTouch: touch as PluginConversionTouch }\n : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * A declared word READS by its plugin's label (`labelContactSource`, AGL-4042:\n * the waivers plugin's `waiver`). ⛔ What it still costs, until the union is\n * widened: the console's source filter keys on the union, so a plugin's word\n * matches no filter option, and an UNDECLARED word also renders raw.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word) && !pluginContactSource(word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["pluginContactSource","CONTACT_SOURCE_LABELS","formLeadSource","normalizePhone","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","contactCaptureActor","emitHostEvent","addHostLeadOutcome","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","readLeadForHost","CONVERSION_TOUCH_DETAIL","convertOpenLeadOntoContact","crmRecordOriginWriter","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","stampedAfter","fileLead","openLeadFor","verdict","captureOnContact","ok","stampOrigin","record","hostId","contactId","by","interaction","source","purchaseCents","error","console","reason","stamp","origin","firstTouchOnly","filed","refusalText","contacts","snapshot","key","lead","data","convertedContactId","hostRef","app","firestore","collection","doc","created","formId","entryPointOf","detail","outcome","name","marketingConsent","disclosureOf","campaignsFiledUnder","phoneFillOf","conversionTouchOf","conversionTouch","touch","stored","cause","actor","leadCreatedPayload","leadId","campaignIds","sourceAdded","String","trim","length","join","contactSourceOf","atMs","undefined","refId","summary","tags","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","phoneFill","facetFill","phone","refused","disclosedConsentGroup","raw","profileFill","text","value","path","ids","containers","word","Object","hasOwn","warn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,QAGd,qDAAoD;AAC3D,SACEC,qBAAqB,QAEhB,kCAAiC;AACxC,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAEEC,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,aAAa,QAAQ,wCAAuC;AACrE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,aAAa,EACbC,wBAAwB,EACxBC,eAAe,QAEV,2BAA0B;AACjC,SACEC,uBAAuB,QAElB,uDAAsD;AAC7D,SAASC,0BAA0B,QAAQ,yBAAqB;AAChE,SAASC,qBAAqB,QAAQ,qBAAiB;AAEvD;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,eAAeC,qBACpBC,OAAoC;QAEpBA;IAAhB,MAAMC,WAAUD,mBAAAA,QAAQC,OAAO,YAAfD,mBAAmB;IACnC,qEAAqE;IACrE,0DAA0D;IAC1D,IAAI,CAACd,sBAAsBc,QAAQE,QAAQ,CAACC,KAAK,GAAG,OAAOC;IAC3D,IAAI;QACF,IAAIH,YAAY,QAAQ;YACtB,IAAI,CAAE,MAAMI,cAAcL,UAAW,O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F"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-contact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginContactSource,\n type PluginContactCaptureRequest,\n type PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport { formLeadSource } from '@aglyn/aglyn/app-utils/forms'\nimport { normalizePhone } from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from './capture-host-contact'\nimport { contactCaptureActor } from '@aglyn/tenant-runtime/capture-actor'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLeadOutcome,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n readLeadForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport {\n CONVERSION_TOUCH_DETAIL,\n type PluginConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\nimport { crmRecordOriginWriter } from './record-origin'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await stampedAfter(request, fileLead(request))\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await stampedAfter(request, fileLead(request))\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok) await stampOrigin(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n // Money changing hands is a purchase whichever door took it — a paid\n // booking or a stay is one as much as an order is.\n by:\n request.interaction.source === 'order' || (request.purchaseCents ?? 0) > 0\n ? 'purchase'\n : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * WHERE THE PERSON CAME FROM (AGL-3519): the door's word — a form, a\n * booking, a newsletter, a member, an order — as the built-in Lead source\n * it names, on a record the capture just started and that names none. A\n * person met before keeps whatever lead source they hold, or the lack of one.\n * Never fails the capture: the writer swallows its own errors.\n */\nasync function stampOrigin(request: PluginContactCaptureRequest): Promise<void> {\n await crmRecordOriginWriter.stamp({\n hostId: request.hostId,\n email: normalizeContactEmail(request.identity.email) ?? '',\n origin: request.interaction.source,\n firstTouchOnly: true,\n })\n}\n\n/** A filed lead's verdict, after its origin is stamped when the filing took. */\nasync function stampedAfter(\n request: PluginContactCaptureRequest,\n filed: Promise<PluginContactCaptured>,\n): Promise<PluginContactCaptured> {\n const verdict = await filed\n if (verdict.ok) await stampOrigin(request)\n return verdict\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n /*\n * Through the seam, which reads the org row and falls back to a lead the\n * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand\n * in the same consent group has to find this person, or its door concludes\n * there is no lead and files the duplicate this migration exists to end.\n */\n const snapshot = await readLeadForHost(request.hostId, key)\n if (!snapshot) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n // `addHostLead` resolves and writes the org collection itself (AGL-3275);\n // this only needs to know whether the person is new, which decides the event.\n const created = !(await readLeadForHost(request.hostId, key))\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? formLeadSource(formId)\n : request.interaction.source\n const outcome = await addHostLeadOutcome({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n ...disclosureOf(request),\n // Filed under the surface's campaigns, as the contact door files a\n // contact (AGL-3458): a lead-routed form in a campaign makes a lead\n // in that campaign.\n ...campaignsFiledUnder(request),\n ...phoneFillOf(request),\n },\n ...(conversionTouchOf(request.detail).conversionTouch\n ? { touch: conversionTouchOf(request.detail).conversionTouch }\n : {}),\n })\n if (!outcome.stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n const cause = contactCaptureActor(\n request.interaction.source,\n email,\n request.actor,\n )\n await emitHostEvent(\n request.hostId,\n 'lead',\n leadCreatedPayload({\n leadId: key,\n email,\n name: request.identity.name,\n source,\n hostId: request.hostId,\n formId,\n campaignIds: campaignsFiledUnder(request).campaignIds,\n }),\n cause ? { actor: cause } : {},\n )\n }\n return { ok: true, record: 'lead', leadId: key, created, sourceAdded: outcome.sourceAdded }\n}\n\n/**\n * The `lead` payload (AGL-3458), as the scalars an event may carry — the\n * shape `contactCreatedPayload` gives a new contact, so one condition reads\n * the same on either event: `name` always present, empty when the door had\n * none; `formId` only when a form filed the lead, so `notEmpty` on it reads\n * as \"came in through a form\" and `equals` picks one form's people out; and\n * `campaignIds` comma-joined, only when the surface is filed under any.\n */\nexport function leadCreatedPayload(lead: {\n leadId: string\n email: string\n name?: string | null\n source: string\n hostId: string\n formId?: string | null\n campaignIds?: readonly string[]\n}): Record<string, string> {\n const formId = String(lead.formId ?? '').trim()\n return {\n leadId: lead.leadId,\n email: lead.email,\n name: String(lead.name ?? '').trim(),\n source: lead.source,\n hostId: lead.hostId,\n ...(formId ? { formId } : {}),\n ...(lead.campaignIds?.length ? { campaignIds: lead.campaignIds.join(',') } : {}),\n }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n ...(request.actor ? { actor: request.actor } : {}),\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...conversionTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...disclosureOf(request),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...campaignsFiledUnder(request),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n ...(phoneFillOf(request).phoneFill\n ? { facetFill: { phone: phoneFillOf(request).phoneFill } }\n : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE DISCLOSURE the capture surface rendered, handed to whichever record the\n * capture lands on (AGL-3320).\n *\n * Passed through unread: both writers resolve the site's group themselves and\n * pool the opt-in only when this is its current key, so a lead and a contact\n * written by one capture record the same sites. A string or nothing, since\n * the writers compare it exactly and anything else could only fail to match.\n */\nfunction disclosureOf(\n request: PluginContactCaptureRequest,\n): { disclosedConsentGroup?: string } {\n const key = request.disclosedConsentGroup\n return typeof key === 'string' && key ? { disclosedConsentGroup: key } : {}\n}\n\n/**\n * THE PHONE A CAPTURE LEARNED IN PASSING (AGL-3493), off `profileFill`.\n *\n * Normalized here so a lead and a contact written by one capture keep the\n * same E.164 string, and dropped when it will not normalize: a fill is an\n * enrichment, and a number in some other shape on the record is the\n * \"stored three ways\" failure `normalizePhone` exists to end. Both writers\n * put it only where the record holds no phone.\n */\nfunction phoneFillOf(request: PluginContactCaptureRequest): { phoneFill?: string } {\n const raw = request.profileFill?.['phone']\n const phone = typeof raw === 'string' ? normalizePhone(raw) : null\n return phone ? { phoneFill: phone } : {}\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * The campaigns the capture surface is filed under, as the contact writer\n * records them. A capture names what its surface is filed under by container\n * kind; the CRM keeps the `campaign` kind on the person's site facet, and a\n * kind it does not keep is the capture's to name and the CRM's to ignore.\n */\nfunction campaignsFiledUnder(\n request: PluginContactCaptureRequest,\n): Pick<UpsertHostContactOptions, 'campaignIds'> {\n const ids = request.containers?.['campaign'] ?? []\n return ids.length ? { campaignIds: ids } : {}\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved by the plugin that\n * credits outcomes (`plugin-conversion-credit`) at the silo's door;\n * `campaignIds` is which campaigns the merchant filed the capture SURFACE\n * under, which is true of everybody who fills that form in. Folding them\n * would credit a campaign for a visitor who typed the address.\n *\n * Passed through as the silo handed it, unread: the touch's shape belongs\n * to the creditor that resolved it, and the creditor checks it again when\n * the contact or the lead is credited. Only its presence is decided here,\n * because `null` and absent mean the same thing to the writer and a caller\n * should not have to know which one it sends.\n */\nfunction conversionTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'conversionTouch'> {\n const touch = detail?.[CONVERSION_TOUCH_DETAIL]\n return touch && typeof touch === 'object'\n ? { conversionTouch: touch as PluginConversionTouch }\n : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * A declared word READS by its plugin's label (`labelContactSource`, AGL-4042:\n * the waivers plugin's `waiver`) and is a choice in the console's source filter\n * (`listContactSourceOptions`, AGL-3680). ⛔ An UNDECLARED word renders raw and\n * no filter offers it.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word) && !pluginContactSource(word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["pluginContactSource","CONTACT_SOURCE_LABELS","formLeadSource","normalizePhone","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","contactCaptureActor","emitHostEvent","addHostLeadOutcome","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","readLeadForHost","CONVERSION_TOUCH_DETAIL","convertOpenLeadOntoContact","crmRecordOriginWriter","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","stampedAfter","fileLead","openLeadFor","verdict","captureOnContact","ok","stampOrigin","record","hostId","contactId","by","interaction","source","purchaseCents","error","console","reason","stamp","origin","firstTouchOnly","filed","refusalText","contacts","snapshot","key","lead","data","convertedContactId","hostRef","app","firestore","collection","doc","created","formId","entryPointOf","detail","outcome","name","marketingConsent","disclosureOf","campaignsFiledUnder","phoneFillOf","conversionTouchOf","conversionTouch","touch","stored","cause","actor","leadCreatedPayload","leadId","campaignIds","sourceAdded","String","trim","length","join","contactSourceOf","atMs","undefined","refId","summary","tags","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","phoneFill","facetFill","phone","refused","disclosedConsentGroup","raw","profileFill","text","value","path","ids","containers","word","Object","hasOwn","warn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,QAGd,qDAAoD;AAC3D,SACEC,qBAAqB,QAEhB,kCAAiC;AACxC,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAEEC,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,aAAa,QAAQ,wCAAuC;AACrE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,aAAa,EACbC,wBAAwB,EACxBC,eAAe,QAEV,2BAA0B;AACjC,SACEC,uBAAuB,QAElB,uDAAsD;AAC7D,SAASC,0BAA0B,QAAQ,yBAAqB;AAChE,SAASC,qBAAqB,QAAQ,qBAAiB;AAEvD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C,IAAI,CAAC2B,OAAOC,MAAM,CAAC1G,uBAAuBwG,SAAS,CAACzG,oBAAoByG,OAAO;QAC7E,sEAAsE;QACtE,2DAA2D;QAC3DjE,QAAQoE,IAAI,CACV,CAAC,6BAA6B,EAAEH,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAAS3D,YAAYL,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
@@ -46,14 +46,13 @@ import type { PipelineDoc } from '../model/deal-board-model';
46
46
  */
47
47
  type Firestore = FirebaseFirestore.Firestore;
48
48
  /** The refusals, in the console's and the routes' words. */
49
- export declare const CRM_SETUP_ROLE_REFUSAL = "Editing the CRM requires the editor role";
50
- export declare const CRM_SETUP_PERMISSION_REFUSAL = "Your organization role does not allow editing organization data";
49
+ export declare const CRM_SETUP_PERMISSION_REFUSAL = "Your role does not include \"Manage data\" \u2014 ask an organization admin";
51
50
  export declare const CRM_SETUP_SCOPE_REFUSAL = "Your access to this organization does not reach that site";
52
51
  export declare const CRM_SETUP_FIELD_SCOPE_REFUSAL = "Custom fields are organization-wide, and your access reaches only some sites";
53
52
  export declare const CRM_SETUP_PICKLIST_SCOPE_REFUSAL = "Picklists are organization-wide, and your access reaches only some sites";
54
53
  /** Who the member is in the org, as the writers ask. */
55
54
  export interface CrmSetupMember {
56
- role: string;
55
+ /** "Manage data" (`data.manage`, AGL-4047), the rules' `canWriteOrgData()`. */
57
56
  canManageData: boolean;
58
57
  /** The membership itself, for its reach and whether it is suspended. */
59
58
  member: Readonly<Record<string, unknown>>;
@@ -28,16 +28,10 @@ import { checkCrmFieldSetup, checkCrmPipelineSetup, crmPipelineSetupFacts, planC
28
28
  import { picklistKeepsGroups } from "../model/picklist-values.js";
29
29
  import { picklistGroupOf, regroupEverywhere } from "./picklist-regroup.js";
30
30
  import { crmSuiteRefusalMessage } from "./suite-gate.js";
31
- /** The refusals, in the console's and the routes' words. */ export const CRM_SETUP_ROLE_REFUSAL = 'Editing the CRM requires the editor role';
32
- export const CRM_SETUP_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data';
31
+ /** The refusals, in the console's and the routes' words. */ export const CRM_SETUP_PERMISSION_REFUSAL = 'Your role does not include "Manage data" — ask an organization admin';
33
32
  export const CRM_SETUP_SCOPE_REFUSAL = 'Your access to this organization does not reach that site';
34
33
  export const CRM_SETUP_FIELD_SCOPE_REFUSAL = 'Custom fields are organization-wide, and your access reaches only some sites';
35
34
  export const CRM_SETUP_PICKLIST_SCOPE_REFUSAL = 'Picklists are organization-wide, and your access reaches only some sites';
36
- /** Roles allowed to write the CRM's setup — the rules' `canWriteOrgData()`. */ const WRITER_ROLES = new Set([
37
- 'owner',
38
- 'admin',
39
- 'editor'
40
- ]);
41
35
  /** The most pipelines one site's read returns, as the board reads them. */ const PIPELINE_READ_LIMIT = 50;
42
36
  /** The org subcollection each picklist target's records live in. */ const TARGET_COLLECTIONS = {
43
37
  contact: 'contacts',
@@ -47,12 +41,10 @@ export const CRM_SETUP_PICKLIST_SCOPE_REFUSAL = 'Picklists are organization-wide
47
41
  task: CRM_COLLECTIONS.tasks
48
42
  };
49
43
  async function platformMember(uid, orgId) {
50
- var _member_role;
51
44
  const membership = await resolveOrgMembership(uid, orgId);
52
45
  const member = membership == null ? void 0 : membership.member;
53
46
  if (!member) return null;
54
47
  return {
55
- role: String((_member_role = member.role) != null ? _member_role : ''),
56
48
  canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),
57
49
  member: member
58
50
  };
@@ -181,7 +173,7 @@ function createCrmSetupGate(deps) {
181
173
  var _deps_orgIdForHost, _deps_member;
182
174
  const orgIdForHost = (_deps_orgIdForHost = deps.orgIdForHost) != null ? _deps_orgIdForHost : (hostId)=>resolveOrgIdForHost(hostId);
183
175
  const memberOf = (_deps_member = deps.member) != null ? _deps_member : platformMember;
184
- /** Everything but the scope: the site is the org's, the plan, the member's role and permission. */ return async (context, scope, scopeRefusal)=>{
176
+ /** Everything but the scope: the site is the org's, the plan, the member's permission. */ return async (context, scope, scopeRefusal)=>{
185
177
  if (await orgIdForHost(context.hostId) !== context.orgId) return {
186
178
  status: 404,
187
179
  error: 'Unknown site'
@@ -193,16 +185,12 @@ function createCrmSetupGate(deps) {
193
185
  };
194
186
  }
195
187
  const member = await memberOf(context.uid, context.orgId);
196
- if (!member || !WRITER_ROLES.has(member.role) || member.member['orgSuspended'] === true) {
188
+ if (!member || member.member['orgSuspended'] === true || !member.canManageData) {
197
189
  return {
198
190
  status: 403,
199
- error: CRM_SETUP_ROLE_REFUSAL
191
+ error: CRM_SETUP_PERMISSION_REFUSAL
200
192
  };
201
193
  }
202
- if (!member.canManageData) return {
203
- status: 403,
204
- error: CRM_SETUP_PERMISSION_REFUSAL
205
- };
206
194
  if (!memberCanSee(member.member, scope)) return {
207
195
  status: 403,
208
196
  error: scopeRefusal
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-setup-writers.server.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CONTACT_FIELDS_MAX_PER_ORG } from '@aglyn/aglyn/app-utils/contact-custom-fields'\nimport {\n CRM_COLLECTIONS,\n type CrmPicklist,\n type CrmPicklistDefinition,\n type CrmPicklistId,\n type CrmPicklistObject,\n type CrmPicklistTarget,\n crmPicklistDefinition,\n crmReadTokens,\n crmScopeTokens,\n effectiveCrmPicklist,\n normalizeCrmPicklist,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { newResourceScopeFields, ORG_SCOPE_TOKEN } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n PluginDraftContext,\n PluginDraftRecord,\n PluginDraftRefusal,\n PluginDraftWrite,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport {\n checkCrmPicklistValuesSetup,\n CRM_CUSTOM_CHOICE_LIST,\n type CrmPicklistValuesOutcome,\n crmPicklistValuesName,\n planCrmCustomChoiceValues,\n planCrmPicklistValues,\n readCrmPicklistValuesSetup,\n} from '../model/crm-picklist-setup-content'\nimport {\n checkCrmFieldSetup,\n checkCrmPipelineSetup,\n type CrmFieldDefinitionDoc,\n crmPipelineSetupFacts,\n planCrmFieldSetup,\n planCrmPipelineSetup,\n readCrmFieldSetup,\n readCrmPipelineSetup,\n} from '../model/crm-setup-content'\nimport type { PipelineDoc } from '../model/deal-board-model'\nimport { picklistKeepsGroups } from '../model/picklist-values'\nimport { picklistGroupOf, regroupEverywhere } from './picklist-regroup'\nimport { crmSuiteRefusalMessage } from './suite-gate'\n\n/**\n * THE CRM'S SETUP WRITERS (AGL-3746): a deal pipeline and a custom field,\n * saved for another plugin — Aglyn AI's build — under the CRM's rules.\n *\n * Registered on the core's resource-drafts seam as `crm-pipeline` and\n * `crm-field`. Neither is a draft: a pipeline and a field have no draft\n * state, and the console saves both live, so these do too, and their AI\n * capabilities say so (`live`). What they write is exactly what the\n * console's Pipelines dialog and Fields section write\n * (`model/crm-setup-content.ts`), and they admit exactly whom the Firestore\n * rules admit for those writes, since the Admin SDK passes the rules by:\n *\n * - THE SITE is the org's, and THE PLAN carries the CRM (`crm`, Starter and\n * up — `orgCarriesCrmSuite`), refused in the suite gate's words;\n * - THE MEMBER is an owner, admin or editor (`canWriteOrgData`) whose org\n * access is not suspended, holding `data.manage`, the key the whole CRM\n * is gated on;\n * - THE SCOPE is one the member can create in (`canCreateScoped`): a\n * pipeline is stamped as the board's seed stamps it from this site\n * (`crmScopeTokens`), a field org-wide, which only an org-wide member\n * reaches.\n *\n * Idempotent: the job's attempt key is a new pipeline's or field's id, and\n * an existing pipeline, stage or field is matched by name (see the model),\n * so asking again changes nothing.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The refusals, in the console's and the routes' words. */\nexport const CRM_SETUP_ROLE_REFUSAL = 'Editing the CRM requires the editor role'\nexport const CRM_SETUP_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data'\nexport const CRM_SETUP_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const CRM_SETUP_FIELD_SCOPE_REFUSAL = 'Custom fields are organization-wide, and your access reaches only some sites'\nexport const CRM_SETUP_PICKLIST_SCOPE_REFUSAL = 'Picklists are organization-wide, and your access reaches only some sites'\n\n/** Roles allowed to write the CRM's setup — the rules' `canWriteOrgData()`. */\nconst WRITER_ROLES = new Set(['owner', 'admin', 'editor'])\n\n/** The most pipelines one site's read returns, as the board reads them. */\nconst PIPELINE_READ_LIMIT = 50\n\n/** Who the member is in the org, as the writers ask. */\nexport interface CrmSetupMember {\n role: string\n canManageData: boolean\n /** The membership itself, for its reach and whether it is suspended. */\n member: Readonly<Record<string, unknown>>\n}\n\n/** The reads and writes the writers make, over the Admin SDK unless a spec hands in its own. */\nexport interface CrmSetupStore {\n /** The pipelines readable under these scope tokens. */\n pipelines(orgId: string, readTokens: readonly string[]): Promise<PipelineDoc[]>\n pipeline(orgId: string, id: string): Promise<PipelineDoc | null>\n /** One batch: the new or changed pipeline, and the default flag off the others. */\n savePipeline(\n orgId: string,\n write: { id: string; create?: Record<string, unknown>; update?: Record<string, unknown>; defaultsOff: string[] },\n now: Date,\n ): Promise<void>\n /** Every definition the org holds, retired ones included, to the ceiling and one past it. */\n fields(orgId: string): Promise<CrmFieldDefinitionDoc[]>\n field(orgId: string, id: string): Promise<CrmFieldDefinitionDoc | null>\n createField(orgId: string, id: string, document: Record<string, unknown>): Promise<void>\n setFieldOptions(orgId: string, id: string, options: string[], now: Date): Promise<void>\n /** A picklist's stored document, or `null` for an org that never stored one (AGL-3756). */\n picklist(orgId: string, id: CrmPicklistId): Promise<Readonly<Record<string, unknown>> | null>\n /**\n * Read a picklist and write it back in one transaction, as the console's\n * route does, so a person editing the list at the same moment is not\n * overwritten. `change` answers the list to write, or `null` for none.\n */\n changePicklist<T>(\n orgId: string,\n id: CrmPicklistId,\n change: (stored: Readonly<Record<string, unknown>> | null) => { write: CrmPicklist | null; result: T },\n stamp: { hostId: string },\n ): Promise<T>\n /** A value's group onto every record of `object` holding `label` (a lead's `leadSourceDirection`). */\n regroup(orgId: string, object: CrmPicklistObject, target: CrmPicklistTarget, label: string, group: string | null): Promise<number>\n}\n\n/** The org subcollection each picklist target's records live in. */\nconst TARGET_COLLECTIONS: Record<CrmPicklistObject, string> = {\n contact: 'contacts',\n lead: 'leads',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n task: CRM_COLLECTIONS.tasks,\n}\n\nexport interface CrmSetupWriterDeps {\n store?: CrmSetupStore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<CrmSetupMember | null>\n}\n\nasync function platformMember(uid: string, orgId: string): Promise<CrmSetupMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n role: String(member.role ?? ''),\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\n/** The CRM's collections over the Admin SDK. */\nexport function adminCrmSetupStore(firestore: () => Firestore = () => firebaseAdmin.app().firestore() as unknown as Firestore): CrmSetupStore {\n const org = (orgId: string) => firestore().collection('orgs').doc(orgId)\n const pipelinesOf = (orgId: string) => org(orgId).collection(CRM_COLLECTIONS.pipelines)\n const fieldsOf = (orgId: string) => org(orgId).collection(CRM_COLLECTIONS.contactFields)\n const withId = <T>(snap: FirebaseFirestore.DocumentSnapshot): T => ({ ...(snap.data() as object), $id: snap.id }) as T\n return {\n pipelines: async (orgId, readTokens) => {\n const snap = await pipelinesOf(orgId)\n .where('visibleTo', 'array-contains-any', [...readTokens])\n .orderBy(FieldPath.documentId())\n .limit(PIPELINE_READ_LIMIT)\n .get()\n return snap.docs.map((one) => withId<PipelineDoc>(one))\n },\n pipeline: async (orgId, id) => {\n const snap = await pipelinesOf(orgId).doc(id).get()\n return snap.exists ? withId<PipelineDoc>(snap) : null\n },\n savePipeline: async (orgId, write, now) => {\n const batch = firestore().batch()\n const ref = pipelinesOf(orgId).doc(write.id)\n if (write.create) batch.create(ref, write.create)\n else if (write.update) batch.update(ref, { ...write.update, updatedAt: now })\n for (const id of write.defaultsOff) {\n batch.update(pipelinesOf(orgId).doc(id), { isDefault: false, updatedAt: now })\n }\n await batch.commit()\n },\n fields: async (orgId) => {\n const snap = await fieldsOf(orgId).limit(CONTACT_FIELDS_MAX_PER_ORG + 1).get()\n return snap.docs.map((one) => withId<CrmFieldDefinitionDoc>(one))\n },\n field: async (orgId, id) => {\n const snap = await fieldsOf(orgId).doc(id).get()\n return snap.exists ? withId<CrmFieldDefinitionDoc>(snap) : null\n },\n createField: async (orgId, id, document) => {\n await fieldsOf(orgId).doc(id).create(document)\n },\n setFieldOptions: async (orgId, id, options, now) => {\n await fieldsOf(orgId).doc(id).update({ options, updatedAt: now })\n },\n picklist: async (orgId, id) => {\n const snap = await org(orgId).collection(CRM_COLLECTIONS.picklists).doc(id).get()\n return snap.exists ? ((snap.data() ?? {}) as Record<string, unknown>) : null\n },\n changePicklist: async (orgId, id, change, stamp) => {\n const ref = org(orgId).collection(CRM_COLLECTIONS.picklists).doc(id)\n return firestore().runTransaction(async (transaction) => {\n const snap = await transaction.get(ref)\n const stored = snap.exists ? ((snap.data() ?? {}) as Record<string, unknown>) : null\n const { write, result } = change(stored)\n if (write) {\n // The stamp the console's first write gives an org-wide CRM document.\n const created = normalizeCrmPicklist(stored) === null\n transaction.set(\n ref,\n {\n values: write.values,\n defaultValueId: write.defaultValueId,\n updatedAt: FieldValue.serverTimestamp(),\n ...(created\n ? { hostId: stamp.hostId, createdAt: FieldValue.serverTimestamp(), ...newResourceScopeFields([ORG_SCOPE_TOKEN]) }\n : {}),\n },\n { merge: true },\n )\n }\n return result\n })\n },\n regroup: (orgId, object, target, label, group) =>\n regroupEverywhere(firestore(), org(orgId).collection(TARGET_COLLECTIONS[object]), target, label, group),\n }\n}\n\n/** The scope a pipeline made from this site is stamped with: the board seed's. */\nfunction pipelineScope(context: Pick<PluginDraftContext, 'org' | 'hostId'>): string[] {\n const org = (context.org ?? null) as Record<string, unknown> | null\n return crmScopeTokens(org, consentGroupForHost(org, context.hostId))\n}\n\n/** What a pipeline's board at this site reads: the org's rows and the site group's. */\nfunction pipelineReadTokens(context: Pick<PluginDraftContext, 'org' | 'hostId'>): string[] {\n const org = (context.org ?? null) as Record<string, unknown> | null\n return crmReadTokens(consentGroupForHost(org, context.hostId))\n}\n\nfunction pipelineRecord(pipeline: PipelineDoc): PluginDraftRecord {\n return { id: pipeline.$id, name: String(pipeline.name ?? ''), versionId: null, facts: crmPipelineSetupFacts(pipeline.stages ?? []) }\n}\n\nfunction fieldRecord(field: CrmFieldDefinitionDoc): PluginDraftRecord {\n return {\n id: field.$id,\n name: String(field.label ?? ''),\n versionId: null,\n facts: {\n object: field.object ?? 'contact',\n key: field.key,\n type: field.type,\n ...(field.options ? { options: field.options } : {}),\n ...(field.currency ? { currency: field.currency } : {}),\n },\n }\n}\n\nfunction createCrmSetupGate(deps: CrmSetupWriterDeps) {\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n /** Everything but the scope: the site is the org's, the plan, the member's role and permission. */\n return async (context: PluginDraftContext, scope: readonly string[], scopeRefusal: string): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n if (!checkEntitlement(context.org as never, 'crm')) {\n return { status: 403, error: crmSuiteRefusalMessage('Setting up the CRM') }\n }\n const member = await memberOf(context.uid, context.orgId)\n if (!member || !WRITER_ROLES.has(member.role) || member.member['orgSuspended'] === true) {\n return { status: 403, error: CRM_SETUP_ROLE_REFUSAL }\n }\n if (!member.canManageData) return { status: 403, error: CRM_SETUP_PERMISSION_REFUSAL }\n if (!memberCanSee(member.member as never, scope)) return { status: 403, error: scopeRefusal }\n return null\n }\n}\n\n/** The `crm-pipeline` writer: creates or brings a pipeline to the ask. */\nexport function createCrmPipelineSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n return {\n refusal: (context) => gate(context, pipelineScope(context), CRM_SETUP_SCOPE_REFUSAL),\n check: (content) => checkCrmPipelineSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n const pipeline = orgId ? await store.pipeline(orgId, id) : null\n return pipeline ? pipelineRecord(pipeline) : null\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmPipelineSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const visibleTo = pipelineScope(request)\n const refused = await gate(request, visibleTo, CRM_SETUP_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n // Asked again under the same id: the pipeline it already made.\n const made = await store.pipeline(request.orgId, request.id)\n if (made) return { ok: true, replayed: true, ...pipelineRecord(made) }\n const pipelines = await store.pipelines(request.orgId, pipelineReadTokens(request))\n const plan = planCrmPipelineSetup(read.value, pipelines, {\n visibleTo,\n hostId: request.hostId,\n uid: request.uid,\n nowMs: request.now.getTime(),\n })\n if (plan.kind === 'refuse') return { ok: false, status: 409, error: plan.error }\n if (plan.kind === 'create') {\n await store.savePipeline(request.orgId, { id: request.id, create: plan.document, defaultsOff: plan.defaultsOff }, request.now)\n return {\n ok: true,\n replayed: false,\n ...pipelineRecord({ ...(plan.document as unknown as PipelineDoc), $id: request.id }),\n }\n }\n const existing = pipelines.find((one) => one.$id === plan.id) as PipelineDoc\n const changed = Object.keys(plan.patch).length > 0 || plan.defaultsOff.length > 0\n if (changed) {\n await store.savePipeline(request.orgId, { id: plan.id, update: plan.patch, defaultsOff: plan.defaultsOff }, request.now)\n }\n return { ok: true, replayed: !changed, ...pipelineRecord({ ...existing, ...plan.patch }) }\n },\n }\n}\n\n/** The `crm-field` writer: creates a custom field, or finds the one asked for. */\nexport function createCrmFieldSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n const scope = [ORG_SCOPE_TOKEN]\n return {\n refusal: (context) => gate(context, scope, CRM_SETUP_FIELD_SCOPE_REFUSAL),\n check: (content) => checkCrmFieldSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n const field = orgId ? await store.field(orgId, id) : null\n return field ? fieldRecord(field) : null\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmFieldSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await gate(request, scope, CRM_SETUP_FIELD_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n const made = await store.field(request.orgId, request.id)\n if (made) return { ok: true, replayed: true, ...fieldRecord(made) }\n const definitions = await store.fields(request.orgId)\n const plan = planCrmFieldSetup(read.value, definitions, { hostId: request.hostId, now: request.now, visibleTo: scope })\n if (plan.kind === 'refuse') return { ok: false, status: plan.status, error: plan.error }\n if (plan.kind === 'create') {\n await store.createField(request.orgId, request.id, plan.document)\n return {\n ok: true,\n replayed: false,\n ...fieldRecord({ ...(plan.document as unknown as CrmFieldDefinitionDoc), $id: request.id }),\n }\n }\n const existing = definitions.find((one) => one.$id === plan.id) as CrmFieldDefinitionDoc\n if (!plan.options.length) return { ok: true, replayed: true, ...fieldRecord(existing) }\n const options = [...(existing.options ?? []), ...plan.options]\n await store.setFieldOptions(request.orgId, plan.id, options, request.now)\n return { ok: true, replayed: false, ...fieldRecord({ ...existing, options }) }\n },\n }\n}\n\nexport const crmPipelineSetupWriter = createCrmPipelineSetupWriter()\nexport const crmFieldSetupWriter = createCrmFieldSetupWriter()\n\n/*==========================================\n * PICKLIST VALUES (AGL-3756)\n *=========================================*/\n\n/** The record id a custom Choice field's values are reported under, beside a picklist's own id. */\nconst CUSTOM_RECORD_PREFIX = `${CRM_CUSTOM_CHOICE_LIST}:`\n\nfunction picklistRecord(definition: CrmPicklistDefinition, picklist: CrmPicklist, outcome?: CrmPicklistValuesOutcome): PluginDraftRecord {\n return {\n id: definition.id,\n name: crmPicklistValuesName(definition),\n versionId: null,\n facts: {\n list: definition.id,\n values: picklist.values.filter((value) => value.active).map((value) => value.label),\n ...(outcome ?? {}),\n },\n }\n}\n\nfunction choiceRecord(field: CrmFieldDefinitionDoc, outcome?: CrmPicklistValuesOutcome): PluginDraftRecord {\n return {\n id: `${CUSTOM_RECORD_PREFIX}${field.$id}`,\n name: String(field.label ?? ''),\n versionId: null,\n facts: { list: CRM_CUSTOM_CHOICE_LIST, object: field.object ?? 'contact', values: field.options ?? [], ...(outcome ?? {}) },\n }\n}\n\n/**\n * The `crm-picklist-values` writer: adds values to a standard CRM picklist\n * or a custom Choice field's choices, never removing, renaming, reordering\n * or reactivating one. Gated as the Fields page is — the `crm` feature, an\n * owner, admin or editor with `data.manage` — and org-wide, as every\n * picklist and field document is. A lead source added where records\n * already hold its label files them under its group (`leadSourceDirection`),\n * as the console's route does (AGL-3577).\n */\nexport function createCrmPicklistValuesSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n const scope = [ORG_SCOPE_TOKEN]\n return {\n refusal: (context) => gate(context, scope, CRM_SETUP_PICKLIST_SCOPE_REFUSAL),\n check: (content) => checkCrmPicklistValuesSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n if (id.startsWith(CUSTOM_RECORD_PREFIX)) {\n const field = await store.field(orgId, id.slice(CUSTOM_RECORD_PREFIX.length))\n return field ? choiceRecord(field) : null\n }\n const definition = crmPicklistDefinition(id)\n if (!definition) return null\n const listId = definition.id as CrmPicklistId\n return picklistRecord(definition, effectiveCrmPicklist(listId, await store.picklist(orgId, listId)))\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmPicklistValuesSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await gate(request, scope, CRM_SETUP_PICKLIST_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n const setup = read.value\n\n if (setup.target.kind === 'custom') {\n const definitions = await store.fields(request.orgId)\n const plan = planCrmCustomChoiceValues({ ...setup, target: setup.target }, definitions)\n if (plan.ok === false) return { ok: false, status: plan.status, error: plan.error }\n const field = definitions.find((one) => one.$id === plan.id) as CrmFieldDefinitionDoc\n const { added, existing, inactive } = plan\n if (added.length) await store.setFieldOptions(request.orgId, plan.id, plan.options, request.now)\n return {\n ok: true,\n replayed: added.length === 0,\n ...choiceRecord({ ...field, options: plan.options }, { added, existing, inactive }),\n }\n }\n\n const id = setup.target.id\n const definition = crmPicklistDefinition(id) as CrmPicklistDefinition\n const planned = await store.changePicklist(\n request.orgId,\n id,\n (stored) => {\n const plan = planCrmPicklistValues(definition, effectiveCrmPicklist(id, stored), setup)\n return { write: plan.ok && plan.added.length ? plan.picklist : null, result: plan }\n },\n { hostId: request.hostId },\n )\n if (planned.ok === false) return { ok: false, status: 409, error: planned.error }\n // Records that already hold an added label take its group (AGL-3577).\n if (planned.added.length && picklistKeepsGroups(definition)) {\n for (const target of definition.targets) {\n if (!target.groupField || target.facet || target.arrayKey) continue\n for (const label of planned.added) {\n await store.regroup(request.orgId, target.object, target, label, picklistGroupOf(planned.picklist, label))\n }\n }\n }\n const { added, existing, inactive } = planned\n return { ok: true, replayed: added.length === 0, ...picklistRecord(definition, planned.picklist, { added, existing, inactive }) }\n },\n }\n}\n\nexport const crmPicklistValuesSetupWriter = createCrmPicklistValuesSetupWriter()\n"],"names":["consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","CRM_COLLECTIONS","crmPicklistDefinition","crmReadTokens","crmScopeTokens","effectiveCrmPicklist","normalizeCrmPicklist","memberCanSee","checkEntitlement","newResourceScopeFields","ORG_SCOPE_TOKEN","firebaseAdmin","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","FieldPath","FieldValue","checkCrmPicklistValuesSetup","CRM_CUSTOM_CHOICE_LIST","crmPicklistValuesName","planCrmCustomChoiceValues","planCrmPicklistValues","readCrmPicklistValuesSetup","checkCrmFieldSetup","checkCrmPipelineSetup","crmPipelineSetupFacts","planCrmFieldSetup","planCrmPipelineSetup","readCrmFieldSetup","readCrmPipelineSetup","picklistKeepsGroups","picklistGroupOf","regroupEverywhere","crmSuiteRefusalMessage","CRM_SETUP_ROLE_REFUSAL","CRM_SETUP_PERMISSION_REFUSAL","CRM_SETUP_SCOPE_REFUSAL","CRM_SETUP_FIELD_SCOPE_REFUSAL","CRM_SETUP_PICKLIST_SCOPE_REFUSAL","WRITER_ROLES","Set","PIPELINE_READ_LIMIT","TARGET_COLLECTIONS","contact","lead","company","companies","deal","deals","task","tasks","platformMember","uid","orgId","member","membership","role","String","canManageData","adminCrmSetupStore","firestore","app","org","collection","doc","pipelinesOf","pipelines","fieldsOf","contactFields","withId","snap","data","$id","id","readTokens","where","orderBy","documentId","limit","get","docs","map","one","pipeline","exists","savePipeline","write","now","batch","ref","create","update","updatedAt","defaultsOff","isDefault","commit","fields","field","createField","document","setFieldOptions","options","picklist","picklists","changePicklist","change","stamp","runTransaction","transaction","stored","result","created","set","values","defaultValueId","serverTimestamp","hostId","createdAt","merge","regroup","object","target","label","group","pipelineScope","context","pipelineReadTokens","pipelineRecord","name","versionId","facts","stages","fieldRecord","key","type","currency","createCrmSetupGate","deps","orgIdForHost","memberOf","scope","scopeRefusal","status","error","has","createCrmPipelineSetupWriter","store","gate","refusal","check","content","read","request","ok","problems","visibleTo","refused","made","replayed","plan","value","nowMs","getTime","kind","existing","find","changed","Object","keys","patch","length","createCrmFieldSetupWriter","definitions","crmPipelineSetupWriter","crmFieldSetupWriter","CUSTOM_RECORD_PREFIX","picklistRecord","definition","outcome","list","filter","active","choiceRecord","createCrmPicklistValuesSetupWriter","startsWith","slice","listId","setup","added","inactive","planned","targets","groupField","facet","arrayKey","crmPicklistValuesSetupWriter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,0BAA0B,QAAQ,+CAA8C;AACzF,SACEC,eAAe,EAMfC,qBAAqB,EACrBC,aAAa,EACbC,cAAc,EACdC,oBAAoB,EACpBC,oBAAoB,QACf,6BAA4B;AACnC,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,sCAAqC;AAQ7F,SAASC,aAAa,QAAQ,2BAA0B;AACxD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Q,EAAEyB,QAAQ,EAAE,GAAGC;YACtC,OAAO;gBAAErC,IAAI;gBAAMK,UAAU8B,MAAMlB,MAAM,KAAK;eAAMM,eAAeC,YAAYa,QAAQxF,QAAQ,EAAE;gBAAEsF;gBAAOxB;gBAAUyB;YAAS;QAC/H;IACF;AACF;AAEA,OAAO,MAAMM,+BAA+BZ,qCAAoC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-setup-writers.server.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CONTACT_FIELDS_MAX_PER_ORG } from '@aglyn/aglyn/app-utils/contact-custom-fields'\nimport {\n CRM_COLLECTIONS,\n type CrmPicklist,\n type CrmPicklistDefinition,\n type CrmPicklistId,\n type CrmPicklistObject,\n type CrmPicklistTarget,\n crmPicklistDefinition,\n crmReadTokens,\n crmScopeTokens,\n effectiveCrmPicklist,\n normalizeCrmPicklist,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { newResourceScopeFields, ORG_SCOPE_TOKEN } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n PluginDraftContext,\n PluginDraftRecord,\n PluginDraftRefusal,\n PluginDraftWrite,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport {\n checkCrmPicklistValuesSetup,\n CRM_CUSTOM_CHOICE_LIST,\n type CrmPicklistValuesOutcome,\n crmPicklistValuesName,\n planCrmCustomChoiceValues,\n planCrmPicklistValues,\n readCrmPicklistValuesSetup,\n} from '../model/crm-picklist-setup-content'\nimport {\n checkCrmFieldSetup,\n checkCrmPipelineSetup,\n type CrmFieldDefinitionDoc,\n crmPipelineSetupFacts,\n planCrmFieldSetup,\n planCrmPipelineSetup,\n readCrmFieldSetup,\n readCrmPipelineSetup,\n} from '../model/crm-setup-content'\nimport type { PipelineDoc } from '../model/deal-board-model'\nimport { picklistKeepsGroups } from '../model/picklist-values'\nimport { picklistGroupOf, regroupEverywhere } from './picklist-regroup'\nimport { crmSuiteRefusalMessage } from './suite-gate'\n\n/**\n * THE CRM'S SETUP WRITERS (AGL-3746): a deal pipeline and a custom field,\n * saved for another plugin — Aglyn AI's build — under the CRM's rules.\n *\n * Registered on the core's resource-drafts seam as `crm-pipeline` and\n * `crm-field`. Neither is a draft: a pipeline and a field have no draft\n * state, and the console saves both live, so these do too, and their AI\n * capabilities say so (`live`). What they write is exactly what the\n * console's Pipelines dialog and Fields section write\n * (`model/crm-setup-content.ts`), and they admit exactly whom the Firestore\n * rules admit for those writes, since the Admin SDK passes the rules by:\n *\n * - THE SITE is the org's, and THE PLAN carries the CRM (`crm`, Starter and\n * up — `orgCarriesCrmSuite`), refused in the suite gate's words;\n * - THE MEMBER is an owner, admin or editor (`canWriteOrgData`) whose org\n * access is not suspended, holding `data.manage`, the key the whole CRM\n * is gated on;\n * - THE SCOPE is one the member can create in (`canCreateScoped`): a\n * pipeline is stamped as the board's seed stamps it from this site\n * (`crmScopeTokens`), a field org-wide, which only an org-wide member\n * reaches.\n *\n * Idempotent: the job's attempt key is a new pipeline's or field's id, and\n * an existing pipeline, stage or field is matched by name (see the model),\n * so asking again changes nothing.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The refusals, in the console's and the routes' words. */\nexport const CRM_SETUP_PERMISSION_REFUSAL = 'Your role does not include \"Manage data\" — ask an organization admin'\nexport const CRM_SETUP_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const CRM_SETUP_FIELD_SCOPE_REFUSAL = 'Custom fields are organization-wide, and your access reaches only some sites'\nexport const CRM_SETUP_PICKLIST_SCOPE_REFUSAL = 'Picklists are organization-wide, and your access reaches only some sites'\n\n/** The most pipelines one site's read returns, as the board reads them. */\nconst PIPELINE_READ_LIMIT = 50\n\n/** Who the member is in the org, as the writers ask. */\nexport interface CrmSetupMember {\n /** \"Manage data\" (`data.manage`, AGL-4047), the rules' `canWriteOrgData()`. */\n canManageData: boolean\n /** The membership itself, for its reach and whether it is suspended. */\n member: Readonly<Record<string, unknown>>\n}\n\n/** The reads and writes the writers make, over the Admin SDK unless a spec hands in its own. */\nexport interface CrmSetupStore {\n /** The pipelines readable under these scope tokens. */\n pipelines(orgId: string, readTokens: readonly string[]): Promise<PipelineDoc[]>\n pipeline(orgId: string, id: string): Promise<PipelineDoc | null>\n /** One batch: the new or changed pipeline, and the default flag off the others. */\n savePipeline(\n orgId: string,\n write: { id: string; create?: Record<string, unknown>; update?: Record<string, unknown>; defaultsOff: string[] },\n now: Date,\n ): Promise<void>\n /** Every definition the org holds, retired ones included, to the ceiling and one past it. */\n fields(orgId: string): Promise<CrmFieldDefinitionDoc[]>\n field(orgId: string, id: string): Promise<CrmFieldDefinitionDoc | null>\n createField(orgId: string, id: string, document: Record<string, unknown>): Promise<void>\n setFieldOptions(orgId: string, id: string, options: string[], now: Date): Promise<void>\n /** A picklist's stored document, or `null` for an org that never stored one (AGL-3756). */\n picklist(orgId: string, id: CrmPicklistId): Promise<Readonly<Record<string, unknown>> | null>\n /**\n * Read a picklist and write it back in one transaction, as the console's\n * route does, so a person editing the list at the same moment is not\n * overwritten. `change` answers the list to write, or `null` for none.\n */\n changePicklist<T>(\n orgId: string,\n id: CrmPicklistId,\n change: (stored: Readonly<Record<string, unknown>> | null) => { write: CrmPicklist | null; result: T },\n stamp: { hostId: string },\n ): Promise<T>\n /** A value's group onto every record of `object` holding `label` (a lead's `leadSourceDirection`). */\n regroup(orgId: string, object: CrmPicklistObject, target: CrmPicklistTarget, label: string, group: string | null): Promise<number>\n}\n\n/** The org subcollection each picklist target's records live in. */\nconst TARGET_COLLECTIONS: Record<CrmPicklistObject, string> = {\n contact: 'contacts',\n lead: 'leads',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n task: CRM_COLLECTIONS.tasks,\n}\n\nexport interface CrmSetupWriterDeps {\n store?: CrmSetupStore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<CrmSetupMember | null>\n}\n\nasync function platformMember(uid: string, orgId: string): Promise<CrmSetupMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\n/** The CRM's collections over the Admin SDK. */\nexport function adminCrmSetupStore(firestore: () => Firestore = () => firebaseAdmin.app().firestore() as unknown as Firestore): CrmSetupStore {\n const org = (orgId: string) => firestore().collection('orgs').doc(orgId)\n const pipelinesOf = (orgId: string) => org(orgId).collection(CRM_COLLECTIONS.pipelines)\n const fieldsOf = (orgId: string) => org(orgId).collection(CRM_COLLECTIONS.contactFields)\n const withId = <T>(snap: FirebaseFirestore.DocumentSnapshot): T => ({ ...(snap.data() as object), $id: snap.id }) as T\n return {\n pipelines: async (orgId, readTokens) => {\n const snap = await pipelinesOf(orgId)\n .where('visibleTo', 'array-contains-any', [...readTokens])\n .orderBy(FieldPath.documentId())\n .limit(PIPELINE_READ_LIMIT)\n .get()\n return snap.docs.map((one) => withId<PipelineDoc>(one))\n },\n pipeline: async (orgId, id) => {\n const snap = await pipelinesOf(orgId).doc(id).get()\n return snap.exists ? withId<PipelineDoc>(snap) : null\n },\n savePipeline: async (orgId, write, now) => {\n const batch = firestore().batch()\n const ref = pipelinesOf(orgId).doc(write.id)\n if (write.create) batch.create(ref, write.create)\n else if (write.update) batch.update(ref, { ...write.update, updatedAt: now })\n for (const id of write.defaultsOff) {\n batch.update(pipelinesOf(orgId).doc(id), { isDefault: false, updatedAt: now })\n }\n await batch.commit()\n },\n fields: async (orgId) => {\n const snap = await fieldsOf(orgId).limit(CONTACT_FIELDS_MAX_PER_ORG + 1).get()\n return snap.docs.map((one) => withId<CrmFieldDefinitionDoc>(one))\n },\n field: async (orgId, id) => {\n const snap = await fieldsOf(orgId).doc(id).get()\n return snap.exists ? withId<CrmFieldDefinitionDoc>(snap) : null\n },\n createField: async (orgId, id, document) => {\n await fieldsOf(orgId).doc(id).create(document)\n },\n setFieldOptions: async (orgId, id, options, now) => {\n await fieldsOf(orgId).doc(id).update({ options, updatedAt: now })\n },\n picklist: async (orgId, id) => {\n const snap = await org(orgId).collection(CRM_COLLECTIONS.picklists).doc(id).get()\n return snap.exists ? ((snap.data() ?? {}) as Record<string, unknown>) : null\n },\n changePicklist: async (orgId, id, change, stamp) => {\n const ref = org(orgId).collection(CRM_COLLECTIONS.picklists).doc(id)\n return firestore().runTransaction(async (transaction) => {\n const snap = await transaction.get(ref)\n const stored = snap.exists ? ((snap.data() ?? {}) as Record<string, unknown>) : null\n const { write, result } = change(stored)\n if (write) {\n // The stamp the console's first write gives an org-wide CRM document.\n const created = normalizeCrmPicklist(stored) === null\n transaction.set(\n ref,\n {\n values: write.values,\n defaultValueId: write.defaultValueId,\n updatedAt: FieldValue.serverTimestamp(),\n ...(created\n ? { hostId: stamp.hostId, createdAt: FieldValue.serverTimestamp(), ...newResourceScopeFields([ORG_SCOPE_TOKEN]) }\n : {}),\n },\n { merge: true },\n )\n }\n return result\n })\n },\n regroup: (orgId, object, target, label, group) =>\n regroupEverywhere(firestore(), org(orgId).collection(TARGET_COLLECTIONS[object]), target, label, group),\n }\n}\n\n/** The scope a pipeline made from this site is stamped with: the board seed's. */\nfunction pipelineScope(context: Pick<PluginDraftContext, 'org' | 'hostId'>): string[] {\n const org = (context.org ?? null) as Record<string, unknown> | null\n return crmScopeTokens(org, consentGroupForHost(org, context.hostId))\n}\n\n/** What a pipeline's board at this site reads: the org's rows and the site group's. */\nfunction pipelineReadTokens(context: Pick<PluginDraftContext, 'org' | 'hostId'>): string[] {\n const org = (context.org ?? null) as Record<string, unknown> | null\n return crmReadTokens(consentGroupForHost(org, context.hostId))\n}\n\nfunction pipelineRecord(pipeline: PipelineDoc): PluginDraftRecord {\n return { id: pipeline.$id, name: String(pipeline.name ?? ''), versionId: null, facts: crmPipelineSetupFacts(pipeline.stages ?? []) }\n}\n\nfunction fieldRecord(field: CrmFieldDefinitionDoc): PluginDraftRecord {\n return {\n id: field.$id,\n name: String(field.label ?? ''),\n versionId: null,\n facts: {\n object: field.object ?? 'contact',\n key: field.key,\n type: field.type,\n ...(field.options ? { options: field.options } : {}),\n ...(field.currency ? { currency: field.currency } : {}),\n },\n }\n}\n\nfunction createCrmSetupGate(deps: CrmSetupWriterDeps) {\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n /** Everything but the scope: the site is the org's, the plan, the member's permission. */\n return async (context: PluginDraftContext, scope: readonly string[], scopeRefusal: string): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n if (!checkEntitlement(context.org as never, 'crm')) {\n return { status: 403, error: crmSuiteRefusalMessage('Setting up the CRM') }\n }\n const member = await memberOf(context.uid, context.orgId)\n if (!member || member.member['orgSuspended'] === true || !member.canManageData) {\n return { status: 403, error: CRM_SETUP_PERMISSION_REFUSAL }\n }\n if (!memberCanSee(member.member as never, scope)) return { status: 403, error: scopeRefusal }\n return null\n }\n}\n\n/** The `crm-pipeline` writer: creates or brings a pipeline to the ask. */\nexport function createCrmPipelineSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n return {\n refusal: (context) => gate(context, pipelineScope(context), CRM_SETUP_SCOPE_REFUSAL),\n check: (content) => checkCrmPipelineSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n const pipeline = orgId ? await store.pipeline(orgId, id) : null\n return pipeline ? pipelineRecord(pipeline) : null\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmPipelineSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const visibleTo = pipelineScope(request)\n const refused = await gate(request, visibleTo, CRM_SETUP_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n // Asked again under the same id: the pipeline it already made.\n const made = await store.pipeline(request.orgId, request.id)\n if (made) return { ok: true, replayed: true, ...pipelineRecord(made) }\n const pipelines = await store.pipelines(request.orgId, pipelineReadTokens(request))\n const plan = planCrmPipelineSetup(read.value, pipelines, {\n visibleTo,\n hostId: request.hostId,\n uid: request.uid,\n nowMs: request.now.getTime(),\n })\n if (plan.kind === 'refuse') return { ok: false, status: 409, error: plan.error }\n if (plan.kind === 'create') {\n await store.savePipeline(request.orgId, { id: request.id, create: plan.document, defaultsOff: plan.defaultsOff }, request.now)\n return {\n ok: true,\n replayed: false,\n ...pipelineRecord({ ...(plan.document as unknown as PipelineDoc), $id: request.id }),\n }\n }\n const existing = pipelines.find((one) => one.$id === plan.id) as PipelineDoc\n const changed = Object.keys(plan.patch).length > 0 || plan.defaultsOff.length > 0\n if (changed) {\n await store.savePipeline(request.orgId, { id: plan.id, update: plan.patch, defaultsOff: plan.defaultsOff }, request.now)\n }\n return { ok: true, replayed: !changed, ...pipelineRecord({ ...existing, ...plan.patch }) }\n },\n }\n}\n\n/** The `crm-field` writer: creates a custom field, or finds the one asked for. */\nexport function createCrmFieldSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n const scope = [ORG_SCOPE_TOKEN]\n return {\n refusal: (context) => gate(context, scope, CRM_SETUP_FIELD_SCOPE_REFUSAL),\n check: (content) => checkCrmFieldSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n const field = orgId ? await store.field(orgId, id) : null\n return field ? fieldRecord(field) : null\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmFieldSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await gate(request, scope, CRM_SETUP_FIELD_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n const made = await store.field(request.orgId, request.id)\n if (made) return { ok: true, replayed: true, ...fieldRecord(made) }\n const definitions = await store.fields(request.orgId)\n const plan = planCrmFieldSetup(read.value, definitions, { hostId: request.hostId, now: request.now, visibleTo: scope })\n if (plan.kind === 'refuse') return { ok: false, status: plan.status, error: plan.error }\n if (plan.kind === 'create') {\n await store.createField(request.orgId, request.id, plan.document)\n return {\n ok: true,\n replayed: false,\n ...fieldRecord({ ...(plan.document as unknown as CrmFieldDefinitionDoc), $id: request.id }),\n }\n }\n const existing = definitions.find((one) => one.$id === plan.id) as CrmFieldDefinitionDoc\n if (!plan.options.length) return { ok: true, replayed: true, ...fieldRecord(existing) }\n const options = [...(existing.options ?? []), ...plan.options]\n await store.setFieldOptions(request.orgId, plan.id, options, request.now)\n return { ok: true, replayed: false, ...fieldRecord({ ...existing, options }) }\n },\n }\n}\n\nexport const crmPipelineSetupWriter = createCrmPipelineSetupWriter()\nexport const crmFieldSetupWriter = createCrmFieldSetupWriter()\n\n/*==========================================\n * PICKLIST VALUES (AGL-3756)\n *=========================================*/\n\n/** The record id a custom Choice field's values are reported under, beside a picklist's own id. */\nconst CUSTOM_RECORD_PREFIX = `${CRM_CUSTOM_CHOICE_LIST}:`\n\nfunction picklistRecord(definition: CrmPicklistDefinition, picklist: CrmPicklist, outcome?: CrmPicklistValuesOutcome): PluginDraftRecord {\n return {\n id: definition.id,\n name: crmPicklistValuesName(definition),\n versionId: null,\n facts: {\n list: definition.id,\n values: picklist.values.filter((value) => value.active).map((value) => value.label),\n ...(outcome ?? {}),\n },\n }\n}\n\nfunction choiceRecord(field: CrmFieldDefinitionDoc, outcome?: CrmPicklistValuesOutcome): PluginDraftRecord {\n return {\n id: `${CUSTOM_RECORD_PREFIX}${field.$id}`,\n name: String(field.label ?? ''),\n versionId: null,\n facts: { list: CRM_CUSTOM_CHOICE_LIST, object: field.object ?? 'contact', values: field.options ?? [], ...(outcome ?? {}) },\n }\n}\n\n/**\n * The `crm-picklist-values` writer: adds values to a standard CRM picklist\n * or a custom Choice field's choices, never removing, renaming, reordering\n * or reactivating one. Gated as the Fields page is — the `crm` feature, an\n * owner, admin or editor with `data.manage` — and org-wide, as every\n * picklist and field document is. A lead source added where records\n * already hold its label files them under its group (`leadSourceDirection`),\n * as the console's route does (AGL-3577).\n */\nexport function createCrmPicklistValuesSetupWriter(deps: CrmSetupWriterDeps = {}): PluginResourceDraftWriter {\n const store = deps.store ?? adminCrmSetupStore()\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const gate = createCrmSetupGate(deps)\n const scope = [ORG_SCOPE_TOKEN]\n return {\n refusal: (context) => gate(context, scope, CRM_SETUP_PICKLIST_SCOPE_REFUSAL),\n check: (content) => checkCrmPicklistValuesSetup(content),\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n if (id.startsWith(CUSTOM_RECORD_PREFIX)) {\n const field = await store.field(orgId, id.slice(CUSTOM_RECORD_PREFIX.length))\n return field ? choiceRecord(field) : null\n }\n const definition = crmPicklistDefinition(id)\n if (!definition) return null\n const listId = definition.id as CrmPicklistId\n return picklistRecord(definition, effectiveCrmPicklist(listId, await store.picklist(orgId, listId)))\n },\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCrmPicklistValuesSetup(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await gate(request, scope, CRM_SETUP_PICKLIST_SCOPE_REFUSAL)\n if (refused) return { ok: false, ...refused }\n const setup = read.value\n\n if (setup.target.kind === 'custom') {\n const definitions = await store.fields(request.orgId)\n const plan = planCrmCustomChoiceValues({ ...setup, target: setup.target }, definitions)\n if (plan.ok === false) return { ok: false, status: plan.status, error: plan.error }\n const field = definitions.find((one) => one.$id === plan.id) as CrmFieldDefinitionDoc\n const { added, existing, inactive } = plan\n if (added.length) await store.setFieldOptions(request.orgId, plan.id, plan.options, request.now)\n return {\n ok: true,\n replayed: added.length === 0,\n ...choiceRecord({ ...field, options: plan.options }, { added, existing, inactive }),\n }\n }\n\n const id = setup.target.id\n const definition = crmPicklistDefinition(id) as CrmPicklistDefinition\n const planned = await store.changePicklist(\n request.orgId,\n id,\n (stored) => {\n const plan = planCrmPicklistValues(definition, effectiveCrmPicklist(id, stored), setup)\n return { write: plan.ok && plan.added.length ? plan.picklist : null, result: plan }\n },\n { hostId: request.hostId },\n )\n if (planned.ok === false) return { ok: false, status: 409, error: planned.error }\n // Records that already hold an added label take its group (AGL-3577).\n if (planned.added.length && picklistKeepsGroups(definition)) {\n for (const target of definition.targets) {\n if (!target.groupField || target.facet || target.arrayKey) continue\n for (const label of planned.added) {\n await store.regroup(request.orgId, target.object, target, label, picklistGroupOf(planned.picklist, label))\n }\n }\n }\n const { added, existing, inactive } = planned\n return { ok: true, replayed: added.length === 0, ...picklistRecord(definition, planned.picklist, { added, existing, inactive }) }\n },\n }\n}\n\nexport const crmPicklistValuesSetupWriter = createCrmPicklistValuesSetupWriter()\n"],"names":["consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","CRM_COLLECTIONS","crmPicklistDefinition","crmReadTokens","crmScopeTokens","effectiveCrmPicklist","normalizeCrmPicklist","memberCanSee","checkEntitlement","newResourceScopeFields","ORG_SCOPE_TOKEN","firebaseAdmin","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","FieldPath","FieldValue","checkCrmPicklistValuesSetup","CRM_CUSTOM_CHOICE_LIST","crmPicklistValuesName","planCrmCustomChoiceValues","planCrmPicklistValues","readCrmPicklistValuesSetup","checkCrmFieldSetup","checkCrmPipelineSetup","crmPipelineSetupFacts","planCrmFieldSetup","planCrmPipelineSetup","readCrmFieldSetup","readCrmPipelineSetup","picklistKeepsGroups","picklistGroupOf","regroupEverywhere","crmSuiteRefusalMessage","CRM_SETUP_PERMISSION_REFUSAL","CRM_SETUP_SCOPE_REFUSAL","CRM_SETUP_FIELD_SCOPE_REFUSAL","CRM_SETUP_PICKLIST_SCOPE_REFUSAL","PIPELINE_READ_LIMIT","TARGET_COLLECTIONS","contact","lead","company","companies","deal","deals","task","tasks","platformMember","uid","orgId","membership","member","canManageData","adminCrmSetupStore","firestore","app","org","collection","doc","pipelinesOf","pipelines","fieldsOf","contactFields","withId","snap","data","$id","id","readTokens","where","orderBy","documentId","limit","get","docs","map","one","pipeline","exists","savePipeline","write","now","batch","ref","create","update","updatedAt","defaultsOff","isDefault","commit","fields","field","createField","document","setFieldOptions","options","picklist","picklists","changePicklist","change","stamp","runTransaction","transaction","stored","result","created","set","values","defaultValueId","serverTimestamp","hostId","createdAt","merge","regroup","object","target","label","group","pipelineScope","context","pipelineReadTokens","pipelineRecord","name","String","versionId","facts","stages","fieldRecord","key","type","currency","createCrmSetupGate","deps","orgIdForHost","memberOf","scope","scopeRefusal","status","error","createCrmPipelineSetupWriter","store","gate","refusal","check","content","read","request","ok","problems","visibleTo","refused","made","replayed","plan","value","nowMs","getTime","kind","existing","find","changed","Object","keys","patch","length","createCrmFieldSetupWriter","definitions","crmPipelineSetupWriter","crmFieldSetupWriter","CUSTOM_RECORD_PREFIX","picklistRecord","definition","outcome","list","filter","active","choiceRecord","createCrmPicklistValuesSetupWriter","startsWith","slice","listId","setup","added","inactive","planned","targets","groupField","facet","arrayKey","crmPicklistValuesSetupWriter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,0BAA0B,QAAQ,+CAA8C;AACzF,SACEC,eAAe,EAMfC,qBAAqB,EACrBC,aAAa,EACbC,cAAc,EACdC,oBAAoB,EACpBC,oBAAoB,QACf,6BAA4B;AACnC,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,sBAAsB,EAAEC,eAAe,QAAQ,sCAAqC;AAQ7F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SACEC,2BAA2B,EAC3BC,sBAAsB,EAEtBC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,0BAA0B,QACrB,yCAAqC;AAC5C,SACEC,kBAAkB,EAClBC,qBAAqB,EAErBC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAoB,EACpBC,iBAAiB,EACjBC,oBAAoB,QACf,gCAA4B;AAEnC,SAASC,mBAAmB,QAAQ,8BAA0B;AAC9D,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,wBAAoB;AACvE,SAASC,sBAAsB,QAAQ,kBAAc;AA+BrD,0DAA0D,GAC1D,OAAO,MAAMC,+BAA+B,uEAAsE;AAClH,OAAO,MAAMC,0BAA0B,4DAA2D;AAClG,OAAO,MAAMC,gCAAgC,+EAA8E;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UwD,WAAWc,OAAO,CAAE;oBACvC,IAAI,CAACtE,OAAOuE,UAAU,IAAIvE,OAAOwE,KAAK,IAAIxE,OAAOyE,QAAQ,EAAE;oBAC3D,KAAK,MAAMxE,SAASoE,QAAQF,KAAK,CAAE;wBACjC,MAAM1C,MAAM3B,OAAO,CAACiC,QAAQjG,KAAK,EAAEkE,OAAOD,MAAM,EAAEC,QAAQC,OAAOtF,gBAAgB0J,QAAQxF,QAAQ,EAAEoB;oBACrG;gBACF;YACF;YACA,MAAM,EAAEkE,KAAK,EAAExB,QAAQ,EAAEyB,QAAQ,EAAE,GAAGC;YACtC,OAAO;gBAAErC,IAAI;gBAAMK,UAAU8B,MAAMlB,MAAM,KAAK;eAAMM,eAAeC,YAAYa,QAAQxF,QAAQ,EAAE;gBAAEsF;gBAAOxB;gBAAUyB;YAAS;QAC/H;IACF;AACF;AAEA,OAAO,MAAMM,+BAA+BZ,qCAAoC"}
@@ -105,10 +105,11 @@ export declare function advanceSharingRuleRun(firestore: Firestore, orgId: strin
105
105
  /**
106
106
  * `POST /api/crm/sharing` — `{ action, hostId | orgId, … }`.
107
107
  *
108
- * Every action but `evaluate` is an org manager's: an OWNER or ADMIN of the
109
- * whole workspace (`authorizeOrgCaller(…, 'manage-org')`), under a site's
110
- * hub or the org's. `evaluate` is what a client-direct write owes the rules
111
- * and is open to whoever may write the CRM. The plan gate is the CRM's own
108
+ * Every action but `evaluate` asks "Change CRM settings" over the whole
109
+ * workspace (`authorizeOrgCaller(…, 'crm.settings')`, AGL-4047; owners and
110
+ * admins by default), under a site's hub or the org's. `evaluate` is what a
111
+ * client-direct write owes the rules and is open to whoever may write the
112
+ * CRM. The plan gate is the CRM's own
112
113
  * (`crmSuiteRefusal`): sharing is only meaningful across several sites, and
113
114
  * the number of sites a workspace may have is already the plan's.
114
115
  */
@@ -41,6 +41,7 @@ import { FieldPath, FieldValue } from "firebase-admin/firestore";
41
41
  import { BUNDLE_ID } from "../constants/bundle-common.js";
42
42
  import { activeSharingRules, CRM_SHARING_CRITERIA_FOR, CRM_SHARING_CRITERIA_KEYS, CRM_SHARING_FIELD, CRM_SHARING_IDS_MAX, CRM_SHARING_OBJECT_LABELS, CRM_SHARING_RULE_IDS_PATH, CRM_SHARING_RULES_MAX, CRM_WRITE_SCOPE_FIELD, describeShareTargets, evaluateRecordGrants, isCrmShareAccess, isCrmSharingObject, planRecordSharing, readCrmSharingRule, readCrmSharingRules, recordHeldScope, sharingPlanChanges, shareTargetsFrom, sharingRulesAskLeadSourceDirection, withManualShares, withoutManualShares } from "../model/crm-sharing.js";
43
43
  import { stampCrmActivityCompany } from "../model/crm-activity-link.js";
44
+ import { crmSettingsPermissionRefusal } from "../model/crm-permissions.js";
44
45
  import { readLeadSourcePicklist } from "./lead-source-picklist.js";
45
46
  import { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from "./org-caller.js";
46
47
  import { crmSuiteRefusal } from "./suite-gate.js";
@@ -494,7 +495,7 @@ const ORG_TARGET = {
494
495
  /*==========================================
495
496
  * THE ROUTE.
496
497
  *=========================================*/ /** How long one request works on a rule before it answers and the page asks again. */ const RUN_BUDGET_MS = 20000;
497
- const MANAGERS_ONLY = 'Sharing records across sites is for the workspace’s owners and admins.';
498
+ /** Names the permission, never a role (AGL-4047). */ const MANAGERS_ONLY = crmSettingsPermissionRefusal();
498
499
  function readIds(raw) {
499
500
  if (!Array.isArray(raw)) return null;
500
501
  const ids = [
@@ -505,10 +506,11 @@ function readIds(raw) {
505
506
  /**
506
507
  * `POST /api/crm/sharing` — `{ action, hostId | orgId, … }`.
507
508
  *
508
- * Every action but `evaluate` is an org manager's: an OWNER or ADMIN of the
509
- * whole workspace (`authorizeOrgCaller(…, 'manage-org')`), under a site's
510
- * hub or the org's. `evaluate` is what a client-direct write owes the rules
511
- * and is open to whoever may write the CRM. The plan gate is the CRM's own
509
+ * Every action but `evaluate` asks "Change CRM settings" over the whole
510
+ * workspace (`authorizeOrgCaller(…, 'crm.settings')`, AGL-4047; owners and
511
+ * admins by default), under a site's hub or the org's. `evaluate` is what a
512
+ * client-direct write owes the rules and is open to whoever may write the
513
+ * CRM. The plan gate is the CRM's own
512
514
  * (`crmSuiteRefusal`): sharing is only meaningful across several sites, and
513
515
  * the number of sites a workspace may have is already the plan's.
514
516
  */ export const crmSharingHandler = async (req, res)=>{
@@ -564,7 +566,7 @@ function readIds(raw) {
564
566
  return;
565
567
  }
566
568
  const caller = await authorizeOrgCaller(req, orgId, {
567
- needs: 'manage-org',
569
+ needs: 'crm.settings',
568
570
  refusal: MANAGERS_ONLY
569
571
  });
570
572
  if (caller.ok === false) {