@aglyn/plugins-crm 1.0.0-beta.217 → 1.0.0-beta.219

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 (249) hide show
  1. package/package.json +14 -13
  2. package/src/index.d.ts +1 -0
  3. package/src/index.js.map +1 -1
  4. package/src/lib/components/companies-bulk-bar.js +12 -4
  5. package/src/lib/components/companies-bulk-bar.js.map +1 -1
  6. package/src/lib/components/company-detail-page.js +11 -0
  7. package/src/lib/components/company-detail-page.js.map +1 -1
  8. package/src/lib/components/company-edit-drawer.js +12 -2
  9. package/src/lib/components/company-edit-drawer.js.map +1 -1
  10. package/src/lib/components/company-import-drawer.d.ts +1 -1
  11. package/src/lib/components/company-picker.js +10 -3
  12. package/src/lib/components/company-picker.js.map +1 -1
  13. package/src/lib/components/contact-detail-page.d.ts +4 -4
  14. package/src/lib/components/contact-detail-page.js +50 -53
  15. package/src/lib/components/contact-detail-page.js.map +1 -1
  16. package/src/lib/components/contact-list-columns.d.ts +3 -0
  17. package/src/lib/components/contact-list-columns.js +21 -5
  18. package/src/lib/components/contact-list-columns.js.map +1 -1
  19. package/src/lib/components/contact-merge-dialog.js +2 -1
  20. package/src/lib/components/contact-merge-dialog.js.map +1 -1
  21. package/src/lib/components/contact-timeline-card.js +4 -3
  22. package/src/lib/components/contact-timeline-card.js.map +1 -1
  23. package/src/lib/components/contacts-bulk-bar.d.ts +3 -3
  24. package/src/lib/components/contacts-bulk-bar.js +24 -51
  25. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  26. package/src/lib/components/contacts-section.js +9 -3
  27. package/src/lib/components/contacts-section.js.map +1 -1
  28. package/src/lib/components/crm-export-all-button.d.ts +1 -1
  29. package/src/lib/components/crm-export-all-button.js.map +1 -1
  30. package/src/lib/components/crm-send-email-dialog.js +9 -6
  31. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  32. package/src/lib/components/csv-import-drawer.js +2 -2
  33. package/src/lib/components/csv-import-drawer.js.map +1 -1
  34. package/src/lib/components/deal-detail-page.js +18 -2
  35. package/src/lib/components/deal-detail-page.js.map +1 -1
  36. package/src/lib/components/deal-edit-drawer.js +10 -0
  37. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  38. package/src/lib/components/deals-bulk-bar.js +13 -5
  39. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  40. package/src/lib/components/lead-campaigns-card.js +6 -0
  41. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  42. package/src/lib/components/lead-detail-page.js +25 -5
  43. package/src/lib/components/lead-detail-page.js.map +1 -1
  44. package/src/lib/components/lead-properties-card.js +6 -0
  45. package/src/lib/components/lead-properties-card.js.map +1 -1
  46. package/src/lib/components/lead-surfaces-note.js +4 -5
  47. package/src/lib/components/lead-surfaces-note.js.map +1 -1
  48. package/src/lib/components/lead-unqualify-dialog.js +6 -0
  49. package/src/lib/components/lead-unqualify-dialog.js.map +1 -1
  50. package/src/lib/components/leads-bulk-bar.js +28 -3
  51. package/src/lib/components/leads-bulk-bar.js.map +1 -1
  52. package/src/lib/components/leads-section.js +36 -7
  53. package/src/lib/components/leads-section.js.map +1 -1
  54. package/src/lib/components/org-lead-surfaces-note.js +6 -2
  55. package/src/lib/components/org-lead-surfaces-note.js.map +1 -1
  56. package/src/lib/components/recipes-card.js +9 -4
  57. package/src/lib/components/recipes-card.js.map +1 -1
  58. package/src/lib/components/record-sharing-card.d.ts +57 -0
  59. package/src/lib/components/record-sharing-card.js +244 -0
  60. package/src/lib/components/record-sharing-card.js.map +1 -0
  61. package/src/lib/components/settings-section.js +7 -0
  62. package/src/lib/components/settings-section.js.map +1 -1
  63. package/src/lib/components/share-records-dialog.d.ts +28 -0
  64. package/src/lib/components/share-records-dialog.js +184 -0
  65. package/src/lib/components/share-records-dialog.js.map +1 -0
  66. package/src/lib/components/sharing-rule-drawer.d.ts +37 -0
  67. package/src/lib/components/sharing-rule-drawer.js +374 -0
  68. package/src/lib/components/sharing-rule-drawer.js.map +1 -0
  69. package/src/lib/components/sharing-rules-card.d.ts +24 -0
  70. package/src/lib/components/sharing-rules-card.js +287 -0
  71. package/src/lib/components/sharing-rules-card.js.map +1 -0
  72. package/src/lib/components/use-crm-api.d.ts +1 -1
  73. package/src/lib/components/use-crm-api.js.map +1 -1
  74. package/src/lib/components/use-site-route-context.d.ts +25 -0
  75. package/src/lib/components/use-site-route-context.js +58 -0
  76. package/src/lib/components/use-site-route-context.js.map +1 -0
  77. package/src/lib/constants/api-routes.d.ts +31 -0
  78. package/src/lib/constants/api-routes.js +27 -1
  79. package/src/lib/constants/api-routes.js.map +1 -1
  80. package/src/lib/declarations.console-server.d.ts +37 -0
  81. package/src/lib/declarations.console-server.js +103 -0
  82. package/src/lib/declarations.console-server.js.map +1 -0
  83. package/src/lib/declarations.server.d.ts +6 -0
  84. package/src/lib/declarations.server.js +33 -0
  85. package/src/lib/declarations.server.js.map +1 -1
  86. package/src/lib/hooks/use-contact-remove.d.ts +35 -0
  87. package/src/lib/hooks/use-contact-remove.js +77 -0
  88. package/src/lib/hooks/use-contact-remove.js.map +1 -0
  89. package/src/lib/hooks/use-crm-sharing.d.ts +30 -0
  90. package/src/lib/hooks/use-crm-sharing.js +109 -0
  91. package/src/lib/hooks/use-crm-sharing.js.map +1 -0
  92. package/src/lib/model/companies-csv.d.ts +1 -1
  93. package/src/lib/model/companies-csv.js +2 -2
  94. package/src/lib/model/companies-csv.js.map +1 -1
  95. package/src/lib/model/contact-holder.d.ts +68 -0
  96. package/src/lib/model/contact-holder.js +129 -0
  97. package/src/lib/model/contact-holder.js.map +1 -0
  98. package/src/lib/model/contact-interaction-links.d.ts +46 -0
  99. package/src/lib/model/contact-interaction-links.js +65 -0
  100. package/src/lib/model/contact-interaction-links.js.map +1 -0
  101. package/src/lib/model/contact-merge.d.ts +136 -0
  102. package/src/lib/model/contact-merge.js +412 -0
  103. package/src/lib/model/contact-merge.js.map +1 -0
  104. package/src/lib/model/contact-record.d.ts +7 -1
  105. package/src/lib/model/contact-record.js +6 -5
  106. package/src/lib/model/contact-record.js.map +1 -1
  107. package/src/lib/model/contact-remove.d.ts +48 -0
  108. package/src/lib/model/contact-remove.js +22 -0
  109. package/src/lib/model/contact-remove.js.map +1 -0
  110. package/src/lib/model/contacts-bulk-writes.d.ts +2 -71
  111. package/src/lib/model/contacts-bulk-writes.js +2 -82
  112. package/src/lib/model/contacts-bulk-writes.js.map +1 -1
  113. package/src/lib/model/contacts-csv.d.ts +2 -2
  114. package/src/lib/model/contacts-csv.js +2 -2
  115. package/src/lib/model/contacts-csv.js.map +1 -1
  116. package/src/lib/model/crm-csv.d.ts +239 -0
  117. package/src/lib/model/crm-csv.js +467 -0
  118. package/src/lib/model/crm-csv.js.map +1 -0
  119. package/src/lib/model/crm-digest.d.ts +185 -0
  120. package/src/lib/model/crm-digest.js +272 -0
  121. package/src/lib/model/crm-digest.js.map +1 -0
  122. package/src/lib/model/crm-import.d.ts +7 -1
  123. package/src/lib/model/crm-import.js +2 -1
  124. package/src/lib/model/crm-import.js.map +1 -1
  125. package/src/lib/model/crm-record-routes.d.ts +5 -0
  126. package/src/lib/model/crm-record-routes.js +7 -0
  127. package/src/lib/model/crm-record-routes.js.map +1 -1
  128. package/src/lib/model/crm-routes.d.ts +6 -5
  129. package/src/lib/model/crm-routes.js +7 -7
  130. package/src/lib/model/crm-routes.js.map +1 -1
  131. package/src/lib/model/crm-search-sources.d.ts +15 -0
  132. package/src/lib/model/crm-search-sources.js +162 -0
  133. package/src/lib/model/crm-search-sources.js.map +1 -0
  134. package/src/lib/model/crm-sharing-api.d.ts +32 -0
  135. package/src/lib/model/crm-sharing-api.js +59 -0
  136. package/src/lib/model/crm-sharing-api.js.map +1 -0
  137. package/src/lib/model/crm-sharing.d.ts +333 -0
  138. package/src/lib/model/crm-sharing.js +603 -0
  139. package/src/lib/model/crm-sharing.js.map +1 -0
  140. package/src/lib/model/deals-csv.d.ts +1 -1
  141. package/src/lib/model/deals-csv.js +4 -5
  142. package/src/lib/model/deals-csv.js.map +1 -1
  143. package/src/lib/model/lead-filters.d.ts +1 -1
  144. package/src/lib/model/leads-csv.d.ts +1 -1
  145. package/src/lib/model/leads-csv.js +1 -1
  146. package/src/lib/model/leads-csv.js.map +1 -1
  147. package/src/lib/model/tasks-csv.d.ts +1 -1
  148. package/src/lib/model/tasks-csv.js +1 -1
  149. package/src/lib/model/tasks-csv.js.map +1 -1
  150. package/src/lib/plan-entitlements.d.ts +75 -0
  151. package/src/lib/plan-entitlements.js +56 -0
  152. package/src/lib/plan-entitlements.js.map +1 -0
  153. package/src/lib/plugin.js +3 -0
  154. package/src/lib/plugin.js.map +1 -1
  155. package/src/lib/server/api-v1/contacts-merge.d.ts +20 -0
  156. package/src/lib/server/api-v1/contacts-merge.js +120 -0
  157. package/src/lib/server/api-v1/contacts-merge.js.map +1 -0
  158. package/src/lib/server/api-v1/contacts.d.ts +18 -0
  159. package/src/lib/server/api-v1/contacts.js +1076 -0
  160. package/src/lib/server/api-v1/contacts.js.map +1 -0
  161. package/src/lib/server/api-v1/crm-activities.d.ts +18 -0
  162. package/src/lib/server/api-v1/crm-activities.js +269 -0
  163. package/src/lib/server/api-v1/crm-activities.js.map +1 -0
  164. package/src/lib/server/api-v1/crm-companies.d.ts +18 -0
  165. package/src/lib/server/api-v1/crm-companies.js +391 -0
  166. package/src/lib/server/api-v1/crm-companies.js.map +1 -0
  167. package/src/lib/server/api-v1/crm-deals.d.ts +18 -0
  168. package/src/lib/server/api-v1/crm-deals.js +631 -0
  169. package/src/lib/server/api-v1/crm-deals.js.map +1 -0
  170. package/src/lib/server/api-v1/crm-email-templates.d.ts +18 -0
  171. package/src/lib/server/api-v1/crm-email-templates.js +336 -0
  172. package/src/lib/server/api-v1/crm-email-templates.js.map +1 -0
  173. package/src/lib/server/api-v1/crm-leads.d.ts +18 -0
  174. package/src/lib/server/api-v1/crm-leads.js +832 -0
  175. package/src/lib/server/api-v1/crm-leads.js.map +1 -0
  176. package/src/lib/server/api-v1/crm-pipelines.d.ts +76 -0
  177. package/src/lib/server/api-v1/crm-pipelines.js +146 -0
  178. package/src/lib/server/api-v1/crm-pipelines.js.map +1 -0
  179. package/src/lib/server/api-v1/crm-shared.d.ts +271 -0
  180. package/src/lib/server/api-v1/crm-shared.js +436 -0
  181. package/src/lib/server/api-v1/crm-shared.js.map +1 -0
  182. package/src/lib/server/api-v1/crm-tasks.d.ts +18 -0
  183. package/src/lib/server/api-v1/crm-tasks.js +398 -0
  184. package/src/lib/server/api-v1/crm-tasks.js.map +1 -0
  185. package/src/lib/server/api-v1/openapi.d.ts +29 -0
  186. package/src/lib/server/api-v1/openapi.js +985 -0
  187. package/src/lib/server/api-v1/openapi.js.map +1 -0
  188. package/src/lib/server/api-v1/usage.d.ts +26 -0
  189. package/src/lib/server/api-v1/usage.js +73 -0
  190. package/src/lib/server/api-v1/usage.js.map +1 -0
  191. package/src/lib/server/consent-group-participant.js +1 -1
  192. package/src/lib/server/consent-group-participant.js.map +1 -1
  193. package/src/lib/server/contact-lifecycle-floor.d.ts +89 -0
  194. package/src/lib/server/contact-lifecycle-floor.js +91 -0
  195. package/src/lib/server/contact-lifecycle-floor.js.map +1 -0
  196. package/src/lib/server/contact-remove.d.ts +75 -0
  197. package/src/lib/server/contact-remove.js +244 -0
  198. package/src/lib/server/contact-remove.js.map +1 -0
  199. package/src/lib/server/contact-update.js +2 -1
  200. package/src/lib/server/contact-update.js.map +1 -1
  201. package/src/lib/server/contacts-import.d.ts +47 -11
  202. package/src/lib/server/contacts-import.js +171 -71
  203. package/src/lib/server/contacts-import.js.map +1 -1
  204. package/src/lib/server/contacts-merge.d.ts +1 -1
  205. package/src/lib/server/contacts-merge.js +3 -2
  206. package/src/lib/server/contacts-merge.js.map +1 -1
  207. package/src/lib/server/convert-host-lead.d.ts +189 -0
  208. package/src/lib/server/convert-host-lead.js +518 -0
  209. package/src/lib/server/convert-host-lead.js.map +1 -0
  210. package/src/lib/server/crm-sharing.d.ts +108 -0
  211. package/src/lib/server/crm-sharing.js +790 -0
  212. package/src/lib/server/crm-sharing.js.map +1 -0
  213. package/src/lib/server/daily-digest-route.d.ts +107 -0
  214. package/src/lib/server/daily-digest-route.js +588 -0
  215. package/src/lib/server/daily-digest-route.js.map +1 -0
  216. package/src/lib/server/export-route.d.ts +60 -0
  217. package/src/lib/server/export-route.js +447 -0
  218. package/src/lib/server/export-route.js.map +1 -0
  219. package/src/lib/server/inbound-route.d.ts +74 -0
  220. package/src/lib/server/inbound-route.js +257 -0
  221. package/src/lib/server/inbound-route.js.map +1 -0
  222. package/src/lib/server/lead-convert.d.ts +1 -1
  223. package/src/lib/server/lead-convert.js +2 -2
  224. package/src/lib/server/lead-convert.js.map +1 -1
  225. package/src/lib/server/merge-contacts.d.ts +55 -0
  226. package/src/lib/server/merge-contacts.js +274 -0
  227. package/src/lib/server/merge-contacts.js.map +1 -0
  228. package/src/lib/server/pipeline-record-index.d.ts +36 -0
  229. package/src/lib/server/pipeline-record-index.js +87 -0
  230. package/src/lib/server/pipeline-record-index.js.map +1 -0
  231. package/src/lib/server/record-facts.js +2 -1
  232. package/src/lib/server/record-facts.js.map +1 -1
  233. package/src/lib/server/task-reminders-route.d.ts +82 -0
  234. package/src/lib/server/task-reminders-route.js +497 -0
  235. package/src/lib/server/task-reminders-route.js.map +1 -0
  236. package/src/lib/server-deal-stage.js +2 -1
  237. package/src/lib/server-deal-stage.js.map +1 -1
  238. package/src/lib/server.d.ts +5 -2
  239. package/src/lib/server.js +47 -2
  240. package/src/lib/server.js.map +1 -1
  241. package/src/lib/testing/stand-in-site-record-routes.d.ts +26 -0
  242. package/src/lib/testing/stand-in-site-record-routes.js +55 -0
  243. package/src/lib/testing/stand-in-site-record-routes.js.map +1 -0
  244. package/src/lib/usage-axes.d.ts +35 -0
  245. package/src/lib/usage-axes.js +68 -0
  246. package/src/lib/usage-axes.js.map +1 -0
  247. package/src/lib/components/use-emails-hub-path.d.ts +0 -24
  248. package/src/lib/components/use-emails-hub-path.js +0 -59
  249. package/src/lib/components/use-emails-hub-path.js.map +0 -1
@@ -82,8 +82,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
82
82
  * not undo the win: the deal is already closed, and the response reports
83
83
  * `customer: null` rather than a 500 for a stage change that did happen.
84
84
  */ import { CRM_COLLECTIONS, dealStageById, hostRoleFor, hostScopeToken, ORG_SCOPE_TOKEN } from "@aglyn/aglyn/server";
85
- import { consentGroupForSite, firebaseAdmin, floorContactLifecycleStage, getOrgForHost, logOrgActivity, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin";
85
+ import { consentGroupForSite, firebaseAdmin, getOrgForHost, logOrgActivity, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin";
86
86
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
87
+ import { floorContactLifecycleStage } from "./server/contact-lifecycle-floor.js";
87
88
  import { emitHostEvent } from "@aglyn/tenant-runtime";
88
89
  import { FieldValue } from "firebase-admin/firestore";
89
90
  import { closingStage, dealEventName, dealEventPayload } from "./model/deal-board-model.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server-deal-stage.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 * `POST /api/crm/deal-stage` — the one writer of a deal's stage (AGL-2598).\n *\n * ## Why a route, when the rules would let the browser do it\n *\n * A deal's title, amount and owner are edited client-direct against the\n * Firestore rules, and nothing about a stage change needs a server to be\n * SAFE. What it needs a server for is to be HEARD: a move between stages, a\n * win and a loss are the three moments an automation wants — \"when a deal is\n * won, email the owner\", \"when one reaches negotiation, file a task\" — and a\n * workflow only fires on an event the tenant runtime emits. A stage written\n * by the browser would be a fact nothing could react to. So every surface\n * that moves a deal calls here, and this handler updates the document and\n * then emits `dealStageChanged`, `dealWon` or `dealLost` with a flat payload\n * a workflow filter can read.\n *\n * ## Who may call it\n *\n * Three gates, in the order the cheapest fails first:\n *\n * 1. A verified Firebase session — the console's `authorizedFetch` puts the\n * id token on every call.\n * 2. An admin or editor role ON THIS SITE, resolved by `hostRoleFor` from\n * the org member document, which is the same projection the rules read.\n * 3. The `data.manage` permission in the org — the key the whole CRM is\n * gated on, resolved through the custom-role and per-member layers by\n * `memberHasOrgPermission`, because a member document alone cannot say\n * what a custom role took away.\n *\n * And then the deal has to be VISIBLE to the site: its `visibleTo` must\n * intersect the scope tokens a contact captured on this site would carry.\n * The Admin SDK evaluates no rules, so without this check an editor of one\n * site in an agency could move another client's deals by id.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, dealId, … }` instead of a site: the org-level hub's board. The\n * caller is authorized by the ORG — an org-wide member holding\n * `data.manage`, the org hub's own gate — and no visibility check is made,\n * because an org-wide member reads every row the org holds. The event\n * still goes to the deal's own capturing site, which is where the\n * automations that listen for it live; a deal no site captured has none to\n * tell. And the act is logged in the org's feed, since there is no one\n * site's feed it happened in.\n *\n * ## What it writes\n *\n * `stageId`, `status` (from the target stage's `kind`, never from the body),\n * `stageChangedAtMs`, `closedAtMs` (set on a close, cleared on a reopen) and\n * `lostReason` (kept on a loss, removed on anything else). A move to the\n * stage the deal is already in writes nothing and emits nothing — an\n * automation must not fire twice because a card was dropped where it was.\n *\n * ## A won deal makes its contact a customer (AGL-2641)\n *\n * A win is the same fact as a purchase — the business has decided this\n * person bought — and an order already floors a contact's lifecycle stage\n * at `customer` on capture. So the transition INTO `won` applies the same\n * floor to the contact the deal names, in the same write path, behind no\n * setting: `floorContactLifecycleStage` fills an empty stage or advances an\n * earlier one inside the facet of the site the deal was made on, and never\n * moves anybody back — a customer stays a customer, an evangelist an\n * evangelist. When the stage did move, `contactStageChanged` is announced\n * after `dealWon`, so an automation keyed on \"became a customer\" hears it,\n * and the org's activity line says so. A failure to write the contact does\n * not undo the win: the deal is already closed, and the response reports\n * `customer: null` rather than a 500 for a stage change that did happen.\n */\n\nimport {\n CRM_COLLECTIONS,\n type CrmDeal,\n type CrmPipeline,\n dealStageById,\n hostRoleFor,\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n type ContactLifecycleFloor,\n firebaseAdmin,\n floorContactLifecycleStage,\n getOrgForHost,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n closingStage,\n dealEventName,\n dealEventPayload,\n} from './model/deal-board-model'\nimport { authorizeOrgCaller, readCrmRouteScope } from './server/org-caller'\nimport { crmSuiteRefusal } from './server/suite-gate'\n\n/** The most a lost reason may carry — a sentence or two, not a post-mortem. */\nexport const LOST_REASON_MAX = 500\n\nexport const crmDealStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const routeScope = readCrmRouteScope(req.body as Record<string, unknown>)\n const dealId = String(req.body?.dealId ?? '').trim()\n const stageId =\n typeof req.body?.stageId === 'string' ? req.body.stageId.trim() : ''\n const status = req.body?.status\n const closing = status === 'won' || status === 'lost' ? status : null\n const lostReason = String(req.body?.lostReason ?? '')\n .trim()\n .slice(0, LOST_REASON_MAX)\n if (!routeScope || !dealId) {\n return res.status(400).json({ error: 'Missing hostId or dealId' })\n }\n if (!stageId && !closing) {\n return res.status(400).json({\n error: 'Name a stageId to move to, or a status of won or lost.',\n })\n }\n\n /*\n * Who is calling, and the org whose deal it is. The site variant\n * resolves the org from the site and the caller's role on it; the org\n * variant is authorized by the org itself, and the site the body may\n * name beside it is not consulted — the deal's own site, read off the\n * document, is the one its event goes to.\n */\n let orgId: string\n let org: Record<string, unknown>\n let actor: { uid: string; email: string | null } | null = null\n // Who moved the deal, at either level, for the runs it sets off (AGL-3376).\n let eventActor: { uid: string; email: string | null }\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'data.manage',\n refusal:\n 'Moving a deal at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.',\n })\n if (caller.ok === false) {\n return res.status(caller.status).json({ error: caller.error })\n }\n orgId = caller.orgId\n org = caller.org as Record<string, unknown>\n actor = { uid: caller.uid, email: caller.email }\n eventActor = actor\n } else {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n let uid: string\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n eventActor = {\n uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n }\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 res.status(401).json({ error: 'Unauthenticated' })\n console.error('[crm] deal-stage could not verify the caller', error)\n return res.status(500).json({ error: 'The sign-in could not be checked. Try again.' })\n }\n\n const owner = await getOrgForHost(routeScope.hostId).catch(() => null)\n if (!owner) {\n return res.status(404).json({\n error: 'This site has no organization, so it has no deals.',\n })\n }\n const membership = await resolveOrgMembership(uid, owner.orgId).catch(\n () => null,\n )\n const member = membership?.member\n const hostRole = hostRoleFor(member, routeScope.hostId)\n if (!member || (hostRole !== 'admin' && hostRole !== 'editor')) {\n return res.status(403).json({\n error: 'Moving a deal needs an admin or editor role on this site.',\n })\n }\n if (!(await memberHasOrgPermission(owner.orgId, member, 'data.manage'))) {\n return res.status(403).json({\n error: 'Moving a deal requires the \"Manage data\" permission.',\n })\n }\n orgId = owner.orgId\n org = owner.org as Record<string, unknown>\n }\n\n // Deals are the CRM suite's, at either level (AGL-2787).\n const suite = crmSuiteRefusal(org, 'Moving a deal through its pipeline')\n if (suite) return res.status(suite.status).json(suite.body)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const dealRef = orgRef.collection(CRM_COLLECTIONS.deals).doc(dealId)\n const dealSnapshot = await dealRef.get()\n if (!dealSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown deal' })\n }\n const deal = dealSnapshot.data() as CrmDeal\n\n if (routeScope.level === 'site') {\n const group = await consentGroupForSite(routeScope.hostId, org)\n const readable = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...group.hostIds.map(hostScopeToken),\n ])\n if (!(deal.visibleTo ?? []).some((token) => readable.has(token))) {\n return res.status(403).json({ error: 'This deal is not visible to this site.' })\n }\n }\n\n const pipelineSnapshot = await orgRef\n .collection(CRM_COLLECTIONS.pipelines)\n .doc(String(deal.pipelineId ?? ''))\n .get()\n if (!pipelineSnapshot.exists) {\n return res.status(409).json({\n error: \"This deal's pipeline no longer exists, so it has no stages to move to.\",\n })\n }\n const pipeline = pipelineSnapshot.data() as CrmPipeline\n const target = stageId\n ? dealStageById(pipeline, stageId)\n : closingStage(pipeline, closing as 'won' | 'lost')\n if (!target) {\n return res.status(400).json({\n error: stageId\n ? 'This pipeline has no such stage.'\n : `This pipeline has no ${closing} stage.`,\n })\n }\n\n const previousStageId = String(deal.stageId ?? '')\n const nextStatus = target.kind\n if (target.id === previousStageId && deal.status === nextStatus) {\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event: null,\n })\n }\n\n const nowMs = Date.now()\n await dealRef.update({\n stageId: target.id,\n status: nextStatus,\n stageChangedAtMs: nowMs,\n closedAtMs: nextStatus === 'open' ? null : nowMs,\n lostReason: nextStatus === 'lost' ? lostReason : FieldValue.delete(),\n updatedAt: new Date(),\n })\n\n const event = dealEventName(nextStatus)\n // The site whose automations hear the move: the mounted site, or at the\n // organization level the deal's own — a deal no site captured has none.\n const eventHostId =\n routeScope.level === 'site' ? routeScope.hostId : String(deal.hostId ?? '').trim()\n\n /*\n * The customer floor, on the transition into `won` alone: a move between\n * open stages, a loss and a reopen say nothing about whether the person\n * bought. The facet written is the site's the deal was made on — under\n * a site the mounted one, at the organization level the deal's own, and\n * for a deal no site captured the person's own capturing site.\n */\n let customer: ContactLifecycleFloor | null = null\n const contactId = String(deal.contactId ?? '').trim()\n if (nextStatus === 'won' && contactId) {\n customer = await floorContactLifecycleStage({\n contactRef: orgRef.collection('contacts').doc(contactId),\n org,\n hostId: eventHostId || null,\n floor: 'customer',\n }).catch((error: unknown) => {\n console.error('[crm] deal-stage: the customer floor failed', dealId, contactId, error)\n return null\n })\n }\n const becameCustomer = customer?.outcome === 'advanced'\n\n if (eventHostId) {\n await emitHostEvent(\n eventHostId,\n event,\n dealEventPayload(\n dealId,\n {\n ...deal,\n stageId: target.id,\n lostReason: nextStatus === 'lost' ? lostReason : undefined,\n },\n previousStageId,\n ),\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (customer?.outcome === 'advanced') {\n // The stage change is the win's effect, announced after its cause, to\n // the site whose facet moved — the same site as the win's, unless no\n // site captured the deal and the person's own site holds the stage.\n await emitHostEvent(\n customer.hostId,\n 'contactStageChanged',\n {\n contactId: customer.contactId,\n email: customer.email,\n lifecycleStage: customer.lifecycleStage,\n previousStage: customer.previousStage,\n },\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (actor) {\n await logOrgActivity(\n orgId,\n actor,\n nextStatus === 'won'\n ? becameCustomer\n ? 'Marked deal won — contact now a customer'\n : 'Marked deal won'\n : nextStatus === 'lost'\n ? 'Marked deal lost'\n : `Moved deal to ${target.name}`,\n { type: 'deal', id: dealId, name: String(deal.title ?? '') },\n )\n }\n\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event,\n /*\n * What the win did to the contact: the stage it now holds and whether\n * this call raised it. `null` on anything but a win, on a deal that\n * names no contact, and on a contact write that failed.\n */\n customer:\n customer && (customer.outcome === 'advanced' || customer.outcome === 'held')\n ? {\n contactId: customer.contactId,\n lifecycleStage: customer.lifecycleStage,\n advanced: customer.outcome === 'advanced',\n }\n : null,\n })\n}\n"],"names":["CRM_COLLECTIONS","dealStageById","hostRoleFor","hostScopeToken","ORG_SCOPE_TOKEN","consentGroupForSite","firebaseAdmin","floorContactLifecycleStage","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","emitHostEvent","FieldValue","closingStage","dealEventName","dealEventPayload","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","LOST_REASON_MAX","crmDealStageHandler","req","res","deal","method","setHeader","status","json","error","routeScope","body","dealId","String","trim","stageId","closing","lostReason","slice","orgId","org","actor","eventActor","level","caller","needs","refusal","ok","uid","email","authorization","headers","idToken","startsWith","length","decoded","app","auth","verifyIdToken","console","owner","hostId","catch","membership","member","hostRole","suite","firestore","orgRef","collection","doc","dealRef","deals","dealSnapshot","get","exists","data","group","readable","Set","hostIds","map","visibleTo","some","token","has","pipelineSnapshot","pipelines","pipelineId","pipeline","target","previousStageId","nextStatus","kind","id","event","nowMs","Date","now","update","stageChangedAtMs","closedAtMs","delete","updatedAt","eventHostId","customer","contactId","contactRef","floor","becameCustomer","outcome","undefined","lifecycleStage","previousStage","name","type","title","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SACEA,eAAe,EAGfC,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,eAAe,QAEV,sBAAqB;AAC5B,SACEC,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,QACA,aACKR;YACHW,SAASuD,OAAOI,EAAE;YAClBzD,YAAYuD,eAAe,SAASvD,aAAa0E;YAEnDpB,kBAEF;YAAElD,OAAO;gBAAEoD,MAAM;eAAanD;QAAa;IAE/C;IACA,IAAI+D,CAAAA,4BAAAA,SAAUK,OAAO,MAAK,YAAY;QACpC,sEAAsE;QACtE,qEAAqE;QACrE,oEAAoE;QACpE,MAAMlG,cACJ6F,SAAS5C,MAAM,EACf,uBACA;YACE6C,WAAWD,SAASC,SAAS;YAC7BzD,OAAOwD,SAASxD,KAAK;YACrB+D,gBAAgBP,SAASO,cAAc;YACvCC,eAAeR,SAASQ,aAAa;QACvC,GACA;YAAExE,OAAO;gBAAEoD,MAAM;eAAanD;QAAa;IAE/C;IACA,IAAID,OAAO;YAWkCjB;QAV3C,MAAMhB,eACJ+B,OACAE,OACAmD,eAAe,QACXiB,iBACE,6CACA,oBACFjB,eAAe,SACb,qBACA,CAAC,cAAc,EAAEF,OAAOwB,IAAI,EAAE,EACpC;YAAEC,MAAM;YAAQrB,IAAI9D;YAAQkF,MAAMjF,QAAOT,cAAAA,KAAK4F,KAAK,YAAV5F,cAAc;QAAI;IAE/D;IAEA,OAAOD,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;QAC1BmB,IAAI;QACJf;QACAG,SAASuD,OAAOI,EAAE;QAClBnE,QAAQiE;QACRD;QACAI;QACA;;;;KAIC,GACDU,UACEA,YAAaA,CAAAA,SAASK,OAAO,KAAK,cAAcL,SAASK,OAAO,KAAK,MAAK,IACtE;YACEJ,WAAWD,SAASC,SAAS;YAC7BM,gBAAgBP,SAASO,cAAc;YACvCK,UAAUZ,SAASK,OAAO,KAAK;QACjC,IACA;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server-deal-stage.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 * `POST /api/crm/deal-stage` — the one writer of a deal's stage (AGL-2598).\n *\n * ## Why a route, when the rules would let the browser do it\n *\n * A deal's title, amount and owner are edited client-direct against the\n * Firestore rules, and nothing about a stage change needs a server to be\n * SAFE. What it needs a server for is to be HEARD: a move between stages, a\n * win and a loss are the three moments an automation wants — \"when a deal is\n * won, email the owner\", \"when one reaches negotiation, file a task\" — and a\n * workflow only fires on an event the tenant runtime emits. A stage written\n * by the browser would be a fact nothing could react to. So every surface\n * that moves a deal calls here, and this handler updates the document and\n * then emits `dealStageChanged`, `dealWon` or `dealLost` with a flat payload\n * a workflow filter can read.\n *\n * ## Who may call it\n *\n * Three gates, in the order the cheapest fails first:\n *\n * 1. A verified Firebase session — the console's `authorizedFetch` puts the\n * id token on every call.\n * 2. An admin or editor role ON THIS SITE, resolved by `hostRoleFor` from\n * the org member document, which is the same projection the rules read.\n * 3. The `data.manage` permission in the org — the key the whole CRM is\n * gated on, resolved through the custom-role and per-member layers by\n * `memberHasOrgPermission`, because a member document alone cannot say\n * what a custom role took away.\n *\n * And then the deal has to be VISIBLE to the site: its `visibleTo` must\n * intersect the scope tokens a contact captured on this site would carry.\n * The Admin SDK evaluates no rules, so without this check an editor of one\n * site in an agency could move another client's deals by id.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, dealId, … }` instead of a site: the org-level hub's board. The\n * caller is authorized by the ORG — an org-wide member holding\n * `data.manage`, the org hub's own gate — and no visibility check is made,\n * because an org-wide member reads every row the org holds. The event\n * still goes to the deal's own capturing site, which is where the\n * automations that listen for it live; a deal no site captured has none to\n * tell. And the act is logged in the org's feed, since there is no one\n * site's feed it happened in.\n *\n * ## What it writes\n *\n * `stageId`, `status` (from the target stage's `kind`, never from the body),\n * `stageChangedAtMs`, `closedAtMs` (set on a close, cleared on a reopen) and\n * `lostReason` (kept on a loss, removed on anything else). A move to the\n * stage the deal is already in writes nothing and emits nothing — an\n * automation must not fire twice because a card was dropped where it was.\n *\n * ## A won deal makes its contact a customer (AGL-2641)\n *\n * A win is the same fact as a purchase — the business has decided this\n * person bought — and an order already floors a contact's lifecycle stage\n * at `customer` on capture. So the transition INTO `won` applies the same\n * floor to the contact the deal names, in the same write path, behind no\n * setting: `floorContactLifecycleStage` fills an empty stage or advances an\n * earlier one inside the facet of the site the deal was made on, and never\n * moves anybody back — a customer stays a customer, an evangelist an\n * evangelist. When the stage did move, `contactStageChanged` is announced\n * after `dealWon`, so an automation keyed on \"became a customer\" hears it,\n * and the org's activity line says so. A failure to write the contact does\n * not undo the win: the deal is already closed, and the response reports\n * `customer: null` rather than a 500 for a stage change that did happen.\n */\n\nimport {\n CRM_COLLECTIONS,\n type CrmDeal,\n type CrmPipeline,\n dealStageById,\n hostRoleFor,\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n type ContactLifecycleFloor,\n floorContactLifecycleStage,\n} from './server/contact-lifecycle-floor'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n closingStage,\n dealEventName,\n dealEventPayload,\n} from './model/deal-board-model'\nimport { authorizeOrgCaller, readCrmRouteScope } from './server/org-caller'\nimport { crmSuiteRefusal } from './server/suite-gate'\n\n/** The most a lost reason may carry — a sentence or two, not a post-mortem. */\nexport const LOST_REASON_MAX = 500\n\nexport const crmDealStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const routeScope = readCrmRouteScope(req.body as Record<string, unknown>)\n const dealId = String(req.body?.dealId ?? '').trim()\n const stageId =\n typeof req.body?.stageId === 'string' ? req.body.stageId.trim() : ''\n const status = req.body?.status\n const closing = status === 'won' || status === 'lost' ? status : null\n const lostReason = String(req.body?.lostReason ?? '')\n .trim()\n .slice(0, LOST_REASON_MAX)\n if (!routeScope || !dealId) {\n return res.status(400).json({ error: 'Missing hostId or dealId' })\n }\n if (!stageId && !closing) {\n return res.status(400).json({\n error: 'Name a stageId to move to, or a status of won or lost.',\n })\n }\n\n /*\n * Who is calling, and the org whose deal it is. The site variant\n * resolves the org from the site and the caller's role on it; the org\n * variant is authorized by the org itself, and the site the body may\n * name beside it is not consulted — the deal's own site, read off the\n * document, is the one its event goes to.\n */\n let orgId: string\n let org: Record<string, unknown>\n let actor: { uid: string; email: string | null } | null = null\n // Who moved the deal, at either level, for the runs it sets off (AGL-3376).\n let eventActor: { uid: string; email: string | null }\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'data.manage',\n refusal:\n 'Moving a deal at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.',\n })\n if (caller.ok === false) {\n return res.status(caller.status).json({ error: caller.error })\n }\n orgId = caller.orgId\n org = caller.org as Record<string, unknown>\n actor = { uid: caller.uid, email: caller.email }\n eventActor = actor\n } else {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n let uid: string\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n eventActor = {\n uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n }\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 res.status(401).json({ error: 'Unauthenticated' })\n console.error('[crm] deal-stage could not verify the caller', error)\n return res.status(500).json({ error: 'The sign-in could not be checked. Try again.' })\n }\n\n const owner = await getOrgForHost(routeScope.hostId).catch(() => null)\n if (!owner) {\n return res.status(404).json({\n error: 'This site has no organization, so it has no deals.',\n })\n }\n const membership = await resolveOrgMembership(uid, owner.orgId).catch(\n () => null,\n )\n const member = membership?.member\n const hostRole = hostRoleFor(member, routeScope.hostId)\n if (!member || (hostRole !== 'admin' && hostRole !== 'editor')) {\n return res.status(403).json({\n error: 'Moving a deal needs an admin or editor role on this site.',\n })\n }\n if (!(await memberHasOrgPermission(owner.orgId, member, 'data.manage'))) {\n return res.status(403).json({\n error: 'Moving a deal requires the \"Manage data\" permission.',\n })\n }\n orgId = owner.orgId\n org = owner.org as Record<string, unknown>\n }\n\n // Deals are the CRM suite's, at either level (AGL-2787).\n const suite = crmSuiteRefusal(org, 'Moving a deal through its pipeline')\n if (suite) return res.status(suite.status).json(suite.body)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const dealRef = orgRef.collection(CRM_COLLECTIONS.deals).doc(dealId)\n const dealSnapshot = await dealRef.get()\n if (!dealSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown deal' })\n }\n const deal = dealSnapshot.data() as CrmDeal\n\n if (routeScope.level === 'site') {\n const group = await consentGroupForSite(routeScope.hostId, org)\n const readable = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...group.hostIds.map(hostScopeToken),\n ])\n if (!(deal.visibleTo ?? []).some((token) => readable.has(token))) {\n return res.status(403).json({ error: 'This deal is not visible to this site.' })\n }\n }\n\n const pipelineSnapshot = await orgRef\n .collection(CRM_COLLECTIONS.pipelines)\n .doc(String(deal.pipelineId ?? ''))\n .get()\n if (!pipelineSnapshot.exists) {\n return res.status(409).json({\n error: \"This deal's pipeline no longer exists, so it has no stages to move to.\",\n })\n }\n const pipeline = pipelineSnapshot.data() as CrmPipeline\n const target = stageId\n ? dealStageById(pipeline, stageId)\n : closingStage(pipeline, closing as 'won' | 'lost')\n if (!target) {\n return res.status(400).json({\n error: stageId\n ? 'This pipeline has no such stage.'\n : `This pipeline has no ${closing} stage.`,\n })\n }\n\n const previousStageId = String(deal.stageId ?? '')\n const nextStatus = target.kind\n if (target.id === previousStageId && deal.status === nextStatus) {\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event: null,\n })\n }\n\n const nowMs = Date.now()\n await dealRef.update({\n stageId: target.id,\n status: nextStatus,\n stageChangedAtMs: nowMs,\n closedAtMs: nextStatus === 'open' ? null : nowMs,\n lostReason: nextStatus === 'lost' ? lostReason : FieldValue.delete(),\n updatedAt: new Date(),\n })\n\n const event = dealEventName(nextStatus)\n // The site whose automations hear the move: the mounted site, or at the\n // organization level the deal's own — a deal no site captured has none.\n const eventHostId =\n routeScope.level === 'site' ? routeScope.hostId : String(deal.hostId ?? '').trim()\n\n /*\n * The customer floor, on the transition into `won` alone: a move between\n * open stages, a loss and a reopen say nothing about whether the person\n * bought. The facet written is the site's the deal was made on — under\n * a site the mounted one, at the organization level the deal's own, and\n * for a deal no site captured the person's own capturing site.\n */\n let customer: ContactLifecycleFloor | null = null\n const contactId = String(deal.contactId ?? '').trim()\n if (nextStatus === 'won' && contactId) {\n customer = await floorContactLifecycleStage({\n contactRef: orgRef.collection('contacts').doc(contactId),\n org,\n hostId: eventHostId || null,\n floor: 'customer',\n }).catch((error: unknown) => {\n console.error('[crm] deal-stage: the customer floor failed', dealId, contactId, error)\n return null\n })\n }\n const becameCustomer = customer?.outcome === 'advanced'\n\n if (eventHostId) {\n await emitHostEvent(\n eventHostId,\n event,\n dealEventPayload(\n dealId,\n {\n ...deal,\n stageId: target.id,\n lostReason: nextStatus === 'lost' ? lostReason : undefined,\n },\n previousStageId,\n ),\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (customer?.outcome === 'advanced') {\n // The stage change is the win's effect, announced after its cause, to\n // the site whose facet moved — the same site as the win's, unless no\n // site captured the deal and the person's own site holds the stage.\n await emitHostEvent(\n customer.hostId,\n 'contactStageChanged',\n {\n contactId: customer.contactId,\n email: customer.email,\n lifecycleStage: customer.lifecycleStage,\n previousStage: customer.previousStage,\n },\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (actor) {\n await logOrgActivity(\n orgId,\n actor,\n nextStatus === 'won'\n ? becameCustomer\n ? 'Marked deal won — contact now a customer'\n : 'Marked deal won'\n : nextStatus === 'lost'\n ? 'Marked deal lost'\n : `Moved deal to ${target.name}`,\n { type: 'deal', id: dealId, name: String(deal.title ?? '') },\n )\n }\n\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event,\n /*\n * What the win did to the contact: the stage it now holds and whether\n * this call raised it. `null` on anything but a win, on a deal that\n * names no contact, and on a contact write that failed.\n */\n customer:\n customer && (customer.outcome === 'advanced' || customer.outcome === 'held')\n ? {\n contactId: customer.contactId,\n lifecycleStage: customer.lifecycleStage,\n advanced: customer.outcome === 'advanced',\n }\n : null,\n })\n}\n"],"names":["CRM_COLLECTIONS","dealStageById","hostRoleFor","hostScopeToken","ORG_SCOPE_TOKEN","consentGroupForSite","firebaseAdmin","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","floorContactLifecycleStage","emitHostEvent","FieldValue","closingStage","dealEventName","dealEventPayload","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","LOST_REASON_MAX","crmDealStageHandler","req","res","deal","method","setHeader","status","json","error","routeScope","body","dealId","String","trim","stageId","closing","lostReason","slice","orgId","org","actor","eventActor","level","caller","needs","refusal","ok","uid","email","authorization","headers","idToken","startsWith","length","decoded","app","auth","verifyIdToken","console","owner","hostId","catch","membership","member","hostRole","suite","firestore","orgRef","collection","doc","dealRef","deals","dealSnapshot","get","exists","data","group","readable","Set","hostIds","map","visibleTo","some","token","has","pipelineSnapshot","pipelines","pipelineId","pipeline","target","previousStageId","nextStatus","kind","id","event","nowMs","Date","now","update","stageChangedAtMs","closedAtMs","delete","updatedAt","eventHostId","customer","contactId","contactRef","floor","becameCustomer","outcome","undefined","lifecycleStage","previousStage","name","type","title","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SACEA,eAAe,EAGfC,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,eAAe,QAEV,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAEEC,0BAA0B,QACrB,sCAAkC;AACzC,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,YAAY,EACZC,aAAa,EACbC,gBAAgB,QACX,8BAA0B;AACjC,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,yBAAqB;AAC3E,SAASC,eAAe,QAAQ,yBAAqB;AAErD,6EAA6E,GAC7E,OAAO,MAAMC,kBAAkB,IAAG;AAElC,OAAO,MAAMC,sBAAwC,OAAOC,KAAKC;qBA6HjDC,kBAmBiBA,eA2B4BA,cAUlCA;QA9KHF,WAEbA,YACMA,YAEWA;IAX1B,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzBF,IAAIG,SAAS,CAAC,SAAS;QACvB,OAAOH,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IAEA,MAAMC,aAAaZ,kBAAkBI,IAAIS,IAAI;IAC7C,MAAMC,SAASC,gBAAOX,YAAAA,IAAIS,IAAI,qBAART,UAAUU,MAAM,mBAAI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IAAI;QACJf;QACAG,SAASuD,OAAOI,EAAE;QAClBnE,QAAQiE;QACRD;QACAI;QACA;;;;KAIC,GACDU,UACEA,YAAaA,CAAAA,SAASK,OAAO,KAAK,cAAcL,SAASK,OAAO,KAAK,MAAK,IACtE;YACEJ,WAAWD,SAASC,SAAS;YAC7BM,gBAAgBP,SAASO,cAAc;YACvCK,UAAUZ,SAASK,OAAO,KAAK;QACjC,IACA;IACR;AACF,EAAC"}
@@ -46,8 +46,10 @@
46
46
  * holder's rows and the audience band are judgments the browser cannot make.
47
47
  * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:
48
48
  * the rules cannot tell one field of a holder's facet from another, so they
49
- * leave a client nothing there but letting a holder go, and the plan is
50
- * asked here about the fields a save carries.
49
+ * leave a client nothing there, and the plan is asked here about the fields
50
+ * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a
51
+ * contact go: the refusals the document holds are kept, which a client
52
+ * write could not be trusted to do.
51
53
  */
52
54
  import { type PluginApiHandler } from '@aglyn/aglyn/server';
53
55
  /**
@@ -148,3 +150,4 @@ export declare const CONTACT_BAND_FULL_MESSAGE: string;
148
150
  export declare const crmContactsCreateHandler: PluginApiHandler;
149
151
  /** Console API registration, named in `plugins.config.json` as `consoleApi`. */
150
152
  export declare function registerCrmConsoleApi(): void;
153
+ export type { crmPlanEntitlements } from './plan-entitlements';
package/src/lib/server.js CHANGED
@@ -46,8 +46,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
46
46
  * holder's rows and the audience band are judgments the browser cannot make.
47
47
  * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:
48
48
  * the rules cannot tell one field of a holder's facet from another, so they
49
- * leave a client nothing there but letting a holder go, and the plan is
50
- * asked here about the fields a save carries.
49
+ * leave a client nothing there, and the plan is asked here about the fields
50
+ * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a
51
+ * contact go: the refusals the document holds are kept, which a client
52
+ * write could not be trusted to do.
51
53
  */ import { CONTACT_ERASED_MESSAGE, contactFacetPath, CRM_COLLECTIONS, crmReadTokens, isContactLifecycleStage, isOrgWideMember, normalizeAddress, normalizeContactEmail, normalizePhone, readContactFacet, registerPluginApiRoute, visibleToHost } from "@aglyn/aglyn/server";
52
54
  import { consentGroupForSite, firebaseAdmin, getOrgForHost, logHostActivity, memberHasOrgPermission, orgDataCollectionForHost, resolveOrgMembership, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
53
55
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
@@ -82,8 +84,11 @@ import { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from "./server/erase-pe
82
84
  import { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from "./server/org-activity.js";
83
85
  import { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from "./server/inbound-address.js";
84
86
  import { crmCompanyDeleteHandler } from "./server/company-delete.js";
87
+ import { crmSharingHandler } from "./server/crm-sharing.js";
88
+ import { CRM_SHARING_ROUTE } from "./model/crm-sharing.js";
85
89
  import { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from "./server/contact-profile.js";
86
90
  import { crmContactUpdateHandler } from "./server/contact-update.js";
91
+ import { crmContactRemoveHandler } from "./server/contact-remove.js";
87
92
  import { CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE, crmEmailTemplateDuplicateHandler } from "./server/email-template-duplicate.js";
88
93
  import { registerCrmRecordFactsReaders } from "./server/record-facts.js";
89
94
  import { crmSuiteRefusal } from "./server/suite-gate.js";
@@ -577,6 +582,7 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
577
582
  // Every other console write to a contact's facets (AGL-2804): the rules
578
583
  // cannot tell one facet field from another, so the plan is asked here.
579
584
  registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler);
585
+ registerPluginApiRoute(CRM_API_ROUTES.contactRemove, crmContactRemoveHandler);
580
586
  // A company's contacts unlinked, then the company (AGL-2804): the unlink
581
587
  // clears a facet, which is the server's to write.
582
588
  registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler);
@@ -589,6 +595,10 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
589
595
  // What a client-direct write the browser cannot follow up asks for: the
590
596
  // fields the CRM lists query, restamped from the record (AGL-3321).
591
597
  registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler);
598
+ // Sharing records with other sites (AGL-3336): a manager's share and
599
+ // unshare, the org's sharing rules and their recompute, and the rules'
600
+ // re-evaluation a client-direct write owes.
601
+ registerPluginApiRoute(CRM_SHARING_ROUTE, crmSharingHandler);
592
602
  // A lead source value renamed or deleted (AGL-3298): the list and every
593
603
  // lead and contact holding the old label, in one request.
594
604
  registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler);
@@ -654,6 +664,41 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
654
664
  // and rotated here, behind the CRM's own gate, and the org document that
655
665
  // carries it is closed to every client.
656
666
  registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler);
667
+ /*
668
+ * The three doors a MACHINE calls (AGL-3080), at the paths they have
669
+ * always answered on: the scheduler's daily digest and hourly task
670
+ * reminders, on the cron secret, and the mail provider's capture webhook,
671
+ * on its signature. None names a site or a member, so each is registered
672
+ * as a machine's route — the dispatcher leaves the plugin's release and
673
+ * enablement gates and its write limit to it — and each judges the CRM's
674
+ * plan and flag for every organization it resolves. Loaded with the
675
+ * first call, not with the surface.
676
+ */ registerPluginApiRoute(CRM_API_ROUTES.dailyDigest, {
677
+ web: async (request)=>(await import("./server/daily-digest-route.js")).crmDailyDigestRoute(request)
678
+ }, {
679
+ machine: true
680
+ });
681
+ registerPluginApiRoute(CRM_API_ROUTES.taskReminders, {
682
+ web: async (request)=>(await import("./server/task-reminders-route.js")).crmTaskRemindersRoute(request)
683
+ }, {
684
+ machine: true
685
+ });
686
+ registerPluginApiRoute(CRM_API_ROUTES.inbound, {
687
+ web: async (request)=>(await import("./server/inbound-route.js")).crmInboundRoute(request)
688
+ }, {
689
+ machine: true
690
+ });
691
+ /*
692
+ * The whole-collection export (AGL-2662). A portability route: the people
693
+ * files — contacts and leads — are what a workspace is owed on every plan
694
+ * and whether or not the CRM is switched on for it, so the dispatcher
695
+ * leaves its release and enablement gates to the route, which asks both
696
+ * of the CRM's own records. Loaded with the first export.
697
+ */ registerPluginApiRoute(CRM_API_ROUTES.export, {
698
+ web: async (request)=>(await import("./server/export-route.js")).crmExportRoute(request)
699
+ }, {
700
+ portability: true
701
+ });
657
702
  registerPluginApiRoute(CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE, crmEmailTemplateDuplicateHandler);
658
703
  // The facts of a contact, company, deal or lead, and an import's field
659
704
  // catalog, for another plugin in this process (AGL-2917): read on the core's
@@ -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; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door 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 but letting a holder go, and the plan is\n * asked here about the fields a save carries.\n */\n\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\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 { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\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 } from './model/lead-source-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 } from './server/lead-source-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\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 { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler } from './server/contact-update'\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? }`. 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 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\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 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 ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\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 { type: 'contact', id: result.contactId, name: name || email },\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 /*\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 // 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 // A lead source value renamed or deleted (AGL-3298): the list and every\n // lead and contact holding the old label, in one request.\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\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 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"],"names":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","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","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","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","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","companyDelete","save","complete","emailSend"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,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,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,4BAA4B,QAAQ,gCAA4B;AACzE,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SAASC,0BAA0B,QAAQ,iCAA6B;AACxE,SAASC,iCAAiC,QAAQ,iCAA6B;AAC/E,SAASC,+BAA+B,QAAQ,8BAA0B;AAC1E,SAASC,sBAAsB,EAAEC,kBAAkB,QAAQ,0BAAsB;AACjF,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAAS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oE;IACpE,iEAAiE;IACjExC,uBAAuBc,eAAegK,SAAS,EAAE5I;IACjD,yEAAyE;IACzE,oEAAoE;IACpE,uEAAuE;IACvE,oDAAoD;IACpDlC,uBAAuBmC,uBAAuBC;IAC9C,yEAAyE;IACzE,uEAAuE;IACvE,0EAA0E;IAC1EpC,uBAAuByC,sBAAsBC;IAC7C,iEAAiE;IACjE,yBAAyB;IACzB1C,uBAAuB2C,wBAAwBC;IAC/C,wEAAwE;IACxE,yEAAyE;IACzE,6CAA6C;IAC7C5C,uBAAuB6C,wBAAwBC;IAC/C,qEAAqE;IACrE,yEAAyE;IACzE,wEAAwE;IACxE9C,uBAAuB0D,0BAA0BE;IACjD5D,uBAAuB2D,yBAAyBE;IAChD,wEAAwE;IACxE,yEAAyE;IACzE,wCAAwC;IACxC7D,uBAAuB+C,2BAA2BC;IAClDhD,uBACEsD,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; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door 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 {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\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 { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\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 } from './model/lead-source-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 } from './server/lead-source-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\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 } from './server/contact-update'\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? }`. 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 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\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 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 ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\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 { type: 'contact', id: result.contactId, name: name || email },\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 /*\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 lead source value renamed or deleted (AGL-3298): the list and every\n // lead and contact holding the old label, in one request.\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\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 /*\n * The whole-collection export (AGL-2662). A portability route: the people\n * files — contacts and leads — are what a workspace is owed on every plan\n * and whether or not the CRM is switched on for it, so the dispatcher\n * leaves its release and enablement gates to the route, which asks both\n * of the CRM's own records. Loaded with the first export.\n */\n registerPluginApiRoute(\n CRM_API_ROUTES.export,\n {\n web: async (request) => (await import('./server/export-route')).crmExportRoute(request),\n },\n { portability: 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":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","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","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","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","contactRemove","companyDelete","save","complete","emailSend","dailyDigest","web","request","crmDailyDigestRoute","machine","taskReminders","crmTaskRemindersRoute","inbound","crmInboundRoute","export","crmExportRoute","portability"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,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,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,4BAA4B,QAAQ,gCAA4B;AACzE,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SA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,CAACJ;IAC1E,GACA;QAAEE,SAAS;IAAK;IAElBvL,uBACEc,eAAe4K,OAAO,EACtB;QACEN,KAAK,OAAOC,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,4BAAwB,EAAGM,eAAe,CAACN;IACnF,GACA;QAAEE,SAAS;IAAK;IAElB;;;;;;GAMC,GACDvL,uBACEc,eAAe8K,MAAM,EACrB;QACER,KAAK,OAAOC,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGQ,cAAc,CAACR;IACjF,GACA;QAAES,aAAa;IAAK;IAEtB9L,uBACEyD,oCACAC;IAEF,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpElC;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;AACF"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The record routes of the plugins a contact's captured history points back
19
+ * at — the inbox's `formSubmission`, commerce's `order`, bookings' `booking`
20
+ * (AGL-3080) — stood in for this plugin's specs, which may not load those
21
+ * plugins. Each answers what its owner publishes, at a site; what each owner
22
+ * publishes is held in its own `*-record-routes.spec.ts`. Registered under
23
+ * the owners' ids, so a spec asking what happens where one is not loaded
24
+ * unregisters that plugin's services.
25
+ */
26
+ export declare function standInSiteRecordRoutes(): void;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { registerPluginRecordRoute } from "@aglyn/aglyn/plugin-manager/plugin-record-routes";
17
+ /**
18
+ * The record routes of the plugins a contact's captured history points back
19
+ * at — the inbox's `formSubmission`, commerce's `order`, bookings' `booking`
20
+ * (AGL-3080) — stood in for this plugin's specs, which may not load those
21
+ * plugins. Each answers what its owner publishes, at a site; what each owner
22
+ * publishes is held in its own `*-record-routes.spec.ts`. Registered under
23
+ * the owners' ids, so a spec asking what happens where one is not loaded
24
+ * unregisters that plugin's services.
25
+ */ export function standInSiteRecordRoutes() {
26
+ const site = (orgSlug, host)=>host ? `/${orgSlug}/hosts/${host}` : null;
27
+ const query = (key, value)=>new URLSearchParams({
28
+ [key]: value
29
+ }).toString();
30
+ registerPluginRecordRoute('formSubmission', {
31
+ list: ({ orgSlug, host })=>{
32
+ var _site;
33
+ return `${(_site = site(orgSlug, host)) != null ? _site : `/${orgSlug}`}/inbox/submissions`;
34
+ },
35
+ record: ({ orgSlug, host }, id)=>host ? `${site(orgSlug, host)}/inbox/submissions?${query('submission', id)}` : null
36
+ }, {
37
+ pluginId: 'inbox'
38
+ });
39
+ registerPluginRecordRoute('order', {
40
+ list: ({ orgSlug, host })=>host ? `${site(orgSlug, host)}/products/orders` : null,
41
+ record: ({ orgSlug, host }, id)=>host ? `${site(orgSlug, host)}/products/orders?${query('order', id)}` : null,
42
+ byEmail: ({ orgSlug, host }, email)=>host ? `${site(orgSlug, host)}/products/orders?${query('email', email)}` : null
43
+ }, {
44
+ pluginId: 'commerce'
45
+ });
46
+ registerPluginRecordRoute('booking', {
47
+ list: ({ orgSlug, host })=>host ? `${site(orgSlug, host)}/bookings` : null,
48
+ record: ({ orgSlug, host })=>host ? `${site(orgSlug, host)}/bookings` : null,
49
+ byEmail: ({ orgSlug, host }, email)=>host ? `${site(orgSlug, host)}/bookings?${query('email', email)}` : null
50
+ }, {
51
+ pluginId: 'bookings'
52
+ });
53
+ }
54
+
55
+ //# sourceMappingURL=stand-in-site-record-routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/testing/stand-in-site-record-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerPluginRecordRoute } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\n\n/**\n * The record routes of the plugins a contact's captured history points back\n * at — the inbox's `formSubmission`, commerce's `order`, bookings' `booking`\n * (AGL-3080) — stood in for this plugin's specs, which may not load those\n * plugins. Each answers what its owner publishes, at a site; what each owner\n * publishes is held in its own `*-record-routes.spec.ts`. Registered under\n * the owners' ids, so a spec asking what happens where one is not loaded\n * unregisters that plugin's services.\n */\nexport function standInSiteRecordRoutes(): void {\n const site = (orgSlug: string, host: string | null) => (host ? `/${orgSlug}/hosts/${host}` : null)\n const query = (key: string, value: string) => new URLSearchParams({ [key]: value }).toString()\n registerPluginRecordRoute(\n 'formSubmission',\n {\n list: ({ orgSlug, host }) => `${site(orgSlug, host) ?? `/${orgSlug}`}/inbox/submissions`,\n record: ({ orgSlug, host }, id) =>\n host ? `${site(orgSlug, host)}/inbox/submissions?${query('submission', id)}` : null,\n },\n { pluginId: 'inbox' },\n )\n registerPluginRecordRoute(\n 'order',\n {\n list: ({ orgSlug, host }) => (host ? `${site(orgSlug, host)}/products/orders` : null),\n record: ({ orgSlug, host }, id) =>\n host ? `${site(orgSlug, host)}/products/orders?${query('order', id)}` : null,\n byEmail: ({ orgSlug, host }, email) =>\n host ? `${site(orgSlug, host)}/products/orders?${query('email', email)}` : null,\n },\n { pluginId: 'commerce' },\n )\n registerPluginRecordRoute(\n 'booking',\n {\n list: ({ orgSlug, host }) => (host ? `${site(orgSlug, host)}/bookings` : null),\n record: ({ orgSlug, host }) => (host ? `${site(orgSlug, host)}/bookings` : null),\n byEmail: ({ orgSlug, host }, email) =>\n host ? `${site(orgSlug, host)}/bookings?${query('email', email)}` : null,\n },\n { pluginId: 'bookings' },\n )\n}\n"],"names":["registerPluginRecordRoute","standInSiteRecordRoutes","site","orgSlug","host","query","key","value","URLSearchParams","toString","list","record","id","pluginId","byEmail","email"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,mDAAkD;AAE5F;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,MAAMC,OAAO,CAACC,SAAiBC,OAAyBA,OAAO,CAAC,CAAC,EAAED,QAAQ,OAAO,EAAEC,MAAM,GAAG;IAC7F,MAAMC,QAAQ,CAACC,KAAaC,QAAkB,IAAIC,gBAAgB;YAAE,CAACF,IAAI,EAAEC;QAAM,GAAGE,QAAQ;IAC5FT,0BACE,kBACA;QACEU,MAAM,CAAC,EAAEP,OAAO,EAAEC,IAAI,EAAE;gBAAQF;mBAAH,IAAGA,QAAAA,KAAKC,SAASC,iBAAdF,QAAuB,CAAC,CAAC,EAAEC,SAAS,CAAC,kBAAkB,CAAC;;QACxFQ,QAAQ,CAAC,EAAER,OAAO,EAAEC,IAAI,EAAE,EAAEQ,KAC1BR,OAAO,GAAGF,KAAKC,SAASC,MAAM,m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