@aglyn/plugins-crm 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/activity-link-fields.d.ts +34 -0
  3. package/src/lib/components/activity-link-fields.js +141 -0
  4. package/src/lib/components/activity-link-fields.js.map +1 -0
  5. package/src/lib/components/activity-list.d.ts +8 -0
  6. package/src/lib/components/activity-list.js +4 -2
  7. package/src/lib/components/activity-list.js.map +1 -1
  8. package/src/lib/components/activity-queries.d.ts +7 -2
  9. package/src/lib/components/activity-queries.js +7 -3
  10. package/src/lib/components/activity-queries.js.map +1 -1
  11. package/src/lib/components/company-contact-roles-card.d.ts +42 -0
  12. package/src/lib/components/company-contact-roles-card.js +137 -0
  13. package/src/lib/components/company-contact-roles-card.js.map +1 -0
  14. package/src/lib/components/company-detail-page.js +12 -1
  15. package/src/lib/components/company-detail-page.js.map +1 -1
  16. package/src/lib/components/company-edit-drawer.js +9 -6
  17. package/src/lib/components/company-edit-drawer.js.map +1 -1
  18. package/src/lib/components/company-picker.js +4 -2
  19. package/src/lib/components/company-picker.js.map +1 -1
  20. package/src/lib/components/contact-associations-card.js +15 -1
  21. package/src/lib/components/contact-associations-card.js.map +1 -1
  22. package/src/lib/components/contact-detail-page.js +13 -14
  23. package/src/lib/components/contact-detail-page.js.map +1 -1
  24. package/src/lib/components/contact-known-by-card.d.ts +2 -1
  25. package/src/lib/components/contact-known-by-card.js +16 -3
  26. package/src/lib/components/contact-known-by-card.js.map +1 -1
  27. package/src/lib/components/contact-list-columns.js +5 -4
  28. package/src/lib/components/contact-list-columns.js.map +1 -1
  29. package/src/lib/components/contact-properties-card.js +41 -20
  30. package/src/lib/components/contact-properties-card.js.map +1 -1
  31. package/src/lib/components/contact-roles-editor.d.ts +54 -0
  32. package/src/lib/components/contact-roles-editor.js +270 -0
  33. package/src/lib/components/contact-roles-editor.js.map +1 -0
  34. package/src/lib/components/contacts-section.js +6 -4
  35. package/src/lib/components/contacts-section.js.map +1 -1
  36. package/src/lib/components/crm-console-sections.js +1 -1
  37. package/src/lib/components/crm-console-sections.js.map +1 -1
  38. package/src/lib/components/crm-record-picker.d.ts +19 -0
  39. package/src/lib/components/crm-record-picker.js +40 -11
  40. package/src/lib/components/crm-record-picker.js.map +1 -1
  41. package/src/lib/components/crm-related-to-picker.d.ts +33 -0
  42. package/src/lib/components/crm-related-to-picker.js +135 -0
  43. package/src/lib/components/crm-related-to-picker.js.map +1 -0
  44. package/src/lib/components/crm-site-picker.d.ts +13 -1
  45. package/src/lib/components/crm-site-picker.js +15 -6
  46. package/src/lib/components/crm-site-picker.js.map +1 -1
  47. package/src/lib/components/crm-transfer-buttons.d.ts +5 -0
  48. package/src/lib/components/crm-transfer-buttons.js +9 -6
  49. package/src/lib/components/crm-transfer-buttons.js.map +1 -1
  50. package/src/lib/components/deal-contact-roles-card.js +21 -239
  51. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  52. package/src/lib/components/deal-detail-page.js +2 -1
  53. package/src/lib/components/deal-detail-page.js.map +1 -1
  54. package/src/lib/components/deal-edit-drawer.js +11 -7
  55. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  56. package/src/lib/components/deals-section.js +5 -4
  57. package/src/lib/components/deals-section.js.map +1 -1
  58. package/src/lib/components/log-activity-dialog.d.ts +27 -9
  59. package/src/lib/components/log-activity-dialog.js +96 -32
  60. package/src/lib/components/log-activity-dialog.js.map +1 -1
  61. package/src/lib/components/new-contact-drawer.d.ts +7 -3
  62. package/src/lib/components/new-contact-drawer.js +27 -15
  63. package/src/lib/components/new-contact-drawer.js.map +1 -1
  64. package/src/lib/components/pipeline-stages-dialog.js +5 -1
  65. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  66. package/src/lib/components/record-activity-card.d.ts +11 -2
  67. package/src/lib/components/record-activity-card.js +90 -5
  68. package/src/lib/components/record-activity-card.js.map +1 -1
  69. package/src/lib/components/settings-section.d.ts +4 -2
  70. package/src/lib/components/settings-section.js +7 -5
  71. package/src/lib/components/settings-section.js.map +1 -1
  72. package/src/lib/hooks/crm-activity-client-reads.d.ts +8 -0
  73. package/src/lib/hooks/crm-activity-client-reads.js +50 -0
  74. package/src/lib/hooks/crm-activity-client-reads.js.map +1 -0
  75. package/src/lib/hooks/use-campaign-filing-log.d.ts +2 -1
  76. package/src/lib/hooks/use-campaign-filing-log.js +10 -3
  77. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
  78. package/src/lib/hooks/use-crm-org-mount.d.ts +8 -6
  79. package/src/lib/hooks/use-crm-org-mount.js +2 -1
  80. package/src/lib/hooks/use-crm-org-mount.js.map +1 -1
  81. package/src/lib/hooks/use-crm-record-names.d.ts +3 -2
  82. package/src/lib/hooks/use-crm-record-names.js +4 -4
  83. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  84. package/src/lib/hooks/use-crm-scope.d.ts +17 -5
  85. package/src/lib/hooks/use-crm-scope.js +12 -5
  86. package/src/lib/hooks/use-crm-scope.js.map +1 -1
  87. package/src/lib/model/contact-holder.d.ts +12 -0
  88. package/src/lib/model/contact-holder.js +20 -1
  89. package/src/lib/model/contact-holder.js.map +1 -1
  90. package/src/lib/model/contact-record.d.ts +5 -0
  91. package/src/lib/model/contact-record.js +7 -1
  92. package/src/lib/model/contact-record.js.map +1 -1
  93. package/src/lib/model/contact-update.d.ts +6 -0
  94. package/src/lib/model/contact-update.js +1 -0
  95. package/src/lib/model/contact-update.js.map +1 -1
  96. package/src/lib/model/crm-activity-link.d.ts +117 -0
  97. package/src/lib/model/crm-activity-link.js +113 -0
  98. package/src/lib/model/crm-activity-link.js.map +1 -0
  99. package/src/lib/model/crm-api.d.ts +4 -1
  100. package/src/lib/model/crm-api.js +9 -5
  101. package/src/lib/model/crm-api.js.map +1 -1
  102. package/src/lib/model/deal-board-model.js +5 -3
  103. package/src/lib/model/deal-board-model.js.map +1 -1
  104. package/src/lib/model/deal-contact-roles.d.ts +25 -1
  105. package/src/lib/model/deal-contact-roles.js +30 -4
  106. package/src/lib/model/deal-contact-roles.js.map +1 -1
  107. package/src/lib/model/native-vocabulary.d.ts +9 -0
  108. package/src/lib/model/native-vocabulary.js +13 -0
  109. package/src/lib/model/native-vocabulary.js.map +1 -1
  110. package/src/lib/model/settle-stage-names.d.ts +25 -0
  111. package/src/lib/model/settle-stage-names.js +29 -0
  112. package/src/lib/model/settle-stage-names.js.map +1 -0
  113. package/src/lib/native-nav.js +1 -1
  114. package/src/lib/native-nav.js.map +1 -1
  115. package/src/lib/server/add-contact-by-hand.d.ts +84 -0
  116. package/src/lib/server/add-contact-by-hand.js +212 -0
  117. package/src/lib/server/add-contact-by-hand.js.map +1 -0
  118. package/src/lib/server/api-v1/contacts.js +61 -23
  119. package/src/lib/server/api-v1/contacts.js.map +1 -1
  120. package/src/lib/server/api-v1/crm-activities.js +13 -3
  121. package/src/lib/server/api-v1/crm-activities.js.map +1 -1
  122. package/src/lib/server/api-v1/crm-pipelines.d.ts +1 -1
  123. package/src/lib/server/api-v1/crm-pipelines.js +8 -2
  124. package/src/lib/server/api-v1/crm-pipelines.js.map +1 -1
  125. package/src/lib/server/api-v1/crm-shared.d.ts +16 -9
  126. package/src/lib/server/api-v1/crm-shared.js +23 -11
  127. package/src/lib/server/api-v1/crm-shared.js.map +1 -1
  128. package/src/lib/server/api-v1/openapi.js +3 -3
  129. package/src/lib/server/api-v1/openapi.js.map +1 -1
  130. package/src/lib/server/automation-steps.js +11 -9
  131. package/src/lib/server/automation-steps.js.map +1 -1
  132. package/src/lib/server/campaign-filing-activity.js +7 -2
  133. package/src/lib/server/campaign-filing-activity.js.map +1 -1
  134. package/src/lib/server/contact-update.d.ts +4 -0
  135. package/src/lib/server/contact-update.js +71 -10
  136. package/src/lib/server/contact-update.js.map +1 -1
  137. package/src/lib/server/convert-host-lead.js +13 -2
  138. package/src/lib/server/convert-host-lead.js.map +1 -1
  139. package/src/lib/server/convert-open-lead.js +8 -1
  140. package/src/lib/server/convert-open-lead.js.map +1 -1
  141. package/src/lib/server/crm-activity-company.d.ts +25 -0
  142. package/src/lib/server/crm-activity-company.js +34 -0
  143. package/src/lib/server/crm-activity-company.js.map +1 -0
  144. package/src/lib/server/crm-inbound-email.js +21 -15
  145. package/src/lib/server/crm-inbound-email.js.map +1 -1
  146. package/src/lib/server/crm-sharing.js +9 -2
  147. package/src/lib/server/crm-sharing.js.map +1 -1
  148. package/src/lib/server/deal-contact-roles.d.ts +2 -0
  149. package/src/lib/server/deal-contact-roles.js +38 -1
  150. package/src/lib/server/deal-contact-roles.js.map +1 -1
  151. package/src/lib/server/email-send.js +10 -8
  152. package/src/lib/server/email-send.js.map +1 -1
  153. package/src/lib/server/merge-contacts.js +6 -2
  154. package/src/lib/server/merge-contacts.js.map +1 -1
  155. package/src/lib/server/org-caller.d.ts +8 -0
  156. package/src/lib/server/org-caller.js +10 -0
  157. package/src/lib/server/org-caller.js.map +1 -1
  158. package/src/lib/server/record-timeline.d.ts +3 -1
  159. package/src/lib/server/record-timeline.js +11 -3
  160. package/src/lib/server/record-timeline.js.map +1 -1
  161. package/src/lib/server.js +152 -43
  162. package/src/lib/server.js.map +1 -1
  163. package/src/lib/transfer/contacts.js +83 -48
  164. package/src/lib/transfer/contacts.js.map +1 -1
  165. package/src/lib/transfer/fields.js +1 -2
  166. package/src/lib/transfer/fields.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/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\n/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event. Every CRM file is imported through the\n * transfer framework (AGL-3527, AGL-3528, `transfer/`), whose writes go\n * through the same doors every other server path uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there, and the plan is asked here about the fields\n * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a\n * contact go: the refusals the document holds are kept, which a client\n * write could not be trusted to do.\n */\n\nimport { registerDealFigureReaders } from './server/deal-figures'\nimport { registerPeopleFigureReader } from './server/people-figures'\nimport {\n CONTACT_ERASED_MESSAGE,\n CONTACT_FIELDS_MAX_PER_ORG,\n contactFacetPath,\n composeContactName,\n type ContactCustomValue,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n judgeCrmPicklistValue,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n readCrmCustomInput,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { captureHostContact } from './server/capture-host-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { registerCrmServerDeclarations } from './declarations.server'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_LIST_FIELDS_ROUTE } from './model/list-fields'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE, CRM_PICKLIST_VALUES_ROUTE } from './model/picklist-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmListFieldsHandler } from './server/list-fields-routes'\nimport { crmLeadSourceValuesHandler, crmPicklistValuesHandler } from './server/picklist-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler } from './server/email-check'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { crmSharingHandler } from './server/crm-sharing'\nimport { CRM_SHARING_ROUTE } from './model/crm-sharing'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler, readContactCreateProfile } from './server/contact-update'\nimport { readCrmPicklist } from './server/read-picklist'\nimport { crmContactRemoveHandler } from './server/contact-remove'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string; email: string | null } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n let email: string | null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n email = typeof decoded.email === 'string' ? decoded.email : null\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid, email }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const hostId = String(req.body?.hostId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if (!hostId || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(\n hostId,\n 'contactStageChanged',\n {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n },\n { actor: { kind: 'member', uid: caller.uid, email: caller.email } },\n )\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent?, disclosedConsentGroup? }`, plus any of Salesforce's\n * standard contact fields `crm/contact-update` reads but the reports-to\n * (`CONTACT_CREATE_PROFILE_FIELDS`, AGL-3515) — read by the same rules, the\n * salutation judged against the org's list, and the holder's name composed\n * from a first and last name when either is given. Answers\n * `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body['email'])\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const profile = readContactCreateProfile(body)\n if (profile.ok === false) {\n res.status(400).json({ error: profile.error })\n return\n }\n const extras = profile.fields\n const name = typed(body['name'], 120)\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\n // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\n // The org's own contact fields, sent in this same call (AGL-3971): a\n // value the create dropped would read as saved and be gone, and a second\n // write after it could land half. Judged below against the definitions.\n const rawCustom = body['custom']\n if (\n rawCustom !== undefined &&\n (!rawCustom || typeof rawCustom !== 'object' || Array.isArray(rawCustom))\n ) {\n res.status(400).json({ error: 'Custom fields must be values keyed by field key.' })\n return\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n // The salutation, judged against the org's list (AGL-3515).\n let salutation = ''\n if (extras.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n await readCrmPicklist(\n firebaseAdmin.app().firestore(),\n resolved.orgId,\n CRM_SALUTATION_PICKLIST,\n ),\n extras.salutation,\n )\n if (judged.ok === false) {\n res.status(400).json({ error: judged.error })\n return\n }\n salutation = judged.value ?? ''\n }\n\n /*\n * The custom values, judged exactly as `crm/contact-update` judges them\n * (AGL-3971): the org's definitions read only when the body carried a\n * map, an unknown, retired or mistyped key refused with the definition\n * reader's own sentence, and a currency amount stored as that field's\n * minor units. Before any write, so a refusal leaves nothing behind.\n */\n let custom: Record<string, ContactCustomValue> | undefined\n if (rawCustom !== undefined) {\n const definitions = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n const judged = readCrmCustomInput(\n rawCustom,\n definitions.docs.map((entry) => entry.data() as ContactFieldDefinition),\n 'contact',\n )\n if ('errors' in judged) {\n const [field, message] = Object.entries(judged.errors)[0] ?? []\n res.status(400).json({\n error: message ?? 'A custom value could not be saved.',\n ...(field ? { field } : {}),\n })\n return\n }\n custom = judged.values\n }\n\n if (companyId) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const readable = new Set<string>(crmReadTokens(group))\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const result = await captureHostContact({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n actor: {\n kind: 'member',\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n // Salesforce's standard fields (AGL-3515); the capture composes the\n // holder's name from the first and last names.\n ...Object.fromEntries(\n Object.entries({ ...extras, salutation }).filter(\n ([key, value]) =>\n key !== 'doNotCall' && key !== 'otherAddress' && typeof value === 'string' && value,\n ),\n ),\n ...(extras.otherAddress ? { otherAddress: extras.otherAddress } : {}),\n ...(extras.doNotCall ? { doNotCall: true } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\n // Written nested into the capturing holder's facet by the upsert,\n // on a new person and on a merge alike.\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n },\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (tags.length || companyName) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contacts.doc(result.contactId), 'contacts')\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n result.created ? 'Added contact' : 'Updated contact',\n {\n type: 'contact',\n id: result.contactId,\n name: name || composeContactName(extras.firstName, extras.lastName) || email,\n },\n )\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n // The pipeline and the deals closed, as figure tables (AGL-3603), for the\n // AI plugin's insights to read by id; the console runs insight jobs.\n registerDealFigureReaders(() => firebaseAdmin.app().firestore())\n // And the leads and contacts gained over a window (AGL-3867), for the\n // weekly summary and for insights.\n registerPeopleFigureReader(() => firebaseAdmin.app().firestore())\n /*\n * The contact-capture writer, again (AGL-3080). Both apps run it at boot\n * from their generated server-declarations manifest, and this is the\n * backstop for a process whose boot did not: the first CRM door to load\n * registers it. Registering twice replaces in place.\n */\n registerCrmServerDeclarations()\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactRemove, crmContactRemoveHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // What a client-direct write the browser cannot follow up asks for: the\n // fields the CRM lists query, restamped from the record (AGL-3321).\n registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler)\n // Sharing records with other sites (AGL-3336): a manager's share and\n // unshare, the org's sharing rules and their recompute, and the rules'\n // re-evaluation a client-direct write owes.\n registerPluginApiRoute(CRM_SHARING_ROUTE, crmSharingHandler)\n // A picklist value renamed or deleted (AGL-3298, AGL-3510): the list and\n // every record holding the old label, in one request. The lead source's\n // own address stays registered for a request that names no picklist.\n registerPluginApiRoute(CRM_PICKLIST_VALUES_ROUTE, crmPicklistValuesHandler)\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // What the platform knows about one address before somebody writes to it\n // (AGL-3328): the gateway chip on a record page, and the composer's\n // warning about a domain with no mail server or a gateway holding this\n // site's mail. DNS and the ledger are the server's.\n registerPluginApiRoute(CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n /*\n * The three doors a MACHINE calls (AGL-3080), at the paths they have\n * always answered on: the scheduler's daily digest and hourly task\n * reminders, on the cron secret, and the mail provider's capture webhook,\n * on its signature. None names a site or a member, so each is registered\n * as a machine's route — the dispatcher leaves the plugin's release and\n * enablement gates and its write limit to it — and each judges the CRM's\n * plan and flag for every organization it resolves. Loaded with the\n * first call, not with the surface.\n */\n registerPluginApiRoute(\n CRM_API_ROUTES.dailyDigest,\n {\n web: async (request) =>\n (await import('./server/daily-digest-route')).crmDailyDigestRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.taskReminders,\n {\n web: async (request) =>\n (await import('./server/task-reminders-route')).crmTaskRemindersRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.inbound,\n {\n web: async (request) => (await import('./server/inbound-route')).crmInboundRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { crmPlanEntitlements } from './plan-entitlements'\n"],"names":["registerDealFigureReaders","registerPeopleFigureReader","CONTACT_ERASED_MESSAGE","CONTACT_FIELDS_MAX_PER_ORG","contactFacetPath","composeContactName","CRM_COLLECTIONS","CRM_SALUTATION_PICKLIST","crmReadTokens","isContactLifecycleStage","isOrgWideMember","judgeCrmPicklistValue","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","readCrmCustomInput","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","emitHostEvent","captureHostContact","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_PICKLIST_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","crmPicklistValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmDealStageHandler","crmEmailSendHandler","CRM_EMAIL_CHECK_ROUTE","crmEmailCheckHandler","leadConvertHandler","leadCreateHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","crmSharingHandler","CRM_SHARING_ROUTE","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","readContactCreateProfile","readCrmPicklist","crmContactRemoveHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","email","decoded","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","contactId","requested","lifecycleStage","clearing","caller","facet","owner","suite","org","contactsRef","snapshot","group","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","actor","kind","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","profile","extras","fields","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","rawCustom","Array","isArray","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","salutation","judged","value","custom","definitions","contactFields","limit","docs","map","entry","Object","field","message","entries","errors","values","readable","Set","companySnapshot","companies","tokens","visible","some","token","has","result","source","interaction","summary","fromEntries","filter","key","otherAddress","doNotCall","keys","refused","reason","contacts","arrayUnion","created","type","id","firstName","lastName","registerCrmConsoleApi","ping","contactStage","contactUpdate","contactRemove","companyDelete","save","complete","emailSend","dailyDigest","web","request","crmDailyDigestRoute","machine","taskReminders","crmTaskRemindersRoute","inbound","crmInboundRoute"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SACEC,sBAAsB,EACtBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,kBAAkB,EAGlBC,eAAe,EACfC,uBAAuB,EACvBC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,qBAAqB,EACrBC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,kBAAkB,EAClBC,sBAAsB,EACtBC,aAAa,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Ec,eAAeuM,OAAO,EACtB;QACEN,KAAK,OAAOC,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,4BAAwB,EAAGM,eAAe,CAACN;IACnF,GACA;QAAEE,SAAS;IAAK;IAElBlN,uBACEwD,oCACAC;IAEF,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE/B;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/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\n/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event. Every CRM file is imported through the\n * transfer framework (AGL-3527, AGL-3528, `transfer/`), whose writes go\n * through the same doors every other server path uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there, and the plan is asked here about the fields\n * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a\n * contact go: the refusals the document holds are kept, which a client\n * write could not be trusted to do.\n */\n\nimport { registerDealFigureReaders } from './server/deal-figures'\nimport { registerPeopleFigureReader } from './server/people-figures'\nimport {\n CONTACT_ERASED_MESSAGE,\n CONTACT_FIELDS_MAX_PER_ORG,\n contactFacetPath,\n composeContactName,\n type ContactCustomValue,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n judgeCrmPicklistValue,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n readCrmCustomInput,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { ORG_CONTACT_HOLDER_ID } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmDefaultScopeOf } from '@aglyn/aglyn/app-utils/crm'\nimport { logOrgActivity } from '@aglyn/tenant-data-admin/server/organizations'\nimport { contactPrimaryGroup } from './model/contact-holder'\nimport { addContactByHand } from './server/add-contact-by-hand'\nimport { authorizeOrgCaller, readOrgForCreate } from './server/org-caller'\nimport { captureHostContact } from './server/capture-host-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { registerCrmServerDeclarations } from './declarations.server'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_LIST_FIELDS_ROUTE } from './model/list-fields'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE, CRM_PICKLIST_VALUES_ROUTE } from './model/picklist-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmListFieldsHandler } from './server/list-fields-routes'\nimport { crmLeadSourceValuesHandler, crmPicklistValuesHandler } from './server/picklist-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler } from './server/email-check'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { crmSharingHandler } from './server/crm-sharing'\nimport { CRM_SHARING_ROUTE } from './model/crm-sharing'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler, readContactCreateProfile } from './server/contact-update'\nimport { readCrmPicklist } from './server/read-picklist'\nimport { crmContactRemoveHandler } from './server/contact-remove'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string; email: string | null } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n let email: string | null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n email = typeof decoded.email === 'string' ? decoded.email : null\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid, email }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const hostId = String(req.body?.hostId ?? '').trim()\n const orgId = String(req.body?.orgId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if ((!hostId && !orgId) || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n /*\n * A person no site holds is staged at the organization level (AGL-4122): the\n * stage is in their org-held facet, and no site has an automation to tell.\n */\n if (!hostId) {\n const caller = await authorizeOrgCaller(req, orgId, {\n needs: 'data.manage',\n refusal: 'Moving a contact’s stage requires the \"Manage data\" permission.',\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n const suite = crmSuiteRefusal(caller.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('contacts')\n .doc(contactId)\n .get()\n if (!snapshot.exists) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const data = snapshot.data() as Record<string, unknown>\n const groupId =\n contactPrimaryGroup(data, caller.org as Record<string, unknown>).groupId ||\n ORG_CONTACT_HOLDER_ID\n const previousStage = readContactFacet(data, groupId).lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res.status(200).json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\n res.status(200).json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', orgId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(\n hostId,\n 'contactStageChanged',\n {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n },\n { actor: { kind: 'member', uid: caller.uid, email: caller.email } },\n )\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent?, disclosedConsentGroup? }`, plus any of Salesforce's\n * standard contact fields `crm/contact-update` reads but the reports-to\n * (`CONTACT_CREATE_PROFILE_FIELDS`, AGL-3515) — read by the same rules, the\n * salutation judged against the org's list, and the holder's name composed\n * from a first and last name when either is given. Answers\n * `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n // The organization, for a person added there with no Source site (AGL-4122).\n const orgIdInBody = typed(body['orgId'], 128)\n if (!hostId && !orgIdInBody) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n // An address is optional, and one that was typed still has to be an address.\n const rawEmail = typed(body['email'], 320)\n const email = rawEmail ? normalizeContactEmail(rawEmail) : null\n if (rawEmail && !email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const profile = readContactCreateProfile(body)\n if (profile.ok === false) {\n res.status(400).json({ error: profile.error })\n return\n }\n const extras = profile.fields\n const name = typed(body['name'], 120)\n // Somebody to call them: a name, an address or a number (AGL-4122).\n if (\n !email &&\n !phone &&\n !extras.mobilePhone &&\n !name &&\n !composeContactName(extras.firstName, extras.lastName)\n ) {\n res.status(400).json({ error: 'Enter a name, an email or a phone number.' })\n return\n }\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\n // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\n // The org's own contact fields, sent in this same call (AGL-3971): a\n // value the create dropped would read as saved and be gone, and a second\n // write after it could land half. Judged below against the definitions.\n const rawCustom = body['custom']\n if (\n rawCustom !== undefined &&\n (!rawCustom || typeof rawCustom !== 'object' || Array.isArray(rawCustom))\n ) {\n res.status(400).json({ error: 'Custom fields must be values keyed by field key.' })\n return\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = hostId\n ? await getOrgForHost(hostId)\n : await readOrgForCreate(orgIdInBody)\n if (!resolved) {\n res.status(404).json({ error: hostId ? 'Unknown site' : 'Unknown workspace' })\n return\n }\n // The org's records belong to every site unless it keeps them apart, and\n // then a record has to come from one (AGL-4122).\n if (\n !hostId &&\n crmDefaultScopeOf(resolved.org as Record<string, unknown>) !== 'org'\n ) {\n res.status(400).json({ error: 'Choose the site this contact came from.' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) ||\n Boolean(hostId && member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n // The salutation, judged against the org's list (AGL-3515).\n let salutation = ''\n if (extras.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n await readCrmPicklist(\n firebaseAdmin.app().firestore(),\n resolved.orgId,\n CRM_SALUTATION_PICKLIST,\n ),\n extras.salutation,\n )\n if (judged.ok === false) {\n res.status(400).json({ error: judged.error })\n return\n }\n salutation = judged.value ?? ''\n }\n\n /*\n * The custom values, judged exactly as `crm/contact-update` judges them\n * (AGL-3971): the org's definitions read only when the body carried a\n * map, an unknown, retired or mistyped key refused with the definition\n * reader's own sentence, and a currency amount stored as that field's\n * minor units. Before any write, so a refusal leaves nothing behind.\n */\n let custom: Record<string, ContactCustomValue> | undefined\n if (rawCustom !== undefined) {\n const definitions = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n const judged = readCrmCustomInput(\n rawCustom,\n definitions.docs.map((entry) => entry.data() as ContactFieldDefinition),\n 'contact',\n )\n if ('errors' in judged) {\n const [field, message] = Object.entries(judged.errors)[0] ?? []\n res.status(400).json({\n error: message ?? 'A custom value could not be saved.',\n ...(field ? { field } : {}),\n })\n return\n }\n custom = judged.values\n }\n\n if (companyId) {\n // With no site the caller is org-wide, and every company is theirs.\n const readable = hostId\n ? new Set<string>(\n crmReadTokens(\n await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n ),\n ),\n )\n : null\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n companySnapshot.exists &&\n (!readable ||\n (Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const facet = {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n // Salesforce's standard fields (AGL-3515); the capture composes the\n // holder's name from the first and last names.\n ...Object.fromEntries(\n Object.entries({ ...extras, salutation }).filter(\n ([key, value]) =>\n key !== 'doNotCall' && key !== 'otherAddress' && typeof value === 'string' && value,\n ),\n ),\n ...(extras.otherAddress ? { otherAddress: extras.otherAddress } : {}),\n ...(extras.doNotCall ? { doNotCall: true } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n // Written nested into the capturing holder's facet by the upsert,\n // on a new person and on a merge alike.\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n }\n const stage =\n rawStage && isContactLifecycleStage(rawStage) ? { lifecycleStage: rawStage } : {}\n // A site and an address are a capture. Anything less is the team adding a\n // person no capture door could take (AGL-4122).\n const captured = Boolean(hostId && email)\n const result = captured\n ? await captureHostContact({\n hostId,\n email: email as string,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n actor: {\n kind: 'member',\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n // The door's stage is the one the drawer picked, or none at all.\n facet: { ...facet, ...stage /* lifecycleStage */ },\n })\n : await addContactByHand({\n orgId: resolved.orgId,\n org: resolved.org as Record<string, unknown>,\n sourceHostId: hostId || null,\n email,\n ...(name ? { name } : {}),\n facet: {\n ...facet,\n ...stage,\n ...(companyName ? { companyName } : {}),\n },\n tags,\n marketingConsent,\n ...(disclosedConsentGroup ? { disclosedConsentGroup } : {}),\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (captured && (tags.length || companyName)) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contacts.doc(result.contactId), 'contacts')\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n const added = result.created ? 'Added contact' : 'Updated contact'\n const addedActor = { uid: decoded.uid, email: decoded.email ?? null }\n const addedTarget = {\n type: 'contact' as const,\n id: result.contactId,\n name:\n name ||\n composeContactName(extras.firstName, extras.lastName) ||\n email ||\n phone ||\n '',\n }\n await (hostId\n ? logHostActivity(hostId, addedActor, added, addedTarget)\n : logOrgActivity(resolved.orgId, addedActor, added, addedTarget))\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n // The pipeline and the deals closed, as figure tables (AGL-3603), for the\n // AI plugin's insights to read by id; the console runs insight jobs.\n registerDealFigureReaders(() => firebaseAdmin.app().firestore())\n // And the leads and contacts gained over a window (AGL-3867), for the\n // weekly summary and for insights.\n registerPeopleFigureReader(() => firebaseAdmin.app().firestore())\n /*\n * The contact-capture writer, again (AGL-3080). Both apps run it at boot\n * from their generated server-declarations manifest, and this is the\n * backstop for a process whose boot did not: the first CRM door to load\n * registers it. Registering twice replaces in place.\n */\n registerCrmServerDeclarations()\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactRemove, crmContactRemoveHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // What a client-direct write the browser cannot follow up asks for: the\n // fields the CRM lists query, restamped from the record (AGL-3321).\n registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler)\n // Sharing records with other sites (AGL-3336): a manager's share and\n // unshare, the org's sharing rules and their recompute, and the rules'\n // re-evaluation a client-direct write owes.\n registerPluginApiRoute(CRM_SHARING_ROUTE, crmSharingHandler)\n // A picklist value renamed or deleted (AGL-3298, AGL-3510): the list and\n // every record holding the old label, in one request. The lead source's\n // own address stays registered for a request that names no picklist.\n registerPluginApiRoute(CRM_PICKLIST_VALUES_ROUTE, crmPicklistValuesHandler)\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // What the platform knows about one address before somebody writes to it\n // (AGL-3328): the gateway chip on a record page, and the composer's\n // warning about a domain with no mail server or a gateway holding this\n // site's mail. DNS and the ledger are the server's.\n registerPluginApiRoute(CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n /*\n * The three doors a MACHINE calls (AGL-3080), at the paths they have\n * always answered on: the scheduler's daily digest and hourly task\n * reminders, on the cron secret, and the mail provider's capture webhook,\n * on its signature. None names a site or a member, so each is registered\n * as a machine's route — the dispatcher leaves the plugin's release and\n * enablement gates and its write limit to it — and each judges the CRM's\n * plan and flag for every organization it resolves. Loaded with the\n * first call, not with the surface.\n */\n registerPluginApiRoute(\n CRM_API_ROUTES.dailyDigest,\n {\n web: async (request) =>\n (await import('./server/daily-digest-route')).crmDailyDigestRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.taskReminders,\n {\n web: async (request) =>\n (await import('./server/task-reminders-route')).crmTaskRemindersRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.inbound,\n {\n web: async (request) => (await import('./server/inbound-route')).crmInboundRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { crmPlanEntitlements } from './plan-entitlements'\n"],"names":["registerDealFigureReaders","registerPeopleFigureReader","CONTACT_ERASED_MESSAGE","CONTACT_FIELDS_MAX_PER_ORG","contactFacetPath","composeContactName","CRM_COLLECTIONS","CRM_SALUTATION_PICKLIST","crmReadTokens","isContactLifecycleStage","isOrgWideMember","judgeCrmPicklistValue","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","readCrmCustomInput","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","emitHostEvent","ORG_CONTACT_HOLDER_ID","crmDefaultScopeOf","logOrgActivity","contactPrimaryGroup","addContactByHand","authorizeOrgCaller","readOrgForCreate","captureHostContact","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_PICKLIST_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","crmPicklistValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmDealStageHandler","crmEmailSendHandler","CRM_EMAIL_CHECK_ROUTE","crmEmailCheckHandler","leadConvertHandler","leadCreateHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","crmSharingHandler","CRM_SHARING_ROUTE","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","readContactCreateProfile","readCrmPicklist","crmContactRemoveHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","email","decoded","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","orgId","contactId","requested","lifecycleStage","clearing","caller","needs","refusal","suite","org","snapshot","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","facet","owner","contactsRef","group","actor","kind","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","orgIdInBody","rawEmail","rawPhone","phone","rawStage","profile","extras","fields","name","mobilePhone","firstName","lastName","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","rawCustom","Array","isArray","resolved","isStaff","member","membership","reaches","Boolean","hostAccess","allowed","salutation","judged","value","custom","definitions","contactFields","limit","docs","map","entry","Object","field","message","entries","errors","values","readable","Set","companySnapshot","companies","tokens","visible","some","token","has","fromEntries","filter","key","otherAddress","doNotCall","keys","stage","captured","result","source","interaction","summary","sourceHostId","refused","reason","contacts","arrayUnion","added","created","addedActor","addedTarget","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","contactRemove","companyDelete","save","complete","emailSend","dailyDigest","web","request","crmDailyDigestRoute","machine","taskReminders","crmTaskRemindersRoute","inbound","crmInboundRoute"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SACEC,sBAAsB,EACtBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,kBAAkB,EAGlBC,eAAe,EACfC,uBAAuB,EACvBC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,qBAAqB,EACrBC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,kBAAkB,EAClBC,sBAAsB,EACtBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,gBAAgB,QAAQ,kCAA8B;AAC/D,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAqB;AAC1E,SAASC,kBAAkB,QAAQ,mCAA+B;AAClE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;A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K,OAAOC,UACV,AAAC,CAAA,MAAM,MAAM,CAAC,mCAA+B,EAAGI,qBAAqB,CAACJ;IAC1E,GACA;QAAEE,SAAS;IAAK;IAElBpO,uBACEqB,eAAekN,OAAO,EACtB;QACEN,KAAK,OAAOC,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,4BAAwB,EAAGM,eAAe,CAACN;IACnF,GACA;QAAEE,SAAS;IAAK;IAElBpO,uBACE+D,oCACAC;IAEF,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE/B;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;AACF"}
@@ -43,14 +43,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
43
43
  * turned on by a file and never off; the full name follows the first and
44
44
  * last names once either is set. The plan holds each one back by row and
45
45
  * names it, so the person acknowledges it before anything is written.
46
- *=========================================*/ import { composeContactName, contactDisplayName, contactFacetPath, CRM_COLLECTIONS, interactionsForGroup, isContactLifecycleStage, normalizeContactBirthdate, normalizePhone, planContactDetach, readContactFacet, readMarketingBasis } from "@aglyn/aglyn/server";
46
+ *=========================================*/ import { composeContactName, crmDefaultScopeOf, ORG_CONTACT_HOLDER_ID, contactDisplayName, contactFacetPath, CRM_COLLECTIONS, interactionsForGroup, isContactLifecycleStage, normalizeContactBirthdate, normalizePhone, planContactDetach, readContactFacet, readMarketingBasis } from "@aglyn/aglyn/server";
47
47
  import { CONTACT_LIFECYCLE_STAGE_LABELS } from "@aglyn/aglyn/app-utils/crm";
48
48
  import { CONTACT_EXTRA_PHONE_FIELDS as PHONE_FIELDS } from "@aglyn/aglyn/app-utils/contacts";
49
49
  import { buildTransferPlan, planTransferUndo, rankTransferLookupSuggestions, TRANSFER_ID_FIELD, transferLookupNewName } from "@aglyn/aglyn/data-transfer";
50
50
  import { prepareContactCaptureBatch, removeContactKeepingRefusals, restampCrmListFieldsOf } from "@aglyn/tenant-data-admin";
51
51
  import { emitHostEvent } from "@aglyn/tenant-runtime";
52
52
  import { FieldValue } from "firebase-admin/firestore";
53
- import { contactPrimaryGroup } from "../model/contact-holder.js";
53
+ import { contactPrimaryGroup, ORG_HOLDER_GROUP } from "../model/contact-holder.js";
54
54
  import { captureHostContact } from "../server/capture-host-contact.js";
55
55
  import { CONTACT_NOTES_MAX } from "../server/contact-profile.js";
56
56
  import { cachedContactReader, clearReportsToOf, CONTACT_REPORTS_TO_LOOP_REFUSAL, CONTACT_REPORTS_TO_SELF_REFUSAL, contactFacetHolders, contactReportsToLoops } from "../server/contact-reports-to.js";
@@ -59,6 +59,7 @@ import { sweepDealContactRoles } from "../server/deal-contact-roles.js";
59
59
  import { CONTACT_ALIASES } from "./aliases.js";
60
60
  import { addCrmPicklistValues, addressFromValues, addressValues, countCrmExport, crmCustomDefinitions, crmMemberEmails, crmMembersTarget, crmPicklistLists, crmRecordsRoom, crmTransferEnv, customTransferValues, customWriteValues, eachWithinBudget, failureMessage, holdBackChanges, IN_LIMIT, isoOf, lookupByField, lookupById, lookupResult, pickValues, plannedValues, readCrmExportPage, requireCrmSuite, requireSite, textOf, TransferEngineError, visibleIn } from "./common.js";
61
61
  import { companyForName } from "./companies.js";
62
+ import { addContactByHand } from "../server/add-contact-by-hand.js";
62
63
  import { CONTACT_TRANSFER_DERIVED, CONTACT_TRANSFER_FIELDS, CONTACT_TRANSFER_GROUPS, CRM_MEMBERS_TARGET, CRM_TIMESTAMP_FIELDS, crmCustomTransferFields, crmLifecycleStageOf, crmLifecycleStageRank } from "./fields.js";
63
64
  /** The sentence an imported person's timeline opens with. */ export const CONTACT_TRANSFER_INTERACTION_SUMMARY = 'Imported from a file';
64
65
  const SUITE_ACT = 'Importing contacts';
@@ -230,7 +231,8 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
230
231
  if (!snapshot.exists || !contact || !visibleIn(run.env, contact['visibleTo'])) {
231
232
  throw new TransferEngineError('notFound', 404, 'That contact no longer exists.');
232
233
  }
233
- const groupId = run.group.groupId;
234
+ // With no site the row is written to the holder the person already has.
235
+ const groupId = (run.hostId ? run.group : contactPrimaryGroup(contact, run.env.org)).groupId || ORG_CONTACT_HOLDER_ID;
234
236
  const stored = readContactFacet(contact, groupId);
235
237
  const { fields, skipped } = profileFields(values, stored);
236
238
  let linkedCompanyName = '';
@@ -276,7 +278,7 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
276
278
  counts: patch.counts
277
279
  }
278
280
  ]);
279
- if (movedFrom !== null) {
281
+ if (movedFrom !== null && run.hostId) {
280
282
  await emitHostEvent(run.hostId, 'contactStageChanged', {
281
283
  contactId,
282
284
  email: textOf(contact['email']),
@@ -294,8 +296,21 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
294
296
  skipped
295
297
  };
296
298
  }
299
+ /**
300
+ * The site a contact import is filed under. None, when the org's records belong
301
+ * to every site (AGL-4122): the file then has no Source site, and the people in
302
+ * it are the organization's. An org that keeps its sites apart must name one.
303
+ */ function contactImportSite(env) {
304
+ if (!env.hostId && crmDefaultScopeOf(env.org) === 'org') {
305
+ return {
306
+ hostId: null,
307
+ group: ORG_HOLDER_GROUP
308
+ };
309
+ }
310
+ return requireSite(env, 'contacts');
311
+ }
297
312
  /** Creates one person through the capture door, then what the door does not take. */ async function createContact(run, values, batch) {
298
- var _fields_tags;
313
+ var _fields_tags, _fields_tags1;
299
314
  const email = textOf(values['email']);
300
315
  const { fields, skipped } = profileFields(values, {
301
316
  sources: {},
@@ -305,7 +320,52 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
305
320
  const custom = customWriteValues(values, run.definitions, 'contact');
306
321
  if ('error' in custom) throw new TransferEngineError('invalid', 422, custom.error);
307
322
  const stage = crmLifecycleStageOf(values['lifecycleStage']);
308
- const verdict = await captureHostContact(_extends({
323
+ const facet = _extends({}, fields.phone ? {
324
+ phone: fields.phone
325
+ } : {}, fields.jobTitle ? {
326
+ jobTitle: fields.jobTitle
327
+ } : {}, fields.salutation ? {
328
+ salutation: fields.salutation
329
+ } : {}, fields.firstName ? {
330
+ firstName: fields.firstName
331
+ } : {}, fields.lastName ? {
332
+ lastName: fields.lastName
333
+ } : {}, fields.department ? {
334
+ department: fields.department
335
+ } : {}, Object.fromEntries(PHONE_FIELDS.filter((key)=>fields[key]).map((key)=>[
336
+ key,
337
+ fields[key]
338
+ ])), fields.birthdate ? {
339
+ birthdate: fields.birthdate
340
+ } : {}, fields.assistantName ? {
341
+ assistantName: fields.assistantName
342
+ } : {}, fields.leadSource ? {
343
+ leadSource: fields.leadSource
344
+ } : {}, fields.doNotCall ? {
345
+ doNotCall: true
346
+ } : {}, fields.address ? {
347
+ address: fields.address
348
+ } : {}, fields.otherAddress ? {
349
+ otherAddress: fields.otherAddress
350
+ } : {}, (link == null ? void 0 : link.id) ? {
351
+ companyId: link.id,
352
+ companyName: link.name
353
+ } : {}, fields.ownerUid ? {
354
+ ownerUid: fields.ownerUid
355
+ } : {}, Object.keys(custom.values).length ? {
356
+ custom: custom.values
357
+ } : {});
358
+ const staged = stage ? {
359
+ lifecycleStage: stage
360
+ } : {};
361
+ /*
362
+ * A SITE AND AN ADDRESS ARE A CAPTURE. Anything less is a person no capture
363
+ * door could take, so a file can hold people with no email and be imported
364
+ * with no site (AGL-4122). A row still has to say who it is about.
365
+ */ if (!email && !fields.name && !facet.phone && !facet.firstName && !facet.lastName && !fields['mobilePhone']) {
366
+ throw new TransferEngineError('invalid', 422, 'A row needs a name, an email or a phone number.');
367
+ }
368
+ const verdict = run.hostId && email ? await captureHostContact(_extends({
309
369
  hostId: run.hostId,
310
370
  email
311
371
  }, fields.name ? {
@@ -323,48 +383,23 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
323
383
  summary: CONTACT_TRANSFER_INTERACTION_SUMMARY
324
384
  },
325
385
  tags: (_fields_tags = fields.tags) != null ? _fields_tags : [],
326
- facet: _extends({}, fields.phone ? {
327
- phone: fields.phone
328
- } : {}, fields.jobTitle ? {
329
- jobTitle: fields.jobTitle
330
- } : {}, fields.salutation ? {
331
- salutation: fields.salutation
332
- } : {}, fields.firstName ? {
333
- firstName: fields.firstName
334
- } : {}, fields.lastName ? {
335
- lastName: fields.lastName
336
- } : {}, fields.department ? {
337
- department: fields.department
338
- } : {}, Object.fromEntries(PHONE_FIELDS.filter((key)=>fields[key]).map((key)=>[
339
- key,
340
- fields[key]
341
- ])), fields.birthdate ? {
342
- birthdate: fields.birthdate
343
- } : {}, fields.assistantName ? {
344
- assistantName: fields.assistantName
345
- } : {}, fields.leadSource ? {
346
- leadSource: fields.leadSource
347
- } : {}, fields.doNotCall ? {
348
- doNotCall: true
349
- } : {}, fields.address ? {
350
- address: fields.address
351
- } : {}, fields.otherAddress ? {
352
- otherAddress: fields.otherAddress
353
- } : {}, (link == null ? void 0 : link.id) ? {
354
- companyId: link.id,
355
- companyName: link.name
356
- } : {}, fields.ownerUid ? {
357
- ownerUid: fields.ownerUid
358
- } : {}, stage ? {
359
- lifecycleStage: stage
360
- } : {}, Object.keys(custom.values).length ? {
361
- custom: custom.values
362
- } : {}),
386
+ // The file's own stage, or none: `lifecycleStage` from the column.
387
+ facet: _extends({}, facet, staged),
363
388
  // An import files nobody under a campaign; the record's picker does.
364
389
  campaignIds: []
365
390
  }, batch ? {
366
391
  batch
367
- } : {}));
392
+ } : {})) : await addContactByHand(_extends({
393
+ orgId: run.env.orgId,
394
+ org: run.env.org,
395
+ sourceHostId: run.hostId,
396
+ email: email || null
397
+ }, fields.name ? {
398
+ name: fields.name
399
+ } : {}, {
400
+ facet: _extends({}, facet, staged),
401
+ tags: (_fields_tags1 = fields.tags) != null ? _fields_tags1 : []
402
+ }));
368
403
  if ('refused' in verdict) {
369
404
  var _CAPTURE_REFUSALS_verdict_refused;
370
405
  throw new TransferEngineError('invalid', 422, (_CAPTURE_REFUSALS_verdict_refused = CAPTURE_REFUSALS[verdict.refused]) != null ? _CAPTURE_REFUSALS_verdict_refused : CAPTURE_REFUSALS['error']);
@@ -520,7 +555,7 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
520
555
  async plan (ctx, input) {
521
556
  const env = await crmTransferEnv(ctx);
522
557
  requireCrmSuite(env, SUITE_ACT);
523
- requireSite(env, 'contacts');
558
+ contactImportSite(env);
524
559
  const plan = buildTransferPlan(input);
525
560
  return holdBackChanges(plan, (row, change)=>{
526
561
  const before = row.recordId ? input.existing.get(row.recordId) : undefined;
@@ -547,7 +582,7 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
547
582
  async apply (ctx, chunk, writer) {
548
583
  const env = await crmTransferEnv(ctx);
549
584
  requireCrmSuite(env, SUITE_ACT);
550
- const { hostId, group } = requireSite(env, 'contacts');
585
+ const { hostId, group } = contactImportSite(env);
551
586
  const run = {
552
587
  env,
553
588
  hostId,
@@ -567,7 +602,7 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
567
602
  }
568
603
  }
569
604
  // The capture door's lookups for every new person at once (AGL-3423).
570
- const batch = creating.length ? await prepareContactCaptureBatch(hostId, creating) : undefined;
605
+ const batch = hostId && creating.length ? await prepareContactCaptureBatch(hostId, creating) : undefined;
571
606
  const results = [];
572
607
  const undo = [];
573
608
  await eachWithinBudget(rows, ()=>writer.timeLeftMs(), async (row)=>{
@@ -651,7 +686,7 @@ const contactsOf = (env)=>env.orgRef.collection('contacts');
651
686
  },
652
687
  async revert (ctx, snapshot, decisions) {
653
688
  const env = await crmTransferEnv(ctx);
654
- const { hostId, group } = requireSite(env, 'contacts');
689
+ const { hostId, group } = contactImportSite(env);
655
690
  const run = {
656
691
  env,
657
692
  hostId,