@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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-sharing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * CRM SHARING FOR MULTI-BRAND ORGS (AGL-3336).\n *\n * An org manager shares a lead, a contact, a company or a deal with other\n * sites — by hand, from the record or a list's bulk bar, or by a SHARING\n * RULE that applies to every record it matches, now and later. The model is\n * Salesforce's three layers:\n *\n * 1. the org-wide default — the consent-group scope a record is captured\n * with (`consentGroupScope`), untouched by anything here;\n * 2. sharing rules — `crm.sharingRules` on the org document;\n * 3. manual shares — per record, per target.\n *\n * ## One field is enforced, so one field is widened\n *\n * Both enforcement layers read `visibleTo`: the rules with `hasAny`, every\n * list with `array-contains-any`. A share therefore ADDS its tokens to\n * `visibleTo`, which is what puts the record on the target site's lists as a\n * real query — no second field, no second index, no loaded-window match.\n * `'org'` is the token for \"all sites\", and it covers a site created later\n * with nothing to recompute, because every site's read set carries it.\n *\n * ## …and the sources stay distinguishable\n *\n * The record keeps its grants under `sharing` (`SCOPE_GRANTS_FIELD` in\n * core): one grant per rule and one per hand-shared target, and `added`,\n * the tokens the grants put on `visibleTo` that were not there already.\n * The record's own scope — its HELD tokens — is `visibleTo` without\n * `added`, so taking a grant away removes only what grants alone\n * contributed, and never a consent-group token. A token a site later\n * captures the person on is held from then on: the capturing sites\n * (`hostId`, `capturedByHostIds`) are never counted as added.\n *\n * ## Visibility is not consent, and not write access\n *\n * Nothing here reads or writes a consent entry. A site a record is shared\n * with sees it; it holds no basis to market to the person, and the\n * audience paths read `heldByHost`, not `visibleTo`. Write access is its\n * own field, `writeTo`, present only on a shared record: the held tokens\n * and the tokens of grants whose access is `edit`. The Firestore rules and\n * the CRM's routes check it; a read-only grant is the default.\n */\n\nimport type { ScopeToken } from '@aglyn/aglyn'\nimport {\n heldScopeTokens,\n hostIdsFromScope,\n hostScopeToken,\n isScopeToken,\n MAX_SCOPE_HOSTS,\n ORG_SCOPE_TOKEN,\n parseScopeToken,\n SCOPE_GRANTS_FIELD,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\n\n/*==========================================\n * WHAT IS SHARED.\n *=========================================*/\n\n/** The four record types a share or a rule applies to, by their collection. */\nexport const CRM_SHARING_OBJECTS = ['leads', 'contacts', 'companies', 'deals'] as const\nexport type CrmSharingObject = (typeof CRM_SHARING_OBJECTS)[number]\n\nexport function isCrmSharingObject(value: unknown): value is CrmSharingObject {\n return (\n typeof value === 'string' && (CRM_SHARING_OBJECTS as readonly string[]).includes(value)\n )\n}\n\n/** How each object reads in a sentence. */\nexport const CRM_SHARING_OBJECT_LABELS: Readonly<\n Record<CrmSharingObject, { one: string; many: string }>\n> = {\n leads: { one: 'lead', many: 'Leads' },\n contacts: { one: 'contact', many: 'Contacts' },\n companies: { one: 'company', many: 'Companies' },\n deals: { one: 'deal', many: 'Deals' },\n}\n\n/** What a target site may do with a shared record. Read-only unless a grant says edit. */\nexport type CrmShareAccess = 'read' | 'edit'\n\nexport function isCrmShareAccess(value: unknown): value is CrmShareAccess {\n return value === 'read' || value === 'edit'\n}\n\n/** Where a grant came from. */\nexport type CrmShareSource = 'manual' | 'rule'\n\n/** One grant on one record. */\nexport interface CrmShareGrant {\n source: CrmShareSource\n /** The sites it shares with: `['org']` for all sites, else host tokens. */\n tokens: ScopeToken[]\n access: CrmShareAccess\n /** The rule behind a `rule` grant. */\n ruleId?: string\n /** Who shared it by hand, as they were named at the time. */\n byUid?: string\n byName?: string\n /** When the grant was made. */\n atMs: number\n}\n\n/** `sharing` on a record — see the module note. */\nexport interface CrmRecordSharing {\n /** Keyed by {@link manualGrantKey} or {@link ruleGrantKey}. */\n grants: Record<string, CrmShareGrant>\n /** Every token any grant names — the record's shares, however held. */\n tokens: ScopeToken[]\n /** The tokens the grants ADDED to `visibleTo` — see `heldScopeTokens`. */\n added: ScopeToken[]\n /** The rules holding a grant here, so a rule's removal can find its records. */\n ruleIds: string[]\n /**\n * The held tokens of a record shared with all sites, and nothing\n * otherwise. `array-contains` on it answers \"is this record shared with\n * everyone AND held by site X\" — the one question `added` alone cannot,\n * since a query takes a single array clause.\n */\n orgWideHeldBy: ScopeToken[]\n}\n\n/** The record field its grants live under — the core's name for it. */\nexport const CRM_SHARING_FIELD = SCOPE_GRANTS_FIELD\n\n/** The record field naming who may WRITE it, present only while it is shared. */\nexport const CRM_WRITE_SCOPE_FIELD = 'writeTo'\n\n/** The array field a rule's removal queries. */\nexport const CRM_SHARING_RULE_IDS_PATH = `${CRM_SHARING_FIELD}.ruleIds`\n\n/** A hand share is one grant per target, so each is unshared on its own. */\nexport function manualGrantKey(token: string): string {\n const parsed = parseScopeToken(token)\n if (!parsed) throw new Error(`not a scope token: ${token}`)\n return parsed.kind === 'org' ? 'manual_org' : `manual_${parsed.hostId}`\n}\n\nexport function ruleGrantKey(ruleId: string): string {\n return `rule_${ruleId}`\n}\n\nfunction tokenList(raw: unknown): ScopeToken[] {\n if (!Array.isArray(raw)) return []\n return [...new Set(raw.filter(isScopeToken))]\n}\n\nfunction readGrant(raw: unknown): CrmShareGrant | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const tokens = tokenList(value['tokens'])\n if (!tokens.length) return null\n const source = value['source'] === 'rule' ? 'rule' : value['source'] === 'manual' ? 'manual' : null\n if (!source) return null\n const ruleId = typeof value['ruleId'] === 'string' ? value['ruleId'] : ''\n if (source === 'rule' && !ruleId) return null\n const byUid = typeof value['byUid'] === 'string' ? value['byUid'] : ''\n const byName = typeof value['byName'] === 'string' ? value['byName'] : ''\n const atMs = typeof value['atMs'] === 'number' && Number.isFinite(value['atMs']) ? value['atMs'] : 0\n return {\n source,\n tokens,\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(ruleId ? { ruleId } : {}),\n ...(byUid ? { byUid } : {}),\n ...(byName ? { byName } : {}),\n atMs,\n }\n}\n\n/** A record's grants, cleaned; `{}` for a record never shared. */\nexport function readRecordGrants(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): Record<string, CrmShareGrant> {\n const sharing = (record ?? {})[CRM_SHARING_FIELD]\n if (!sharing || typeof sharing !== 'object' || Array.isArray(sharing)) return {}\n const grants = (sharing as Record<string, unknown>)['grants']\n if (!grants || typeof grants !== 'object' || Array.isArray(grants)) return {}\n const out: Record<string, CrmShareGrant> = {}\n for (const [key, raw] of Object.entries(grants as Record<string, unknown>)) {\n const grant = readGrant(raw)\n if (grant) out[key] = grant\n }\n return out\n}\n\n/*==========================================\n * THE PLAN: grants in, the three fields out.\n *=========================================*/\n\n/**\n * The sites that captured or created the record. Their tokens are HELD,\n * whatever `added` says: a person shared to site B and later captured on B\n * is B's own from then on, and unsharing must not hide them from B.\n */\nexport function recordHolderHostIds(record: Readonly<Record<string, unknown>>): string[] {\n const ids = new Set<string>()\n const hostId = record['hostId']\n if (typeof hostId === 'string' && hostId) ids.add(hostId)\n const captured = record['capturedByHostIds']\n if (Array.isArray(captured)) {\n for (const id of captured) if (typeof id === 'string' && id) ids.add(id)\n }\n return [...ids]\n}\n\n/**\n * The record's own scope: `visibleTo` less what grants added, its capturing\n * sites kept — the core's `heldScopeTokens`, as scope tokens.\n */\nexport function recordHeldScope(record: Readonly<Record<string, unknown>>): ScopeToken[] {\n return tokenList(heldScopeTokens(record))\n}\n\nexport interface CrmSharingPlan {\n visibleTo: ScopeToken[]\n /** `null` removes the field: an unshared record writes by `visibleTo`. */\n writeTo: ScopeToken[] | null\n /** `null` removes the field. */\n sharing: CrmRecordSharing | null\n}\n\n/**\n * The fields a record carries under `grants`.\n *\n * A grant naming a token the record already holds adds nothing, and a\n * record held org-wide adds nothing at all — every site sees it already, so\n * a share there would only make a later unshare look like it hid something.\n * The token order is the held scope first and the additions after it, so an\n * unchanged record plans the `visibleTo` it has.\n */\nexport function planRecordSharing(\n record: Readonly<Record<string, unknown>>,\n grants: Readonly<Record<string, CrmShareGrant>>,\n): CrmSharingPlan {\n const held = recordHeldScope(record)\n const entries = Object.entries(grants)\n if (!entries.length) return { visibleTo: held, writeTo: null, sharing: null }\n const heldSet = new Set<string>(held)\n const heldOrgWide = heldSet.has(ORG_SCOPE_TOKEN)\n const tokens: ScopeToken[] = []\n const editTokens: ScopeToken[] = []\n const ruleIds: string[] = []\n for (const [, grant] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n for (const token of grant.tokens) {\n if (!tokens.includes(token)) tokens.push(token)\n if (grant.access === 'edit' && !editTokens.includes(token)) editTokens.push(token)\n }\n if (grant.source === 'rule' && grant.ruleId && !ruleIds.includes(grant.ruleId)) {\n ruleIds.push(grant.ruleId)\n }\n }\n const added = heldOrgWide ? [] : tokens.filter((token) => !heldSet.has(token))\n const writeTo = [...held]\n for (const token of editTokens) if (!writeTo.includes(token)) writeTo.push(token)\n return {\n visibleTo: [...held, ...added],\n writeTo,\n sharing: {\n grants: Object.fromEntries(entries),\n tokens,\n added,\n ruleIds,\n orgWideHeldBy: added.includes(ORG_SCOPE_TOKEN) ? [...held] : [],\n },\n }\n}\n\nconst sameList = (a: readonly unknown[] | null | undefined, b: readonly unknown[] | null | undefined) =>\n (a ?? null) === null\n ? (b ?? null) === null\n : (b ?? null) !== null && a!.length === b!.length && a!.every((entry, at) => entry === b![at])\n\nconst sameGrant = (a: CrmShareGrant | undefined, b: CrmShareGrant | undefined) =>\n !!a &&\n !!b &&\n a.source === b.source &&\n a.access === b.access &&\n (a.ruleId ?? '') === (b.ruleId ?? '') &&\n (a.byUid ?? '') === (b.byUid ?? '') &&\n (a.byName ?? '') === (b.byName ?? '') &&\n a.atMs === b.atMs &&\n sameList(a.tokens, b.tokens)\n\n/** Whether writing `plan` would change what the record stores. */\nexport function sharingPlanChanges(\n record: Readonly<Record<string, unknown>>,\n plan: CrmSharingPlan,\n): boolean {\n if (!sameList(tokenList(record['visibleTo']), plan.visibleTo)) return true\n const storedWrite = record[CRM_WRITE_SCOPE_FIELD]\n if (!sameList(Array.isArray(storedWrite) ? tokenList(storedWrite) : null, plan.writeTo)) return true\n const stored = record[CRM_SHARING_FIELD]\n if (!plan.sharing) return stored !== undefined && stored !== null\n const grants = readRecordGrants(record)\n const keys = Object.keys(plan.sharing.grants)\n if (keys.length !== Object.keys(grants).length) return true\n if (!keys.every((key) => sameGrant(grants[key], plan.sharing!.grants[key]))) return true\n const sharing = (stored ?? {}) as Record<string, unknown>\n return (\n !sameList(tokenList(sharing['tokens']), plan.sharing.tokens) ||\n !sameList(tokenList(sharing['added']), plan.sharing.added) ||\n !sameList(\n Array.isArray(sharing['ruleIds']) ? (sharing['ruleIds'] as unknown[]) : [],\n plan.sharing.ruleIds,\n ) ||\n !sameList(tokenList(sharing['orgWideHeldBy']), plan.sharing.orgWideHeldBy)\n )\n}\n\n/*==========================================\n * SHARING RULES: `crm.sharingRules` on the org document.\n *=========================================*/\n\n/** The org document path the rules are stored under. */\nexport const CRM_SHARING_RULES_PATH = 'crm.sharingRules'\n\n/** A workspace keeps at most this many. */\nexport const CRM_SHARING_RULES_MAX = 20\n\n/** At most this many values per criterion. */\nexport const CRM_SHARING_CRITERION_MAX = 20\n\n/**\n * Which records a rule matches, beyond the object and the capturing site.\n * AND across the keys, OR within one; an absent or empty key matches\n * everything.\n */\nexport interface CrmSharingCriteria {\n /** A lead's or a contact's lead source, by label. */\n leadSources?: string[]\n /** Any of these tags (lead, contact, company). */\n tags?: string[]\n /** Filed under any of these campaigns (lead, contact). */\n campaignIds?: string[]\n /** A lead's status, a contact's lifecycle stage, or a deal's stage id. */\n stages?: string[]\n /** Owned by any of these members. */\n ownerUids?: string[]\n}\n\nexport const CRM_SHARING_CRITERIA_KEYS = [\n 'leadSources',\n 'tags',\n 'campaignIds',\n 'stages',\n 'ownerUids',\n] as const satisfies readonly (keyof CrmSharingCriteria)[]\n\n/** Which criteria an object's records can answer. */\nexport const CRM_SHARING_CRITERIA_FOR: Readonly<\n Record<CrmSharingObject, readonly (keyof CrmSharingCriteria)[]>\n> = {\n leads: ['leadSources', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n contacts: ['leadSources', 'tags', 'campaignIds', 'stages', 'ownerUids'],\n companies: ['tags', 'ownerUids'],\n deals: ['stages', 'ownerUids'],\n}\n\n/** Where a rule's recompute stands. */\nexport interface CrmSharingRuleRun {\n status: 'running' | 'done' | 'failed'\n /** What the run does: apply the rule everywhere, or take it away. */\n mode: 'apply' | 'remove'\n /** Records examined. */\n processed: number\n /** Records whose sharing changed. */\n changed: number\n /** The last record id an `apply` run examined, to continue after. */\n cursor?: string | null\n startedAtMs: number\n finishedAtMs?: number\n error?: string\n}\n\nexport interface CrmSharingRule {\n id: string\n name: string\n object: CrmSharingObject\n /** Off keeps the rule and takes away what it granted. */\n enabled: boolean\n /** Records captured or created on any of these sites; empty is every site. */\n sourceHostIds: string[]\n criteria: CrmSharingCriteria\n /** `['org']` for all sites, including sites added later; else host tokens. */\n targets: ScopeToken[]\n access: CrmShareAccess\n /** Being deleted: its grants are being removed, and it matches nothing. */\n deleting?: boolean\n createdByUid?: string\n createdAtMs: number\n updatedAtMs: number\n run?: CrmSharingRuleRun\n}\n\nconst RULE_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nfunction stringList(raw: unknown, max = CRM_SHARING_CRITERION_MAX): string[] {\n if (!Array.isArray(raw)) return []\n const out: string[] = []\n for (const entry of raw) {\n const value = String(entry ?? '').trim().slice(0, 200)\n if (value && !out.includes(value)) out.push(value)\n if (out.length >= max) break\n }\n return out\n}\n\n/** One rule as stored, cleaned, or null when it cannot be applied. */\nexport function readCrmSharingRule(raw: unknown): CrmSharingRule | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const value = raw as Record<string, unknown>\n const id = String(value['id'] ?? '')\n if (!RULE_ID.test(id)) return null\n if (!isCrmSharingObject(value['object'])) return null\n const targets = normalizeShareTargets(tokenList(value['targets']))\n if (!targets) return null\n const rawCriteria = (value['criteria'] ?? {}) as Record<string, unknown>\n const criteria: CrmSharingCriteria = {}\n for (const key of CRM_SHARING_CRITERIA_FOR[value['object']]) {\n const list = stringList(rawCriteria[key])\n if (list.length) criteria[key] = key === 'tags' ? list.map((tag) => tag.toLowerCase()) : list\n }\n const run = value['run'] as Record<string, unknown> | undefined\n return {\n id,\n name: String(value['name'] ?? '').trim().slice(0, 120) || 'Sharing rule',\n object: value['object'],\n enabled: value['enabled'] !== false,\n sourceHostIds: stringList(value['sourceHostIds'], MAX_SCOPE_HOSTS),\n criteria,\n targets,\n access: value['access'] === 'edit' ? 'edit' : 'read',\n ...(value['deleting'] === true ? { deleting: true } : {}),\n ...(typeof value['createdByUid'] === 'string' ? { createdByUid: value['createdByUid'] } : {}),\n createdAtMs: Number(value['createdAtMs']) || 0,\n updatedAtMs: Number(value['updatedAtMs']) || 0,\n ...(run && typeof run === 'object'\n ? {\n run: {\n status:\n run['status'] === 'done' || run['status'] === 'failed' ? run['status'] : 'running',\n mode: run['mode'] === 'remove' ? 'remove' : 'apply',\n processed: Number(run['processed']) || 0,\n changed: Number(run['changed']) || 0,\n cursor: typeof run['cursor'] === 'string' ? run['cursor'] : null,\n startedAtMs: Number(run['startedAtMs']) || 0,\n ...(typeof run['finishedAtMs'] === 'number' ? { finishedAtMs: run['finishedAtMs'] } : {}),\n ...(typeof run['error'] === 'string' ? { error: run['error'] } : {}),\n },\n }\n : {}),\n }\n}\n\n/** The org's sharing rules, in their stored order. */\nexport function readCrmSharingRules(\n org: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingRule[] {\n const crm = (org ?? {})['crm']\n const raw =\n crm && typeof crm === 'object' && !Array.isArray(crm)\n ? (crm as Record<string, unknown>)['sharingRules']\n : undefined\n if (!Array.isArray(raw)) return []\n const out: CrmSharingRule[] = []\n for (const entry of raw) {\n const rule = readCrmSharingRule(entry)\n if (rule && !out.some((existing) => existing.id === rule.id)) out.push(rule)\n }\n return out\n}\n\n/** The rules that grant anything now: enabled, and not being deleted. */\nexport function activeSharingRules(\n rules: readonly CrmSharingRule[],\n object?: CrmSharingObject,\n): CrmSharingRule[] {\n return rules.filter(\n (rule) => rule.enabled && !rule.deleting && (!object || rule.object === object),\n )\n}\n\n/**\n * A share's targets, cleaned for storage: `['org']` when all sites are\n * named, else the host tokens, capped. `null` when nothing is left.\n */\nexport function normalizeShareTargets(tokens: readonly string[]): ScopeToken[] | null {\n const clean = tokenList(tokens)\n if (!clean.length) return null\n if (clean.includes(ORG_SCOPE_TOKEN)) return [ORG_SCOPE_TOKEN]\n if (clean.length > MAX_SCOPE_HOSTS) return null\n return clean\n}\n\n/** Targets from a request: `'all'`, or a list of host ids. */\nexport function shareTargetsFrom(input: unknown): ScopeToken[] | null {\n if (input === 'all') return [ORG_SCOPE_TOKEN]\n if (!Array.isArray(input)) return null\n return normalizeShareTargets(\n input\n .map((id) => String(id ?? '').trim())\n .filter((id) => id && !id.includes('/') && !id.includes(':'))\n .map(hostScopeToken),\n )\n}\n\n/*==========================================\n * WHAT A RULE READS OFF A RECORD.\n *=========================================*/\n\nexport interface CrmSharingFacts {\n hostIds: string[]\n leadSources: string[]\n tags: string[]\n campaignIds: string[]\n stages: string[]\n ownerUids: string[]\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\nconst strs = (value: unknown): string[] =>\n Array.isArray(value) ? value.map(str).filter(Boolean) : []\n\n/**\n * The facts a rule's criteria are matched against. A contact keeps each\n * holder's working fields in its own facet, so a contact answers with the\n * union of its facets: a rule about \"contacts tagged vip\" matches a person\n * any holder tagged.\n */\nexport function crmSharingFacts(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n): CrmSharingFacts {\n const facts: CrmSharingFacts = {\n hostIds: recordHolderHostIds(record),\n leadSources: [],\n tags: [],\n campaignIds: [],\n stages: [],\n ownerUids: [],\n }\n const take = (source: Readonly<Record<string, unknown>>, stageField: string | null) => {\n const leadSource = str(source['leadSource'])\n if (leadSource) facts.leadSources.push(leadSource)\n facts.tags.push(...strs(source['tags']).map((tag) => tag.toLowerCase()))\n facts.campaignIds.push(...strs(source['campaignIds']))\n const stage = stageField ? str(source[stageField]) : ''\n if (stage) facts.stages.push(stage)\n const owner = str(source['ownerUid'])\n if (owner) facts.ownerUids.push(owner)\n }\n if (object === 'leads') take(record, 'status')\n else if (object === 'companies') take(record, null)\n else if (object === 'deals') take(record, 'stageId')\n else {\n const facets = record['facets']\n if (facets && typeof facets === 'object' && !Array.isArray(facets)) {\n for (const facet of Object.values(facets as Record<string, unknown>)) {\n if (facet && typeof facet === 'object' && !Array.isArray(facet)) {\n take(facet as Record<string, unknown>, 'lifecycleStage')\n }\n }\n }\n }\n // A lead with no status is New, as every lead reader answers it.\n if (object === 'leads' && !facts.stages.length) facts.stages.push('new')\n return facts\n}\n\nconst anyOf = (wanted: readonly string[] | undefined, have: readonly string[], fold = false) => {\n if (!wanted?.length) return true\n const set = new Set(fold ? have.map((value) => value.toLowerCase()) : have)\n return wanted.some((value) => set.has(fold ? value.toLowerCase() : value))\n}\n\n/** Whether a rule shares this record. */\nexport function crmSharingRuleMatches(\n rule: CrmSharingRule,\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n): boolean {\n if (!rule.enabled || rule.deleting || rule.object !== object) return false\n const facts = crmSharingFacts(object, record)\n if (rule.sourceHostIds.length && !facts.hostIds.some((id) => rule.sourceHostIds.includes(id))) {\n return false\n }\n const { criteria } = rule\n return (\n anyOf(criteria.leadSources, facts.leadSources, true) &&\n anyOf(criteria.tags, facts.tags, true) &&\n anyOf(criteria.campaignIds, facts.campaignIds) &&\n anyOf(criteria.stages, facts.stages) &&\n anyOf(criteria.ownerUids, facts.ownerUids)\n )\n}\n\n/**\n * The grants a record should carry: its hand shares as they are, and one\n * grant per active rule that matches it now. A rule grant already present\n * keeps its date, so re-evaluating an unchanged record writes nothing.\n *\n * A rule grant whose rule is not among `rules` is dropped — the caller\n * passes every active rule of the org, so a rule absent from them has been\n * switched off or deleted.\n */\nexport function evaluateRecordGrants(\n object: CrmSharingObject,\n record: Readonly<Record<string, unknown>>,\n rules: readonly CrmSharingRule[],\n atMs: number,\n): Record<string, CrmShareGrant> {\n const current = readRecordGrants(record)\n const next: Record<string, CrmShareGrant> = {}\n for (const [key, grant] of Object.entries(current)) {\n if (grant.source === 'manual') next[key] = grant\n }\n for (const rule of activeSharingRules(rules, object)) {\n if (!crmSharingRuleMatches(rule, object, record)) continue\n const key = ruleGrantKey(rule.id)\n const before = current[key]\n next[key] = {\n source: 'rule',\n ruleId: rule.id,\n tokens: [...rule.targets],\n access: rule.access,\n atMs: before && sameList(before.tokens, rule.targets) && before.access === rule.access\n ? before.atMs\n : atMs,\n }\n }\n return next\n}\n\n/** The hand shares after sharing with `targets`, by `by`. */\nexport function withManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly ScopeToken[],\n access: CrmShareAccess,\n by: { uid: string; name?: string | null },\n atMs: number,\n): Record<string, CrmShareGrant> {\n const next = { ...grants }\n for (const token of targets) {\n const name = String(by.name ?? '').trim()\n next[manualGrantKey(token)] = {\n source: 'manual',\n tokens: [token],\n access,\n byUid: by.uid,\n ...(name ? { byName: name } : {}),\n atMs,\n }\n }\n return next\n}\n\n/** The hand shares after unsharing `targets`. Rule grants are the rule's to take away. */\nexport function withoutManualShares(\n grants: Readonly<Record<string, CrmShareGrant>>,\n targets: readonly string[],\n): Record<string, CrmShareGrant> {\n const drop = new Set(targets.filter(isScopeToken).map(manualGrantKey))\n return Object.fromEntries(Object.entries(grants).filter(([key]) => !drop.has(key)))\n}\n\n/*==========================================\n * WHAT A READER SEES.\n *=========================================*/\n\n/**\n * Whether a caller holding `tokens` may write the record: `writeTo` on a\n * shared record, else `visibleTo` — the Firestore rules' own predicate.\n */\nexport function crmRecordWritableBy(\n record: Readonly<Record<string, unknown>>,\n tokens: readonly string[],\n): boolean {\n const writeTo = record[CRM_WRITE_SCOPE_FIELD]\n const scope = Array.isArray(writeTo) ? writeTo : record['visibleTo']\n if (!Array.isArray(scope) || !tokens.length) return false\n return scope.some((token) => tokens.includes(token as string))\n}\n\n/** How a record reached a site that sees it only through a share. */\nexport interface CrmShareChip {\n source: CrmShareSource\n access: CrmShareAccess\n /** The member who shared it by hand. */\n byName?: string\n /** The rule that shared it. */\n ruleId?: string\n /** Shared with every site. */\n allSites: boolean\n}\n\n/**\n * Why a site seeing this record sees it, when the answer is a share — or\n * `null` when the site holds it (or cannot see it at all). `hostIds` are\n * the viewing group's sites; at the organization level there is none.\n */\nexport function crmShareChipFor(\n record: Readonly<Record<string, unknown>> | null | undefined,\n hostIds: readonly string[],\n): CrmShareChip | null {\n if (!record || !hostIds.length) return null\n const held = recordHeldScope(record)\n if (held.includes(ORG_SCOPE_TOKEN)) return null\n const viewing = new Set(hostIds.map(hostScopeToken))\n if (held.some((token) => viewing.has(token))) return null\n const grants = Object.values(readRecordGrants(record))\n const reaching = grants.filter((grant) =>\n grant.tokens.some((token) => token === ORG_SCOPE_TOKEN || viewing.has(token)),\n )\n if (!reaching.length) return null\n // A hand share names a person, so it leads; an edit grant outranks read.\n const pick =\n reaching.find((grant) => grant.source === 'manual' && grant.access === 'edit') ??\n reaching.find((grant) => grant.source === 'manual') ??\n reaching.find((grant) => grant.access === 'edit') ??\n reaching[0]\n return {\n source: pick.source,\n access: reaching.some((grant) => grant.access === 'edit') ? 'edit' : 'read',\n ...(pick.byName ? { byName: pick.byName } : {}),\n ...(pick.ruleId ? { ruleId: pick.ruleId } : {}),\n allSites: pick.tokens.includes(ORG_SCOPE_TOKEN),\n }\n}\n\n/** The chip's words: \"Shared by Dana\", \"Shared by rule Brand A leads\". */\nexport function crmShareChipLabel(\n chip: CrmShareChip,\n rules: readonly Pick<CrmSharingRule, 'id' | 'name'>[] = [],\n): string {\n if (chip.source === 'manual') return chip.byName ? `Shared by ${chip.byName}` : 'Shared by hand'\n const rule = rules.find((entry) => entry.id === chip.ruleId)\n return rule ? `Shared by rule ${rule.name}` : 'Shared by a rule'\n}\n\n/** One line of a record's Sharing card. */\nexport type CrmSharingLine =\n | { kind: 'held'; hostIds: string[]; allSites: boolean }\n | {\n kind: 'manual'\n key: string\n token: ScopeToken\n access: CrmShareAccess\n byName?: string\n atMs: number\n }\n | { kind: 'rule'; key: string; ruleId: string; tokens: ScopeToken[]; access: CrmShareAccess; atMs: number }\n\n/**\n * Where a record is visible and why: the sites that hold it (its consent\n * group or its creating site), then one line per hand share, then one per\n * rule. The held line is never unsharable; a hand share is, in one click.\n */\nexport function describeRecordSharing(\n record: Readonly<Record<string, unknown>> | null | undefined,\n): CrmSharingLine[] {\n if (!record) return []\n const held = recordHeldScope(record)\n const lines: CrmSharingLine[] = [\n { kind: 'held', hostIds: hostIdsFromScope(held), allSites: held.includes(ORG_SCOPE_TOKEN) },\n ]\n const grants = Object.entries(readRecordGrants(record))\n for (const [key, grant] of grants) {\n if (grant.source !== 'manual') continue\n lines.push({\n kind: 'manual',\n key,\n token: grant.tokens[0],\n access: grant.access,\n ...(grant.byName ? { byName: grant.byName } : {}),\n atMs: grant.atMs,\n })\n }\n for (const [key, grant] of grants) {\n if (grant.source !== 'rule' || !grant.ruleId) continue\n lines.push({\n kind: 'rule',\n key,\n ruleId: grant.ruleId,\n tokens: grant.tokens,\n access: grant.access,\n atMs: grant.atMs,\n })\n }\n return lines\n}\n\n/** \"All sites\", a site's name, or \"N sites\". */\nexport function describeShareTargets(\n tokens: readonly string[],\n siteName: (hostId: string) => string,\n): string {\n if (tokens.includes(ORG_SCOPE_TOKEN)) return 'All sites'\n const ids = hostIdsFromScope(tokens)\n if (ids.length === 1) return siteName(ids[0])\n if (ids.length <= 3) return ids.map(siteName).join(', ')\n return `${ids.length} sites`\n}\n\n/** A rule as one sentence of its \"which records\" half. */\nexport function describeSharingRuleScope(\n rule: Pick<CrmSharingRule, 'object' | 'sourceHostIds' | 'criteria'>,\n siteName: (hostId: string) => string,\n labels: { owner?: (uid: string) => string; stage?: (id: string) => string } = {},\n): string {\n const parts: string[] = [CRM_SHARING_OBJECT_LABELS[rule.object].many]\n if (rule.sourceHostIds.length) {\n parts.push(`captured on ${rule.sourceHostIds.map(siteName).join(' or ')}`)\n }\n const { criteria } = rule\n if (criteria.leadSources?.length) parts.push(`from ${criteria.leadSources.join(' or ')}`)\n if (criteria.tags?.length) parts.push(`tagged ${criteria.tags.join(' or ')}`)\n if (criteria.campaignIds?.length) {\n parts.push(`in ${criteria.campaignIds.length === 1 ? 'a campaign' : `${criteria.campaignIds.length} campaigns`}`)\n }\n if (criteria.stages?.length) {\n parts.push(`at ${criteria.stages.map((id) => labels.stage?.(id) ?? id).join(' or ')}`)\n }\n if (criteria.ownerUids?.length) {\n parts.push(`owned by ${criteria.ownerUids.map((uid) => labels.owner?.(uid) ?? uid).join(' or ')}`)\n }\n return parts.join(', ')\n}\n\n/*==========================================\n * THE ROUTE.\n *=========================================*/\n\n/** `POST /api/crm/sharing` — every sharing act, by `action`. */\nexport const CRM_SHARING_ROUTE = 'crm/sharing' as const\n\nexport const crmSharingRouteUrl = (): string => `/api/${CRM_SHARING_ROUTE}`\n\n/** Records one share or unshare may name. */\nexport const CRM_SHARING_IDS_MAX = 200\n\nexport type CrmSharingAction =\n | 'sites'\n | 'share'\n | 'unshare'\n | 'evaluate'\n | 'rule-save'\n | 'rule-delete'\n | 'rule-continue'\n\nexport interface CrmSharingSite {\n id: string\n name: string\n}\n\nexport interface CrmSharingResponse {\n ok: true\n /** `sites`: the org's sites, by name. */\n sites?: CrmSharingSite[]\n /** `share`/`unshare`/`evaluate`: records whose sharing changed. */\n changed?: number\n /** Records named that could not be found. */\n missing?: number\n /** The rule a rule action saved or ran. */\n rule?: CrmSharingRule | null\n /** Whether a rule run has more to do (`rule-continue` again). */\n more?: boolean\n}\n"],"names":["heldScopeTokens","hostIdsFromScope","hostScopeToken","isScopeToken","MAX_SCOPE_HOSTS","ORG_SCOPE_TOKEN","parseScopeToken","SCOPE_GRANTS_FIELD","CRM_SHARING_OBJECTS","isCrmSharingObject","value","includes","CRM_SHARING_OBJECT_LABELS","leads","one","many","contacts","companies","deals","isCrmShareAccess","CRM_SHARING_FIELD","CRM_WRITE_SCOPE_FIELD","CRM_SHARING_RULE_IDS_PATH","manualGrantKey","token","parsed","Error","kind","hostId","ruleGrantKey","ruleId","tokenList","raw","Array","isArray","Set","filter","readGrant","tokens","length","source","byUid","byName","atMs","Number","isFinite","access","readRecordGrants","record","sharing","grants","out","key","Object","entries","grant","recordHolderHostIds","ids","add","captured","id","recordHeldScope","planRecordSharing","held","visibleTo","writeTo","heldSet","heldOrgWide","has","editTokens","ruleIds","sort","a","b","push","added","fromEntries","orgWideHeldBy","sameList","every","entry","at","sameGrant","sharingPlanChanges","plan","storedWrite","stored","undefined","keys","CRM_SHARING_RULES_PATH","CRM_SHARING_RULES_MAX","CRM_SHARING_CRITERION_MAX","CRM_SHARING_CRITERIA_KEYS","CRM_SHARING_CRITERIA_FOR","RULE_ID","stringList","max","String","trim","slice","readCrmSharingRule","test","targets","normalizeShareTargets","rawCriteria","criteria","list","map","tag","toLowerCase","run","name","object","enabled","sourceHostIds","deleting","createdByUid","createdAtMs","updatedAtMs","status","mode","processed","changed","cursor","startedAtMs","finishedAtMs","error","readCrmSharingRules","org","crm","rule","some","existing","activeSharingRules","rules","clean","shareTargetsFrom","input","str","strs","Boolean","crmSharingFacts","facts","hostIds","leadSources","tags","campaignIds","stages","ownerUids","take","stageField","leadSource","stage","owner","facets","facet","values","anyOf","wanted","have","fold","set","crmSharingRuleMatches","evaluateRecordGrants","current","next","before","withManualShares","by","uid","withoutManualShares","drop","crmRecordWritableBy","scope","crmShareChipFor","reaching","viewing","pick","find","allSites","crmShareChipLabel","chip","describeRecordSharing","lines","describeShareTargets","siteName","join","describeSharingRuleScope","labels","parts","CRM_SHARING_ROUTE","crmSharingRouteUrl","CRM_SHARING_IDS_MAX"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC;AAGD,SACEA,eAAe,EACfC,gBAAgB,EAChBC,cAAc,EACdC,YAAY,EACZC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,kBAAkB,QACb,sCAAqC;AAE5C;;2CAE2C,GAE3C,6EAA6E,GAC7E,OAAO,MAAMC,sBAAsB;IAAC;IAAS;IAAY;IAAa;CAAQ,CAAS;AAGvF,OAAO,SAASC,mBAAmBC,KAAc;IAC/C,OACE,OAAOA,UAAU,YAAY,AAACF,oBAA0CG,QAAQ,CAACD;AAErF;AAEA,yCAAyC,GACzC,OAAO,MAAME,4BAET;IACFC,OAAO;QAAEC,KAAK;QAAQC,MAAM;IAAQ;IACpCC,UAAU;QAAEF,KAAK;QAAWC,MAAM;IAAW;IAC7CE,WAAW;QAAEH,KAAK;QAAWC,MAAM;IAAY;IAC/CG,OAAO;QAAEJ,KAAK;QAAQC,MAAM;IAAQ;AACtC,EAAC;AAKD,OAAO,SAASI,iBAAiBT,KAAc;IAC7C,OAAOA,UAAU,UAAUA,UAAU;AACvC;AAuCA,qEAAqE,GACrE,OAAO,MAAMU,oBAAoBb,mBAAkB;AAEnD,+EAA+E,GAC/E,OAAO,MAAMc,wBAAwB,UAAS;AAE9C,8CAA8C,GAC9C,OAAO,MAAMC,4BAA4B,GAAGF,kBAAkB,QAAQ,CAAC,CAAA;AAEvE,0EAA0E,GAC1E,OAAO,SAASG,eAAeC,KAAa;IAC1C,MAAMC,SAASnB,gBAAgBkB;IAC/B,IAAI,CAACC,QAAQ,MAAM,IAAIC,MAAM,CAAC,mBAAmB,EAAEF,OAAO;IAC1D,OAAOC,OAAOE,IAAI,KAAK,QAAQ,eAAe,CAAC,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,SAAS0C,MAAM,qBAAf1C,iBAAiBlE,MAAM,EAAE;QAC3BsJ,MAAMnH,IAAI,CAAC,CAAC,GAAG,EAAE+B,SAAS0C,MAAM,CAACxC,GAAG,CAAC,CAAC/C;;2BAAOgI,OAAOpC,KAAK,oBAAZoC,OAAOpC,KAAK,MAAZoC,QAAehI,sBAAOA;WAAI8H,IAAI,CAAC,SAAS;IACvF;IACA,KAAIjF,sBAAAA,SAAS2C,SAAS,qBAAlB3C,oBAAoBlE,MAAM,EAAE;QAC9BsJ,MAAMnH,IAAI,CAAC,CAAC,SAAS,EAAE+B,SAAS2C,SAAS,CAACzC,GAAG,CAAC,CAAC8D;;2BAAQmB,OAAOnC,KAAK,oBAAZmC,OAAOnC,KAAK,MAAZmC,QAAenB,uBAAQA;WAAKiB,IAAI,CAAC,SAAS;IACnG;IACA,OAAOG,MAAMH,IAAI,CAAC;AACpB;AAEA;;2CAE2C,GAE3C,8DAA8D,GAC9D,OAAO,MAAMI,oBAAoB,cAAsB;AAEvD,OAAO,MAAMC,qBAAqB,IAAc,CAAC,KAAK,EAAED,mBAAmB,CAAA;AAE3E,2CAA2C,GAC3C,OAAO,MAAME,sBAAsB,IAAG"}
@@ -29,4 +29,4 @@
29
29
  * There is no deals import, so the header is free to read well; it stays
30
30
  * in the table's column order so the file and the screen agree.
31
31
  */
32
- export { csvAmount, csvInstant, DEAL_CSV_COLUMNS, dealsCsv, type DealCsvOptions, type DealCsvRow, } from '@aglyn/aglyn';
32
+ export { csvAmount, csvInstant, DEAL_CSV_COLUMNS, dealsCsv, type DealCsvOptions, type DealCsvRow, } from './crm-csv';
@@ -28,10 +28,9 @@
28
28
  * There is no deals import, so the header is free to read well; it stays
29
29
  * in the table's column order so the file and the screen agree.
30
30
  */ /*
31
- * The columns and the cells moved to `@aglyn/aglyn` under AGL-2662 so the
32
- * server's whole-collection export can write the same file: the console
33
- * app may not import a feature plugin, and one feature must not have two
34
- * file formats. This module keeps its name and its callers.
35
- */ export { csvAmount, csvInstant, DEAL_CSV_COLUMNS, dealsCsv } from "@aglyn/aglyn";
31
+ * The columns and the cells are `crm-csv.ts`, which the server's
32
+ * whole-collection export writes too (AGL-2662): one feature, one file
33
+ * format. This module keeps its name and its callers.
34
+ */ export { csvAmount, csvInstant, DEAL_CSV_COLUMNS, dealsCsv } from "./crm-csv.js";
36
35
 
37
36
  //# sourceMappingURL=deals-csv.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deals-csv.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 deals CSV — one file from the table's Export button and the bulk\n * bar's (AGL-2621).\n *\n * A deal names its stage, its owner, its contact and its company by id, and\n * an id is nothing a spreadsheet can read: the stage and the pipeline are\n * written by NAME, resolved through the caller's pipelines, the owner by\n * address, and the contact and the company by the names the deal already\n * carries as captions. The amount is written in major units (`1250.00`),\n * with the currency beside it, because a column of cents is a column\n * somebody will sum wrongly.\n *\n * There is no deals import, so the header is free to read well; it stays\n * in the table's column order so the file and the screen agree.\n */\n\n/*\n * The columns and the cells moved to `@aglyn/aglyn` under AGL-2662 so the\n * server's whole-collection export can write the same file: the console\n * app may not import a feature plugin, and one feature must not have two\n * file formats. This module keeps its name and its callers.\n */\nexport {\n csvAmount,\n csvInstant,\n DEAL_CSV_COLUMNS,\n dealsCsv,\n type DealCsvOptions,\n type DealCsvRow,\n} from '@aglyn/aglyn'\n"],"names":["csvAmount","csvInstant","DEAL_CSV_COLUMNS","dealsCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED;;;;;CAKC,GACD,SACEA,SAAS,EACTC,UAAU,EACVC,gBAAgB,EAChBC,QAAQ,QAGH,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deals-csv.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 deals CSV — one file from the table's Export button and the bulk\n * bar's (AGL-2621).\n *\n * A deal names its stage, its owner, its contact and its company by id, and\n * an id is nothing a spreadsheet can read: the stage and the pipeline are\n * written by NAME, resolved through the caller's pipelines, the owner by\n * address, and the contact and the company by the names the deal already\n * carries as captions. The amount is written in major units (`1250.00`),\n * with the currency beside it, because a column of cents is a column\n * somebody will sum wrongly.\n *\n * There is no deals import, so the header is free to read well; it stays\n * in the table's column order so the file and the screen agree.\n */\n\n/*\n * The columns and the cells are `crm-csv.ts`, which the server's\n * whole-collection export writes too (AGL-2662): one feature, one file\n * format. This module keeps its name and its callers.\n */\nexport {\n csvAmount,\n csvInstant,\n DEAL_CSV_COLUMNS,\n dealsCsv,\n type DealCsvOptions,\n type DealCsvRow,\n} from './crm-csv'\n"],"names":["csvAmount","csvInstant","DEAL_CSV_COLUMNS","dealsCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED;;;;CAIC,GACD,SACEA,SAAS,EACTC,UAAU,EACVC,gBAAgB,EAChBC,QAAQ,QAGH,eAAW"}
@@ -57,7 +57,7 @@ export declare const LEAD_STATUS_FILTER_OPTIONS: {
57
57
  }[];
58
58
  /** The choices for Email: every verdict, plus the two aggregates. */
59
59
  export declare const LEAD_EMAIL_FILTER_OPTIONS: {
60
- value: "none" | "bounced" | "complained" | "ok" | "blocked" | "undeliverable" | "unsubscribed" | "do_not_contact" | "problem";
60
+ value: "none" | "ok" | "bounced" | "complained" | "blocked" | "undeliverable" | "unsubscribed" | "do_not_contact" | "problem";
61
61
  label: string;
62
62
  }[];
63
63
  /**
@@ -37,4 +37,4 @@
37
37
  * capture door's own record (the sources, the two timestamps, the capture
38
38
  * count) and the conversion's stamp on "Do not import".
39
39
  */
40
- export { LEAD_CSV_COLUMNS, leadCsvHeader, leadsCsv, type LeadCsvOptions, type LeadCsvRow, } from '@aglyn/aglyn';
40
+ export { LEAD_CSV_COLUMNS, leadCsvHeader, leadsCsv, type LeadCsvOptions, type LeadCsvRow, } from './crm-csv';
@@ -35,6 +35,6 @@
35
35
  * name, and the team's status, owner, reason and notes — and leaves the
36
36
  * capture door's own record (the sources, the two timestamps, the capture
37
37
  * count) and the conversion's stamp on "Do not import".
38
- */ /* The writer moved to `@aglyn/aglyn` under AGL-2662 — see `deals-csv.ts`. */ export { LEAD_CSV_COLUMNS, leadCsvHeader, leadsCsv } from "@aglyn/aglyn";
38
+ */ /* The writer is `crm-csv.ts`, shared with the server's export — see `deals-csv.ts`. */ export { LEAD_CSV_COLUMNS, leadCsvHeader, leadsCsv } from "./crm-csv.js";
39
39
 
40
40
  //# sourceMappingURL=leads-csv.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/leads-csv.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 leads CSV — one file from the Leads section's Export button and the\n * bulk bar's (AGL-2662).\n *\n * A lead is a capture the CRM has annotated: what the door wrote (the\n * address, the name, every surface that met the person, when, how often)\n * and what the team wrote on top (a status, an owner, a reason, notes).\n * The file carries both. The status is written by its LABEL and an absent\n * one as `New`, the way the list reads it, and the owner by ADDRESS rather\n * than uid, the way every other CRM file writes one. The sources are joined\n * with `|` as the contacts file joins its multi-valued cells.\n *\n * At the organization level the same file gains a `Site` column, because a\n * row there is some site's lead and the file must say which; under a site\n * every row is the site's own and the column is not written.\n *\n * The header is written to READ well rather than to round-trip, and the\n * import (`lead-import-drawer.tsx`) is built to that header rather than the\n * other way round: it maps the columns a file may set — the address, the\n * name, and the team's status, owner, reason and notes — and leaves the\n * capture door's own record (the sources, the two timestamps, the capture\n * count) and the conversion's stamp on \"Do not import\".\n */\n\n/* The writer moved to `@aglyn/aglyn` under AGL-2662 — see `deals-csv.ts`. */\nexport {\n LEAD_CSV_COLUMNS,\n leadCsvHeader,\n leadsCsv,\n type LeadCsvOptions,\n type LeadCsvRow,\n} from '@aglyn/aglyn'\n"],"names":["LEAD_CSV_COLUMNS","leadCsvHeader","leadsCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,2EAA2E,GAC3E,SACEA,gBAAgB,EAChBC,aAAa,EACbC,QAAQ,QAGH,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/leads-csv.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 leads CSV — one file from the Leads section's Export button and the\n * bulk bar's (AGL-2662).\n *\n * A lead is a capture the CRM has annotated: what the door wrote (the\n * address, the name, every surface that met the person, when, how often)\n * and what the team wrote on top (a status, an owner, a reason, notes).\n * The file carries both. The status is written by its LABEL and an absent\n * one as `New`, the way the list reads it, and the owner by ADDRESS rather\n * than uid, the way every other CRM file writes one. The sources are joined\n * with `|` as the contacts file joins its multi-valued cells.\n *\n * At the organization level the same file gains a `Site` column, because a\n * row there is some site's lead and the file must say which; under a site\n * every row is the site's own and the column is not written.\n *\n * The header is written to READ well rather than to round-trip, and the\n * import (`lead-import-drawer.tsx`) is built to that header rather than the\n * other way round: it maps the columns a file may set — the address, the\n * name, and the team's status, owner, reason and notes — and leaves the\n * capture door's own record (the sources, the two timestamps, the capture\n * count) and the conversion's stamp on \"Do not import\".\n */\n\n/* The writer is `crm-csv.ts`, shared with the server's export — see `deals-csv.ts`. */\nexport {\n LEAD_CSV_COLUMNS,\n leadCsvHeader,\n leadsCsv,\n type LeadCsvOptions,\n type LeadCsvRow,\n} from './crm-csv'\n"],"names":["LEAD_CSV_COLUMNS","leadCsvHeader","leadsCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,qFAAqF,GACrF,SACEA,gBAAgB,EAChBC,aAAa,EACbC,QAAQ,QAGH,eAAW"}
@@ -25,4 +25,4 @@
25
25
  * at nine in the assignee's zone — so it is written as an ISO timestamp,
26
26
  * and a spreadsheet renders it in whatever zone it is opened in.
27
27
  */
28
- export { TASK_CSV_COLUMNS, tasksCsv, type TaskCsvOptions, type TaskCsvRow, } from '@aglyn/aglyn';
28
+ export { TASK_CSV_COLUMNS, tasksCsv, type TaskCsvOptions, type TaskCsvRow, } from './crm-csv';
@@ -23,6 +23,6 @@
23
23
  * for the same reason. A due date is an INSTANT — a task due at nine is due
24
24
  * at nine in the assignee's zone — so it is written as an ISO timestamp,
25
25
  * and a spreadsheet renders it in whatever zone it is opened in.
26
- */ /* The writer moved to `@aglyn/aglyn` under AGL-2662 — see `deals-csv.ts`. */ export { TASK_CSV_COLUMNS, tasksCsv } from "@aglyn/aglyn";
26
+ */ /* The writer is `crm-csv.ts`, shared with the server's export — see `deals-csv.ts`. */ export { TASK_CSV_COLUMNS, tasksCsv } from "./crm-csv.js";
27
27
 
28
28
  //# sourceMappingURL=tasks-csv.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/tasks-csv.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 tasks CSV — one file from the section's Export button and the bulk\n * bar's (AGL-2621).\n *\n * A task hangs off a contact, a company or a deal by id; the file names\n * each by the name the list already resolved for the row, so a spreadsheet\n * reads \"Acme\" and not a document id. The assignee is written by address\n * for the same reason. A due date is an INSTANT — a task due at nine is due\n * at nine in the assignee's zone — so it is written as an ISO timestamp,\n * and a spreadsheet renders it in whatever zone it is opened in.\n */\n\n/* The writer moved to `@aglyn/aglyn` under AGL-2662 — see `deals-csv.ts`. */\nexport {\n TASK_CSV_COLUMNS,\n tasksCsv,\n type TaskCsvOptions,\n type TaskCsvRow,\n} from '@aglyn/aglyn'\n"],"names":["TASK_CSV_COLUMNS","tasksCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAED,2EAA2E,GAC3E,SACEA,gBAAgB,EAChBC,QAAQ,QAGH,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/tasks-csv.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 tasks CSV — one file from the section's Export button and the bulk\n * bar's (AGL-2621).\n *\n * A task hangs off a contact, a company or a deal by id; the file names\n * each by the name the list already resolved for the row, so a spreadsheet\n * reads \"Acme\" and not a document id. The assignee is written by address\n * for the same reason. A due date is an INSTANT — a task due at nine is due\n * at nine in the assignee's zone — so it is written as an ISO timestamp,\n * and a spreadsheet renders it in whatever zone it is opened in.\n */\n\n/* The writer is `crm-csv.ts`, shared with the server's export — see `deals-csv.ts`. */\nexport {\n TASK_CSV_COLUMNS,\n tasksCsv,\n type TaskCsvOptions,\n type TaskCsvRow,\n} from './crm-csv'\n"],"names":["TASK_CSV_COLUMNS","tasksCsv"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAED,qFAAqF,GACrF,SACEA,gBAAgB,EAChBC,QAAQ,QAGH,eAAW"}
@@ -0,0 +1,75 @@
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
+ import type { OrgPlan } from '@aglyn/aglyn/foundation/definitions/org-billing.types';
18
+ import type { PluginPlanEntitlementsDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-plan-entitlements';
19
+ /**
20
+ * THE CRM'S PLAN BAND (AGL-3080): the one-to-one email pace each plan
21
+ * includes. Compiled into core's `PLAN_ENTITLEMENTS` by the manifest
22
+ * generator (`register.planEntitlements`); this is where the figure is
23
+ * written, beside the reasoning that sized it.
24
+ */
25
+ declare module '@aglyn/aglyn/plugin-manager/plugin-entitlement-keys' {
26
+ interface PluginEntitlementQuotas {
27
+ /**
28
+ * One-to-one emails a workspace may send from CRM records per UTC day —
29
+ * the message a rep writes to one person from their contact page, as
30
+ * against a campaign (`emailSendsPerMonth`) or transactional mail.
31
+ *
32
+ * A HARD cap on every tier and a daily one, because it is the only send
33
+ * class a person can produce by hand at volume: a campaign is one act
34
+ * over a metered audience, and a receipt follows an order somebody paid
35
+ * for, but a rep with a template and a list can put a thousand messages
36
+ * onto the platform's sending reputation in an afternoon. The day
37
+ * boundary is what makes the cap a pace rather than a wall — tomorrow the
38
+ * count is zero again — and the number is sized so that every tier holds
39
+ * its margin with the whole day spent, which is the arithmetic the Drive
40
+ * pricing decision of 2026-09-05 records. `checkCrmEmailQuota` reads it;
41
+ * the counter it is enforced against is
42
+ * `orgs/{orgId}/crmEmailUsage/{day}`.
43
+ *
44
+ * Every send still counts on the org's `emailSends` cost meter, like any
45
+ * other message the provider charged for. 0 on Free, which has no CRM,
46
+ * and finite on every paid tier, Enterprise's 2,000 included.
47
+ *
48
+ * ## This ladder and `emailSendsPerMonth` are NOT the same ladder
49
+ *
50
+ * They answer to different principles, deliberately, and a tier's two
51
+ * numbers are not expected to look like each other. `emailSendsPerMonth`
52
+ * is sized against SHARED-DOMAIN REPUTATION: campaign mail is bulk on a
53
+ * pool every tier without its own verified sending domain rides under
54
+ * `p=reject`, so what one workspace sends is a cost every other workspace
55
+ * pays. This one is sized against COGS SHARE: one-to-one mail is a
56
+ * per-tier margin question, which is why it is a daily pace rather than a
57
+ * monthly band.
58
+ *
59
+ * The two are far apart at the entry tier — a band of 0 beside a real
60
+ * daily allowance — and that reads as an inconsistency until the
61
+ * principles are named. It is not one. One-to-one mail is addressed to a
62
+ * single person, usually inside a relationship the recipient started, and
63
+ * it reaches the provider through a per-user pace limit, both suppression
64
+ * lists, a `declined` consent basis as a hard stop, and an atomic daily
65
+ * reservation. Complaint rates on it are structurally unlike bulk.
66
+ * Reconciling the two ladders would price a reply to one customer as
67
+ * though it carried a campaign's reputation risk.
68
+ */
69
+ crmEmailsPerDay?: number;
70
+ }
71
+ }
72
+ /** The one-to-one emails each plan may send a UTC day — see the key's docblock. */
73
+ export declare const CRM_EMAILS_PER_DAY_BY_PLAN: Readonly<Record<OrgPlan, number>>;
74
+ /** The CRM's plan figures, for the manifest generator. */
75
+ export declare function crmPlanEntitlements(): PluginPlanEntitlementsDeclaration;
@@ -0,0 +1,56 @@
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
+ */ // Types only: the manifest generator loads this module on its own to compile
17
+ // the plan figures, so nothing here may reach a core module at runtime.
18
+ /** The one-to-one emails each plan may send a UTC day — see the key's docblock. */ export const CRM_EMAILS_PER_DAY_BY_PLAN = {
19
+ // No one-to-one email on Free, which has no CRM: the send lives on a
20
+ // record's page, and Free opens no record. Zero here is what
21
+ // `checkCrmEmailQuota` refuses against, so a per-org grant of
22
+ // `features.crm` alone still sends nothing until the band is raised with
23
+ // it.
24
+ free: 0,
25
+ // One-to-one email from a CRM record, per UTC day (AGL-2611). A hard daily
26
+ // pace rather than a monthly meter, sized so the whole day spent at $0.0009
27
+ // a message leaves the tier's CRM axis inside the 20% cost share the Drive
28
+ // pricing decision of 2026-09-05 sets. 50 a day is $1.35 a month against a
29
+ // $16 annual price. Every send still lands on the `emailSends` cost meter
30
+ // beside the transactional mail this tier already sends.
31
+ starter: 50,
32
+ pro: 150,
33
+ business: 200,
34
+ scale: 300,
35
+ advanced: 500,
36
+ agency: 1000,
37
+ // Finite like the campaign allowance beside it, and for the same reason
38
+ // one-to-one mail is capped on every other tier: a rep with a template and
39
+ // a list can put thousands of messages onto the platform's sending
40
+ // reputation in an afternoon. A negotiated agreement whose reps need more
41
+ // than 2,000 a day says so, and the override is what carries it.
42
+ enterprise: 2000
43
+ };
44
+ /** The CRM's plan figures, for the manifest generator. */ export function crmPlanEntitlements() {
45
+ return {
46
+ quotas: [
47
+ {
48
+ key: 'crmEmailsPerDay',
49
+ label: 'One-to-one emails / day',
50
+ byPlan: CRM_EMAILS_PER_DAY_BY_PLAN
51
+ }
52
+ ]
53
+ };
54
+ }
55
+
56
+ //# sourceMappingURL=plan-entitlements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/plan-entitlements.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// Types only: the manifest generator loads this module on its own to compile\n// the plan figures, so nothing here may reach a core module at runtime.\nimport type { OrgPlan } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { PluginPlanEntitlementsDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-plan-entitlements'\n\n/**\n * THE CRM'S PLAN BAND (AGL-3080): the one-to-one email pace each plan\n * includes. Compiled into core's `PLAN_ENTITLEMENTS` by the manifest\n * generator (`register.planEntitlements`); this is where the figure is\n * written, beside the reasoning that sized it.\n */\ndeclare module '@aglyn/aglyn/plugin-manager/plugin-entitlement-keys' {\n interface PluginEntitlementQuotas {\n /**\n * One-to-one emails a workspace may send from CRM records per UTC day —\n * the message a rep writes to one person from their contact page, as\n * against a campaign (`emailSendsPerMonth`) or transactional mail.\n *\n * A HARD cap on every tier and a daily one, because it is the only send\n * class a person can produce by hand at volume: a campaign is one act\n * over a metered audience, and a receipt follows an order somebody paid\n * for, but a rep with a template and a list can put a thousand messages\n * onto the platform's sending reputation in an afternoon. The day\n * boundary is what makes the cap a pace rather than a wall — tomorrow the\n * count is zero again — and the number is sized so that every tier holds\n * its margin with the whole day spent, which is the arithmetic the Drive\n * pricing decision of 2026-09-05 records. `checkCrmEmailQuota` reads it;\n * the counter it is enforced against is\n * `orgs/{orgId}/crmEmailUsage/{day}`.\n *\n * Every send still counts on the org's `emailSends` cost meter, like any\n * other message the provider charged for. 0 on Free, which has no CRM,\n * and finite on every paid tier, Enterprise's 2,000 included.\n *\n * ## This ladder and `emailSendsPerMonth` are NOT the same ladder\n *\n * They answer to different principles, deliberately, and a tier's two\n * numbers are not expected to look like each other. `emailSendsPerMonth`\n * is sized against SHARED-DOMAIN REPUTATION: campaign mail is bulk on a\n * pool every tier without its own verified sending domain rides under\n * `p=reject`, so what one workspace sends is a cost every other workspace\n * pays. This one is sized against COGS SHARE: one-to-one mail is a\n * per-tier margin question, which is why it is a daily pace rather than a\n * monthly band.\n *\n * The two are far apart at the entry tier — a band of 0 beside a real\n * daily allowance — and that reads as an inconsistency until the\n * principles are named. It is not one. One-to-one mail is addressed to a\n * single person, usually inside a relationship the recipient started, and\n * it reaches the provider through a per-user pace limit, both suppression\n * lists, a `declined` consent basis as a hard stop, and an atomic daily\n * reservation. Complaint rates on it are structurally unlike bulk.\n * Reconciling the two ladders would price a reply to one customer as\n * though it carried a campaign's reputation risk.\n */\n crmEmailsPerDay?: number\n }\n}\n\n/** The one-to-one emails each plan may send a UTC day — see the key's docblock. */\nexport const CRM_EMAILS_PER_DAY_BY_PLAN: Readonly<Record<OrgPlan, number>> = {\n // No one-to-one email on Free, which has no CRM: the send lives on a\n // record's page, and Free opens no record. Zero here is what\n // `checkCrmEmailQuota` refuses against, so a per-org grant of\n // `features.crm` alone still sends nothing until the band is raised with\n // it.\n free: 0,\n // One-to-one email from a CRM record, per UTC day (AGL-2611). A hard daily\n // pace rather than a monthly meter, sized so the whole day spent at $0.0009\n // a message leaves the tier's CRM axis inside the 20% cost share the Drive\n // pricing decision of 2026-09-05 sets. 50 a day is $1.35 a month against a\n // $16 annual price. Every send still lands on the `emailSends` cost meter\n // beside the transactional mail this tier already sends.\n starter: 50,\n pro: 150,\n business: 200,\n scale: 300,\n advanced: 500,\n agency: 1000,\n // Finite like the campaign allowance beside it, and for the same reason\n // one-to-one mail is capped on every other tier: a rep with a template and\n // a list can put thousands of messages onto the platform's sending\n // reputation in an afternoon. A negotiated agreement whose reps need more\n // than 2,000 a day says so, and the override is what carries it.\n enterprise: 2_000,\n}\n\n/** The CRM's plan figures, for the manifest generator. */\nexport function crmPlanEntitlements(): PluginPlanEntitlementsDeclaration {\n return {\n quotas: [\n {\n key: 'crmEmailsPerDay',\n label: 'One-to-one emails / day',\n byPlan: CRM_EMAILS_PER_DAY_BY_PLAN,\n },\n ],\n }\n}\n"],"names":["CRM_EMAILS_PER_DAY_BY_PLAN","free","starter","pro","business","scale","advanced","agency","enterprise","crmPlanEntitlements","quotas","key","label","byPlan"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,6EAA6E;AAC7E,wEAAwE;AA0DxE,iFAAiF,GACjF,OAAO,MAAMA,6BAAgE;IAC3E,qEAAqE;IACrE,6DAA6D;IAC7D,8DAA8D;IAC9D,yEAAyE;IACzE,MAAM;IACNC,MAAM;IACN,2EAA2E;IAC3E,4EAA4E;IAC5E,2EAA2E;IAC3E,2EAA2E;IAC3E,0EAA0E;IAC1E,yDAAyD;IACzDC,SAAS;IACTC,KAAK;IACLC,UAAU;IACVC,OAAO;IACPC,UAAU;IACVC,QAAQ;IACR,wEAAwE;IACxE,2EAA2E;IAC3E,mEAAmE;IACnE,0EAA0E;IAC1E,iEAAiE;IACjEC,YAAY;AACd,EAAC;AAED,wDAAwD,GACxD,OAAO,SAASC;IACd,OAAO;QACLC,QAAQ;YACN;gBACEC,KAAK;gBACLC,OAAO;gBACPC,QAAQb;YACV;SACD;IACH;AACF"}
package/src/lib/plugin.js CHANGED
@@ -21,6 +21,7 @@ import { CrmGlanceCard } from "./components/crm-glance-card.js";
21
21
  import { BUNDLE_ID } from "./constants/bundle-common.js";
22
22
  import { withCrmOrgMount } from "./hooks/use-crm-org-mount.js";
23
23
  import { registerCrmRecordRoutes } from "./model/crm-record-routes.js";
24
+ import { CRM_SEARCH_SOURCES } from "./model/crm-search-sources.js";
24
25
  import { registerPluginZone } from "@aglyn/aglyn/plugin-manager/plugin-zones";
25
26
  import { CRM_RECORD_ATTRIBUTION_ZONE } from "./components/crm-attribution-zone.js";
26
27
  import { CRM_RECORD_BOOKING_ZONE } from "./components/crm-booking-zone.js";
@@ -109,6 +110,8 @@ const CrmTasksDueCard = lazy(()=>import("./components/crm-tasks-due-card.js"));
109
110
  * and the Firestore rules ask the same question where the data is
110
111
  * (`server/suite-gate.ts`).
111
112
  */ featureFlag: 'crm',
113
+ // What the console's search finds here, under the two gates above.
114
+ searchSources: CRM_SEARCH_SOURCES,
112
115
  /*
113
116
  * Dashboard cards (AGL-2599, AGL-2604): the site dashboard's `hostDashboard`
114
117
  * slot composes this extension's permission over each, so a card appears
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/plugin.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiCardAccountDetailsOutline } from '@aglyn/shared-data-mdi'\nimport { lazy } from 'react'\nimport { CRM_CONSOLE_SECTIONS } from './components/crm-console-sections'\nimport { CrmGlanceCard } from './components/crm-glance-card'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { withCrmOrgMount } from './hooks/use-crm-org-mount'\nimport { registerCrmRecordRoutes } from './model/crm-record-routes'\nimport { registerPluginZone } from '@aglyn/aglyn/plugin-manager/plugin-zones'\nimport { CRM_RECORD_ATTRIBUTION_ZONE } from './components/crm-attribution-zone'\nimport { CRM_RECORD_BOOKING_ZONE } from './components/crm-booking-zone'\n\n/** Code-split: the CRM hub only loads when opened. */\nconst CrmConsolePage = lazy(\n () => import('./components/crm-console-page'),\n)\n/** The dashboard glance, split the same way: it loads where the slot mounts it. */\n/** Where a form's fields save on a contact, drawn on the form's own page. */\nconst FormContactFieldsCard = lazy(\n () => import('./components/form-contact-fields-card'),\n)\n\nconst CrmTasksDueCard = lazy(\n () => import('./components/crm-tasks-due-card'),\n)\n\n/**\n * CRM feature plugin (AGL-395, the hub since AGL-2595). Console-only — its\n * records live in Firestore and have no canvas element, so there is no UI\n * bundle. The console half declares the CRM nav + hub through the\n * ConsoleExtension registry (release_crm gate via the nav tab); the\n * contacts section reads the `contactsPerHost` quota off the shell-passed\n * `org`.\n *\n * The plugin id is `crm` (AGL-2595). It was `contacts` while the surface was\n * one list; the id is persisted in every org's `enabledPlugins` and every\n * host's `disabledPlugins`, so the runtime read the old value as this one\n * until the stored documents had been rewritten, and the alias was retired\n * once that backfill reported nothing left (AGL-2614). The `/contacts`\n * address is a URL, not a stored id, and the nav item keeps redirecting it.\n */\nexport function registerCrmConsole(): void {\n registerCrmRecordRoutes()\n registerPluginZone(\n {\n zone: CRM_RECORD_BOOKING_ZONE,\n label: 'Book a meeting from a CRM record',\n surface: 'console',\n // One control in a record header's row of actions, and one beside the\n // composer's fields: the page lays them out, so the zone adds nothing.\n layout: 'bare',\n description:\n 'In a record’s header and beside the one-to-one composer. A widget here offers the site’s bookable services and the link a visitor books one at; it is handed the site, the record and, from the composer, a way to insert the chosen link. It writes nothing.',\n },\n { pluginId: BUNDLE_ID },\n )\n registerPluginZone(\n {\n zone: CRM_RECORD_ATTRIBUTION_ZONE,\n label: 'Where a CRM record came from',\n surface: 'console',\n description:\n 'On a contact’s page and in a lead’s history. A widget here says which campaign or link brought the person; it is handed the site, what the record is and its id, and it writes nothing.',\n },\n { pluginId: BUNDLE_ID },\n )\n Aglyn.registerConsoleExtension({\n pluginId: BUNDLE_ID,\n displayName: 'CRM',\n /*\n * WHO may open the CRM, declared so the shell enforces it.\n *\n * `navTabId` below is a release flag, not authorization: it says whether\n * the surface has shipped, and `FeatureGate` reads it as\n * `released || isStaff`. Nothing above this page decided who among a\n * workspace's members may read it, and the page is a full editor over\n * org-shared people data — names, addresses, order history, notes,\n * consent, and a CSV export of all of it.\n *\n * `data.manage` rather than a key of this plugin's own, because it is\n * the catalog key whose subject is exactly this data. The Firestore\n * rules place contacts in the org-shared data block with datasets and\n * gate writes on `canWriteOrgData()` — owner, admin, editor — which is\n * the population `data.manage` defaults to, so the console gate and the\n * rules agree on the built-in roles by construction. A custom role or a\n * per-member override then narrows the console further, and the rules\n * stay the boundary for the data itself.\n *\n * Minting a `contacts.*` key instead would advertise a control that does\n * not exist. Console contact writes are client-direct against the rules,\n * so a new key would have no server enforcement point to sit on, and a\n * permission a customer can untick that changes nothing is worse than\n * its absence.\n *\n * A SITE COLLABORATOR holding it reaches this page deliberately. They\n * are a real org member document, so this gate is the first thing that\n * has ever asked about them here — and the answer is yes, scoped: the\n * listener filters on `visibleTo`, the rules prove the same predicate\n * per document, and every field the page shows is read through the\n * viewing group's own facet. Refusing them outright would delete a\n * shipped capability rather than close a hole.\n */\n permission: 'data.manage',\n /*\n * WHAT the workspace must have bought (AGL-2851). The CRM is included\n * from Starter and a Free workspace has none of it, so the flag is\n * declared once, here, and the shell refuses every surface this\n * registers on a plan without it: the hub body at both mounts, every\n * section and record beneath it, drawn locked beside the upgrade notice,\n * and the dashboard cards. The nav tab stays, as every plan-locked tab\n * does, because it is the way to that notice. The CRM's routes, `/v1`\n * and the Firestore rules ask the same question where the data is\n * (`server/suite-gate.ts`).\n */\n featureFlag: 'crm',\n /*\n * Dashboard cards (AGL-2599, AGL-2604): the site dashboard's `hostDashboard`\n * slot composes this extension's permission over each, so a card appears\n * only where the CRM is enabled and only for a reader who may open it —\n * registered here rather than imported by the dashboard so the shell's\n * enablement and entitlement gate decides whether a site that never turned\n * the CRM on sees them, the rule every card on that row follows. The tasks\n * card is a glance at the reader's own overdue and due-today work and\n * renders nothing on a workspace that has never made a task; the glance\n * card is four server-counted figures, each a link into the hub.\n *\n * Both name `features.crm`, as the extension does (AGL-2611, AGL-2851):\n * the slot composes the two, so a plan without the CRM gets neither card\n * — absent, not upsold, the treatment every gated card gets.\n *\n * The same two cards again on the organization's `orgDashboard` slot\n * (AGL-2636) — the org's sites page — under the same flag, with the same\n * ids: the id names the card, and it is one card totaling the whole\n * organization there instead of one site. The shell hands that slot the\n * org mount as a prop, and `withCrmOrgMount` is what puts the mount's\n * provider around each card, since the sites page cannot import one.\n */\n widgets: [\n // Which contact field each of a form's fields saves to, on the form's\n // own page. The forms plugin hosts the zone and writes the form\n // document; what a contact's fields ARE is this plugin's, so the card\n // is too.\n {\n slot: 'formContactFields',\n widgetId: 'crm-form-contact-fields',\n title: 'Saves to contact fields',\n // A contact's custom fields are part of the suite, so a workspace\n // without it has none to map a form's field onto.\n featureFlag: 'crm',\n Component: FormContactFieldsCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.hostDashboard,\n widgetId: 'crm-tasks-due',\n title: 'Tasks due',\n featureFlag: 'crm',\n Component: CrmTasksDueCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.hostDashboard,\n widgetId: 'crm-glance',\n title: 'CRM at a glance',\n featureFlag: 'crm',\n Component: CrmGlanceCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.orgDashboard,\n widgetId: 'crm-tasks-due',\n title: 'Tasks due',\n featureFlag: 'crm',\n Component: withCrmOrgMount(CrmTasksDueCard),\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.orgDashboard,\n widgetId: 'crm-glance',\n title: 'CRM at a glance',\n featureFlag: 'crm',\n Component: withCrmOrgMount(CrmGlanceCard),\n },\n ],\n navItems: [\n {\n label: 'CRM',\n href: '/crm',\n // The address the surface had while it was one list. A link kept\n // from then — a bookmark, a docs page, an email — still opens the\n // hub rather than the shell's \"not available\" notice.\n legacyHrefs: ['/contacts'],\n // Sections as ROUTES (AGL-2595): each is a real URL the shell\n // resolves and gates, so the page mounts the one being read and a\n // bare `/crm` lands on the first. Every section inherits this\n // item's `release_crm` gate.\n sections: CRM_CONSOLE_SECTIONS,\n navTabId: 'nav-tab-contacts',\n icon: { path: mdiCardAccountDetailsOutline.path },\n header: {\n title: 'CRM',\n icon: { path: mdiCardAccountDetailsOutline.path },\n docsTopic: 'crm',\n },\n Component: CrmConsolePage,\n },\n ],\n })\n}\n"],"names":["Aglyn","mdiCardAccountDetailsOutline","lazy","CRM_CONSOLE_SECTIONS","CrmGlanceCard","BUNDLE_ID","withCrmOrgMount","registerCrmRecordRoutes","registerPluginZone","CRM_RECORD_ATTRIBUTION_ZONE","CRM_RECORD_BOOKING_ZONE","CrmConsolePage","FormContactFieldsCard","CrmTasksDueCard","registerCrmConsole","zone","label","surface","layout","description","pluginId","registerConsoleExtension","displayName","permission","featureFlag","widgets","slot","widgetId","title","Component","CONSOLE_WIDGET_SLOTS","hostDashboard","orgDashboard","navItems","href","legacyHrefs","sections","navTabId","icon","path","header","docsTopic"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,4BAA4B,QAAQ,yBAAwB;AACrE,SAASC,IAAI,QAAQ,QAAO;AAC5B,SAASC,oBAAoB,QAAQ,uCAAmC;AACxE,SAASC,aAAa,QAAQ,kCAA8B;AAC5D,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,eAAe,QAAQ,+BAA2B;AAC3D,SAASC,uBAAuB,QAAQ,+BAA2B;AACnE,SAASC,kBAAkB,QAAQ,2CAA0C;AAC7E,SAASC,2BAA2B,QAAQ,uCAAmC;AAC/E,SAASC,uBAAuB,QAAQ,mCAA+B;AAEvE,oDAAoD,GACpD,MAAMC,iBAAiBT,KACrB,IAAM,MAAM,CAAC;AAEf,iFAAiF,GACjF,2EAA2E,GAC3E,MAAMU,wBAAwBV,KAC5B,IAAM,MAAM,CAAC;AAGf,MAAMW,kBAAkBX,KACtB,IAAM,MAAM,CAAC;AAGf;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASY;IACdP;IACAC,mBACE;QACEO,MAAML;QACNM,OAAO;QACPC,SAAS;QACT,sEAAsE;QACtE,uEAAuE;QACvEC,QAAQ;QACRC,aACE;IACJ,GACA;QAAEC,UAAUf;IAAU;IAExBG,mBACE;QACEO,MAAMN;QACNO,OAAO;QACPC,SAAS;QACTE,aACE;IACJ,GACA;QAAEC,UAAUf;IAAU;IAExBL,MAAMqB,wBAAwB,CAAC;QAC7BD,UAAUf;QACViB,aAAa;QACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgCC,GACDC,YAAY;QACZ;;;;;;;;;;KAUC,GACDC,aAAa;QACb;;;;;;;;;;;;;;;;;;;;;KAqBC,GACDC,SAAS;YACP,sEAAsE;YACtE,gEAAgE;YAChE,sEAAsE;YACtE,UAAU;YACV;gBACEC,MAAM;gBACNC,UAAU;gBACVC,OAAO;gBACP,kEAAkE;gBAClE,kDAAkD;gBAClDJ,aAAa;gBACbK,WAAWjB;YACb;YACA;gBACEc,MAAM1B,MAAM8B,oBAAoB,CAACC,aAAa;gBAC9CJ,UAAU;gBACVC,OAAO;gBACPJ,aAAa;gBACbK,WAAWhB;YACb;YACA;gBACEa,MAAM1B,MAAM8B,oBAAoB,CAACC,aAAa;gBAC9CJ,UAAU;gBACVC,OAAO;gBACPJ,aAAa;gBACbK,WAAWzB;YACb;YACA;gBACEsB,MAAM1B,MAAM8B,oBAAoB,CAACE,YAAY;gBAC7CL,UAAU;gBACVC,OAAO;gBACPJ,aAAa;gBACbK,WAAWvB,gBAAgBO;YAC7B;YACA;gBACEa,MAAM1B,MAAM8B,oBAAoB,CAACE,YAAY;gBAC7CL,UAAU;gBACVC,OAAO;gBACPJ,aAAa;gBACbK,WAAWvB,gBAAgBF;YAC7B;SACD;QACD6B,UAAU;YACR;gBACEjB,OAAO;gBACPkB,MAAM;gBACN,iEAAiE;gBACjE,kEAAkE;gBAClE,sDAAsD;gBACtDC,aAAa;oBAAC;iBAAY;gBAC1B,8DAA8D;gBAC9D,kEAAkE;gBAClE,8DAA8D;gBAC9D,6BAA6B;gBAC7BC,UAAUjC;gBACVkC,UAAU;gBACVC,MAAM;oBAAEC,MAAMtC,6BAA6BsC,IAAI;gBAAC;gBAChDC,QAAQ;oBACNZ,OAAO;oBACPU,MAAM;wBAAEC,MAAMtC,6BAA6BsC,IAAI;oBAAC;oBAChDE,WAAW;gBACb;gBACAZ,WAAWlB;YACb;SACD;IACH;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/plugin.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiCardAccountDetailsOutline } from '@aglyn/shared-data-mdi'\nimport { lazy } from 'react'\nimport { CRM_CONSOLE_SECTIONS } from './components/crm-console-sections'\nimport { CrmGlanceCard } from './components/crm-glance-card'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { withCrmOrgMount } from './hooks/use-crm-org-mount'\nimport { registerCrmRecordRoutes } from './model/crm-record-routes'\nimport { CRM_SEARCH_SOURCES } from './model/crm-search-sources'\nimport { registerPluginZone } from '@aglyn/aglyn/plugin-manager/plugin-zones'\nimport { CRM_RECORD_ATTRIBUTION_ZONE } from './components/crm-attribution-zone'\nimport { CRM_RECORD_BOOKING_ZONE } from './components/crm-booking-zone'\n\n/** Code-split: the CRM hub only loads when opened. */\nconst CrmConsolePage = lazy(\n () => import('./components/crm-console-page'),\n)\n/** The dashboard glance, split the same way: it loads where the slot mounts it. */\n/** Where a form's fields save on a contact, drawn on the form's own page. */\nconst FormContactFieldsCard = lazy(\n () => import('./components/form-contact-fields-card'),\n)\n\nconst CrmTasksDueCard = lazy(\n () => import('./components/crm-tasks-due-card'),\n)\n\n/**\n * CRM feature plugin (AGL-395, the hub since AGL-2595). Console-only — its\n * records live in Firestore and have no canvas element, so there is no UI\n * bundle. The console half declares the CRM nav + hub through the\n * ConsoleExtension registry (release_crm gate via the nav tab); the\n * contacts section reads the `contactsPerHost` quota off the shell-passed\n * `org`.\n *\n * The plugin id is `crm` (AGL-2595). It was `contacts` while the surface was\n * one list; the id is persisted in every org's `enabledPlugins` and every\n * host's `disabledPlugins`, so the runtime read the old value as this one\n * until the stored documents had been rewritten, and the alias was retired\n * once that backfill reported nothing left (AGL-2614). The `/contacts`\n * address is a URL, not a stored id, and the nav item keeps redirecting it.\n */\nexport function registerCrmConsole(): void {\n registerCrmRecordRoutes()\n registerPluginZone(\n {\n zone: CRM_RECORD_BOOKING_ZONE,\n label: 'Book a meeting from a CRM record',\n surface: 'console',\n // One control in a record header's row of actions, and one beside the\n // composer's fields: the page lays them out, so the zone adds nothing.\n layout: 'bare',\n description:\n 'In a record’s header and beside the one-to-one composer. A widget here offers the site’s bookable services and the link a visitor books one at; it is handed the site, the record and, from the composer, a way to insert the chosen link. It writes nothing.',\n },\n { pluginId: BUNDLE_ID },\n )\n registerPluginZone(\n {\n zone: CRM_RECORD_ATTRIBUTION_ZONE,\n label: 'Where a CRM record came from',\n surface: 'console',\n description:\n 'On a contact’s page and in a lead’s history. A widget here says which campaign or link brought the person; it is handed the site, what the record is and its id, and it writes nothing.',\n },\n { pluginId: BUNDLE_ID },\n )\n Aglyn.registerConsoleExtension({\n pluginId: BUNDLE_ID,\n displayName: 'CRM',\n /*\n * WHO may open the CRM, declared so the shell enforces it.\n *\n * `navTabId` below is a release flag, not authorization: it says whether\n * the surface has shipped, and `FeatureGate` reads it as\n * `released || isStaff`. Nothing above this page decided who among a\n * workspace's members may read it, and the page is a full editor over\n * org-shared people data — names, addresses, order history, notes,\n * consent, and a CSV export of all of it.\n *\n * `data.manage` rather than a key of this plugin's own, because it is\n * the catalog key whose subject is exactly this data. The Firestore\n * rules place contacts in the org-shared data block with datasets and\n * gate writes on `canWriteOrgData()` — owner, admin, editor — which is\n * the population `data.manage` defaults to, so the console gate and the\n * rules agree on the built-in roles by construction. A custom role or a\n * per-member override then narrows the console further, and the rules\n * stay the boundary for the data itself.\n *\n * Minting a `contacts.*` key instead would advertise a control that does\n * not exist. Console contact writes are client-direct against the rules,\n * so a new key would have no server enforcement point to sit on, and a\n * permission a customer can untick that changes nothing is worse than\n * its absence.\n *\n * A SITE COLLABORATOR holding it reaches this page deliberately. They\n * are a real org member document, so this gate is the first thing that\n * has ever asked about them here — and the answer is yes, scoped: the\n * listener filters on `visibleTo`, the rules prove the same predicate\n * per document, and every field the page shows is read through the\n * viewing group's own facet. Refusing them outright would delete a\n * shipped capability rather than close a hole.\n */\n permission: 'data.manage',\n /*\n * WHAT the workspace must have bought (AGL-2851). The CRM is included\n * from Starter and a Free workspace has none of it, so the flag is\n * declared once, here, and the shell refuses every surface this\n * registers on a plan without it: the hub body at both mounts, every\n * section and record beneath it, drawn locked beside the upgrade notice,\n * and the dashboard cards. The nav tab stays, as every plan-locked tab\n * does, because it is the way to that notice. The CRM's routes, `/v1`\n * and the Firestore rules ask the same question where the data is\n * (`server/suite-gate.ts`).\n */\n featureFlag: 'crm',\n // What the console's search finds here, under the two gates above.\n searchSources: CRM_SEARCH_SOURCES,\n /*\n * Dashboard cards (AGL-2599, AGL-2604): the site dashboard's `hostDashboard`\n * slot composes this extension's permission over each, so a card appears\n * only where the CRM is enabled and only for a reader who may open it —\n * registered here rather than imported by the dashboard so the shell's\n * enablement and entitlement gate decides whether a site that never turned\n * the CRM on sees them, the rule every card on that row follows. The tasks\n * card is a glance at the reader's own overdue and due-today work and\n * renders nothing on a workspace that has never made a task; the glance\n * card is four server-counted figures, each a link into the hub.\n *\n * Both name `features.crm`, as the extension does (AGL-2611, AGL-2851):\n * the slot composes the two, so a plan without the CRM gets neither card\n * — absent, not upsold, the treatment every gated card gets.\n *\n * The same two cards again on the organization's `orgDashboard` slot\n * (AGL-2636) — the org's sites page — under the same flag, with the same\n * ids: the id names the card, and it is one card totaling the whole\n * organization there instead of one site. The shell hands that slot the\n * org mount as a prop, and `withCrmOrgMount` is what puts the mount's\n * provider around each card, since the sites page cannot import one.\n */\n widgets: [\n // Which contact field each of a form's fields saves to, on the form's\n // own page. The forms plugin hosts the zone and writes the form\n // document; what a contact's fields ARE is this plugin's, so the card\n // is too.\n {\n slot: 'formContactFields',\n widgetId: 'crm-form-contact-fields',\n title: 'Saves to contact fields',\n // A contact's custom fields are part of the suite, so a workspace\n // without it has none to map a form's field onto.\n featureFlag: 'crm',\n Component: FormContactFieldsCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.hostDashboard,\n widgetId: 'crm-tasks-due',\n title: 'Tasks due',\n featureFlag: 'crm',\n Component: CrmTasksDueCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.hostDashboard,\n widgetId: 'crm-glance',\n title: 'CRM at a glance',\n featureFlag: 'crm',\n Component: CrmGlanceCard,\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.orgDashboard,\n widgetId: 'crm-tasks-due',\n title: 'Tasks due',\n featureFlag: 'crm',\n Component: withCrmOrgMount(CrmTasksDueCard),\n },\n {\n slot: Aglyn.CONSOLE_WIDGET_SLOTS.orgDashboard,\n widgetId: 'crm-glance',\n title: 'CRM at a glance',\n featureFlag: 'crm',\n Component: withCrmOrgMount(CrmGlanceCard),\n },\n ],\n navItems: [\n {\n label: 'CRM',\n href: '/crm',\n // The address the surface had while it was one list. A link kept\n // from then — a bookmark, a docs page, an email — still opens the\n // hub rather than the shell's \"not available\" notice.\n legacyHrefs: ['/contacts'],\n // Sections as ROUTES (AGL-2595): each is a real URL the shell\n // resolves and gates, so the page mounts the one being read and a\n // bare `/crm` lands on the first. Every section inherits this\n // item's `release_crm` gate.\n sections: CRM_CONSOLE_SECTIONS,\n navTabId: 'nav-tab-contacts',\n icon: { path: mdiCardAccountDetailsOutline.path },\n header: {\n title: 'CRM',\n icon: { path: mdiCardAccountDetailsOutline.path },\n docsTopic: 'crm',\n },\n Component: CrmConsolePage,\n },\n ],\n })\n}\n"],"names":["Aglyn","mdiCardAccountDetailsOutline","lazy","CRM_CONSOLE_SECTIONS","CrmGlanceCard","BUNDLE_ID","withCrmOrgMount","registerCrmRecordRoutes","CRM_SEARCH_SOURCES","registerPluginZone","CRM_RECORD_ATTRIBUTION_ZONE","CRM_RECORD_BOOKING_ZONE","CrmConsolePage","FormContactFieldsCard","CrmTasksDueCard","registerCrmConsole","zone","label","surface","layout","description","pluginId","registerConsoleExtension","displayName","permission","featureFlag","searchSources","widgets","slot","widgetId","title","Component","CONSOLE_WIDGET_SLOTS","hostDashboard","orgDashboard","navItems","href","legacyHrefs","sections","navTabId","icon","path","header","docsTopic"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,4BAA4B,QAAQ,yBAAwB;AACrE,SAASC,IAAI,QAAQ,QAAO;AAC5B,SAASC,oBAAoB,QAAQ,uCAAmC;AACxE,SAASC,aAAa,QAAQ,kCAA8B;AAC5D,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,eAAe,QAAQ,+BAA2B;AAC3D,SAASC,uBAAuB,QAAQ,+BAA2B;AACnE,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,SAASC,kBAAkB,QAAQ,2CAA0C;AAC7E,SAASC,2BAA2B,QAAQ,uCAAmC;AAC/E,SAASC,uBAAuB,QAAQ,mCAA+B;AAEvE,oDAAoD,GACpD,MAAMC,iBAAiBV,KACrB,IAAM,MAAM,CAAC;AAEf,iFAAiF,GACjF,2EAA2E,GAC3E,MAAMW,wBAAwBX,KAC5B,IAAM,MAAM,CAAC;AAGf,MAAMY,kBAAkBZ,KACtB,IAAM,MAAM,CAAC;AAGf;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASa;IACdR;IACAE,mBACE;QACEO,MAAML;QACNM,OAAO;QACPC,SAAS;QACT,sEAAsE;QACtE,uEAAuE;QACvEC,QAAQ;QACRC,aACE;IACJ,GACA;QAAEC,UAAUhB;IAAU;IAExBI,mBACE;QACEO,MAAMN;QACNO,OAAO;QACPC,SAAS;QACTE,aACE;IACJ,GACA;QAAEC,UAAUhB;IAAU;IAExBL,MAAMsB,wBAAwB,CAAC;QAC7BD,UAAUhB;QACVkB,aAAa;QACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgCC,GACDC,YAAY;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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
+ import { type ApiV1Context } from '@aglyn/tenant-data-admin/server/api-v1-kit';
18
+ /** The key an integration names the record to fold in by. */
19
+ export declare const MERGE_SOURCE_FIELD = "sourceContactId";
20
+ export declare function mergeContactRoute(request: Request, ctx: ApiV1Context, survivorRef: FirebaseFirestore.DocumentReference, view: (snapshot: FirebaseFirestore.DocumentSnapshot) => unknown): Promise<Response>;