@aglyn/plugins-crm 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/contact-list-columns.js +4 -3
  3. package/src/lib/components/contact-list-columns.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.js +6 -2
  5. package/src/lib/components/contact-properties-card.js.map +1 -1
  6. package/src/lib/components/contacts-bulk-bar.js +16 -5
  7. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  8. package/src/lib/components/contacts-section.js +6 -13
  9. package/src/lib/components/contacts-section.js.map +1 -1
  10. package/src/lib/components/crm-record-insights-zone.js +7 -0
  11. package/src/lib/components/crm-record-insights-zone.js.map +1 -1
  12. package/src/lib/components/crm-send-email-dialog.js +1 -1
  13. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  14. package/src/lib/components/deal-board.d.ts +2 -0
  15. package/src/lib/components/deal-board.js +20 -11
  16. package/src/lib/components/deal-board.js.map +1 -1
  17. package/src/lib/components/deal-stage-card.js +41 -28
  18. package/src/lib/components/deal-stage-card.js.map +1 -1
  19. package/src/lib/components/deals-bulk-bar.js +20 -10
  20. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  21. package/src/lib/components/deals-section.js +1 -0
  22. package/src/lib/components/deals-section.js.map +1 -1
  23. package/src/lib/components/email-capture-card.d.ts +1 -1
  24. package/src/lib/components/email-capture-card.js +2 -1
  25. package/src/lib/components/email-capture-card.js.map +1 -1
  26. package/src/lib/components/record-sharing-card.d.ts +6 -5
  27. package/src/lib/components/record-sharing-card.js +45 -30
  28. package/src/lib/components/record-sharing-card.js.map +1 -1
  29. package/src/lib/components/settings-section.d.ts +18 -11
  30. package/src/lib/components/settings-section.js +36 -19
  31. package/src/lib/components/settings-section.js.map +1 -1
  32. package/src/lib/components/sharing-rules-card.js +2 -1
  33. package/src/lib/components/sharing-rules-card.js.map +1 -1
  34. package/src/lib/components/use-org-members.d.ts +17 -10
  35. package/src/lib/components/use-org-members.js +31 -66
  36. package/src/lib/components/use-org-members.js.map +1 -1
  37. package/src/lib/declarations.d.ts +6 -2
  38. package/src/lib/declarations.js +14 -2
  39. package/src/lib/declarations.js.map +1 -1
  40. package/src/lib/declarations.server.js +16 -0
  41. package/src/lib/declarations.server.js.map +1 -1
  42. package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
  43. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  44. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  45. package/src/lib/hooks/use-crm-record-names.js +59 -6
  46. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  47. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  48. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  49. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  50. package/src/lib/hooks/use-org-member-directory.js +49 -12
  51. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  52. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  53. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  54. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  55. package/src/lib/model/crm-api.d.ts +1 -1
  56. package/src/lib/model/crm-api.js +1 -1
  57. package/src/lib/model/crm-api.js.map +1 -1
  58. package/src/lib/model/crm-permissions.d.ts +35 -0
  59. package/src/lib/model/crm-permissions.js +87 -0
  60. package/src/lib/model/crm-permissions.js.map +1 -0
  61. package/src/lib/model/crm-sharing.d.ts +1 -1
  62. package/src/lib/model/crm-sharing.js +1 -1
  63. package/src/lib/model/crm-sharing.js.map +1 -1
  64. package/src/lib/plugin.js +4 -5
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/capture-contact.d.ts +3 -3
  67. package/src/lib/server/capture-contact.js +3 -3
  68. package/src/lib/server/capture-contact.js.map +1 -1
  69. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  70. package/src/lib/server/crm-setup-writers.server.js +4 -16
  71. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  72. package/src/lib/server/crm-sharing.d.ts +5 -4
  73. package/src/lib/server/crm-sharing.js +8 -6
  74. package/src/lib/server/crm-sharing.js.map +1 -1
  75. package/src/lib/server/email-template-duplicate.js +7 -7
  76. package/src/lib/server/email-template-duplicate.js.map +1 -1
  77. package/src/lib/server/inbound-address.d.ts +9 -7
  78. package/src/lib/server/inbound-address.js +18 -15
  79. package/src/lib/server/inbound-address.js.map +1 -1
  80. package/src/lib/server/org-caller.d.ts +19 -5
  81. package/src/lib/server/org-caller.js +25 -5
  82. package/src/lib/server/org-caller.js.map +1 -1
  83. package/src/lib/server/recipe-routes.d.ts +0 -34
  84. package/src/lib/server/recipe-routes.js +11 -10
  85. package/src/lib/server/recipe-routes.js.map +1 -1
  86. package/src/lib/server/scope-sharing-patch.d.ts +22 -0
  87. package/src/lib/server/scope-sharing-patch.js +25 -0
  88. package/src/lib/server/scope-sharing-patch.js.map +1 -0
  89. package/src/lib/server/task-routes.d.ts +6 -5
  90. package/src/lib/server/task-routes.js +11 -13
  91. package/src/lib/server/task-routes.js.map +1 -1
  92. package/src/lib/server-deal-stage.d.ts +11 -6
  93. package/src/lib/server-deal-stage.js +18 -16
  94. package/src/lib/server-deal-stage.js.map +1 -1
  95. package/src/lib/server.js +16 -18
  96. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/sharing-rules-card.tsx"],"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'use client'\n\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n type ContactLifecycleStage,\n crmLeadStatusLabelFor,\n isCrmLeadStatus,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline, mdiRefresh } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n LinearProgress,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport { useCallback, useState } from 'react'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { useCrmSharingRules, useCrmSharingSites } from '../hooks/use-crm-sharing'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { useLeadStatusPicklist } from '../hooks/use-lead-status-picklist'\nimport type { CrmOrgDoc } from '../hooks/use-crm-scope'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport {\n CRM_SHARING_RULES_MAX,\n type CrmSharingAction,\n type CrmSharingRule,\n describeShareTargets,\n describeSharingRuleScope,\n} from '../model/crm-sharing'\nimport { callCrmSharing } from '../model/crm-sharing-api'\nimport { SharingRuleDrawer, type SharingRuleDraft } from './sharing-rule-drawer'\n\nexport interface SharingRulesCardProps {\n orgId: string | null\n org: CrmOrgDoc\n canManage: boolean\n ready: boolean\n}\n\n/** How far a rule's recompute has got, as the table shows it. */\nfunction runLabel(rule: CrmSharingRule): string {\n const run = rule.run\n if (rule.deleting) return 'Removing what it shared…'\n if (!run) return rule.enabled ? 'On' : 'Off'\n if (run.status === 'running') {\n return `${run.mode === 'remove' ? 'Removing' : 'Applying'} — ${run.processed} checked, ${run.changed} changed`\n }\n if (run.status === 'failed') return run.error ?? 'Stopped'\n return `${rule.enabled ? 'On' : 'Off'} — ${run.changed} ${run.changed === 1 ? 'record' : 'records'} changed`\n}\n\n/**\n * SHARING RULES — the organization's automated sharing (AGL-3336).\n *\n * A rule shares every record it matches with other sites: the existing ones\n * through a recompute that runs when the rule is saved, with its progress\n * on the row, and every later capture or change through the record-written\n * seam. The recompute runs in passes; the card keeps asking while the page\n * is open, and a rule whose run stopped offers Resume.\n *\n * Mounted at the organization level only: a rule is a fact about the org,\n * and its targets are the org's sites.\n */\nexport function SharingRulesCard(props: SharingRulesCardProps) {\n const { orgId, org, canManage, ready } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const rules = useCrmSharingRules(org)\n const sites = useCrmSharingSites({ hostId: null, orgId, enabled: canManage })\n const roster = useOrgMemberDirectory(orgId)\n const campaigns = useCrmCampaigns({ hostId: null, orgId }, { enabled: canManage })\n // The values the Lead source criterion picks from, under their groups (AGL-3511).\n const leadSources = useLeadSourcePicklist(canManage ? orgId : null)\n // The org's names for the lead statuses a rule matches (AGL-3512).\n const leadStatuses = useLeadStatusPicklist(orgId)\n const [editing, setEditing] = useState<CrmSharingRule | null>(null)\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [busy, setBusy] = useState(false)\n const scope = orgId ? { orgId } : null\n\n /** One action, then `rule-continue` until the rule's run has nothing left. */\n const run = useCallback(\n async (action: CrmSharingAction, body: Record<string, unknown>, said: string) => {\n if (!scope) return\n setBusy(true)\n try {\n let answer = await callCrmSharing(user, scope, action, body)\n const ruleId = answer.rule?.id ?? String(body['ruleId'] ?? '')\n while (answer.more && ruleId) {\n answer = await callCrmSharing(user, scope, 'rule-continue', { ruleId })\n }\n enqueueSnackbar(said, { variant: 'success', persist: false })\n setDrawerOpen(false)\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n },\n // `scope` is rebuilt from `orgId` every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [user, orgId, enqueueSnackbar],\n )\n\n const save = (draft: SharingRuleDraft) =>\n void run('rule-save', { rule: draft }, draft.id ? 'Rule saved' : 'Rule added')\n\n const canEdit = ready && canManage && !busy\n const stageLabel = (id: string) =>\n (isCrmLeadStatus(id) ? crmLeadStatusLabelFor(leadStatuses.picklist, id) : null) ??\n CONTACT_LIFECYCLE_STAGE_LABELS[id as ContactLifecycleStage] ??\n id\n return (\n <CardDisplay\n header={'Sharing rules'}\n help={pluginDocsHelp('crmSharing', { anchor: '#sharing-rules' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n variant=\"contained\"\n disabled={!canEdit || rules.length >= CRM_SHARING_RULES_MAX}\n onClick={() => {\n setEditing(null)\n setDrawerOpen(true)\n }}\n >\n {'Add rule'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Share leads, contacts, companies or deals captured on one site with other sites, ' +\n 'automatically. A rule applies to the records you have now and to every one captured ' +\n 'or changed later. Sharing is visibility only: a site never gains a person’s consent ' +\n 'through it.'}\n </Typography>\n {busy ? <LinearProgress /> : null}\n {rules.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No sharing rules. Every record is visible only to the sites that captured it.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Rule'}</TableCell>\n <TableCell>{'Which records'}</TableCell>\n <TableCell>{'Shared with'}</TableCell>\n <TableCell>{'Status'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {rules.map((rule) => (\n <TableRow key={rule.id} hover>\n <TableCell>\n <Typography variant=\"body2\">{rule.name}</Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">\n {describeSharingRuleScope(rule, sites.siteName, {\n owner: roster.nameOf,\n stage: stageLabel,\n })}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">\n {`${describeShareTargets(rule.targets, sites.siteName)}, ${\n rule.access === 'edit' ? 'read and edit' : 'read-only'\n }`}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {runLabel(rule)}\n </Typography>\n </TableCell>\n <TableCell align=\"right\" sx={{ width: 56 }}>\n <RowActionsMenu\n label={rule.name}\n items={[\n {\n key: 'edit',\n label: 'Edit rule',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n disabled: !canEdit || rule.deleting === true,\n onClick: () => {\n setEditing(rule)\n setDrawerOpen(true)\n },\n },\n ...(rule.run && rule.run.status !== 'done'\n ? [\n {\n key: 'resume',\n label: 'Resume',\n icon: <MdiIcon path={mdiRefresh.path} size={0.8} />,\n disabled: !canEdit,\n onClick: () =>\n void run('rule-continue', { ruleId: rule.id }, 'Rule applied'),\n },\n ]\n : []),\n {\n key: 'delete',\n label: 'Delete rule',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !canEdit,\n onClick: () =>\n void run('rule-delete', { ruleId: rule.id }, 'Rule deleted'),\n },\n ]}\n />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n {ready && !canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only a workspace owner or admin can change sharing rules.'}\n </Typography>\n ) : null}\n </Stack>\n <SharingRuleDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n rule={editing}\n sites={sites.sites}\n members={roster.members}\n campaigns={campaigns.options}\n leadSourceList={leadSources.picklist}\n leadStatusList={leadStatuses.picklist}\n busy={busy}\n onSubmit={save}\n />\n </CardDisplay>\n )\n}\nSharingRulesCard.displayName = 'SharingRulesCard'\n\nexport default SharingRulesCard\n"],"names":["CONTACT_LIFECYCLE_STAGE_LABELS","crmLeadStatusLabelFor","isCrmLeadStatus","pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","mdiRefresh","CardDisplay","MdiIcon","RowActionsMenu","ScrollTable","useSnackbar","useUser","Button","LinearProgress","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useCallback","useState","useCrmCampaigns","useCrmSharingRules","useCrmSharingSites","useLeadSourcePicklist","useLeadStatusPicklist","useOrgMemberDirectory","CRM_SHARING_RULES_MAX","describeShareTargets","describeSharingRuleScope","callCrmSharing","SharingRuleDrawer","runLabel","rule","run","deleting","enabled","status","mode","processed","changed","error","SharingRulesCard","props","orgId","org","canManage","ready","data","user","enqueueSnackbar","rules","sites","hostId","roster","campaigns","leadSources","leadStatuses","editing","setEditing","drawerOpen","setDrawerOpen","busy","setBusy","scope","action","body","said","answer","ruleId","id","String","more","variant","persist","message","allowDuplicate","save","draft","canEdit","stageLabel","picklist","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","disabled","length","onClick","spacing","color","size","align","map","hover","name","siteName","owner","nameOf","stage","targets","access","sx","width","label","items","key","icon","path","destructive","open","onClose","members","options","leadSourceList","leadStatusList","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,8BAA8B,EAE9BC,qBAAqB,EACrBC,eAAe,EACfC,cAAc,QACT,eAAc;AACrB,SAASC,gBAAgB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,yBAAwB;AACvF,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AAC3D,OAAOC,oBAAoB,6DAA4D;AACvF,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,MAAM,EACNC,cAAc,EACdC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,eAAe,QAAQ,gCAA4B;AAC5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oB,OAAM;kCACjC;yBAED;;;0BAEN,KAAC9D;gBACCkF,MAAMrD;gBACNsD,SAAS,IAAMrD,cAAc;gBAC7B5B,MAAMyB;gBACNN,OAAOA,MAAMA,KAAK;gBAClB+D,SAAS7D,OAAO6D,OAAO;gBACvB5D,WAAWA,UAAU6D,OAAO;gBAC5BC,gBAAgB7D,YAAYyB,QAAQ;gBACpCqC,gBAAgB7D,aAAawB,QAAQ;gBACrCnB,MAAMA;gBACNyD,UAAU1C;;;;AAIlB;AACAnC,iBAAiB8E,WAAW,GAAG;AAE/B,eAAe9E,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/sharing-rules-card.tsx"],"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'use client'\n\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n type ContactLifecycleStage,\n crmLeadStatusLabelFor,\n isCrmLeadStatus,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline, mdiRefresh } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n LinearProgress,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport { useCallback, useState } from 'react'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { useCrmSharingRules, useCrmSharingSites } from '../hooks/use-crm-sharing'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { useLeadStatusPicklist } from '../hooks/use-lead-status-picklist'\nimport type { CrmOrgDoc } from '../hooks/use-crm-scope'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport {\n CRM_SHARING_RULES_MAX,\n type CrmSharingAction,\n type CrmSharingRule,\n describeShareTargets,\n describeSharingRuleScope,\n} from '../model/crm-sharing'\nimport { crmSettingsPermissionRefusal } from '../model/crm-permissions'\nimport { callCrmSharing } from '../model/crm-sharing-api'\nimport { SharingRuleDrawer, type SharingRuleDraft } from './sharing-rule-drawer'\n\nexport interface SharingRulesCardProps {\n orgId: string | null\n org: CrmOrgDoc\n canManage: boolean\n ready: boolean\n}\n\n/** How far a rule's recompute has got, as the table shows it. */\nfunction runLabel(rule: CrmSharingRule): string {\n const run = rule.run\n if (rule.deleting) return 'Removing what it shared…'\n if (!run) return rule.enabled ? 'On' : 'Off'\n if (run.status === 'running') {\n return `${run.mode === 'remove' ? 'Removing' : 'Applying'} — ${run.processed} checked, ${run.changed} changed`\n }\n if (run.status === 'failed') return run.error ?? 'Stopped'\n return `${rule.enabled ? 'On' : 'Off'} — ${run.changed} ${run.changed === 1 ? 'record' : 'records'} changed`\n}\n\n/**\n * SHARING RULES — the organization's automated sharing (AGL-3336).\n *\n * A rule shares every record it matches with other sites: the existing ones\n * through a recompute that runs when the rule is saved, with its progress\n * on the row, and every later capture or change through the record-written\n * seam. The recompute runs in passes; the card keeps asking while the page\n * is open, and a rule whose run stopped offers Resume.\n *\n * Mounted at the organization level only: a rule is a fact about the org,\n * and its targets are the org's sites.\n */\nexport function SharingRulesCard(props: SharingRulesCardProps) {\n const { orgId, org, canManage, ready } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const rules = useCrmSharingRules(org)\n const sites = useCrmSharingSites({ hostId: null, orgId, enabled: canManage })\n const roster = useOrgMemberDirectory(orgId)\n const campaigns = useCrmCampaigns({ hostId: null, orgId }, { enabled: canManage })\n // The values the Lead source criterion picks from, under their groups (AGL-3511).\n const leadSources = useLeadSourcePicklist(canManage ? orgId : null)\n // The org's names for the lead statuses a rule matches (AGL-3512).\n const leadStatuses = useLeadStatusPicklist(orgId)\n const [editing, setEditing] = useState<CrmSharingRule | null>(null)\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [busy, setBusy] = useState(false)\n const scope = orgId ? { orgId } : null\n\n /** One action, then `rule-continue` until the rule's run has nothing left. */\n const run = useCallback(\n async (action: CrmSharingAction, body: Record<string, unknown>, said: string) => {\n if (!scope) return\n setBusy(true)\n try {\n let answer = await callCrmSharing(user, scope, action, body)\n const ruleId = answer.rule?.id ?? String(body['ruleId'] ?? '')\n while (answer.more && ruleId) {\n answer = await callCrmSharing(user, scope, 'rule-continue', { ruleId })\n }\n enqueueSnackbar(said, { variant: 'success', persist: false })\n setDrawerOpen(false)\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n },\n // `scope` is rebuilt from `orgId` every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [user, orgId, enqueueSnackbar],\n )\n\n const save = (draft: SharingRuleDraft) =>\n void run('rule-save', { rule: draft }, draft.id ? 'Rule saved' : 'Rule added')\n\n const canEdit = ready && canManage && !busy\n const stageLabel = (id: string) =>\n (isCrmLeadStatus(id) ? crmLeadStatusLabelFor(leadStatuses.picklist, id) : null) ??\n CONTACT_LIFECYCLE_STAGE_LABELS[id as ContactLifecycleStage] ??\n id\n return (\n <CardDisplay\n header={'Sharing rules'}\n help={pluginDocsHelp('crmSharing', { anchor: '#sharing-rules' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n variant=\"contained\"\n disabled={!canEdit || rules.length >= CRM_SHARING_RULES_MAX}\n onClick={() => {\n setEditing(null)\n setDrawerOpen(true)\n }}\n >\n {'Add rule'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Share leads, contacts, companies or deals captured on one site with other sites, ' +\n 'automatically. A rule applies to the records you have now and to every one captured ' +\n 'or changed later. Sharing is visibility only: a site never gains a person’s consent ' +\n 'through it.'}\n </Typography>\n {busy ? <LinearProgress /> : null}\n {rules.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No sharing rules. Every record is visible only to the sites that captured it.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Rule'}</TableCell>\n <TableCell>{'Which records'}</TableCell>\n <TableCell>{'Shared with'}</TableCell>\n <TableCell>{'Status'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {rules.map((rule) => (\n <TableRow key={rule.id} hover>\n <TableCell>\n <Typography variant=\"body2\">{rule.name}</Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">\n {describeSharingRuleScope(rule, sites.siteName, {\n owner: roster.nameOf,\n stage: stageLabel,\n })}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">\n {`${describeShareTargets(rule.targets, sites.siteName)}, ${\n rule.access === 'edit' ? 'read and edit' : 'read-only'\n }`}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {runLabel(rule)}\n </Typography>\n </TableCell>\n <TableCell align=\"right\" sx={{ width: 56 }}>\n <RowActionsMenu\n label={rule.name}\n items={[\n {\n key: 'edit',\n label: 'Edit rule',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n disabled: !canEdit || rule.deleting === true,\n onClick: () => {\n setEditing(rule)\n setDrawerOpen(true)\n },\n },\n ...(rule.run && rule.run.status !== 'done'\n ? [\n {\n key: 'resume',\n label: 'Resume',\n icon: <MdiIcon path={mdiRefresh.path} size={0.8} />,\n disabled: !canEdit,\n onClick: () =>\n void run('rule-continue', { ruleId: rule.id }, 'Rule applied'),\n },\n ]\n : []),\n {\n key: 'delete',\n label: 'Delete rule',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !canEdit,\n onClick: () =>\n void run('rule-delete', { ruleId: rule.id }, 'Rule deleted'),\n },\n ]}\n />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n {ready && !canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {crmSettingsPermissionRefusal()}\n </Typography>\n ) : null}\n </Stack>\n <SharingRuleDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n rule={editing}\n sites={sites.sites}\n members={roster.members}\n campaigns={campaigns.options}\n leadSourceList={leadSources.picklist}\n leadStatusList={leadStatuses.picklist}\n busy={busy}\n onSubmit={save}\n />\n </CardDisplay>\n )\n}\nSharingRulesCard.displayName = 'SharingRulesCard'\n\nexport default SharingRulesCard\n"],"names":["CONTACT_LIFECYCLE_STAGE_LABELS","crmLeadStatusLabelFor","isCrmLeadStatus","pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","mdiRefresh","CardDisplay","MdiIcon","RowActionsMenu","ScrollTable","useSnackbar","useUser","Button","LinearProgress","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useCallback","useState","useCrmCampaigns","useCrmSharingRules","useCrmSharingSites","useLeadSourcePicklist","useLeadStatusPicklist","useOrgMemberDirectory","CRM_SHARING_RULES_MAX","describeShareTargets","describeSharingRuleScope","crmSettingsPermissionRefusal","callCrmSharing","SharingRuleDrawer","runLabel","rule","run","deleting","enabled","status","mode","processed","changed","error","SharingRulesCard","props","orgId","org","canManage","ready","data","user","enqueueSnackbar","rules","sites","hostId","roster","campaigns","leadSources","leadStatuses","editing","setEditing","drawerOpen","setDrawerOpen","busy","setBusy","scope","action","body","said","answer","ruleId","id","String","more","variant","persist","message","allowDuplicate","save","draft","canEdit","stageLabel","picklist","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","disabled","length","onClick","spacing","color","size","align","map","hover","name","siteName","owner","nameOf","stage","targets","access","sx","width","label","items","key","icon","path","destructive","open","onClose","members","options","leadSourceList","leadStatusList","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,8BAA8B,EAE9BC,qBAAqB,EACrBC,eAAe,EACfC,cAAc,QACT,eAAc;AACrB,SAASC,gBAAgB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,yBAAwB;AACvF,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AAC3D,OAAOC,oBAAoB,6DAA4D;AACvF,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,MAAM,EACNC,cAAc,EACdC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,eAAe,QAAQ,gCAA4B;AAC5D,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,8BAA0B;AACjF,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,qBAAqB,QAAQ,uCAAmC;AAEzE,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SACEC,qBAAqB,EAGrBC,oBAAoB,EACpBC,wBAAwB,QACnB,0BAAsB;AAC7B,SAASC,4BAA4B,QAAQ,8BAA0B;AACvE,SAASC,cAAc,QAAQ,8BAA0B;AACzD,SAASC,iBAAiB,QAA+B,2BAAuB;AAShF,+DAA+D,GAC/D,SAASC,SAASC,IAAoB;QAOAC;IANpC,MAAMA,MAAMD,KAAKC,GAAG;IACpB,IAAID,KAAKE,QAAQ,EAAE,OAAO;IAC1B,IAA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S ROSTER, for picking and naming a contact's owner
23
23
  * (AGL-2596).
24
24
  *
25
- * Read through `/api/orgs/members`, not from Firestore: the roster is
26
- * evaluated against the QUERY by the rules, and a scoped member's read of
27
- * `orgs/{orgId}/members` is refused for exactly the shape the owner picker
28
- * needs — every row. The route re-derives membership with the Admin SDK and
29
- * answers any member of the org, which is who may see who else is on the
30
- * team.
25
+ * The same read the deal and task cards name their owners and assignees
26
+ * with, {@link useOrgMemberDirectory}: `/api/orgs/members`, not Firestore,
27
+ * because a scoped member's read of `orgs/{orgId}/members` is refused for
28
+ * exactly the shape the owner picker needs, every row. One request per
29
+ * workspace for the life of the page, shared by every card that names a
30
+ * teammate.
31
31
  *
32
- * Read only when ASKED — `enabled` — and once per workspace for the life of
33
- * the mount. The list of contacts does not need the roster until a row
34
- * carries an owner or the create drawer opens, and a request per mount of a
35
- * page that may never show a name is a read paid for nothing.
32
+ * This hook used to make its own request, once per mount, with whatever
33
+ * sign-in it had at that moment, and kept a failed answer as the roster. A
34
+ * contact page whose one request failed (the token not ready yet, a busy
35
+ * route) named its owner by uid until it was reloaded, while the deal page
36
+ * beside it, reading through the directory, named the same person. The
37
+ * directory waits for the signed-in user and asks again after a failure that
38
+ * can clear.
39
+ *
40
+ * Read only when ASKED — `enabled`. The list of contacts does not need the
41
+ * roster until a row carries an owner or the create drawer opens, and a
42
+ * request for a page that may never show a name is a read paid for nothing.
36
43
  */
37
44
  export declare function useOrgMembers(orgId: string | null | undefined, options?: {
38
45
  enabled?: boolean;
@@ -14,84 +14,49 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
- import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
18
- import { crmMemberOption, findOrgMember } from "@aglyn/aglyn";
19
- import { useUser } from "@aglyn/tenant-feature-instance";
20
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
17
+ import { findOrgMember } from "@aglyn/aglyn";
18
+ import { useCallback } from "react";
19
+ import { useOrgMemberDirectory } from "../hooks/use-org-member-directory.js";
21
20
  /**
22
21
  * THE WORKSPACE'S ROSTER, for picking and naming a contact's owner
23
22
  * (AGL-2596).
24
23
  *
25
- * Read through `/api/orgs/members`, not from Firestore: the roster is
26
- * evaluated against the QUERY by the rules, and a scoped member's read of
27
- * `orgs/{orgId}/members` is refused for exactly the shape the owner picker
28
- * needs — every row. The route re-derives membership with the Admin SDK and
29
- * answers any member of the org, which is who may see who else is on the
30
- * team.
24
+ * The same read the deal and task cards name their owners and assignees
25
+ * with, {@link useOrgMemberDirectory}: `/api/orgs/members`, not Firestore,
26
+ * because a scoped member's read of `orgs/{orgId}/members` is refused for
27
+ * exactly the shape the owner picker needs, every row. One request per
28
+ * workspace for the life of the page, shared by every card that names a
29
+ * teammate.
31
30
  *
32
- * Read only when ASKED — `enabled` — and once per workspace for the life of
33
- * the mount. The list of contacts does not need the roster until a row
34
- * carries an owner or the create drawer opens, and a request per mount of a
35
- * page that may never show a name is a read paid for nothing.
31
+ * This hook used to make its own request, once per mount, with whatever
32
+ * sign-in it had at that moment, and kept a failed answer as the roster. A
33
+ * contact page whose one request failed (the token not ready yet, a busy
34
+ * route) named its owner by uid until it was reloaded, while the deal page
35
+ * beside it, reading through the directory, named the same person. The
36
+ * directory waits for the signed-in user and asks again after a failure that
37
+ * can clear.
38
+ *
39
+ * Read only when ASKED — `enabled`. The list of contacts does not need the
40
+ * roster until a row carries an owner or the create drawer opens, and a
41
+ * request for a page that may never show a name is a read paid for nothing.
36
42
  */ export function useOrgMembers(orgId, options = {}) {
37
- var _options_enabled, _ref;
43
+ var _options_enabled;
38
44
  const enabled = (_options_enabled = options.enabled) != null ? _options_enabled : false;
39
- const { data: user } = useUser();
40
- const userRef = useRef(user);
41
- userRef.current = user;
42
- const [loaded, setLoaded] = useState(null);
43
- const loadedOrgId = (_ref = loaded == null ? void 0 : loaded.orgId) != null ? _ref : null;
44
- useEffect(()=>{
45
- if (!enabled || !orgId || loadedOrgId === orgId) return undefined;
46
- let active = true;
47
- void authorizedFetch(userRef.current, `/api/orgs/members?orgId=${encodeURIComponent(orgId)}`).then(async (response)=>response.ok ? await response.json() : {}).then((json)=>{
48
- if (!active) return;
49
- const members = Array.isArray(json == null ? void 0 : json.members) ? json.members : [];
50
- setLoaded({
51
- orgId,
52
- options: members.map((member)=>crmMemberOption(member != null ? member : {})).filter((option)=>option !== null).sort((a, b)=>a.label.localeCompare(b.label))
53
- });
54
- }).catch(()=>{
55
- // An unanswered roster is an EMPTY picker, not a broken page: the
56
- // owner column falls back to the uid, and the picker says it has
57
- // nobody to offer.
58
- if (active) setLoaded({
59
- orgId,
60
- options: []
61
- });
62
- });
63
- return ()=>{
64
- active = false;
65
- };
66
- }, [
67
- enabled,
68
- orgId,
69
- loadedOrgId
70
- ]);
71
- const current = loaded && loaded.orgId === orgId ? loaded : null;
72
- const roster = useMemo(()=>{
73
- var _ref;
74
- return (_ref = current == null ? void 0 : current.options) != null ? _ref : [];
75
- }, [
76
- current
77
- ]);
78
- const memberName = useCallback((ref)=>{
79
- var _ref;
80
- var _findOrgMember;
81
- return (_ref = (_findOrgMember = findOrgMember(roster, ref)) == null ? void 0 : _findOrgMember.label) != null ? _ref : ref;
82
- }, [
83
- roster
84
- ]);
45
+ const directory = useOrgMemberDirectory(enabled ? orgId : null);
46
+ const { members, nameOf } = directory;
85
47
  const memberEmail = useCallback((ref)=>{
86
- const member = findOrgMember(roster, ref);
48
+ const member = findOrgMember(members, ref);
87
49
  return (member == null ? void 0 : member.email) || (member == null ? void 0 : member.label) || ref;
88
50
  }, [
89
- roster
51
+ members
90
52
  ]);
91
53
  return {
92
- options: roster,
93
- ready: current !== null,
94
- memberName,
54
+ options: members,
55
+ // An unanswered roster is an EMPTY picker, not a broken page: the owner
56
+ // column falls back to the uid, and the picker says it has nobody to
57
+ // offer.
58
+ ready: enabled && Boolean(orgId) && !directory.loading,
59
+ memberName: nameOf,
95
60
  memberEmail
96
61
  };
97
62
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/use-org-members.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'use client'\n\nimport {\n authorizedFetch,\n type TokenSource,\n} from '@aglyn/shared-util-http/authorized-token'\nimport { type CrmMemberOption, crmMemberOption, findOrgMember } from '@aglyn/aglyn'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\n/** One team member, as an owner picker lists them. */\nexport type OrgMemberOption = CrmMemberOption\n\nexport interface OrgMembers {\n /** Every member of the workspace, by name. */\n options: OrgMemberOption[]\n /** The roster has answered — an empty list is then a real answer. */\n ready: boolean\n /**\n * The name to show for a stored reference — a uid, or an address the\n * roster has — or the reference itself when the roster does not know it.\n */\n memberName: (ref: string) => string\n /**\n * The member's ADDRESS for a stored reference — what a CSV export writes\n * in the owner column, because the import resolves an owner by email —\n * falling back to the name and then to the reference itself.\n */\n memberEmail: (ref: string) => string\n}\n\n/**\n * THE WORKSPACE'S ROSTER, for picking and naming a contact's owner\n * (AGL-2596).\n *\n * Read through `/api/orgs/members`, not from Firestore: the roster is\n * evaluated against the QUERY by the rules, and a scoped member's read of\n * `orgs/{orgId}/members` is refused for exactly the shape the owner picker\n * needs — every row. The route re-derives membership with the Admin SDK and\n * answers any member of the org, which is who may see who else is on the\n * team.\n *\n * Read only when ASKED — `enabled` — and once per workspace for the life of\n * the mount. The list of contacts does not need the roster until a row\n * carries an owner or the create drawer opens, and a request per mount of a\n * page that may never show a name is a read paid for nothing.\n */\nexport function useOrgMembers(\n orgId: string | null | undefined,\n options: { enabled?: boolean } = {},\n): OrgMembers {\n const enabled = options.enabled ?? false\n const { data: user } = useUser()\n const userRef = useRef(user)\n userRef.current = user\n const [loaded, setLoaded] = useState<{\n orgId: string\n options: OrgMemberOption[]\n } | null>(null)\n const loadedOrgId = loaded?.orgId ?? null\n\n useEffect(() => {\n if (!enabled || !orgId || loadedOrgId === orgId) return undefined\n let active = true\n void authorizedFetch(\n userRef.current as TokenSource | null | undefined,\n `/api/orgs/members?orgId=${encodeURIComponent(orgId)}`,\n )\n .then(async (response) =>\n response.ok ? ((await response.json()) as { members?: unknown[] }) : {},\n )\n .then((json) => {\n if (!active) return\n const members = Array.isArray(json?.members) ? json.members : []\n setLoaded({\n orgId,\n options: members\n .map((member) => crmMemberOption((member ?? {}) as Record<string, unknown>))\n .filter((option): option is OrgMemberOption => option !== null)\n .sort((a, b) => a.label.localeCompare(b.label)),\n })\n })\n .catch(() => {\n // An unanswered roster is an EMPTY picker, not a broken page: the\n // owner column falls back to the uid, and the picker says it has\n // nobody to offer.\n if (active) setLoaded({ orgId, options: [] })\n })\n return () => {\n active = false\n }\n }, [enabled, orgId, loadedOrgId])\n\n const current = loaded && loaded.orgId === orgId ? loaded : null\n const roster = useMemo(() => current?.options ?? [], [current])\n const memberName = useCallback(\n (ref: string) => findOrgMember(roster, ref)?.label ?? ref,\n [roster],\n )\n const memberEmail = useCallback(\n (ref: string) => {\n const member = findOrgMember(roster, ref)\n return member?.email || member?.label || ref\n },\n [roster],\n )\n return {\n options: roster,\n ready: current !== null,\n memberName,\n memberEmail,\n }\n}\n\nexport default useOrgMembers\n"],"names":["authorizedFetch","crmMemberOption","findOrgMember","useUser","useCallback","useEffect","useMemo","useRef","useState","useOrgMembers","orgId","options","enabled","data","user","userRef","current","loaded","setLoaded","loadedOrgId","undefined","active","encodeURIComponent","then","response","ok","json","members","Array","isArray","map","member","filter","option","sort","a","b","label","localeCompare","catch","roster","memberName","ref","memberEmail","email","ready"],"mappings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ACL,kEAAkE;YAClE,iEAAiE;YACjE,mBAAmB;YACnB,IAAIlB,QAAQH,UAAU;gBAAER;gBAAOC,SAAS,EAAE;YAAC;QAC7C;QACF,OAAO;YACLU,SAAS;QACX;IACF,GAAG;QAACT;QAASF;QAAOS;KAAY;IAEhC,MAAMH,UAAUC,UAAUA,OAAOP,KAAK,KAAKA,QAAQO,SAAS;IAC5D,MAAMuB,SAASlC,QAAQ;;uBAAMU,2BAAAA,QAASL,OAAO,mBAAI,EAAE;OAAE;QAACK;KAAQ;IAC9D,MAAMyB,aAAarC,YACjB,CAACsC;;YAAgBxC;wBAAAA,iBAAAA,cAAcsC,QAAQE,yBAAtBxC,eAA4BmC,KAAK,mBAAIK;OACtD;QAACF;KAAO;IAEV,MAAMG,cAAcvC,YAClB,CAACsC;QACC,MAAMX,SAAS7B,cAAcsC,QAAQE;QACrC,OAAOX,CAAAA,0BAAAA,OAAQa,KAAK,MAAIb,0BAAAA,OAAQM,KAAK,KAAIK;IAC3C,GACA;QAACF;KAAO;IAEV,OAAO;QACL7B,SAAS6B;QACTK,OAAO7B,YAAY;QACnByB;QACAE;IACF;AACF;AAEA,eAAelC,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/use-org-members.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'use client'\n\nimport { type CrmMemberOption, findOrgMember } from '@aglyn/aglyn'\nimport { useCallback } from 'react'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\n\n/** One team member, as an owner picker lists them. */\nexport type OrgMemberOption = CrmMemberOption\n\nexport interface OrgMembers {\n /** Every member of the workspace, by name. */\n options: OrgMemberOption[]\n /** The roster has answered — an empty list is then a real answer. */\n ready: boolean\n /**\n * The name to show for a stored reference — a uid, or an address the\n * roster has — or the reference itself when the roster does not know it.\n */\n memberName: (ref: string) => string\n /**\n * The member's ADDRESS for a stored reference — what a CSV export writes\n * in the owner column, because the import resolves an owner by email —\n * falling back to the name and then to the reference itself.\n */\n memberEmail: (ref: string) => string\n}\n\n/**\n * THE WORKSPACE'S ROSTER, for picking and naming a contact's owner\n * (AGL-2596).\n *\n * The same read the deal and task cards name their owners and assignees\n * with, {@link useOrgMemberDirectory}: `/api/orgs/members`, not Firestore,\n * because a scoped member's read of `orgs/{orgId}/members` is refused for\n * exactly the shape the owner picker needs, every row. One request per\n * workspace for the life of the page, shared by every card that names a\n * teammate.\n *\n * This hook used to make its own request, once per mount, with whatever\n * sign-in it had at that moment, and kept a failed answer as the roster. A\n * contact page whose one request failed (the token not ready yet, a busy\n * route) named its owner by uid until it was reloaded, while the deal page\n * beside it, reading through the directory, named the same person. The\n * directory waits for the signed-in user and asks again after a failure that\n * can clear.\n *\n * Read only when ASKED — `enabled`. The list of contacts does not need the\n * roster until a row carries an owner or the create drawer opens, and a\n * request for a page that may never show a name is a read paid for nothing.\n */\nexport function useOrgMembers(\n orgId: string | null | undefined,\n options: { enabled?: boolean } = {},\n): OrgMembers {\n const enabled = options.enabled ?? false\n const directory = useOrgMemberDirectory(enabled ? orgId : null)\n const { members, nameOf } = directory\n const memberEmail = useCallback(\n (ref: string) => {\n const member = findOrgMember(members, ref)\n return member?.email || member?.label || ref\n },\n [members],\n )\n return {\n options: members,\n // An unanswered roster is an EMPTY picker, not a broken page: the owner\n // column falls back to the uid, and the picker says it has nobody to\n // offer.\n ready: enabled && Boolean(orgId) && !directory.loading,\n memberName: nameOf,\n memberEmail,\n }\n}\n\nexport default useOrgMembers\n"],"names":["findOrgMember","useCallback","useOrgMemberDirectory","useOrgMembers","orgId","options","enabled","directory","members","nameOf","memberEmail","ref","member","email","label","ready","Boolean","loading","memberName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAA+BA,aAAa,QAAQ,eAAc;AAClE,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,qBAAqB,QAAQ,uCAAmC;AAuBzE;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASC,cACdC,KAAgC,EAChCC,UAAiC,CAAC,CAAC;QAEnBA;IAAhB,MAAMC,WAAUD,mBAAAA,QAAQC,OAAO,YAAfD,mBAAmB;IACnC,MAAME,YAAYL,sBAAsBI,UAAUF,QAAQ;IAC1D,MAAM,EAAEI,OAAO,EAAEC,MAAM,EAAE,GAAGF;IAC5B,MAAMG,cAAcT,YAClB,CAACU;QACC,MAAMC,SAASZ,cAAcQ,SAASG;QACtC,OAAOC,CAAAA,0BAAAA,OAAQC,KAAK,MAAID,0BAAAA,OAAQE,KAAK,KAAIH;IAC3C,GACA;QAACH;KAAQ;IAEX,OAAO;QACLH,SAASG;QACT,wEAAwE;QACxE,qEAAqE;QACrE,SAAS;QACTO,OAAOT,WAAWU,QAAQZ,UAAU,CAACG,UAAUU,OAAO;QACtDC,YAAYT;QACZC;IACF;AACF;AAEA,eAAeP,cAAa"}
@@ -20,7 +20,11 @@
20
20
  *
21
21
  * Its recipes (AGL-2626), so the automation editor's Recipes menu offers
22
22
  * "Welcome a new lead" on a site whose CRM pages were never opened, and the
23
- * automation it builds names the recipe it began as. Light by construction:
24
- * the recipes are definitions, and nothing here reaches Firestore or React.
23
+ * automation it builds names the recipe it began as. And its keys, "Change CRM
24
+ * settings" and "Move contacts and deals between stages" (AGL-4047), so the
25
+ * role editor offers them, a custom role or a per-member override keeps them,
26
+ * and the routes and the projection resolve them before any CRM surface loads.
27
+ * Light by construction: all of it is definitions, and nothing here reaches
28
+ * Firestore or React.
25
29
  */
26
30
  export declare function registerCrmDeclarations(): void;
@@ -16,7 +16,10 @@
16
16
  */ // The seam from its own module, not the plugin-manager barrel: both apps load
17
17
  // this at boot, and the barrel reaches the client contexts.
18
18
  import { registerInteractionRecipes } from "@aglyn/aglyn/plugin-manager/interaction-recipes";
19
+ import { registerPluginEntitlements } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
20
+ import { registerPluginPermissions } from "@aglyn/aglyn/plugin-manager/plugin-permissions";
19
21
  import { BUNDLE_ID } from "./constants/bundle-common.js";
22
+ import { CRM_PERMISSIONS, CRM_SITE_PERMISSIONS } from "./model/crm-permissions.js";
20
23
  import { CRM_ACTION_RECIPES } from "./model/crm-recipes.js";
21
24
  /**
22
25
  * The CRM's DECLARATIONS: what another surface reads of this plugin before any
@@ -24,12 +27,21 @@ import { CRM_ACTION_RECIPES } from "./model/crm-recipes.js";
24
27
  *
25
28
  * Its recipes (AGL-2626), so the automation editor's Recipes menu offers
26
29
  * "Welcome a new lead" on a site whose CRM pages were never opened, and the
27
- * automation it builds names the recipe it began as. Light by construction:
28
- * the recipes are definitions, and nothing here reaches Firestore or React.
30
+ * automation it builds names the recipe it began as. And its keys, "Change CRM
31
+ * settings" and "Move contacts and deals between stages" (AGL-4047), so the
32
+ * role editor offers them, a custom role or a per-member override keeps them,
33
+ * and the routes and the projection resolve them before any CRM surface loads.
34
+ * Light by construction: all of it is definitions, and nothing here reaches
35
+ * Firestore or React.
29
36
  */ export function registerCrmDeclarations() {
30
37
  registerInteractionRecipes(CRM_ACTION_RECIPES, {
31
38
  pluginId: BUNDLE_ID
32
39
  });
40
+ registerPluginPermissions(CRM_PERMISSIONS);
41
+ registerPluginEntitlements({
42
+ pluginId: BUNDLE_ID,
43
+ orgPermissions: CRM_SITE_PERMISSIONS
44
+ });
33
45
  }
34
46
 
35
47
  //# sourceMappingURL=declarations.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.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// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionRecipes } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_ACTION_RECIPES } from './model/crm-recipes'\n\n/**\n * The CRM's DECLARATIONS: what another surface reads of this plugin before any\n * of its own surfaces load, in both apps and in the console's browser.\n *\n * Its recipes (AGL-2626), so the automation editor's Recipes menu offers\n * \"Welcome a new lead\" on a site whose CRM pages were never opened, and the\n * automation it builds names the recipe it began as. Light by construction:\n * the recipes are definitions, and nothing here reaches Firestore or React.\n */\nexport function registerCrmDeclarations(): void {\n registerInteractionRecipes(CRM_ACTION_RECIPES, { pluginId: BUNDLE_ID })\n}\n"],"names":["registerInteractionRecipes","BUNDLE_ID","CRM_ACTION_RECIPES","registerCrmDeclarations","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,kBAAkB,QAAQ,yBAAqB;AAExD;;;;;;;;CAQC,GACD,OAAO,SAASC;IACdH,2BAA2BE,oBAAoB;QAAEE,UAAUH;IAAU;AACvE"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.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// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionRecipes } from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport { registerPluginEntitlements } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { registerPluginPermissions } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_PERMISSIONS, CRM_SITE_PERMISSIONS } from './model/crm-permissions'\nimport { CRM_ACTION_RECIPES } from './model/crm-recipes'\n\n/**\n * The CRM's DECLARATIONS: what another surface reads of this plugin before any\n * of its own surfaces load, in both apps and in the console's browser.\n *\n * Its recipes (AGL-2626), so the automation editor's Recipes menu offers\n * \"Welcome a new lead\" on a site whose CRM pages were never opened, and the\n * automation it builds names the recipe it began as. And its keys, \"Change CRM\n * settings\" and \"Move contacts and deals between stages\" (AGL-4047), so the\n * role editor offers them, a custom role or a per-member override keeps them,\n * and the routes and the projection resolve them before any CRM surface loads.\n * Light by construction: all of it is definitions, and nothing here reaches\n * Firestore or React.\n */\nexport function registerCrmDeclarations(): void {\n registerInteractionRecipes(CRM_ACTION_RECIPES, { pluginId: BUNDLE_ID })\n registerPluginPermissions(CRM_PERMISSIONS)\n registerPluginEntitlements({ pluginId: BUNDLE_ID, orgPermissions: CRM_SITE_PERMISSIONS })\n}\n"],"names":["registerInteractionRecipes","registerPluginEntitlements","registerPluginPermissions","BUNDLE_ID","CRM_PERMISSIONS","CRM_SITE_PERMISSIONS","CRM_ACTION_RECIPES","registerCrmDeclarations","pluginId","orgPermissions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,yBAAyB,QAAQ,iDAAgD;AAC1F,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,eAAe,EAAEC,oBAAoB,QAAQ,6BAAyB;AAC/E,SAASC,kBAAkB,QAAQ,yBAAqB;AAExD;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC;IACdP,2BAA2BM,oBAAoB;QAAEE,UAAUL;IAAU;IACrED,0BAA0BE;IAC1BH,2BAA2B;QAAEO,UAAUL;QAAWM,gBAAgBJ;IAAqB;AACzF"}
@@ -25,6 +25,7 @@ import { registerPluginRecordEmailStateWriter } from "@aglyn/aglyn/plugin-manage
25
25
  import { registerPluginRecordOriginWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-origin";
26
26
  import { registerPluginRecordTimelineWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-timeline";
27
27
  import { registerPluginRecordWrittenListener } from "@aglyn/aglyn/plugin-manager/plugin-record-written";
28
+ import { registerPluginScopeSharingPatch } from "@aglyn/aglyn/plugin-manager/plugin-scope-sharing";
28
29
  import { registerServerStepExecutor } from "@aglyn/aglyn/plugin-manager/plugin-server-steps";
29
30
  import { registerPluginUsageMeter } from "@aglyn/aglyn/plugin-manager/plugin-usage-meters";
30
31
  import { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from "./constants/bundle-common.js";
@@ -170,6 +171,21 @@ import { summarizeConsentGroupChange } from "./model/consent-group-summary.js";
170
171
  registerPluginPersonRecords(crmPersonRecordsService, {
171
172
  pluginId: BUNDLE_ID
172
173
  });
174
+ // A record's scoped list fields follow its sites, so the sweep that keeps
175
+ // "all sites except" current restamps them in the same write (AGL-4047).
176
+ // Deferred like the capture.
177
+ registerPluginScopeSharingPatch([
178
+ 'contacts',
179
+ 'leads',
180
+ 'companies',
181
+ 'deals',
182
+ 'crmTasks'
183
+ ], async (collection, next)=>{
184
+ const { crmScopeSharingPatch } = await import("./server/scope-sharing-patch.js");
185
+ return crmScopeSharingPatch(collection, next);
186
+ }, {
187
+ pluginId: BUNDLE_ID
188
+ });
173
189
  // The CRM's own share of a lead conversion (AGL-3254): the lead's
174
190
  // campaigns go onto the contact's facet. Through the seam every door
175
191
  // that converts a lead reaches, and deferred like the capture: the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The contract from its own module, not the plugin-manager barrel: boot needs\n// the registry and nothing else, and the barrel reaches the client contexts.\nimport { registerPluginConsentGroupParticipant } from '@aglyn/aglyn/plugin-manager/plugin-consent-group-change'\nimport {\n registerPluginContactCaptureWriter,\n type PluginContactCaptureWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { registerPluginLeadConversionListener } from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { registerPluginPersonMatcher } from '@aglyn/aglyn/plugin-manager/plugin-person-matches'\nimport {\n registerPluginPersonRecords,\n type PluginPersonRecords,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n registerPluginRecordIndex,\n type PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { registerPluginRecordEmailStateWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { registerPluginRecordOriginWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n registerPluginRecordTimelineWriter,\n type PluginRecordTimelineWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { registerPluginRecordWrittenListener } from '@aglyn/aglyn/plugin-manager/plugin-record-written'\nimport { registerServerStepExecutor } from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport { registerPluginUsageMeter } from '@aglyn/aglyn/plugin-manager/plugin-usage-meters'\nimport { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from './constants/bundle-common'\nimport { summarizeConsentGroupChange } from './model/consent-group-summary'\n\n/**\n * The CRM as the plugin that keeps people.\n *\n * Light by construction, the way the workflows listener is: the capture\n * itself is imported when the first one arrives, not when the process\n * starts, so a process that never captures anybody pays for this object and\n * nothing else. That matters because this registers in EVERY server process,\n * including ones that will never touch the CRM.\n */\nexport const crmContactCaptureWriter: PluginContactCaptureWriter = {\n async capture(request) {\n const { captureContactForCrm } = await import('./server/capture-contact')\n return await captureContactForCrm(request)\n },\n}\n\n/**\n * The CRM as the plugin other plugins ask for people (AGL-3080), deferred\n * like the capture: `server/person-records.ts` and the Admin SDK it brings\n * load with the first question, not when the process starts.\n */\nexport const crmPersonRecordsService: PluginPersonRecords = {\n async find(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.find(request)\n },\n async read(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.read(request)\n },\n async fileUnder(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.fileUnder(request)\n },\n async recordRefund(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.recordRefund(request)\n },\n async peopleInView(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.peopleInView(request)\n },\n async wroteIn(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.wroteIn(request)\n },\n async search(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.search(request)\n },\n // The walk a connector copies a site's people out by (AGL-3639).\n async changedSince(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.changedSince(request)\n },\n}\n\n/**\n * The `pipeline` record index, its reads loaded with the first one — see\n * `server/pipeline-record-index.ts` for what it answers.\n */\nexport const crmPipelineRecordIndex: PluginRecordIndex = {\n async list(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.list(request)\n },\n async get(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.get(request)\n },\n}\n\n/** One of `server/crm-record-indexes.ts`'s indexes, its reads loaded with the first one. */\nfunction lazyCrmRecordIndex(kind: 'company' | 'messageTemplate'): PluginRecordIndex {\n return {\n async list(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].list(request)\n },\n async get(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].get(request)\n },\n }\n}\n\n/** The companies a person works for, as another plugin reads them (AGL-3080). */\nexport const crmCompanyRecordIndex = lazyCrmRecordIndex('company')\n\n/** The email templates and snippets reps write, as another plugin reads them (AGL-3080). */\nexport const crmMessageTemplateRecordIndex = lazyCrmRecordIndex('messageTemplate')\n\n/**\n * The CRM's writer on the record-timeline seam (AGL-2981), deferred: the\n * writer and the Admin SDK it brings load with the first entry filed.\n */\nexport const crmRecordTimelineWriter: PluginRecordTimelineWriter = {\n async logActivity(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).logActivity(request)\n },\n async createTask(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).createTask(request)\n },\n async recordEmailDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordEmailDelivery!(request)\n },\n // A delivery event for a message the CRM tagged (AGL-2615, AGL-3080).\n async recordTaggedDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordTaggedDelivery!(request)\n },\n // An automation's email to the person its event is about, filed on that\n // person's timeline with its delivery state (AGL-2615, AGL-3080).\n async prepareEmail(request) {\n const { prepareCrmRecordEmail } = await import('./server/automation-steps')\n return prepareCrmRecordEmail(request)\n },\n}\n\n/**\n * The plugin's SERVER declarations: what the server must know at boot, before\n * any door of the CRM has been called.\n *\n * ## Why a declaration and not a `tenantApi` registration\n *\n * The doors that meet a person mostly never load this plugin. A form\n * submission is a core route; an order and a booking are captured inside\n * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry\n * filled by a surface that did not load answers `null` — which\n * `capturePluginContact` defines as \"this workspace has no record system\", a\n * sentence that would be false and silent. Orders would stop creating\n * contacts with nothing red anywhere, which is the AGL-3025 shape.\n *\n * Running from both apps' generated server-declarations manifest at boot is\n * what makes the answer true in every process. It is also called from the\n * plugin's own API register functions, so a process whose boot did not run it\n * still registers the writer the first time a CRM door loads. Registering\n * twice replaces in place.\n *\n * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A\n * second plugin's is refused naming both, and the incumbent keeps serving.\n */\nexport function registerCrmServerDeclarations(): void {\n registerPluginContactCaptureWriter(crmContactCaptureWriter, {\n pluginId: BUNDLE_ID,\n })\n // The other half of keeping people (AGL-3080): another plugin that holds\n // an address, or a record the CRM handed it, asks here for the person —\n // a flow email's consent read, a refund, an automation filing somebody\n // under a campaign — and never opens the CRM's collections itself.\n registerPluginPersonRecords(crmPersonRecordsService, { pluginId: BUNDLE_ID })\n // The CRM's own share of a lead conversion (AGL-3254): the lead's\n // campaigns go onto the contact's facet. Through the seam every door\n // that converts a lead reaches, and deferred like the capture: the\n // module that writes is loaded when the first conversion arrives, and\n // it brings the Admin SDK with it — this file defers the plugin's OWN\n // module only. A library imported statically across the plugin cannot\n // also be lazy-loaded here: `enforce-module-boundaries` refuses every\n // static import of a library the project lazy-loads anywhere.\n registerPluginLeadConversionListener(\n async (request) => {\n const { carryLeadCampaignsOnConversion } =\n await import('./server/lead-campaign-carry')\n return carryLeadCampaignsOnConversion(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // \"Did this workspace already know this person?\" (AGL-3289), asked by the\n // staff console's acquisition card. Deferred like the rest: the reads load\n // when a staff member first opens a card, not when the process starts.\n registerPluginPersonMatcher(\n async (request) => {\n const { matchCrmPeople } = await import('./server/person-matches')\n return matchCrmPeople(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's share of a consent group change (AGL-3320): a contact's\n // per-site refusal carried across a separation, and the records keyed by a\n // group re-homed after the flip. Registered whether or not a workspace has\n // the CRM switched on, because the contacts — and the refusals on them —\n // outlive the switch. Deferred like the rest; the summary is plain words\n // and answers synchronously.\n // The record email-state writer (AGL-3245), here as well as in the console\n // API so the tenant's doors reach it too: a form submission's capture is\n // checked for deliverability after its response (AGL-3328), and the \"Would\n // bounce\" that check finds is written through this seam. Deferred like the\n // rest; the console's own registration replaces this one with the same\n // writer, loaded eagerly.\n registerPluginRecordEmailStateWriter(\n {\n async stamp(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).stamp(request)\n },\n // A send's first opens and clicks, stamped on the contacts they name\n // (AGL-2616) — the campaign webhook's courtesy, deferred like the rest.\n async engaged(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).engaged!(request)\n },\n // A delivered campaign's leads, moved to Nurturing (AGL-3446).\n async reached(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).reached!(request)\n },\n // A lead that wrote back, moved to Working (AGL-3080).\n async replied(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).replied!(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // The record timeline writer (AGL-2981), here as well as in the API\n // surfaces so a door in either app reaches it: a booking confirmed on the\n // tenant, or by the payment webhook, files its meeting and follow-up\n // through it (AGL-2660). Deferred like the rest; an API registration\n // replaces this one with the same writer, loaded eagerly.\n registerPluginRecordTimelineWriter(crmRecordTimelineWriter, { pluginId: BUNDLE_ID })\n // Where a person came from (AGL-3519): a door the CRM does not run — the\n // platform's account sign-up, a sequence enrolling someone — names its\n // origin, and the CRM stamps the built-in Lead source on a record holding\n // none. Deferred like the rest.\n registerPluginRecordOriginWriter(\n {\n async stamp(request) {\n const { crmRecordOriginWriter } = await import('./server/record-origin')\n return crmRecordOriginWriter.stamp(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // Sharing rules (AGL-3336), re-evaluated after every server write of a\n // lead, a contact, a company or a deal: the core tells its record-written\n // listeners from the list-field restamp every such writer ends with, in\n // both apps — a form's capture on the tenant, an edit in the console.\n // Deferred like the rest: an org with no rules pays one cached read.\n registerPluginRecordWrittenListener(\n async (event) => {\n const { crmSharingRecordWritten } = await import('./server/crm-sharing')\n await crmSharingRecordWritten(event)\n },\n { pluginId: BUNDLE_ID, key: 'sharing' },\n )\n // The organization's pipelines and their stages, as another plugin reads\n // them (AGL-3080): an automation the AI drafts names the stage a deal\n // moves to. Deferred like the rest: the reads load with the first one.\n registerPluginRecordIndex('pipeline', crmPipelineRecordIndex, { pluginId: BUNDLE_ID })\n // The company a person works for, and the templates reps write, as a sales\n // sequence reads them (AGL-3080). Deferred like the rest.\n registerPluginRecordIndex('company', crmCompanyRecordIndex, { pluginId: BUNDLE_ID })\n registerPluginRecordIndex('messageTemplate', crmMessageTemplateRecordIndex, { pluginId: BUNDLE_ID })\n // The automation steps that write the CRM (AGL-2605, AGL-3080), run for the\n // workflows engine through the server-step seam and declared under\n // `serverSteps`. Deferred like the rest: the writes load with the first step.\n registerServerStepExecutor(\n CRM_STEP_TYPES,\n async (request) => (await import('./server/automation-steps')).runCrmAutomationStep(request),\n { pluginId: BUNDLE_ID },\n )\n registerPluginConsentGroupParticipant(\n {\n async preview(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.preview(request)\n },\n async run(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.run(request)\n },\n summarize: summarizeConsentGroupChange,\n },\n { pluginId: BUNDLE_ID },\n )\n // The records band in the monthly usage sweep, a core cron that never\n // loads a CRM door; declared in `usageAxes` so the sweep refuses to bill a\n // month without it. Deferred like the rest: the counts load with the\n // first sweep.\n registerPluginUsageMeter({\n pluginId: BUNDLE_ID,\n id: CRM_RECORDS_METER_ID,\n measure: async (context) => {\n const { measureCrmRecords } = await import('./server/crm-records-meter')\n return measureCrmRecords(context)\n },\n })\n}\n\n"],"names":["registerPluginConsentGroupParticipant","registerPluginContactCaptureWriter","registerPluginLeadConversionListener","registerPluginPersonMatcher","registerPluginPersonRecords","registerPluginRecordIndex","registerPluginRecordEmailStateWriter","registerPluginRecordOriginWriter","registerPluginRecordTimelineWriter","registerPluginRecordWrittenListener","registerServerStepExecutor","registerPluginUsageMeter","BUNDLE_ID","CRM_RECORDS_METER_ID","CRM_STEP_TYPES","summarizeConsentGroupChange","crmContactCaptureWriter","capture","request","captureContactForCrm","crmPersonRecordsService","find","crmPersonRecords","read","fileUnder","recordRefund","peopleInView","wroteIn","search","changedSince","crmPipelineRecordIndex","list","pipelineRecordIndex","get","lazyCrmRecordIndex","kind","crmRecordIndexes","crmCompanyRecordIndex","crmMessageTemplateRecordIndex","crmRecordTimelineWriter","logActivity","createCrmRecordTimelineWriter","defaultCrmRecordTimelineDeps","createTask","recordEmailDelivery","recordTaggedDelivery","prepareEmail","prepareCrmRecordEmail","registerCrmServerDeclarations","pluginId","carryLeadCampaignsOnConversion","matchCrmPeople","stamp","createCrmRecordEmailStateWriter","defaultCrmRecordEmailStateDeps","engaged","reached","replied","crmRecordOriginWriter","event","crmSharingRecordWritten","key","runCrmAutomationStep","preview","consentGroupParticipant","run","summarize","id","measure","context","measureCrmRecords"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,6EAA6E;AAC7E,SAASA,qCAAqC,QAAQ,0DAAyD;AAC/G,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,oCAAoC,QAAQ,qDAAoD;AACzG,SAASC,2BAA2B,QAAQ,oDAAmD;AAC/F,SACEC,2BAA2B,QAEtB,oDAAmD;AAC1D,SACEC,yBAAyB,QAEpB,kDAAiD;AACxD,SAASC,oCAAoC,QAAQ,wDAAuD;AAC5G,SAASC,gCAAgC,QAAQ,mDAAkD;AACnG,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,mCAAmC,QAAQ,oDAAmD;AACvG,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,wBAAwB,QAAQ,kDAAiD;AAC1F,SAASC,SAAS,EAAEC,oBAAoB,EAAEC,cAAc,QAAQ,+BAA2B;AAC3F,SAASC,2BAA2B,QAAQ,mCAA+B;AAE3E;;;;;;;;CAQC,GACD,OAAO,MAAMC,0BAAsD;IACjE,MAAMC,SAAQC,OAAO;QACnB,MAAM,EAAEC,oBAAoB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC9C,OAAO,MAAMA,qBAAqBD;IACpC;AACF,EAAC;AAED;;;;CAIC,GACD,OAAO,MAAME,0BAA+C;IAC1D,MAAMC,MAAKH,OAAO;QAChB,MAAM,EAAEI,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,OAAOA,iBAAiBD,IA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;IACnE,8EAA8E;IAC9EF,2BACEI,gBACA,OAAOI,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA2B,EAAG4C,oBAAoB,CAAC5C,UACpF;QAAE+B,UAAUrC;IAAU;IAExBZ,sCACE;QACE,MAAM+D,SAAQ7C,OAAO;YACnB,MAAM,EAAE8C,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBD,OAAO,CAAC7C;QACzC;QACA,MAAM+C,KAAI/C,OAAO;YACf,MAAM,EAAE8C,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBC,GAAG,CAAC/C;QACrC;QACAgD,WAAWnD;IACb,GACA;QAAEkC,UAAUrC;IAAU;IAExB,sEAAsE;IACtE,2EAA2E;IAC3E,qEAAqE;IACrE,eAAe;IACfD,yBAAyB;QACvBsC,UAAUrC;QACVuD,IAAItD;QACJuD,SAAS,OAAOC;YACd,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC3C,OAAOA,kBAAkBD;QAC3B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The contract from its own module, not the plugin-manager barrel: boot needs\n// the registry and nothing else, and the barrel reaches the client contexts.\nimport { registerPluginConsentGroupParticipant } from '@aglyn/aglyn/plugin-manager/plugin-consent-group-change'\nimport {\n registerPluginContactCaptureWriter,\n type PluginContactCaptureWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { registerPluginLeadConversionListener } from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { registerPluginPersonMatcher } from '@aglyn/aglyn/plugin-manager/plugin-person-matches'\nimport {\n registerPluginPersonRecords,\n type PluginPersonRecords,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n registerPluginRecordIndex,\n type PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { registerPluginRecordEmailStateWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { registerPluginRecordOriginWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n registerPluginRecordTimelineWriter,\n type PluginRecordTimelineWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { registerPluginRecordWrittenListener } from '@aglyn/aglyn/plugin-manager/plugin-record-written'\nimport { registerPluginScopeSharingPatch } from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport { registerServerStepExecutor } from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport { registerPluginUsageMeter } from '@aglyn/aglyn/plugin-manager/plugin-usage-meters'\nimport { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from './constants/bundle-common'\nimport { summarizeConsentGroupChange } from './model/consent-group-summary'\n\n/**\n * The CRM as the plugin that keeps people.\n *\n * Light by construction, the way the workflows listener is: the capture\n * itself is imported when the first one arrives, not when the process\n * starts, so a process that never captures anybody pays for this object and\n * nothing else. That matters because this registers in EVERY server process,\n * including ones that will never touch the CRM.\n */\nexport const crmContactCaptureWriter: PluginContactCaptureWriter = {\n async capture(request) {\n const { captureContactForCrm } = await import('./server/capture-contact')\n return await captureContactForCrm(request)\n },\n}\n\n/**\n * The CRM as the plugin other plugins ask for people (AGL-3080), deferred\n * like the capture: `server/person-records.ts` and the Admin SDK it brings\n * load with the first question, not when the process starts.\n */\nexport const crmPersonRecordsService: PluginPersonRecords = {\n async find(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.find(request)\n },\n async read(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.read(request)\n },\n async fileUnder(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.fileUnder(request)\n },\n async recordRefund(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.recordRefund(request)\n },\n async peopleInView(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.peopleInView(request)\n },\n async wroteIn(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.wroteIn(request)\n },\n async search(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.search(request)\n },\n // The walk a connector copies a site's people out by (AGL-3639).\n async changedSince(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.changedSince(request)\n },\n}\n\n/**\n * The `pipeline` record index, its reads loaded with the first one — see\n * `server/pipeline-record-index.ts` for what it answers.\n */\nexport const crmPipelineRecordIndex: PluginRecordIndex = {\n async list(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.list(request)\n },\n async get(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.get(request)\n },\n}\n\n/** One of `server/crm-record-indexes.ts`'s indexes, its reads loaded with the first one. */\nfunction lazyCrmRecordIndex(kind: 'company' | 'messageTemplate'): PluginRecordIndex {\n return {\n async list(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].list(request)\n },\n async get(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].get(request)\n },\n }\n}\n\n/** The companies a person works for, as another plugin reads them (AGL-3080). */\nexport const crmCompanyRecordIndex = lazyCrmRecordIndex('company')\n\n/** The email templates and snippets reps write, as another plugin reads them (AGL-3080). */\nexport const crmMessageTemplateRecordIndex = lazyCrmRecordIndex('messageTemplate')\n\n/**\n * The CRM's writer on the record-timeline seam (AGL-2981), deferred: the\n * writer and the Admin SDK it brings load with the first entry filed.\n */\nexport const crmRecordTimelineWriter: PluginRecordTimelineWriter = {\n async logActivity(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).logActivity(request)\n },\n async createTask(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).createTask(request)\n },\n async recordEmailDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordEmailDelivery!(request)\n },\n // A delivery event for a message the CRM tagged (AGL-2615, AGL-3080).\n async recordTaggedDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordTaggedDelivery!(request)\n },\n // An automation's email to the person its event is about, filed on that\n // person's timeline with its delivery state (AGL-2615, AGL-3080).\n async prepareEmail(request) {\n const { prepareCrmRecordEmail } = await import('./server/automation-steps')\n return prepareCrmRecordEmail(request)\n },\n}\n\n/**\n * The plugin's SERVER declarations: what the server must know at boot, before\n * any door of the CRM has been called.\n *\n * ## Why a declaration and not a `tenantApi` registration\n *\n * The doors that meet a person mostly never load this plugin. A form\n * submission is a core route; an order and a booking are captured inside\n * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry\n * filled by a surface that did not load answers `null` — which\n * `capturePluginContact` defines as \"this workspace has no record system\", a\n * sentence that would be false and silent. Orders would stop creating\n * contacts with nothing red anywhere, which is the AGL-3025 shape.\n *\n * Running from both apps' generated server-declarations manifest at boot is\n * what makes the answer true in every process. It is also called from the\n * plugin's own API register functions, so a process whose boot did not run it\n * still registers the writer the first time a CRM door loads. Registering\n * twice replaces in place.\n *\n * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A\n * second plugin's is refused naming both, and the incumbent keeps serving.\n */\nexport function registerCrmServerDeclarations(): void {\n registerPluginContactCaptureWriter(crmContactCaptureWriter, {\n pluginId: BUNDLE_ID,\n })\n // The other half of keeping people (AGL-3080): another plugin that holds\n // an address, or a record the CRM handed it, asks here for the person —\n // a flow email's consent read, a refund, an automation filing somebody\n // under a campaign — and never opens the CRM's collections itself.\n registerPluginPersonRecords(crmPersonRecordsService, { pluginId: BUNDLE_ID })\n // A record's scoped list fields follow its sites, so the sweep that keeps\n // \"all sites except\" current restamps them in the same write (AGL-4047).\n // Deferred like the capture.\n registerPluginScopeSharingPatch(\n ['contacts', 'leads', 'companies', 'deals', 'crmTasks'],\n async (collection, next) => {\n const { crmScopeSharingPatch } = await import('./server/scope-sharing-patch')\n return crmScopeSharingPatch(collection, next)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's own share of a lead conversion (AGL-3254): the lead's\n // campaigns go onto the contact's facet. Through the seam every door\n // that converts a lead reaches, and deferred like the capture: the\n // module that writes is loaded when the first conversion arrives, and\n // it brings the Admin SDK with it — this file defers the plugin's OWN\n // module only. A library imported statically across the plugin cannot\n // also be lazy-loaded here: `enforce-module-boundaries` refuses every\n // static import of a library the project lazy-loads anywhere.\n registerPluginLeadConversionListener(\n async (request) => {\n const { carryLeadCampaignsOnConversion } =\n await import('./server/lead-campaign-carry')\n return carryLeadCampaignsOnConversion(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // \"Did this workspace already know this person?\" (AGL-3289), asked by the\n // staff console's acquisition card. Deferred like the rest: the reads load\n // when a staff member first opens a card, not when the process starts.\n registerPluginPersonMatcher(\n async (request) => {\n const { matchCrmPeople } = await import('./server/person-matches')\n return matchCrmPeople(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's share of a consent group change (AGL-3320): a contact's\n // per-site refusal carried across a separation, and the records keyed by a\n // group re-homed after the flip. Registered whether or not a workspace has\n // the CRM switched on, because the contacts — and the refusals on them —\n // outlive the switch. Deferred like the rest; the summary is plain words\n // and answers synchronously.\n // The record email-state writer (AGL-3245), here as well as in the console\n // API so the tenant's doors reach it too: a form submission's capture is\n // checked for deliverability after its response (AGL-3328), and the \"Would\n // bounce\" that check finds is written through this seam. Deferred like the\n // rest; the console's own registration replaces this one with the same\n // writer, loaded eagerly.\n registerPluginRecordEmailStateWriter(\n {\n async stamp(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).stamp(request)\n },\n // A send's first opens and clicks, stamped on the contacts they name\n // (AGL-2616) — the campaign webhook's courtesy, deferred like the rest.\n async engaged(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).engaged!(request)\n },\n // A delivered campaign's leads, moved to Nurturing (AGL-3446).\n async reached(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).reached!(request)\n },\n // A lead that wrote back, moved to Working (AGL-3080).\n async replied(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).replied!(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // The record timeline writer (AGL-2981), here as well as in the API\n // surfaces so a door in either app reaches it: a booking confirmed on the\n // tenant, or by the payment webhook, files its meeting and follow-up\n // through it (AGL-2660). Deferred like the rest; an API registration\n // replaces this one with the same writer, loaded eagerly.\n registerPluginRecordTimelineWriter(crmRecordTimelineWriter, { pluginId: BUNDLE_ID })\n // Where a person came from (AGL-3519): a door the CRM does not run — the\n // platform's account sign-up, a sequence enrolling someone — names its\n // origin, and the CRM stamps the built-in Lead source on a record holding\n // none. Deferred like the rest.\n registerPluginRecordOriginWriter(\n {\n async stamp(request) {\n const { crmRecordOriginWriter } = await import('./server/record-origin')\n return crmRecordOriginWriter.stamp(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // Sharing rules (AGL-3336), re-evaluated after every server write of a\n // lead, a contact, a company or a deal: the core tells its record-written\n // listeners from the list-field restamp every such writer ends with, in\n // both apps — a form's capture on the tenant, an edit in the console.\n // Deferred like the rest: an org with no rules pays one cached read.\n registerPluginRecordWrittenListener(\n async (event) => {\n const { crmSharingRecordWritten } = await import('./server/crm-sharing')\n await crmSharingRecordWritten(event)\n },\n { pluginId: BUNDLE_ID, key: 'sharing' },\n )\n // The organization's pipelines and their stages, as another plugin reads\n // them (AGL-3080): an automation the AI drafts names the stage a deal\n // moves to. Deferred like the rest: the reads load with the first one.\n registerPluginRecordIndex('pipeline', crmPipelineRecordIndex, { pluginId: BUNDLE_ID })\n // The company a person works for, and the templates reps write, as a sales\n // sequence reads them (AGL-3080). Deferred like the rest.\n registerPluginRecordIndex('company', crmCompanyRecordIndex, { pluginId: BUNDLE_ID })\n registerPluginRecordIndex('messageTemplate', crmMessageTemplateRecordIndex, { pluginId: BUNDLE_ID })\n // The automation steps that write the CRM (AGL-2605, AGL-3080), run for the\n // workflows engine through the server-step seam and declared under\n // `serverSteps`. Deferred like the rest: the writes load with the first step.\n registerServerStepExecutor(\n CRM_STEP_TYPES,\n async (request) => (await import('./server/automation-steps')).runCrmAutomationStep(request),\n { pluginId: BUNDLE_ID },\n )\n registerPluginConsentGroupParticipant(\n {\n async preview(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.preview(request)\n },\n async run(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.run(request)\n },\n summarize: summarizeConsentGroupChange,\n },\n { pluginId: BUNDLE_ID },\n )\n // The records band in the monthly usage sweep, a core cron that never\n // loads a CRM door; declared in `usageAxes` so the sweep refuses to bill a\n // month without it. Deferred like the rest: the counts load with the\n // first sweep.\n registerPluginUsageMeter({\n pluginId: BUNDLE_ID,\n id: CRM_RECORDS_METER_ID,\n measure: async (context) => {\n const { measureCrmRecords } = await import('./server/crm-records-meter')\n return measureCrmRecords(context)\n },\n })\n}\n\n"],"names":["registerPluginConsentGroupParticipant","registerPluginContactCaptureWriter","registerPluginLeadConversionListener","registerPluginPersonMatcher","registerPluginPersonRecords","registerPluginRecordIndex","registerPluginRecordEmailStateWriter","registerPluginRecordOriginWriter","registerPluginRecordTimelineWriter","registerPluginRecordWrittenListener","registerPluginScopeSharingPatch","registerServerStepExecutor","registerPluginUsageMeter","BUNDLE_ID","CRM_RECORDS_METER_ID","CRM_STEP_TYPES","summarizeConsentGroupChange","crmContactCaptureWriter","capture","request","captureContactForCrm","crmPersonRecordsService","find","crmPersonRecords","read","fileUnder","recordRefund","peopleInView","wroteIn","search","changedSince","crmPipelineRecordIndex","list","pipelineRecordIndex","get","lazyCrmRecordIndex","kind","crmRecordIndexes","crmCompanyRecordIndex","crmMessageTemplateRecordIndex","crmRecordTimelineWriter","logActivity","createCrmRecordTimelineWriter","defaultCrmRecordTimelineDeps","createTask","recordEmailDelivery","recordTaggedDelivery","prepareEmail","prepareCrmRecordEmail","registerCrmServerDeclarations","pluginId","collection","next","crmScopeSharingPatch","carryLeadCampaignsOnConversion","matchCrmPeople","stamp","createCrmRecordEmailStateWriter","defaultCrmRecordEmailStateDeps","engaged","reached","replied","crmRecordOriginWriter","event","crmSharingRecordWritten","key","runCrmAutomationStep","preview","consentGroupParticipant","run","summarize","id","measure","context","measureCrmRecords"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,6EAA6E;AAC7E,SAASA,qCAAqC,QAAQ,0DAAyD;AAC/G,SACEC,kCAAkC,QAE7B,qDAAo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b,sCACE;QACE,MAAMmE,SAAQhD,OAAO;YACnB,MAAM,EAAEiD,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBD,OAAO,CAAChD;QACzC;QACA,MAAMkD,KAAIlD,OAAO;YACf,MAAM,EAAEiD,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBC,GAAG,CAAClD;QACrC;QACAmD,WAAWtD;IACb,GACA;QAAEkC,UAAUrC;IAAU;IAExB,sEAAsE;IACtE,2EAA2E;IAC3E,qEAAqE;IACrE,eAAe;IACfD,yBAAyB;QACvBsC,UAAUrC;QACV0D,IAAIzD;QACJ0D,SAAS,OAAOC;YACd,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC3C,OAAOA,kBAAkBD;QAC3B;IACF;AACF"}
@@ -27,8 +27,8 @@ export interface CrmActivityTarget {
27
27
  *
28
28
  * ## The two gates are on different axes, and that is the bug this closes
29
29
  *
30
- * The record write asks `canWriteOrgData()` — an org role of owner, admin
31
- * or editor, plus the scope tokens. The line asks `canWriteHostContent()`,
30
+ * The record write asks `canWriteOrgData()` — "Manage data" in the org, plus
31
+ * the scope tokens. The line asks `canWriteHostContent()`,
32
32
  * which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows
33
33
  * nothing about the org roster. At the org hub the two come apart for
34
34
  * members who are genuinely admitted to the hub:
@@ -30,8 +30,8 @@ import { useCrmOrgMount } from "./use-crm-org-mount.js";
30
30
  *
31
31
  * ## The two gates are on different axes, and that is the bug this closes
32
32
  *
33
- * The record write asks `canWriteOrgData()` — an org role of owner, admin
34
- * or editor, plus the scope tokens. The line asks `canWriteHostContent()`,
33
+ * The record write asks `canWriteOrgData()` — "Manage data" in the org, plus
34
+ * the scope tokens. The line asks `canWriteHostContent()`,
35
35
  * which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows
36
36
  * nothing about the org roster. At the org hub the two come apart for
37
37
  * members who are genuinely admitted to the hub:
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-activity-logger.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'use client'\n\nimport {\n type HostActivityTarget,\n useHostActivityLogger,\n} from '@aglyn/tenant-feature-instance'\nimport { useCallback } from 'react'\nimport { useCrmApi } from '../components/use-crm-api'\nimport type { CrmOrgActivityKind } from '../constants/api-routes'\nimport {\n orgActivityRefusal,\n reportDroppedActivityLine,\n} from '../model/crm-activity-report'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/**\n * A record kind BOTH feeds accept.\n *\n * The org feed also files tasks and the host feed also files screens, and a\n * line that can land in either has to name something both presenters can\n * render as a link. Spelled as the intersection rather than a third hand-\n * written union so a kind added to one side alone cannot silently become a\n * line the other side draws as unknown.\n */\nexport type CrmActivityKind = Extract<\n CrmOrgActivityKind,\n HostActivityTarget['type']\n>\n\n/** What a CRM activity line points at. */\nexport interface CrmActivityTarget {\n type: CrmActivityKind\n id?: string\n name?: string\n}\n\n/**\n * ONE LINE FOR ONE RECORD, IN THE FEED THE ACT BELONGS TO (AGL-2738).\n *\n * A CRM record is org data whichever hub it is edited from, but the feed\n * that holds \"who deleted it\" is not: under a SITE the line goes into that\n * site's `hosts/{hostId}/activity` client-direct, and at the ORGANIZATION\n * level it goes into `orgs/{orgId}/activity` through `crm/org-activity`,\n * because the org feed is closed to every client by rule.\n *\n * ## The two gates are on different axes, and that is the bug this closes\n *\n * The record write asks `canWriteOrgData()` — an org role of owner, admin\n * or editor, plus the scope tokens. The line asks `canWriteHostContent()`,\n * which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows\n * nothing about the org roster. At the org hub the two come apart for\n * members who are genuinely admitted to the hub:\n *\n * - a pre-`allHosts` member doc reads as org-wide (`isOrgWideMember`) and\n * projects to NO host role at all (`hostRoleFor` returns null without\n * `allHosts`), so an editor holding `data.manage` org-wide appears in no\n * site's `memberRoles`;\n * - an org editor carrying an explicit `hostAccess` entry of `viewer` on\n * one site writes the record and cannot write that site's feed;\n * - a site whose projection never ran, and a SUSPENDED site, refuse the\n * append while the org-level record write goes through untouched.\n *\n * Each of those used to spend its audit line on a rejected client write\n * that `useHostActivityLogger` swallowed. Widening the rule is not the\n * answer — `cloud/rules-tests/firestore-rules.test.mjs` pins that a viewer\n * cannot forge a line, and adding `activity` to the create exclusion list\n * ends host logging rather than moving it. Routing the org-level line\n * through the org's own door is: `crm/org-activity` authorizes the caller\n * on the ORG, which is the axis the record write was authorized on, and\n * appends with the Admin SDK.\n *\n * ## Which door, decided by the MOUNTED site and not by the record's\n *\n * `hostId` here is the site the surface is mounted under, never the site\n * the record was captured by. A record page at the org hub is handed\n * `null` and posts to the org feed; the lead page, which the hub mounts\n * UNDER a site by address (AGL-2630), is handed that site and keeps\n * writing client-direct exactly as it does on the site's own hub. Falling\n * back to the record's own site is what put an org-level act in front of a\n * site-level gate in the first place.\n *\n * This is the same split `useCrmBulkApply` makes for the bulk bars and the\n * email and stage routes make on the server: the level the act was\n * performed at decides the feed.\n *\n * @param hostId the site the surface is MOUNTED under — `props.hostId`,\n * which is `null` at the organization hub. Never the record's own\n * `hostId`.\n */\nexport function useCrmActivityLogger(hostId: string | null | undefined) {\n const mount = useCrmOrgMount()\n const logHostActivity = useHostActivityLogger(hostId ?? undefined)\n // `null`, because the line is about the org and not about a site: the\n // hook stamps the mount's `orgId` into the body, which is what makes the\n // call the route's org variant.\n const callCrm = useCrmApi(null)\n return useCallback(\n (action: string, target: CrmActivityTarget) => {\n if (hostId || !mount) {\n logHostActivity(action, target)\n return\n }\n void callCrm('org-activity', { action, target })\n .then(({ response, payload }) => {\n if (!response.ok) throw orgActivityRefusal(response.status, payload)\n })\n .catch(reportDroppedActivityLine)\n },\n [hostId, mount, logHostActivity, callCrm],\n )\n}\n\nexport default useCrmActivityLogger\n"],"names":["useHostActivityLogger","useCallback","useCrmApi","orgActivityRefusal","reportDroppedActivityLine","useCrmOrgMount","useCrmActivityLogger","hostId","mount","logHostActivity","undefined","callCrm","action","target","then","response","payload","ok","status","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAEEA,qBAAqB,QAChB,iCAAgC;AACvC,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,SAAS,QAAQ,+BAA2B;AAErD,SACEC,kBAAkB,EAClBC,yBAAyB,QACpB,kCAA8B;AACrC,SAASC,cAAc,QAAQ,yBAAqB;AAuBpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDC,GACD,OAAO,SAASC,qBAAqBC,MAAiC;IACpE,MAAMC,QAAQH;IACd,MAAMI,kBAAkBT,sBAAsBO,iBAAAA,SAAUG;IACxD,sEAAsE;IACtE,yEAAyE;IACzE,gCAAgC;IAChC,MAAMC,UAAUT,UAAU;IAC1B,OAAOD,YACL,CAACW,QAAgBC;QACf,IAAIN,UAAU,CAACC,OAAO;YACpBC,gBAAgBG,QAAQC;YACxB;QACF;QACA,KAAKF,QAAQ,gBAAgB;YAAEC;YAAQC;QAAO,GAC3CC,IAAI,CAAC,CAAC,EAAEC,QAAQ,EAAEC,OAAO,EAAE;YAC1B,IAAI,CAACD,SAASE,EAAE,EAAE,MAAMd,mBAAmBY,SAASG,MAAM,EAAEF;QAC9D,GACCG,KAAK,CAACf;IACX,GACA;QAACG;QAAQC;QAAOC;QAAiBE;KAAQ;AAE7C;AAEA,eAAeL,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-activity-logger.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'use client'\n\nimport {\n type HostActivityTarget,\n useHostActivityLogger,\n} from '@aglyn/tenant-feature-instance'\nimport { useCallback } from 'react'\nimport { useCrmApi } from '../components/use-crm-api'\nimport type { CrmOrgActivityKind } from '../constants/api-routes'\nimport {\n orgActivityRefusal,\n reportDroppedActivityLine,\n} from '../model/crm-activity-report'\nimport { useCrmOrgMount } from './use-crm-org-mount'\n\n/**\n * A record kind BOTH feeds accept.\n *\n * The org feed also files tasks and the host feed also files screens, and a\n * line that can land in either has to name something both presenters can\n * render as a link. Spelled as the intersection rather than a third hand-\n * written union so a kind added to one side alone cannot silently become a\n * line the other side draws as unknown.\n */\nexport type CrmActivityKind = Extract<\n CrmOrgActivityKind,\n HostActivityTarget['type']\n>\n\n/** What a CRM activity line points at. */\nexport interface CrmActivityTarget {\n type: CrmActivityKind\n id?: string\n name?: string\n}\n\n/**\n * ONE LINE FOR ONE RECORD, IN THE FEED THE ACT BELONGS TO (AGL-2738).\n *\n * A CRM record is org data whichever hub it is edited from, but the feed\n * that holds \"who deleted it\" is not: under a SITE the line goes into that\n * site's `hosts/{hostId}/activity` client-direct, and at the ORGANIZATION\n * level it goes into `orgs/{orgId}/activity` through `crm/org-activity`,\n * because the org feed is closed to every client by rule.\n *\n * ## The two gates are on different axes, and that is the bug this closes\n *\n * The record write asks `canWriteOrgData()` — \"Manage data\" in the org, plus\n * the scope tokens. The line asks `canWriteHostContent()`,\n * which resolves a role out of `hosts/{hostId}.memberRoles[uid]` and knows\n * nothing about the org roster. At the org hub the two come apart for\n * members who are genuinely admitted to the hub:\n *\n * - a pre-`allHosts` member doc reads as org-wide (`isOrgWideMember`) and\n * projects to NO host role at all (`hostRoleFor` returns null without\n * `allHosts`), so an editor holding `data.manage` org-wide appears in no\n * site's `memberRoles`;\n * - an org editor carrying an explicit `hostAccess` entry of `viewer` on\n * one site writes the record and cannot write that site's feed;\n * - a site whose projection never ran, and a SUSPENDED site, refuse the\n * append while the org-level record write goes through untouched.\n *\n * Each of those used to spend its audit line on a rejected client write\n * that `useHostActivityLogger` swallowed. Widening the rule is not the\n * answer — `cloud/rules-tests/firestore-rules.test.mjs` pins that a viewer\n * cannot forge a line, and adding `activity` to the create exclusion list\n * ends host logging rather than moving it. Routing the org-level line\n * through the org's own door is: `crm/org-activity` authorizes the caller\n * on the ORG, which is the axis the record write was authorized on, and\n * appends with the Admin SDK.\n *\n * ## Which door, decided by the MOUNTED site and not by the record's\n *\n * `hostId` here is the site the surface is mounted under, never the site\n * the record was captured by. A record page at the org hub is handed\n * `null` and posts to the org feed; the lead page, which the hub mounts\n * UNDER a site by address (AGL-2630), is handed that site and keeps\n * writing client-direct exactly as it does on the site's own hub. Falling\n * back to the record's own site is what put an org-level act in front of a\n * site-level gate in the first place.\n *\n * This is the same split `useCrmBulkApply` makes for the bulk bars and the\n * email and stage routes make on the server: the level the act was\n * performed at decides the feed.\n *\n * @param hostId the site the surface is MOUNTED under — `props.hostId`,\n * which is `null` at the organization hub. Never the record's own\n * `hostId`.\n */\nexport function useCrmActivityLogger(hostId: string | null | undefined) {\n const mount = useCrmOrgMount()\n const logHostActivity = useHostActivityLogger(hostId ?? undefined)\n // `null`, because the line is about the org and not about a site: the\n // hook stamps the mount's `orgId` into the body, which is what makes the\n // call the route's org variant.\n const callCrm = useCrmApi(null)\n return useCallback(\n (action: string, target: CrmActivityTarget) => {\n if (hostId || !mount) {\n logHostActivity(action, target)\n return\n }\n void callCrm('org-activity', { action, target })\n .then(({ response, payload }) => {\n if (!response.ok) throw orgActivityRefusal(response.status, payload)\n })\n .catch(reportDroppedActivityLine)\n },\n [hostId, mount, logHostActivity, callCrm],\n )\n}\n\nexport default useCrmActivityLogger\n"],"names":["useHostActivityLogger","useCallback","useCrmApi","orgActivityRefusal","reportDroppedActivityLine","useCrmOrgMount","useCrmActivityLogger","hostId","mount","logHostActivity","undefined","callCrm","action","target","then","response","payload","ok","status","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAEEA,qBAAqB,QAChB,iCAAgC;AACvC,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,SAAS,QAAQ,+BAA2B;AAErD,SACEC,kBAAkB,EAClBC,yBAAyB,QACpB,kCAA8B;AACrC,SAASC,cAAc,QAAQ,yBAAqB;AAuBpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDC,GACD,OAAO,SAASC,qBAAqBC,MAAiC;IACpE,MAAMC,QAAQH;IACd,MAAMI,kBAAkBT,sBAAsBO,iBAAAA,SAAUG;IACxD,sEAAsE;IACtE,yEAAyE;IACzE,gCAAgC;IAChC,MAAMC,UAAUT,UAAU;IAC1B,OAAOD,YACL,CAACW,QAAgBC;QACf,IAAIN,UAAU,CAACC,OAAO;YACpBC,gBAAgBG,QAAQC;YACxB;QACF;QACA,KAAKF,QAAQ,gBAAgB;YAAEC;YAAQC;QAAO,GAC3CC,IAAI,CAAC,CAAC,EAAEC,QAAQ,EAAEC,OAAO,EAAE;YAC1B,IAAI,CAACD,SAASE,EAAE,EAAE,MAAMd,mBAAmBY,SAASG,MAAM,EAAEF;QAC9D,GACCG,KAAK,CAACf;IACX,GACA;QAACG;QAAQC;QAAOC;QAAiBE;KAAQ;AAE7C;AAEA,eAAeL,qBAAoB"}