@aglyn/plugins-crm 1.10.0 → 1.12.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 (91) 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-record-picker.js +25 -9
  13. package/src/lib/components/crm-record-picker.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/hooks/use-crm-activity-logger.d.ts +2 -2
  41. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  42. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  43. package/src/lib/hooks/use-crm-record-names.js +59 -6
  44. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  45. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  46. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  47. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  48. package/src/lib/hooks/use-org-member-directory.js +49 -12
  49. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  50. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  51. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  52. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  53. package/src/lib/model/crm-api.d.ts +1 -1
  54. package/src/lib/model/crm-api.js +1 -1
  55. package/src/lib/model/crm-api.js.map +1 -1
  56. package/src/lib/model/crm-permissions.d.ts +35 -0
  57. package/src/lib/model/crm-permissions.js +87 -0
  58. package/src/lib/model/crm-permissions.js.map +1 -0
  59. package/src/lib/model/crm-sharing.d.ts +1 -1
  60. package/src/lib/model/crm-sharing.js +1 -1
  61. package/src/lib/model/crm-sharing.js.map +1 -1
  62. package/src/lib/plugin.js +4 -5
  63. package/src/lib/plugin.js.map +1 -1
  64. package/src/lib/server/capture-contact.d.ts +3 -3
  65. package/src/lib/server/capture-contact.js +3 -3
  66. package/src/lib/server/capture-contact.js.map +1 -1
  67. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  68. package/src/lib/server/crm-setup-writers.server.js +4 -16
  69. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  70. package/src/lib/server/crm-sharing.d.ts +5 -4
  71. package/src/lib/server/crm-sharing.js +8 -6
  72. package/src/lib/server/crm-sharing.js.map +1 -1
  73. package/src/lib/server/email-template-duplicate.js +7 -7
  74. package/src/lib/server/email-template-duplicate.js.map +1 -1
  75. package/src/lib/server/inbound-address.d.ts +9 -7
  76. package/src/lib/server/inbound-address.js +18 -15
  77. package/src/lib/server/inbound-address.js.map +1 -1
  78. package/src/lib/server/org-caller.d.ts +19 -5
  79. package/src/lib/server/org-caller.js +25 -5
  80. package/src/lib/server/org-caller.js.map +1 -1
  81. package/src/lib/server/recipe-routes.d.ts +0 -34
  82. package/src/lib/server/recipe-routes.js +11 -10
  83. package/src/lib/server/recipe-routes.js.map +1 -1
  84. package/src/lib/server/task-routes.d.ts +6 -5
  85. package/src/lib/server/task-routes.js +11 -13
  86. package/src/lib/server/task-routes.js.map +1 -1
  87. package/src/lib/server-deal-stage.d.ts +11 -6
  88. package/src/lib/server-deal-stage.js +18 -16
  89. package/src/lib/server-deal-stage.js.map +1 -1
  90. package/src/lib/server.js +16 -18
  91. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/settings-section.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 type AglynOrgBilling,\n canManageOrg,\n type ConsolePluginPageProps,\n CRM_ASSIGNMENT_RULES_MAX,\n CRM_ASSIGNMENT_RULES_PATH,\n CRM_AUTO_CREATE_COMPANIES_PATH,\n CRM_DEFAULT_RECORD_SCOPE_PATH,\n CRM_ROUND_ROBIN_POOL_MAX,\n CRM_ROUND_ROBIN_POOL_PATH,\n type CrmAssignmentRule,\n crmDefaultScopeOf,\n crmHostDefaultOwnerSegments,\n describeAssignmentRule,\n orgAutoCreatesCompanies,\n type OrgRole,\n pluginDocsHelp,\n readCrmAssignmentSettings,\n roundRobinOrder,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { mdiArrowDown, mdiArrowUp, mdiDeleteOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon, SrOnly } 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 {\n useFirestore,\n useFirestoreDoc,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormGroup,\n FormHelperText,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport { deleteField, doc, FieldPath, updateDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport AssignmentRuleDrawer from './assignment-rule-drawer'\nimport EmailTemplatesCard from './email-templates-card'\nimport EmailCaptureCard from './email-capture-card'\nimport RecipesCard from './recipes-card'\nimport SendingAddressesCard from './sending-addresses-card'\nimport SharingRulesCard from './sharing-rules-card'\n\nexport type CrmSettingsSectionProps = Pick<ConsolePluginPageProps, 'hostId' | 'org'>\n\n/**\n * Whether the signed-in member may change an org-wide CRM setting, and\n * whether that is known yet.\n *\n * The org document's client branch admits an OWNER or ADMIN and nobody\n * else — `canManageOrg()` in the rules — so the question is the caller's\n * org role, read off their own membership document, which the rules let a\n * member read for themselves. A scoped collaborator, an editor, a viewer:\n * each sees the switch and cannot move it, with the reason beside it,\n * rather than a switch that moves and snaps back with a bare\n * `permission-denied`. `ready` separates \"no\" from \"not yet\", so the\n * control disables with a reason instead of hiding until the read lands.\n */\nexport function useCanManageCrmSettings(orgId: string | undefined): {\n canManage: boolean\n ready: boolean\n} {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid ?? ''\n const { data: member, status } = useFirestoreDoc<{ role?: OrgRole }>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n return {\n canManage: canManageOrg(member?.role ?? null),\n ready: Boolean(orgId && uid) && status !== 'loading',\n }\n}\n\nexport interface AutoCreateCompaniesCardProps {\n /** The site the section is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}\n\n/**\n * \"Create companies from work email domains\" — the org's one switch over\n * what a capture does with a company nobody has filed yet (AGL-2613).\n *\n * ## What the switch decides, and what it does not\n *\n * A contact captured from `jane@acme.com` is linked to the company at\n * `acme.com` whether this is on or off, provided exactly one such company\n * is visible to the capturing site. The switch decides the case where NO\n * company carries the domain: on, the capture creates one named after the\n * domain and links the contact; off — the default — it creates nothing and\n * the contact waits for a person to file them. Public mailbox domains never\n * create a company either way; a workspace's consumer list is not a list\n * of accounts.\n *\n * ## Written where it is read\n *\n * One dotted-path `update()` onto `orgs/{orgId}`, so the org's other keys\n * are untouched and the map under `crm` can grow a key per setting. The\n * shell's org listener delivers the new value back, which is what the\n * switch reflects; a local copy holds the click only until then.\n */\nexport function AutoCreateCompaniesCard(props: AutoCreateCompaniesCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n\n const stored = orgAutoCreatesCompanies(org as Record<string, unknown> | undefined)\n const [checked, setChecked] = useState(stored)\n const [busy, setBusy] = useState(false)\n // The stored value wins whenever it changes: the click is optimistic, and\n // the org document is what the capture door will actually read.\n useEffect(() => setChecked(stored), [stored])\n\n const handleChange = async (next: boolean) => {\n // The switch is disabled for a member who may not move it; the guard\n // stands anyway, because a disabled control still delivers a change\n // event in some environments and the rules would refuse the write.\n if (!orgId || !canManage) return\n setChecked(next)\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_AUTO_CREATE_COMPANIES_PATH]: next,\n })\n enqueueSnackbar(\n next\n ? 'Companies will be created from work email domains'\n : 'Companies will no longer be created from email domains',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n setChecked(stored)\n enqueueSnackbar('The setting could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n return (\n <CardDisplay\n header={'Companies'}\n help={pluginDocsHelp('crmSettings', { anchor: '#companies' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={checked}\n disabled={!ready || !canManage || busy}\n onChange={(event) => void handleChange(event.target.checked)}\n />\n }\n label=\"Create companies from work email domains\"\n />\n <FormHelperText>\n {'A contact captured with a work email address is linked to the ' +\n 'company whose domain matches it. When this is on and no such ' +\n 'company exists yet, one is created from the domain — acme.com ' +\n 'becomes Acme — and the contact is linked to it. Public mailbox ' +\n 'domains such as gmail.com never create a company.'}\n </FormHelperText>\n {ready && !canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only a workspace owner or admin can change this.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nAutoCreateCompaniesCard.displayName = 'AutoCreateCompaniesCard'\n\n/**\n * \"Default sharing for new records\" (AGL-3662) — what a new contact,\n * company, deal or task starts shared with, set apart from the org's\n * defaults for new datasets and media.\n *\n * Changes nothing that already exists: narrowing an address book from a\n * select would hide records from sites already working them, with no\n * confirmation. Each record's own sharing is where that is decided.\n *\n * Reads `crmDefaultScopeOf`, the same reader the capture door and every CRM\n * creator stamp from, so the control cannot show one thing while records\n * get another — including for an org that has never set it, which shares\n * with every site unless it set the older dataset default to keep them\n * apart. Keeping each site's records apart is the agency's choice: one\n * client's collaborator then sees only that client's people.\n */\nexport function DefaultRecordSharingCard(props: AutoCreateCompaniesCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n\n const stored =\n crmDefaultScopeOf(org as Record<string, unknown> | undefined) ?? 'org'\n const [value, setValue] = useState<'org' | 'host'>(stored)\n const [busy, setBusy] = useState(false)\n useEffect(() => setValue(stored), [stored])\n\n const handleChange = async (next: 'org' | 'host') => {\n if (!orgId || !canManage) return\n setValue(next)\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_DEFAULT_RECORD_SCOPE_PATH]: next,\n })\n enqueueSnackbar('Default sharing updated', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n setValue(stored)\n enqueueSnackbar('The setting could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n return (\n <CardDisplay\n header={'Default sharing for new records'}\n help={pluginDocsHelp('crmSharing', {\n anchor: '#access-read-only-or-read-and-edit',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1} sx={{ maxWidth: 480 }}>\n <TextField\n select\n size=\"small\"\n label=\"New contacts, companies, deals and tasks are shared with\"\n value={value}\n disabled={!ready || !canManage || busy}\n onChange={(event) =>\n void handleChange(event.target.value as 'org' | 'host')\n }\n helperText={\n 'Only affects records created from now on. Datasets and media ' +\n 'have defaults of their own, on the organization Data and ' +\n 'Media pages.'\n }\n >\n <MenuItem value=\"org\">{'All sites in the organization'}</MenuItem>\n <MenuItem value=\"host\">\n {'Only the site they came in on (keeps clients apart, for agencies)'}\n </MenuItem>\n </TextField>\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nDefaultRecordSharingCard.displayName = 'DefaultRecordSharingCard'\n\n/** The caption every card shows a member who may read but not change it. */\nfunction ManagersOnlyNote(props: { ready: boolean; canManage: boolean }) {\n return props.ready && !props.canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only a workspace owner or admin can change this.'}\n </Typography>\n ) : null\n}\nManagersOnlyNote.displayName = 'ManagersOnlyNote'\n\n/** The `value` of the default-owner picker's \"nobody\" entry. */\nconst NO_DEFAULT_OWNER = ''\n\nexport interface AssignmentCardProps {\n /** The site the section is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}\n\n/**\n * \"Default owner\" — who gets the records captured on a site when no\n * assignment rule claims them (AGL-2618).\n *\n * Per site, on the org document: the reader is the org-level assignment\n * pass, which reads one document for every site's default, and the writer\n * is the same owner-or-admin the rest of the `crm` map admits. Under a\n * site the card is that site's one picker; at the ORGANIZATION level\n * (AGL-2630) it is one picker per site in the org, because the map is per\n * site and this is the one place all of it is on screen at once. The\n * field is addressed by `FieldPath` segments rather than a dotted string\n * because a host id is a document id and may contain a dot — joined with\n * dots, the write would land beside the setting rather than in it.\n * Clearing a picker deletes its field, so an org that once set a default\n * and unset it reads exactly like one that never did.\n */\nexport function DefaultOwnerCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const mount = useCrmOrgMount()\n const sites = useMemo<ReadonlyArray<{ id: string; name: string | null }>>(\n () =>\n hostId\n ? [{ id: hostId, name: null }]\n : (mount?.hosts ?? []).map((host) => ({ id: host.id, name: host.name })),\n [hostId, mount?.hosts],\n )\n const ready = scopeReady && roleReady && (Boolean(hostId) || Boolean(mount?.hostsReady))\n return (\n <CardDisplay\n header={'Default owner'}\n help={pluginDocsHelp('crmSettings', { anchor: '#default-owner' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {sites.map((site) => (\n <DefaultOwnerPicker\n key={site.id}\n orgId={orgId}\n siteId={site.id}\n siteName={site.name}\n org={org}\n roster={roster}\n canManage={canManage}\n ready={ready}\n />\n ))}\n {!hostId && ready && sites.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This organization has no sites yet, so there is nobody to route to.'}\n </Typography>\n ) : null}\n <FormHelperText>\n {'Every contact captured on a site — a form, a sign-up, a booking, ' +\n 'an order — that no assignment rule claims is handed to that ' +\n \"site's default owner, and they are notified. A contact added by \" +\n 'hand or imported with an owner keeps the owner you chose.'}\n </FormHelperText>\n {roster.error ? (\n <Typography variant=\"caption\" color=\"error\">\n {roster.error}\n </Typography>\n ) : null}\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nDefaultOwnerCard.displayName = 'DefaultOwnerCard'\n\n/** One site's slot in the org-wide default-owner map, as a picker. */\nfunction DefaultOwnerPicker(props: {\n orgId: string | undefined\n siteId: string\n /** How the site reads; `null` under the site itself, where \"this site\" will do. */\n siteName: string | null\n org?: Partial<AglynOrgBilling> | null\n roster: ReturnType<typeof useOrgMemberDirectory>\n canManage: boolean\n ready: boolean\n}) {\n const { orgId, siteId, siteName, org, roster, canManage, ready } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const siteLabel = siteName ?? 'this site'\n\n const stored =\n readCrmAssignmentSettings(org as Record<string, unknown> | undefined)\n .hostDefaultOwners[siteId] ?? NO_DEFAULT_OWNER\n const [value, setValue] = useState(stored)\n const [busy, setBusy] = useState(false)\n useEffect(() => setValue(stored), [stored])\n\n const handleChange = async (next: string) => {\n if (!orgId || !canManage) return\n setValue(next)\n setBusy(true)\n try {\n await updateDoc(\n doc(firestore, 'orgs', orgId),\n new FieldPath(...crmHostDefaultOwnerSegments(siteId)),\n next || deleteField(),\n )\n enqueueSnackbar(\n next\n ? `New contacts on ${siteLabel} go to ${roster.nameOf(next)} unless a rule says otherwise`\n : `New contacts on ${siteLabel} stay unassigned unless a rule says otherwise`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n setValue(stored)\n enqueueSnackbar('The default owner could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n // A stored owner the roster no longer lists is still shown, by uid, so\n // the picker never silently reads \"Nobody\" for a setting that is there.\n const options = useMemo(\n () =>\n stored && !roster.members.some((member) => member.uid === stored)\n ? [...roster.members, { uid: stored, label: `${stored} (former member)` }]\n : roster.members,\n [roster.members, stored],\n )\n return (\n <TextField\n select\n size=\"small\"\n label={siteName ? `Default owner · ${siteName}` : 'Default owner for this site'}\n value={value}\n onChange={(event) => void handleChange(event.target.value)}\n disabled={!ready || !canManage || busy || roster.loading}\n // \"Nobody\" is the empty value, which a select would otherwise\n // render as a blank rather than as the choice it is. The label is\n // shrunk with it: a field that always draws a value has no empty\n // state for the label to sit in, and left to itself it decides from\n // the value alone and paints the label over the choice.\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n sx={{ maxWidth: 360 }}\n >\n <MenuItem value={NO_DEFAULT_OWNER}>{'Nobody — leave unassigned'}</MenuItem>\n {options.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n )\n}\nDefaultOwnerPicker.displayName = 'DefaultOwnerPicker'\n\n/**\n * \"Assignment rules\" — the ordered list the capture pass tries first\n * (AGL-2618), with Add rule in a drawer, reorder and delete.\n *\n * ## The whole list is the unit of write\n *\n * The rules are an array on the org document and every edit — a new rule,\n * a move, a delete — writes the whole array by its dotted path. A per-rule\n * write has no address (an array element is not a field), and the list is\n * bounded at fifty, so the write is small. The array the card writes is\n * the array it read off the org prop plus the one edit, so two admins\n * editing at once last-write-wins at the granularity of one edit, which\n * is what a list this short and this rarely edited needs.\n *\n * ## First match wins, so order is the meaning\n *\n * A rule's position is a fact about it — \"bookings go to Kim, and\n * everything else to Sam\" is two rules in that order and nonsense in the\n * other — which is why the reorder controls sit in the first column and\n * the row reads \"1st, 2nd…\" rather than a name. Up and down rather than\n * drag, the way the custom-field list does it: a drag handle needs a\n * pointer, and the reorder is rare.\n */\nexport function AssignmentRulesCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const settings = useMemo(\n () => readCrmAssignmentSettings(org as Record<string, unknown> | undefined),\n [org],\n )\n const { rules } = settings\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [busy, setBusy] = useState(false)\n\n const writeRules = useCallback(\n async (next: CrmAssignmentRule[], said: string) => {\n if (!orgId || !canManage) return\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_ASSIGNMENT_RULES_PATH]: next,\n })\n enqueueSnackbar(said, { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The rules could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n throw error\n } finally {\n setBusy(false)\n }\n },\n [firestore, orgId, canManage, enqueueSnackbar],\n )\n\n const move = (index: number, by: -1 | 1) => {\n const target = index + by\n if (target < 0 || target >= rules.length) return\n const next = [...rules]\n ;[next[index], next[target]] = [next[target], next[index]]\n void writeRules(next, 'Rule moved').catch(() => undefined)\n }\n const remove = (rule: CrmAssignmentRule) => {\n void writeRules(\n rules.filter((entry) => entry.id !== rule.id),\n 'Rule deleted',\n ).catch(() => undefined)\n }\n const handleAdd = async (rule: CrmAssignmentRule) => {\n await writeRules([...rules, rule], 'Rule added')\n setDrawerOpen(false)\n }\n\n const ready = scopeReady && roleReady\n const atCap = rules.length >= CRM_ASSIGNMENT_RULES_MAX\n const canEdit = ready && canManage && !busy\n const ordinal = (index: number) => {\n const n = index + 1\n const suffix =\n n % 100 >= 11 && n % 100 <= 13\n ? 'th'\n : (['th', 'st', 'nd', 'rd'] as const)[n % 10] ?? 'th'\n return `${n}${suffix}`\n }\n return (\n <CardDisplay\n header={'Assignment rules'}\n help={pluginDocsHelp('crmSettings', { anchor: '#assignment-rules' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n variant=\"contained\"\n disabled={!canEdit || atCap}\n onClick={() => setDrawerOpen(true)}\n >\n {'Add rule'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Tried in order for every new contact captured on any site in the ' +\n 'workspace; the first rule whose every condition holds assigns the ' +\n 'owner. A contact no rule claims goes to the capturing site’s ' +\n 'default owner, or stays unassigned.'}\n </Typography>\n {rules.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No rules yet. Add one to route new contacts by where they came from.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell sx={{ width: 120 }}>{'Order'}</TableCell>\n <TableCell>{'When'}</TableCell>\n <TableCell>{'Assign to'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {rules.map((rule, index) => {\n const described = describeAssignmentRule(rule, roster.nameOf)\n return (\n <TableRow key={rule.id} hover>\n <TableCell>\n <Stack direction=\"row\" spacing={0} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ minWidth: 32 }}>\n {ordinal(index)}\n </Typography>\n <IconButton\n size=\"small\"\n disabled={!canEdit || index === 0}\n onClick={() => move(index, -1)}\n >\n <MdiIcon path={mdiArrowUp.path} size={0.7} />\n <SrOnly>{`Move rule ${index + 1} up`}</SrOnly>\n </IconButton>\n <IconButton\n size=\"small\"\n disabled={!canEdit || index === rules.length - 1}\n onClick={() => move(index, 1)}\n >\n <MdiIcon path={mdiArrowDown.path} size={0.7} />\n <SrOnly>{`Move rule ${index + 1} down`}</SrOnly>\n </IconButton>\n </Stack>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">{described.when}</Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">{described.assign}</Typography>\n </TableCell>\n <TableCell align=\"right\" sx={{ width: 56 }}>\n <RowActionsMenu\n label={`Rule ${index + 1}`}\n items={[\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: () => remove(rule),\n },\n ]}\n />\n </TableCell>\n </TableRow>\n )\n })}\n </TableBody>\n </ScrollTable>\n )}\n {atCap ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`A workspace keeps at most ${CRM_ASSIGNMENT_RULES_MAX} rules. Delete one to add another.`}\n </Typography>\n ) : null}\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n <AssignmentRuleDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n members={roster.members}\n membersLoading={roster.loading}\n poolSize={settings.pool.memberUids.length}\n existingIds={rules.map((rule) => rule.id)}\n onSubmit={handleAdd}\n />\n </CardDisplay>\n )\n}\nAssignmentRulesCard.displayName = 'AssignmentRulesCard'\n\n/**\n * \"Round robin\" — the members handed records in turn (AGL-2618).\n *\n * The pool is the roster with a checkbox per member, and its ORDER is the\n * order members were checked: a member checked later joins the end of the\n * rotation, and unchecking removes them without disturbing the others. The\n * pointer — who got the last record — is the server's to move and is only\n * read here, as \"next up\", so an admin can see where the rotation stands\n * without being able to put a thumb on it.\n */\nexport function RoundRobinCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const { pool } = useMemo(\n () => readCrmAssignmentSettings(org as Record<string, unknown> | undefined),\n [org],\n )\n const [busy, setBusy] = useState(false)\n\n const toggle = async (uid: string, inPool: boolean) => {\n if (!orgId || !canManage) return\n const next = inPool\n ? [...pool.memberUids.filter((entry) => entry !== uid), uid]\n : pool.memberUids.filter((entry) => entry !== uid)\n if (next.length > CRM_ROUND_ROBIN_POOL_MAX) return\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_ROUND_ROBIN_POOL_PATH]: next,\n })\n enqueueSnackbar(\n inPool\n ? `${roster.nameOf(uid)} joined the rotation`\n : `${roster.nameOf(uid)} left the rotation`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The pool could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n const canEdit = ready && canManage && !busy && !roster.loading\n const order = roundRobinOrder(pool.memberUids, pool.lastAssignedUid)\n const nextUp = order[0]\n // The rotation names people the way the checkboxes above do — with the\n // address, since two members can share a display name.\n const rotationName = (uid: string): string => {\n const member = roster.members.find((row) => row.uid === uid)\n return member ? crmMemberPickerLabel(member) : roster.nameOf(uid)\n }\n return (\n <CardDisplay\n header={'Round robin'}\n help={pluginDocsHelp('crmSettings', { anchor: '#round-robin' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The members a round-robin rule, or an automation set to round ' +\n 'robin, hands records to in turn. Each new record goes to the ' +\n 'member after the last one who got a record, wrapping round.'}\n </Typography>\n {roster.loading ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Loading the team…'}\n </Typography>\n ) : roster.error ? (\n <Typography variant=\"body2\" color=\"error\">\n {roster.error}\n </Typography>\n ) : (\n <FormGroup>\n {roster.members.map((member) => (\n <FormControlLabel\n key={member.uid}\n control={\n <Checkbox\n size=\"small\"\n checked={pool.memberUids.includes(member.uid)}\n disabled={!canEdit}\n onChange={(event) => void toggle(member.uid, event.target.checked)}\n />\n }\n label={crmMemberPickerLabel(member)}\n />\n ))}\n </FormGroup>\n )}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {pool.memberUids.length === 0\n ? 'Nobody is in the rotation; a round-robin rule is skipped until somebody is.'\n : `Rotation: ${pool.memberUids.map(rotationName).join(' → ')}. Next up: ${rotationName(nextUp)}.`}\n </Typography>\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nRoundRobinCard.displayName = 'RoundRobinCard'\n\n/**\n * `/crm/settings` — what the CRM does on its own, for every site in the\n * workspace (AGL-2613).\n *\n * A stack of cards, one per concern, so a later setting arrives as a card\n * beside this one rather than a field inside it. Every card writes the org\n * document, because a CRM setting is a fact about how the business files\n * people and not about one site; the section is reached from a site's hub\n * or from the organization's (AGL-2630), and writes the same document from\n * either. The one per-site setting — the default owner — is the site's\n * slot in an org-wide map: under a site the card names the site it is for,\n * and at the organization level it lists every site's slot.\n *\n * The Recipes card (AGL-2639) is the one card that mounts at the\n * ORGANIZATION level only. It installs an automation onto a site of the\n * reader's choosing, which is the org's need; under a site the Actions\n * page's own Recipes menu is the door, and a second one here would write\n * the same action by a different route. Last, because the welcome recipe\n * leans on the round-robin pool set up in the card above it.\n *\n * The Email templates card (AGL-2658) is the one card every CRM editor may\n * write to — a template is working material, not policy — and mounts at\n * both levels, listing the site's letters under a site and the whole\n * workspace's from the organization's hub.\n *\n * Your sending addresses (AGL-2975) sits directly under Email capture,\n * because it is where a member who copies that address from an alias looks\n * next: it is the reader's OWN list, at both levels, and writes through the\n * core route rather than the org document.\n */\nexport function CrmSettingsSection(props: CrmSettingsSectionProps) {\n const { hostId, org } = props\n const mount = useCrmOrgMount()\n // The Email capture card (AGL-2657) rotates on the same owner-or-admin\n // bar every other card writes on; the scope and the role are resolved\n // here once and handed down, since the card itself writes no document.\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n return (\n <Stack spacing={3}>\n <DefaultRecordSharingCard hostId={hostId} org={org} />\n <AutoCreateCompaniesCard hostId={hostId} org={org} />\n <DefaultOwnerCard hostId={hostId} org={org} />\n <AssignmentRulesCard hostId={hostId} org={org} />\n <RoundRobinCard hostId={hostId} org={org} />\n <EmailTemplatesCard hostId={hostId} org={org} />\n <EmailCaptureCard hostId={hostId} canManage={canManage} ready={scopeReady && roleReady} />\n <SendingAddressesCard orgId={orgId} ready={scopeReady} />\n {/* Sharing rules (AGL-3336) are the organization's: mounted where its\n sites are listed, at the org level only — before Recipes, which\n stays last. */}\n {mount ? (\n <SharingRulesCard\n orgId={orgId ?? null}\n org={org}\n canManage={canManage}\n ready={scopeReady && roleReady}\n />\n ) : null}\n {mount ? <RecipesCard org={org} /> : null}\n </Stack>\n )\n}\nCrmSettingsSection.displayName = 'CrmSettingsSection'\n\nexport default CrmSettingsSection\n"],"names":["canManageOrg","CRM_ASSIGNMENT_RULES_MAX","CRM_ASSIGNMENT_RULES_PATH","CRM_AUTO_CREATE_COMPANIES_PATH","CRM_DEFAULT_RECORD_SCOPE_PATH","CRM_ROUND_ROBIN_POOL_MAX","CRM_ROUND_ROBIN_POOL_PATH","crmDefaultScopeOf","crmHostDefaultOwnerSegments","describeAssignmentRule","orgAutoCreatesCompanies","pluginDocsHelp","readCrmAssignmentSettings","roundRobinOrder","crmMemberPickerLabel","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","CardDisplay","MdiIcon","SrOnly","RowActionsMenu","ScrollTable","useSnackbar","useFirestore","useFirestoreDoc","useUser","Button","Checkbox","FormControlLabel","FormGroup","FormHelperText","IconButton","MenuItem","Stack","Switch","TableBody","TableCell","TableHead","TableRow","TextField","Typography","deleteField","doc","FieldPath","updateDoc","useCallback","useEffect","useMemo","useState","useCrmOrgMount","useCrmScope","useOrgMemberDirectory","AssignmentRuleDrawer","EmailTemplatesCard","EmailCaptureCard","RecipesCard","SendingAddressesCard","SharingRulesCard","useCanManageCrmSettings","orgId","firestore","data","user","uid","member","status","canManage","role","ready","Boolean","AutoCreateCompaniesCard","props","hostId","org","enqueueSnackbar","scopeReady","roleReady","stored","checked","setChecked","busy","setBusy","handleChange","next","variant","persist","error","console","allowDuplicate","header","help","anchor","contentGutterX","contentGutterY","spacing","control","size","disabled","onChange","event","target","label","color","displayName","DefaultRecordSharingCard","value","setValue","sx","maxWidth","select","helperText","ManagersOnlyNote","NO_DEFAULT_OWNER","DefaultOwnerCard","roster","mount","sites","id","name","hosts","map","host","hostsReady","site","DefaultOwnerPicker","siteId","siteName","length","siteLabel","hostDefaultOwners","nameOf","options","members","some","loading","slotProps","displayEmpty","inputLabel","shrink","AssignmentRulesCard","settings","rules","drawerOpen","setDrawerOpen","writeRules","said","move","index","by","catch","undefined","remove","rule","filter","entry","handleAdd","atCap","canEdit","ordinal","n","suffix","contentBordered","HeaderProps","action","onClick","width","align","described","hover","direction","alignItems","minWidth","path","when","assign","items","key","icon","destructive","open","onClose","membersLoading","poolSize","pool","memberUids","existingIds","onSubmit","RoundRobinCard","toggle","inPool","order","lastAssignedUid","nextUp","rotationName","find","row","includes","join","CrmSettingsSection"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAEEA,YAAY,EAEZC,wBAAwB,EACxBC,yBAAyB,EACzBC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,wBAAwB,EACxBC,yBAAyB,EAEzBC,iBAAiB,EACjBC,2BAA2B,EAC3BC,sBAAsB,EACtBC,uBAAuB,EAEvBC,cAAc,EACdC,yBAAyB,EACzBC,eAAe,EACfC,oBAAoB,QACf,eAAc;AACrB,SAASC,YAAY,EAAEC,UAAU,EAAEC,gBAAgB,QAAQ,yBA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kB,QAAQA;gBAAQN,WAAWA;gBAAWE,OAAOO,cAAcC;;0BAC7E,KAACpB;gBAAqBG,OAAOA;gBAAOS,OAAOO;;YAI1CwC,sBACC,KAAC1D;gBACCE,KAAK,EAAEA,gBAAAA,QAAS;gBAChBc,KAAKA;gBACLP,WAAWA;gBACXE,OAAOO,cAAcC;iBAErB;YACHuC,sBAAQ,KAAC5D;gBAAYkB,KAAKA;iBAAU;;;AAG3C;AACA6H,mBAAmB/F,WAAW,GAAG;AAEjC,eAAe+F,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/settings-section.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 type AglynOrgBilling,\n type AglynOrgCustomRole,\n type ConsolePluginPageProps,\n CRM_ASSIGNMENT_RULES_MAX,\n CRM_ASSIGNMENT_RULES_PATH,\n CRM_AUTO_CREATE_COMPANIES_PATH,\n CRM_DEFAULT_RECORD_SCOPE_PATH,\n CRM_ROUND_ROBIN_POOL_MAX,\n CRM_ROUND_ROBIN_POOL_PATH,\n type CrmAssignmentRule,\n crmDefaultScopeOf,\n crmHostDefaultOwnerSegments,\n describeAssignmentRule,\n isOrgWideMember,\n orgAutoCreatesCompanies,\n pluginDocsHelp,\n readCrmAssignmentSettings,\n resolveOrgPermissions,\n roundRobinOrder,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { mdiArrowDown, mdiArrowUp, mdiDeleteOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon, SrOnly } 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 {\n useFirestore,\n useFirestoreDoc,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormGroup,\n FormHelperText,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport { deleteField, doc, FieldPath, updateDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_SETTINGS_PERMISSION, crmSettingsPermissionRefusal } from '../model/crm-permissions'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport AssignmentRuleDrawer from './assignment-rule-drawer'\nimport EmailTemplatesCard from './email-templates-card'\nimport EmailCaptureCard from './email-capture-card'\nimport RecipesCard from './recipes-card'\nimport SendingAddressesCard from './sending-addresses-card'\nimport SharingRulesCard from './sharing-rules-card'\n\nexport type CrmSettingsSectionProps = Pick<ConsolePluginPageProps, 'hostId' | 'org'>\n\n/** A membership document, as the permission resolver reads one. */\ntype MemberRecord = NonNullable<Parameters<typeof resolveOrgPermissions>[0]>\n\n/**\n * Whether the signed-in member may change an org-wide CRM setting, and\n * whether that is known yet: \"Change CRM settings\" (`crm.settings`, AGL-4047)\n * over the whole workspace.\n *\n * The same key everything behind these cards asks: the org document's client\n * rule for its `crm` map, `authorizeOrgCaller(…, 'crm.settings')` for record\n * sharing and the sharing rules, and the capture address's rotation. On for\n * owners and admins by default; a custom role or an override can hand it to\n * another member of the whole workspace, or take it from an admin. A site\n * collaborator never holds it, whatever they are granted.\n *\n * Read off the member's own membership document and their custom role when\n * they hold one, both of which the rules let a member read, the way the erase\n * item answers \"Privacy requests\". Each card shows its switch to a member who\n * cannot move it, disabled with the reason beside it, rather than a switch\n * that moves and snaps back with a bare `permission-denied`. `ready`\n * separates \"no\" from \"not yet\", so the control disables with a reason\n * instead of hiding until the read lands.\n */\nexport function useCanManageCrmSettings(orgId: string | undefined): {\n canManage: boolean\n ready: boolean\n} {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid ?? ''\n const memberRead = useFirestoreDoc<MemberRecord>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n const member = memberRead.status === 'success' ? memberRead.data : undefined\n const roleId = typeof member?.roleId === 'string' ? member.roleId : ''\n const roleRead = useFirestoreDoc<AglynOrgCustomRole>(\n () => (orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null),\n [firestore, orgId, roleId],\n )\n const ready =\n Boolean(orgId && uid) && memberRead.status !== 'loading' && (!roleId || roleRead.status !== 'loading')\n const granted = resolveOrgPermissions(\n member ?? null,\n roleId && roleRead.status === 'success' ? (roleRead.data ?? null) : null,\n )\n return {\n canManage: Boolean(member) && isOrgWideMember(member) && granted[CRM_SETTINGS_PERMISSION] === true,\n ready,\n }\n}\n\nexport interface AutoCreateCompaniesCardProps {\n /** The site the section is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}\n\n/**\n * \"Create companies from work email domains\" — the org's one switch over\n * what a capture does with a company nobody has filed yet (AGL-2613).\n *\n * ## What the switch decides, and what it does not\n *\n * A contact captured from `jane@acme.com` is linked to the company at\n * `acme.com` whether this is on or off, provided exactly one such company\n * is visible to the capturing site. The switch decides the case where NO\n * company carries the domain: on, the capture creates one named after the\n * domain and links the contact; off — the default — it creates nothing and\n * the contact waits for a person to file them. Public mailbox domains never\n * create a company either way; a workspace's consumer list is not a list\n * of accounts.\n *\n * ## Written where it is read\n *\n * One dotted-path `update()` onto `orgs/{orgId}`, so the org's other keys\n * are untouched and the map under `crm` can grow a key per setting. The\n * shell's org listener delivers the new value back, which is what the\n * switch reflects; a local copy holds the click only until then.\n */\nexport function AutoCreateCompaniesCard(props: AutoCreateCompaniesCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n\n const stored = orgAutoCreatesCompanies(org as Record<string, unknown> | undefined)\n const [checked, setChecked] = useState(stored)\n const [busy, setBusy] = useState(false)\n // The stored value wins whenever it changes: the click is optimistic, and\n // the org document is what the capture door will actually read.\n useEffect(() => setChecked(stored), [stored])\n\n const handleChange = async (next: boolean) => {\n // The switch is disabled for a member who may not move it; the guard\n // stands anyway, because a disabled control still delivers a change\n // event in some environments and the rules would refuse the write.\n if (!orgId || !canManage) return\n setChecked(next)\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_AUTO_CREATE_COMPANIES_PATH]: next,\n })\n enqueueSnackbar(\n next\n ? 'Companies will be created from work email domains'\n : 'Companies will no longer be created from email domains',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n setChecked(stored)\n enqueueSnackbar('The setting could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n return (\n <CardDisplay\n header={'Companies'}\n help={pluginDocsHelp('crmSettings', { anchor: '#companies' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={checked}\n disabled={!ready || !canManage || busy}\n onChange={(event) => void handleChange(event.target.checked)}\n />\n }\n label=\"Create companies from work email domains\"\n />\n <FormHelperText>\n {'A contact captured with a work email address is linked to the ' +\n 'company whose domain matches it. When this is on and no such ' +\n 'company exists yet, one is created from the domain — acme.com ' +\n 'becomes Acme — and the contact is linked to it. Public mailbox ' +\n 'domains such as gmail.com never create a company.'}\n </FormHelperText>\n {ready && !canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {crmSettingsPermissionRefusal()}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nAutoCreateCompaniesCard.displayName = 'AutoCreateCompaniesCard'\n\n/**\n * \"Default sharing for new records\" (AGL-3662) — what a new contact,\n * company, deal or task starts shared with, set apart from the org's\n * defaults for new datasets and media.\n *\n * Changes nothing that already exists: narrowing an address book from a\n * select would hide records from sites already working them, with no\n * confirmation. Each record's own sharing is where that is decided.\n *\n * Reads `crmDefaultScopeOf`, the same reader the capture door and every CRM\n * creator stamp from, so the control cannot show one thing while records\n * get another — including for an org that has never set it, which shares\n * with every site unless it set the older dataset default to keep them\n * apart. Keeping each site's records apart is the agency's choice: one\n * client's collaborator then sees only that client's people.\n */\nexport function DefaultRecordSharingCard(props: AutoCreateCompaniesCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n\n const stored =\n crmDefaultScopeOf(org as Record<string, unknown> | undefined) ?? 'org'\n const [value, setValue] = useState<'org' | 'host'>(stored)\n const [busy, setBusy] = useState(false)\n useEffect(() => setValue(stored), [stored])\n\n const handleChange = async (next: 'org' | 'host') => {\n if (!orgId || !canManage) return\n setValue(next)\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_DEFAULT_RECORD_SCOPE_PATH]: next,\n })\n enqueueSnackbar('Default sharing updated', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n setValue(stored)\n enqueueSnackbar('The setting could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n return (\n <CardDisplay\n header={'Default sharing for new records'}\n help={pluginDocsHelp('crmSharing', {\n anchor: '#access-read-only-or-read-and-edit',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1} sx={{ maxWidth: 480 }}>\n <TextField\n select\n size=\"small\"\n label=\"New contacts, companies, deals and tasks are shared with\"\n value={value}\n disabled={!ready || !canManage || busy}\n onChange={(event) =>\n void handleChange(event.target.value as 'org' | 'host')\n }\n helperText={\n 'Only affects records created from now on. Datasets and media ' +\n 'have defaults of their own, on the organization Data and ' +\n 'Media pages.'\n }\n >\n <MenuItem value=\"org\">{'All sites in the organization'}</MenuItem>\n <MenuItem value=\"host\">\n {'Only the site they came in on (keeps clients apart, for agencies)'}\n </MenuItem>\n </TextField>\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nDefaultRecordSharingCard.displayName = 'DefaultRecordSharingCard'\n\n/** The caption every card shows a member who may read but not change it. */\nfunction ManagersOnlyNote(props: { ready: boolean; canManage: boolean }) {\n return props.ready && !props.canManage ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {crmSettingsPermissionRefusal()}\n </Typography>\n ) : null\n}\nManagersOnlyNote.displayName = 'ManagersOnlyNote'\n\n/** The `value` of the default-owner picker's \"nobody\" entry. */\nconst NO_DEFAULT_OWNER = ''\n\nexport interface AssignmentCardProps {\n /** The site the section is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}\n\n/**\n * \"Default owner\" — who gets the records captured on a site when no\n * assignment rule claims them (AGL-2618).\n *\n * Per site, on the org document: the reader is the org-level assignment\n * pass, which reads one document for every site's default, and the writer\n * is whoever holds \"Change CRM settings\", as for the rest of the `crm` map. Under a\n * site the card is that site's one picker; at the ORGANIZATION level\n * (AGL-2630) it is one picker per site in the org, because the map is per\n * site and this is the one place all of it is on screen at once. The\n * field is addressed by `FieldPath` segments rather than a dotted string\n * because a host id is a document id and may contain a dot — joined with\n * dots, the write would land beside the setting rather than in it.\n * Clearing a picker deletes its field, so an org that once set a default\n * and unset it reads exactly like one that never did.\n */\nexport function DefaultOwnerCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const mount = useCrmOrgMount()\n const sites = useMemo<ReadonlyArray<{ id: string; name: string | null }>>(\n () =>\n hostId\n ? [{ id: hostId, name: null }]\n : (mount?.hosts ?? []).map((host) => ({ id: host.id, name: host.name })),\n [hostId, mount?.hosts],\n )\n const ready = scopeReady && roleReady && (Boolean(hostId) || Boolean(mount?.hostsReady))\n return (\n <CardDisplay\n header={'Default owner'}\n help={pluginDocsHelp('crmSettings', { anchor: '#default-owner' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {sites.map((site) => (\n <DefaultOwnerPicker\n key={site.id}\n orgId={orgId}\n siteId={site.id}\n siteName={site.name}\n org={org}\n roster={roster}\n canManage={canManage}\n ready={ready}\n />\n ))}\n {!hostId && ready && sites.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This organization has no sites yet, so there is nobody to route to.'}\n </Typography>\n ) : null}\n <FormHelperText>\n {'Every contact captured on a site — a form, a sign-up, a booking, ' +\n 'an order — that no assignment rule claims is handed to that ' +\n \"site's default owner, and they are notified. A contact added by \" +\n 'hand or imported with an owner keeps the owner you chose.'}\n </FormHelperText>\n {roster.error ? (\n <Typography variant=\"caption\" color=\"error\">\n {roster.error}\n </Typography>\n ) : null}\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nDefaultOwnerCard.displayName = 'DefaultOwnerCard'\n\n/** One site's slot in the org-wide default-owner map, as a picker. */\nfunction DefaultOwnerPicker(props: {\n orgId: string | undefined\n siteId: string\n /** How the site reads; `null` under the site itself, where \"this site\" will do. */\n siteName: string | null\n org?: Partial<AglynOrgBilling> | null\n roster: ReturnType<typeof useOrgMemberDirectory>\n canManage: boolean\n ready: boolean\n}) {\n const { orgId, siteId, siteName, org, roster, canManage, ready } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const siteLabel = siteName ?? 'this site'\n\n const stored =\n readCrmAssignmentSettings(org as Record<string, unknown> | undefined)\n .hostDefaultOwners[siteId] ?? NO_DEFAULT_OWNER\n const [value, setValue] = useState(stored)\n const [busy, setBusy] = useState(false)\n useEffect(() => setValue(stored), [stored])\n\n const handleChange = async (next: string) => {\n if (!orgId || !canManage) return\n setValue(next)\n setBusy(true)\n try {\n await updateDoc(\n doc(firestore, 'orgs', orgId),\n new FieldPath(...crmHostDefaultOwnerSegments(siteId)),\n next || deleteField(),\n )\n enqueueSnackbar(\n next\n ? `New contacts on ${siteLabel} go to ${roster.nameOf(next)} unless a rule says otherwise`\n : `New contacts on ${siteLabel} stay unassigned unless a rule says otherwise`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n setValue(stored)\n enqueueSnackbar('The default owner could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n // A stored owner the roster no longer lists is still shown, by uid, so\n // the picker never silently reads \"Nobody\" for a setting that is there.\n const options = useMemo(\n () =>\n stored && !roster.members.some((member) => member.uid === stored)\n ? [...roster.members, { uid: stored, label: `${stored} (former member)` }]\n : roster.members,\n [roster.members, stored],\n )\n return (\n <TextField\n select\n size=\"small\"\n label={siteName ? `Default owner · ${siteName}` : 'Default owner for this site'}\n value={value}\n onChange={(event) => void handleChange(event.target.value)}\n disabled={!ready || !canManage || busy || roster.loading}\n // \"Nobody\" is the empty value, which a select would otherwise\n // render as a blank rather than as the choice it is. The label is\n // shrunk with it: a field that always draws a value has no empty\n // state for the label to sit in, and left to itself it decides from\n // the value alone and paints the label over the choice.\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n sx={{ maxWidth: 360 }}\n >\n <MenuItem value={NO_DEFAULT_OWNER}>{'Nobody — leave unassigned'}</MenuItem>\n {options.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n )\n}\nDefaultOwnerPicker.displayName = 'DefaultOwnerPicker'\n\n/**\n * \"Assignment rules\" — the ordered list the capture pass tries first\n * (AGL-2618), with Add rule in a drawer, reorder and delete.\n *\n * ## The whole list is the unit of write\n *\n * The rules are an array on the org document and every edit — a new rule,\n * a move, a delete — writes the whole array by its dotted path. A per-rule\n * write has no address (an array element is not a field), and the list is\n * bounded at fifty, so the write is small. The array the card writes is\n * the array it read off the org prop plus the one edit, so two admins\n * editing at once last-write-wins at the granularity of one edit, which\n * is what a list this short and this rarely edited needs.\n *\n * ## First match wins, so order is the meaning\n *\n * A rule's position is a fact about it — \"bookings go to Kim, and\n * everything else to Sam\" is two rules in that order and nonsense in the\n * other — which is why the reorder controls sit in the first column and\n * the row reads \"1st, 2nd…\" rather than a name. Up and down rather than\n * drag, the way the custom-field list does it: a drag handle needs a\n * pointer, and the reorder is rare.\n */\nexport function AssignmentRulesCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const settings = useMemo(\n () => readCrmAssignmentSettings(org as Record<string, unknown> | undefined),\n [org],\n )\n const { rules } = settings\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [busy, setBusy] = useState(false)\n\n const writeRules = useCallback(\n async (next: CrmAssignmentRule[], said: string) => {\n if (!orgId || !canManage) return\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_ASSIGNMENT_RULES_PATH]: next,\n })\n enqueueSnackbar(said, { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The rules could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n throw error\n } finally {\n setBusy(false)\n }\n },\n [firestore, orgId, canManage, enqueueSnackbar],\n )\n\n const move = (index: number, by: -1 | 1) => {\n const target = index + by\n if (target < 0 || target >= rules.length) return\n const next = [...rules]\n ;[next[index], next[target]] = [next[target], next[index]]\n void writeRules(next, 'Rule moved').catch(() => undefined)\n }\n const remove = (rule: CrmAssignmentRule) => {\n void writeRules(\n rules.filter((entry) => entry.id !== rule.id),\n 'Rule deleted',\n ).catch(() => undefined)\n }\n const handleAdd = async (rule: CrmAssignmentRule) => {\n await writeRules([...rules, rule], 'Rule added')\n setDrawerOpen(false)\n }\n\n const ready = scopeReady && roleReady\n const atCap = rules.length >= CRM_ASSIGNMENT_RULES_MAX\n const canEdit = ready && canManage && !busy\n const ordinal = (index: number) => {\n const n = index + 1\n const suffix =\n n % 100 >= 11 && n % 100 <= 13\n ? 'th'\n : (['th', 'st', 'nd', 'rd'] as const)[n % 10] ?? 'th'\n return `${n}${suffix}`\n }\n return (\n <CardDisplay\n header={'Assignment rules'}\n help={pluginDocsHelp('crmSettings', { anchor: '#assignment-rules' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n variant=\"contained\"\n disabled={!canEdit || atCap}\n onClick={() => setDrawerOpen(true)}\n >\n {'Add rule'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Tried in order for every new contact captured on any site in the ' +\n 'workspace; the first rule whose every condition holds assigns the ' +\n 'owner. A contact no rule claims goes to the capturing site’s ' +\n 'default owner, or stays unassigned.'}\n </Typography>\n {rules.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No rules yet. Add one to route new contacts by where they came from.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell sx={{ width: 120 }}>{'Order'}</TableCell>\n <TableCell>{'When'}</TableCell>\n <TableCell>{'Assign to'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {rules.map((rule, index) => {\n const described = describeAssignmentRule(rule, roster.nameOf)\n return (\n <TableRow key={rule.id} hover>\n <TableCell>\n <Stack direction=\"row\" spacing={0} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ minWidth: 32 }}>\n {ordinal(index)}\n </Typography>\n <IconButton\n size=\"small\"\n disabled={!canEdit || index === 0}\n onClick={() => move(index, -1)}\n >\n <MdiIcon path={mdiArrowUp.path} size={0.7} />\n <SrOnly>{`Move rule ${index + 1} up`}</SrOnly>\n </IconButton>\n <IconButton\n size=\"small\"\n disabled={!canEdit || index === rules.length - 1}\n onClick={() => move(index, 1)}\n >\n <MdiIcon path={mdiArrowDown.path} size={0.7} />\n <SrOnly>{`Move rule ${index + 1} down`}</SrOnly>\n </IconButton>\n </Stack>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">{described.when}</Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">{described.assign}</Typography>\n </TableCell>\n <TableCell align=\"right\" sx={{ width: 56 }}>\n <RowActionsMenu\n label={`Rule ${index + 1}`}\n items={[\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: () => remove(rule),\n },\n ]}\n />\n </TableCell>\n </TableRow>\n )\n })}\n </TableBody>\n </ScrollTable>\n )}\n {atCap ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`A workspace keeps at most ${CRM_ASSIGNMENT_RULES_MAX} rules. Delete one to add another.`}\n </Typography>\n ) : null}\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n <AssignmentRuleDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n members={roster.members}\n membersLoading={roster.loading}\n poolSize={settings.pool.memberUids.length}\n existingIds={rules.map((rule) => rule.id)}\n onSubmit={handleAdd}\n />\n </CardDisplay>\n )\n}\nAssignmentRulesCard.displayName = 'AssignmentRulesCard'\n\n/**\n * \"Round robin\" — the members handed records in turn (AGL-2618).\n *\n * The pool is the roster with a checkbox per member, and its ORDER is the\n * order members were checked: a member checked later joins the end of the\n * rotation, and unchecking removes them without disturbing the others. The\n * pointer — who got the last record — is the server's to move and is only\n * read here, as \"next up\", so an admin can see where the rotation stands\n * without being able to put a thumb on it.\n */\nexport function RoundRobinCard(props: AssignmentCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const roster = useOrgMemberDirectory(orgId)\n const { pool } = useMemo(\n () => readCrmAssignmentSettings(org as Record<string, unknown> | undefined),\n [org],\n )\n const [busy, setBusy] = useState(false)\n\n const toggle = async (uid: string, inPool: boolean) => {\n if (!orgId || !canManage) return\n const next = inPool\n ? [...pool.memberUids.filter((entry) => entry !== uid), uid]\n : pool.memberUids.filter((entry) => entry !== uid)\n if (next.length > CRM_ROUND_ROBIN_POOL_MAX) return\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_ROUND_ROBIN_POOL_PATH]: next,\n })\n enqueueSnackbar(\n inPool\n ? `${roster.nameOf(uid)} joined the rotation`\n : `${roster.nameOf(uid)} left the rotation`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The pool could not be saved', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }\n\n const ready = scopeReady && roleReady\n const canEdit = ready && canManage && !busy && !roster.loading\n const order = roundRobinOrder(pool.memberUids, pool.lastAssignedUid)\n const nextUp = order[0]\n // The rotation names people the way the checkboxes above do — with the\n // address, since two members can share a display name.\n const rotationName = (uid: string): string => {\n const member = roster.members.find((row) => row.uid === uid)\n return member ? crmMemberPickerLabel(member) : roster.nameOf(uid)\n }\n return (\n <CardDisplay\n header={'Round robin'}\n help={pluginDocsHelp('crmSettings', { anchor: '#round-robin' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The members a round-robin rule, or an automation set to round ' +\n 'robin, hands records to in turn. Each new record goes to the ' +\n 'member after the last one who got a record, wrapping round.'}\n </Typography>\n {roster.loading ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Loading the team…'}\n </Typography>\n ) : roster.error ? (\n <Typography variant=\"body2\" color=\"error\">\n {roster.error}\n </Typography>\n ) : (\n <FormGroup>\n {roster.members.map((member) => (\n <FormControlLabel\n key={member.uid}\n control={\n <Checkbox\n size=\"small\"\n checked={pool.memberUids.includes(member.uid)}\n disabled={!canEdit}\n onChange={(event) => void toggle(member.uid, event.target.checked)}\n />\n }\n label={crmMemberPickerLabel(member)}\n />\n ))}\n </FormGroup>\n )}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {pool.memberUids.length === 0\n ? 'Nobody is in the rotation; a round-robin rule is skipped until somebody is.'\n : `Rotation: ${pool.memberUids.map(rotationName).join(' → ')}. Next up: ${rotationName(nextUp)}.`}\n </Typography>\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nRoundRobinCard.displayName = 'RoundRobinCard'\n\n/**\n * `/crm/settings` — what the CRM does on its own, for every site in the\n * workspace (AGL-2613).\n *\n * A stack of cards, one per concern, so a later setting arrives as a card\n * beside this one rather than a field inside it. Every card writes the org\n * document, because a CRM setting is a fact about how the business files\n * people and not about one site; the section is reached from a site's hub\n * or from the organization's (AGL-2630), and writes the same document from\n * either. The one per-site setting — the default owner — is the site's\n * slot in an org-wide map: under a site the card names the site it is for,\n * and at the organization level it lists every site's slot.\n *\n * The Recipes card (AGL-2639) is the one card that mounts at the\n * ORGANIZATION level only. It installs an automation onto a site of the\n * reader's choosing, which is the org's need; under a site the Actions\n * page's own Recipes menu is the door, and a second one here would write\n * the same action by a different route. Last, because the welcome recipe\n * leans on the round-robin pool set up in the card above it.\n *\n * The Email templates card (AGL-2658) is the one card every CRM editor may\n * write to — a template is working material, not policy — and mounts at\n * both levels, listing the site's letters under a site and the whole\n * workspace's from the organization's hub.\n *\n * Your sending addresses (AGL-2975) sits directly under Email capture,\n * because it is where a member who copies that address from an alias looks\n * next: it is the reader's OWN list, at both levels, and writes through the\n * core route rather than the org document.\n */\nexport function CrmSettingsSection(props: CrmSettingsSectionProps) {\n const { hostId, org } = props\n const mount = useCrmOrgMount()\n // The Email capture card (AGL-2657) rotates on the same key every other\n // card writes on, \"Change CRM settings\"; the scope and the key are resolved\n // here once and handed down, since the card itself writes no document.\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n return (\n <Stack spacing={3}>\n <DefaultRecordSharingCard hostId={hostId} org={org} />\n <AutoCreateCompaniesCard hostId={hostId} org={org} />\n <DefaultOwnerCard hostId={hostId} org={org} />\n <AssignmentRulesCard hostId={hostId} org={org} />\n <RoundRobinCard hostId={hostId} org={org} />\n <EmailTemplatesCard hostId={hostId} org={org} />\n <EmailCaptureCard hostId={hostId} canManage={canManage} ready={scopeReady && roleReady} />\n <SendingAddressesCard orgId={orgId} ready={scopeReady} />\n {/* Sharing rules (AGL-3336) are the organization's: mounted where its\n sites are listed, at the org level only — before Recipes, which\n stays last. */}\n {mount ? (\n <SharingRulesCard\n orgId={orgId ?? null}\n org={org}\n canManage={canManage}\n ready={scopeReady && roleReady}\n />\n ) : null}\n {mount ? <RecipesCard org={org} /> : null}\n </Stack>\n )\n}\nCrmSettingsSection.displayName = 'CrmSettingsSection'\n\nexport default CrmSettingsSection\n"],"names":["CRM_ASSIGNMENT_RULES_MAX","CRM_ASSIGNMENT_RULES_PATH","CRM_AUTO_CREATE_COMPANIES_PATH","CRM_DEFAULT_RECORD_SCOPE_PATH","CRM_ROUND_ROBIN_POOL_MAX","CRM_ROUND_ROBIN_POOL_PATH","crmDefaultScopeOf","crmHostDefaultOwnerSegments","describeAssignmentRule","isOrgWideMember","orgAutoCreatesCompanies","pluginDocsHelp","readCrmAssignmentSettings","resolveOrgPermissions","roundRobinOrder","crmMemberPickerLabel","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","CardDisplay","MdiIcon","SrOnly","RowActionsMenu","ScrollTable","useSnackbar","useFirestore","useFirestoreDoc","useUser","Button","Checkbox","FormControlLabel","FormGroup","FormHelperText","IconButton","MenuItem","Stack","Switch","TableBody","TableCell","TableHead","TableRow","TextField","Typography","deleteField","doc","FieldPath","updateDoc","useCallback","useEffect","useMemo","useState","useCrmOrgMount","useCrmScope","CRM_SETTINGS_PERMISSION","crmSettingsPermissionRefusal","useOrgMemberDirectory","AssignmentRuleDrawer","EmailTemplatesCard","EmailCaptureCard","RecipesCard","SendingAddressesCard","SharingRulesCard","useCanManageCrmSettings","orgId","roleRead","firestore","data","user","uid","memberRead","member","status","undefined","roleId","ready","Boolean","granted","canManage","AutoCreateCompaniesCard","props","hostId","org","enqueueSnackbar","scopeReady","roleReady","stored","checked","setChecked","busy","setBusy","handleChange","next","variant","persist","error","console","allowDuplicate","header","help","anchor","contentGutterX","contentGutterY","spacing","control","size","disabled","onChange","event","target","label","color","displayName","DefaultRecordSharingCard","value","setValue","sx","maxWidth","select","helperText","ManagersOnlyNote","NO_DEFAULT_OWNER","DefaultOwnerCard","roster","mount","sites","id","name","hosts","map","host","hostsReady","site","DefaultOwnerPicker","siteId","siteName","length","siteLabel","hostDefaultOwners","nameOf","options","members","some","loading","slotProps","displayEmpty","inputLabel","shrink","AssignmentRulesCard","settings","rules","drawerOpen","setDrawerOpen","writeRules","said","move","index","by","catch","remove","rule","filter","entry","handleAdd","atCap","canEdit","ordinal","n","suffix","contentBordered","HeaderProps","action","onClick","width","align","described","hover","direction","alignItems","minWidth","path","when","assign","items","key","icon","destructive","open","onClose","membersLoading","poolSize","pool","memberUids","existingIds","onSubmit","RoundRobinCard","toggle","inPool","order","lastAssignedUid","nextUp","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mBAAmB9F,WAAW,GAAG;AAEjC,eAAe8F,mBAAkB"}
@@ -30,6 +30,7 @@ import { useLeadSourcePicklist } from "../hooks/use-lead-source-picklist.js";
30
30
  import { useLeadStatusPicklist } from "../hooks/use-lead-status-picklist.js";
31
31
  import { useOrgMemberDirectory } from "../hooks/use-org-member-directory.js";
32
32
  import { CRM_SHARING_RULES_MAX, describeShareTargets, describeSharingRuleScope } from "../model/crm-sharing.js";
33
+ import { crmSettingsPermissionRefusal } from "../model/crm-permissions.js";
33
34
  import { callCrmSharing } from "../model/crm-sharing-api.js";
34
35
  import { SharingRuleDrawer } from "./sharing-rule-drawer.js";
35
36
  /** How far a rule's recompute has got, as the table shows it. */ function runLabel(rule) {
@@ -270,7 +271,7 @@ import { SharingRuleDrawer } from "./sharing-rule-drawer.js";
270
271
  ready && !canManage ? /*#__PURE__*/ _jsx(Typography, {
271
272
  variant: "caption",
272
273
  color: "text.secondary",
273
- children: 'Only a workspace owner or admin can change sharing rules.'
274
+ children: crmSettingsPermissionRefusal()
274
275
  }) : null
275
276
  ]
276
277
  }),
@@ -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;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,EACpB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AC5BC,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","onSubm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,KAAKC,GAAG,CAACG,MAAM,KAAK,SAChC;4DACE;gEACEwE,KAAK;gEACLF,OAAO;gEACPG,oBAAM,KAACzG;oEAAQ0G,MAAM5G,WAAW4G,IAAI;oEAAEjB,MAAM;;gEAC5CL,UAAU,CAACV;gEACXY,SAAS,IACP,KAAKzD,IAAI,iBAAiB;wEAAEmC,QAAQpC,KAAKqC,EAAE;oEAAC,GAAG;4DACnD;yDACD,GACD,EAAE;wDACN;4DACEuC,KAAK;4DACLF,OAAO;4DACPG,oBAAM,KAACzG;gEAAQ0G,MAAM9G,iBAAiB8G,IAAI;gEAAEjB,MAAM;;4DAClDkB,aAAa;4DACbvB,UAAU,CAACV;4DACXY,SAAS,IACP,KAAKzD,IAAI,eAAe;oEAAEmC,QAAQpC,KAAKqC,EAAE;gEAAC,GAAG;wDACjD;qDACD;;;;uCA3DQrC,KAAKqC,EAAE;;;;oBAmE7BvB,SAAS,CAACD,0BACT,KAAC7B;wBAAWwD,SAAQ;wBAAUoB,OAAM;kCACjChE;yBAED;;;0BAEN,KAACE;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"}
@@ -22,17 +22,24 @@ export interface OrgMembers {
22
22
  * THE WORKSPACE'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":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SACEA,eAAe,QAEV,2CAA0C;AACjD,SAA+BC,eAAe,EAAEC,aAAa,QAAQ,eAAc;AACnF,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC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A,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"}