@aglyn/plugins-crm 1.18.0 → 1.20.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.
- package/package.json +14 -14
- package/src/lib/components/log-activity-dialog.d.ts +2 -0
- package/src/lib/components/log-activity-dialog.js +11 -2
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/record-sharing-card.js +8 -7
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +10 -3
- package/src/lib/components/settings-section.js +286 -35
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/share-records-dialog.d.ts +17 -3
- package/src/lib/components/share-records-dialog.js +59 -45
- package/src/lib/components/share-records-dialog.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
- package/src/lib/components/sharing-rule-drawer.js +51 -40
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/declarations.server.js +10 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -2
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
- package/src/lib/hooks/use-crm-sharing.js +20 -0
- package/src/lib/hooks/use-crm-sharing.js.map +1 -1
- package/src/lib/model/crm-sharing-api.d.ts +5 -2
- package/src/lib/model/crm-sharing-api.js +3 -0
- package/src/lib/model/crm-sharing-api.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +153 -5
- package/src/lib/model/crm-sharing.js +243 -20
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/add-contact-by-hand.js +11 -4
- package/src/lib/server/add-contact-by-hand.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +2 -2
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +2 -2
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +2 -2
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
- package/src/lib/server/api-v1/crm-shared.js +12 -1
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +2 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/associate-company-by-domain.d.ts +1 -1
- package/src/lib/server/associate-company-by-domain.js +4 -4
- package/src/lib/server/associate-company-by-domain.js.map +1 -1
- package/src/lib/server/automation-steps.js +24 -12
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -3
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -4
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/crm-default-sharing.d.ts +86 -0
- package/src/lib/server/crm-default-sharing.js +409 -0
- package/src/lib/server/crm-default-sharing.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +2 -2
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing-runs.d.ts +71 -0
- package/src/lib/server/crm-sharing-runs.js +221 -0
- package/src/lib/server/crm-sharing-runs.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +24 -1
- package/src/lib/server/crm-sharing.js +183 -31
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +5 -2
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +2 -1
- package/src/lib/server/record-timeline.js +11 -6
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +10 -6
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server.js +23 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/common.d.ts +5 -1
- package/src/lib/transfer/common.js +8 -5
- package/src/lib/transfer/common.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 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","rotationName","find","row","includes","join","CrmSettingsSection"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAIEA,wBAAwB,EACxBC,yBAAyB,EACzBC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,wBAAwB,EACxBC,yBAAyB,EAEzBC,iBAAiB,EACjBC,2BAA2B,EAC3BC,sBAAsB,EACtBC,eAA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AE7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAAS8F,mBAAmB9H,KAA8B;IAC/D,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAE,GAAGF;IACxB,MAAM4C,QAAQxE;IACd,wEAAwE;IACxE,4EAA4E;IAC5E,uEAAuE;IACvE,MAAM,EAAEY,KAAK,EAAEW,OAAOS,UAAU,EAAE,GAAG/B,YAAY;QAAE4B;QAAQC;IAAI;IAC/D,MAAM,EAAEJ,SAAS,EAAEH,OAAOU,SAAS,EAAE,GAAGtB,wBAAwBC;IAChE,qBACE,MAAC5B;QAAMmE,SAAS;;0BACd,KAACU;gBAAyBhC,QAAQA;gBAAQC,KAAKA;;0BAC/C,KAACH;gBAAwBE,QAAQA;gBAAQC,KAAKA;;0BAC9C,KAACwC;gBAAiBzC,QAAQA;gBAAQC,KAAKA;;0BACvC,KAACkE;gBAAoBnE,QAAQA;gBAAQC,KAAKA;;0BAC1C,KAACiH;gBAAelH,QAAQA;gBAAQC,KAAKA;;0BACrC,KAACxB;gBAAmBuB,QAAQA;gBAAQC,KAAKA;;0BACzC,KAACvB;gBAAiBsB,QAAQA;gBAAQH,WAAWA;gBAAWH,OAAOS,cAAcC;;0BAC7E,KAACxB;gBAAqBG,OAAOA;gBAAOW,OAAOS;;YAI1CwC,sBACC,KAAC9D;gBACCE,KAAK,EAAEA,gBAAAA,QAAS;gBAChBkB,KAAKA;gBACLJ,WAAWA;gBACXH,OAAOS,cAAcC;iBAErB;YACHuC,sBAAQ,KAAChE;gBAAYsB,KAAKA;iBAAU;;;AAG3C;AACA4H,mBAAmB9F,WAAW,GAAG;AAEjC,eAAe8F,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_MAX_INCLUDED,\n CRM_DEFAULT_RECORD_EXCEPT_AT_PATH,\n CRM_DEFAULT_RECORD_EXCEPT_PATH,\n CRM_DEFAULT_RECORD_SCOPE_PATH,\n CRM_ROUND_ROBIN_POOL_MAX,\n CRM_ROUND_ROBIN_POOL_PATH,\n type CrmAssignmentRule,\n crmDefaultExceptOf,\n crmDefaultSharingOf,\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 { sharingFromChoice } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { CardDisplay, MdiIcon, SrOnly, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\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 FormControl,\n FormControlLabel,\n FormGroup,\n FormHelperText,\n FormLabel,\n IconButton,\n MenuItem,\n Radio,\n RadioGroup,\n Stack,\n Switch,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport { deleteField, doc, FieldPath, serverTimestamp, 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 { useCrmSharingSites } from '../hooks/use-crm-sharing'\nimport { type CrmDefaultApplyRun, readCrmDefaultApplyRun } from '../model/crm-sharing'\nimport { callCrmSharing } from '../model/crm-sharing-api'\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 * setting would hide records from sites already working them, with no\n * confirmation. Each record's own sharing is where that is decided, and\n * under \"All sites except…\" (AGL-4047) the explicit \"Apply to existing\n * records\" run below, which says what it does before it starts.\n *\n * Reads `crmDefaultSharingOf`, 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 *\n * Radios and a visible list of sites, never a dropdown: the sites left out\n * are the part people come to check. \"All sites except…\" is stored beside\n * `defaultRecordScope: 'host'`, so a reader that predates it keeps new\n * records to the site they came in on rather than sharing them wider.\n */\nexport function DefaultRecordSharingCard(props: AutoCreateCompaniesCardProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { orgId, ready: scopeReady } = useCrmScope({ hostId, org })\n const { canManage, ready: roleReady } = useCanManageCrmSettings(orgId)\n const sites = useCrmSharingSites({ hostId, orgId: orgId ?? null, enabled: canManage })\n const orgDocument = org as Record<string, unknown> | undefined\n\n const storedMode = crmDefaultSharingOf(orgDocument) ?? 'org'\n const storedExcept = useMemo(() => crmDefaultExceptOf(orgDocument) ?? [], [orgDocument])\n const [mode, setMode] = useState<CrmDefaultChoice>(storedMode)\n const [except, setExcept] = useState<string[]>(storedExcept)\n const [busy, setBusy] = useState(false)\n const [applying, setApplying] = useState(false)\n const [pass, setPass] = useState<CrmDefaultApplyRun | null>(null)\n useEffect(() => setMode(storedMode), [storedMode])\n useEffect(() => setExcept(storedExcept), [storedExcept])\n\n const siteIds = sites.sites.map((site) => site.id)\n const exceptOff = !canManage\n ? null\n : !sites.ready\n ? 'Reading this workspace’s sites…'\n : sites.sites.length < 2\n ? 'This workspace has one site, so there is nothing to leave out.'\n : sites.sites.length > CRM_DEFAULT_MAX_INCLUDED\n ? `This works up to ${CRM_DEFAULT_MAX_INCLUDED} sites, and this workspace has ${sites.sites.length}. Choose another option.`\n : null\n // The answer the stamp gives, from the same helper the server uses.\n const problem =\n mode === 'allExcept' && sites.ready\n ? sharingFromChoice({ mode: 'allExcept', exceptHostIds: except }, siteIds).problem\n : null\n const changed =\n mode !== storedMode ||\n (mode === 'allExcept' &&\n (except.length !== storedExcept.length || except.some((id) => !storedExcept.includes(id))))\n const ready = scopeReady && roleReady\n const canSave = ready && canManage && !busy && changed && !problem && (mode !== 'allExcept' || !exceptOff)\n\n const save = async () => {\n if (!orgId || !canSave) return\n setBusy(true)\n try {\n await updateDoc(doc(firestore, 'orgs', orgId), {\n [CRM_DEFAULT_RECORD_SCOPE_PATH]: mode === 'org' ? 'org' : 'host',\n [CRM_DEFAULT_RECORD_EXCEPT_PATH]:\n mode === 'allExcept' ? except.filter((id) => siteIds.includes(id)) : deleteField(),\n [CRM_DEFAULT_RECORD_EXCEPT_AT_PATH]: mode === 'allExcept' ? serverTimestamp() : deleteField(),\n })\n enqueueSnackbar('Default sharing updated', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n setMode(storedMode)\n setExcept(storedExcept)\n enqueueSnackbar('The setting could not be saved', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n }\n\n const storedRun = readCrmDefaultApplyRun(orgDocument)\n const run = pass ?? storedRun\n const running = applying || run?.status === 'running'\n const applyOff =\n storedMode !== 'allExcept'\n ? 'Choose All sites except… and save it first.'\n : changed\n ? 'Save the default first.'\n : running\n ? 'Applying now.'\n : null\n\n const apply = async (action: 'default-apply' | 'default-apply-continue') => {\n if (!orgId) return\n if (action === 'default-apply') {\n const leftOut = storedExcept.map(sites.siteName).join(', ')\n const confirmed = await confirm({\n title: 'Apply to existing records?',\n description:\n `Every contact, lead, company, deal, task and logged activity this workspace has is shared ` +\n `with every site except ${leftOut}. The site that captured a person keeps them. ` +\n 'Sites left out stop seeing the rest. Records shared by hand or by a sharing rule keep those shares.',\n confirmationText: 'Apply to existing records',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n }\n setApplying(true)\n try {\n let answer = await callCrmSharing(user, { orgId }, action)\n setPass(answer.applyRun ?? null)\n while (answer.more) {\n answer = await callCrmSharing(user, { orgId }, 'default-apply-continue')\n if (answer.applyRun) setPass(answer.applyRun)\n }\n if (answer.applyRun?.status === 'done') {\n enqueueSnackbar('The default sharing is applied to existing records', {\n variant: 'success',\n persist: false,\n })\n }\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error', allowDuplicate: true })\n } finally {\n setApplying(false)\n }\n }\n\n const toggle = (hostIdToToggle: string) => () =>\n setExcept((current) =>\n current.includes(hostIdToToggle)\n ? current.filter((id) => id !== hostIdToToggle)\n : [...current, hostIdToToggle],\n )\n const stillIn = siteIds.filter((id) => !except.includes(id))\n const editable = ready && canManage && !busy\n\n return (\n <CardDisplay\n header={'Default sharing for new records'}\n help={pluginDocsHelp('crmSharing', { anchor: '#default-sharing-for-new-records' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5} sx={{ maxWidth: 520 }}>\n <FormControl component=\"fieldset\" disabled={!editable}>\n <FormLabel component=\"legend\" sx={{ typography: 'caption' }}>\n {'New contacts, companies, deals and tasks are shared with'}\n </FormLabel>\n <RadioGroup\n value={mode}\n onChange={(event) => {\n const next = event.target.value as CrmDefaultChoice\n setMode(next)\n if (next === 'allExcept' && storedMode !== 'allExcept') setExcept([])\n }}\n >\n <FormControlLabel value=\"org\" control={<Radio size=\"small\" />} label=\"All sites in the organization\" />\n <FormControlLabel\n value=\"host\"\n control={<Radio size=\"small\" />}\n label={\n <Stack>\n <Typography variant=\"body2\">{'Only the site they came in on'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Keeps clients apart, for agencies.'}\n </Typography>\n </Stack>\n }\n />\n <FormControlLabel\n value=\"allExcept\"\n // The saved choice stays on: nobody is told they can't have what they have.\n disabled={!editable || (Boolean(exceptOff) && storedMode !== 'allExcept')}\n control={<Radio size=\"small\" />}\n label={\n <Stack>\n <Typography variant=\"body2\">{'All sites except…'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {exceptOff ??\n 'Every site but the ones you leave out, including sites added later. The site a person came in on always keeps them.'}\n </Typography>\n </Stack>\n }\n />\n </RadioGroup>\n {mode === 'allExcept' ? (\n <Stack spacing={0.5} sx={{ pl: 3.5 }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Sites to leave out'}\n </Typography>\n <FormGroup sx={{ flexWrap: 'nowrap', maxHeight: (theme) => theme.spacing(30), overflowY: 'auto' }}>\n {sites.sites.map((site) => {\n const locked = stillIn.length === 1 && stillIn[0] === site.id\n return (\n <FormControlLabel\n key={site.id}\n disabled={!editable || locked}\n control={\n <Checkbox size=\"small\" checked={except.includes(site.id)} onChange={toggle(site.id)} />\n }\n label={\n <Stack>\n <Typography variant=\"body2\">{site.name}</Typography>\n {locked ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'At least one site has to stay in.'}\n </Typography>\n ) : null}\n </Stack>\n }\n />\n )\n })}\n </FormGroup>\n </Stack>\n ) : null}\n {problem ? <FormHelperText error>{problem}</FormHelperText> : null}\n <FormHelperText>\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 </FormHelperText>\n </FormControl>\n <Stack direction=\"row\" spacing={1}>\n <BlockedControl blocked={ready && !canManage} reason={crmSettingsPermissionRefusal()}>\n <Button variant=\"contained\" size=\"small\" disabled={!canSave} onClick={() => void save()}>\n {'Save'}\n </Button>\n </BlockedControl>\n </Stack>\n <Typography variant=\"subtitle2\">{'Records you already have'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Saving changes only new records. To share the ones you already have the same way, ' +\n 'apply it to them. The site that captured each person keeps them.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <BlockedControl\n blocked={(ready && !canManage) || Boolean(applyOff)}\n reason={ready && !canManage ? crmSettingsPermissionRefusal() : (applyOff ?? '')}\n >\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={!ready || !canManage || Boolean(applyOff)}\n onClick={() => void apply('default-apply')}\n >\n {'Apply to existing records…'}\n </Button>\n </BlockedControl>\n {run?.status === 'failed' && storedMode === 'allExcept' && !applying ? (\n <Button size=\"small\" disabled={!canManage} onClick={() => void apply('default-apply-continue')}>\n {'Resume'}\n </Button>\n ) : null}\n </Stack>\n {run ? (\n <Typography\n variant=\"caption\"\n color={run.status === 'failed' ? 'error' : 'text.secondary'}\n role=\"status\"\n >\n {run.status === 'running'\n ? `Applying: ${run.processed} records checked, ${run.changed} changed so far.`\n : run.status === 'done'\n ? `Applied: ${run.processed} records checked, ${run.changed} changed${\n run.capped ? `, ${run.capped} left as they were because they would reach more than ${CRM_DEFAULT_MAX_INCLUDED} sites` : ''\n }.`\n : (run.error ?? 'Applying stopped.')}\n </Typography>\n ) : null}\n <ManagersOnlyNote ready={ready} canManage={canManage} />\n </Stack>\n </CardDisplay>\n )\n}\nDefaultRecordSharingCard.displayName = 'DefaultRecordSharingCard'\n\n/** The three choices the default card offers. */\ntype CrmDefaultChoice = 'org' | 'host' | 'allExcept'\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_MAX_INCLUDED","CRM_DEFAULT_RECORD_EXCEPT_AT_PATH","CRM_DEFAULT_RECORD_EXCEPT_PATH","CRM_DEFAULT_RECORD_SCOPE_PATH","CRM_ROUND_ROBIN_POOL_MAX","CRM_ROUND_ROBIN_POOL_PATH","crmDefaultExceptOf","crmDefaultSharingOf","crmHostDefaultOwnerSegments","describeAssignmentRule","isOrgWideMember","orgAutoCreatesCompanies","pluginDocsHelp","readCrmAssignmentSettings","resolveOrgPermissions","roundRobinOrder","crmMemberPickerLabel","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","sharingFromChoice","CardDisplay","MdiIcon","SrOnly","useConfirmationContext","BlockedControl","RowActionsMenu","ScrollTable","useSnackbar","useFirestore","useFirestoreDoc","useUser","Button","Checkbox","FormControl","FormControlLabel","FormGroup","FormHelperText","FormLabel","IconButton","MenuItem","Radio","RadioGroup","Stack","Switch","TableBody","TableCell","TableHead","TableRow","TextField","Typography","deleteField","doc","FieldPath","serverTimestamp","updateDoc","useCallback","useEffect","useMemo","useState","useCrmOrgMount","useCrmScope","useCrmSharingSites","readCrmDefaultApplyRun","callCrmSharing","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","run","confirm","sites","enabled","orgDocument","storedMode","storedExcept","mode","setMode","except","setExcept","applying","setApplying","pass","setPass","siteIds","map","site","id","exceptOff","length","problem","exceptHostIds","changed","some","includes","canSave","save","filter","storedRun","running","applyOff","apply","action","leftOut","siteName","join","confirmed","title","description","confirmationText","then","catch","answer","applyRun","more","message","toggle","hostIdToToggle","current","stillIn","editable","sx","maxWidth","component","typography","value","pl","flexWrap","maxHeight","theme","overflowY","locked","name","direction","blocked","reason","onClick","alignItems","role","processed","capped","ManagersOnlyNote","NO_DEFAULT_OWNER","DefaultOwnerCard","roster","mount","hosts","host","hostsReady","DefaultOwnerPicker","siteId","siteLabel","hostDefaultOwners","setValue","nameOf","options","members","select","loading","slotProps","displayEmpty","inputLabel","shrink","AssignmentRulesCard","settings","rules","drawerOpen","setDrawerOpen","writeRules","said","move","index","by","remove","rule","entry","handleAdd","atCap","canEdit","ordinal","n","suffix","contentBordered","HeaderProps","width","align","described","hover","minWidth","path","when","assign","items","key","icon","destructive","open","onClose","membersLoading","poolSize","pool","memberUids","existingIds","onSubmit","RoundRobinCard","inPool","order","lastAssignedUid","nextUp","rotationName","find","row","CrmSettingsSection"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAIEA,wBAAwB,EACxBC,yBAAyB,EACzBC,8BAA8B,EAC9BC,wBAAwB,EACxBC,iCAAiC,EACjCC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,wBAAwB,EACxBC,yBAAyB,EAEzBC,kBAAkB,EAClBC,mBAAmB,EACnBC,2BAA2B,EAC3BC,sBAAsB,EACtBC,eAAe,EACfC,uBAAuB,EACvBC,cAAc,EACdC,yBAAyB,EACzBC,qBAAqB,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EAAEC,MAAM,EAAEC,GAAG,EAAE,GAAGF;IACxB,MAAM8G,QAAQ7I;IACd,wEAAwE;IACxE,4EAA4E;IAC5E,uEAAuE;IACvE,MAAM,EAAEe,KAAK,EAAEW,OAAOS,UAAU,EAAE,GAAGlC,YAAY;QAAE+B;QAAQC;IAAI;IAC/D,MAAM,EAAEJ,SAAS,EAAEH,OAAOU,SAAS,EAAE,GAAGtB,wBAAwBC;IAChE,qBACE,MAAChC;QAAMuE,SAAS;;0BACd,KAACU;gBAAyBhC,QAAQA;gBAAQC,KAAKA;;0BAC/C,KAACH;gBAAwBE,QAAQA;gBAAQC,KAAKA;;0BAC9C,KAAC0G;gBAAiB3G,QAAQA;gBAAQC,KAAKA;;0BACvC,KAAC8H;gBAAoB/H,QAAQA;gBAAQC,KAAKA;;0BAC1C,KAACuK;gBAAexK,QAAQA;gBAAQC,KAAKA;;0BACrC,KAACxB;gBAAmBuB,QAAQA;gBAAQC,KAAKA;;0BACzC,KAACvB;gBAAiBsB,QAAQA;gBAAQH,WAAWA;gBAAWH,OAAOS,cAAcC;;0BAC7E,KAACxB;gBAAqBG,OAAOA;gBAAOW,OAAOS;;YAI1C0G,sBACC,KAAChI;gBACCE,KAAK,EAAEA,gBAAAA,QAAS;gBAChBkB,KAAKA;gBACLJ,WAAWA;gBACXH,OAAOS,cAAcC;iBAErB;YACHyG,sBAAQ,KAAClI;gBAAYsB,KAAKA;iBAAU;;;AAG3C;AACA+K,mBAAmBjJ,WAAW,GAAG;AAEjC,eAAeiJ,mBAAkB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type SiteSharingValue } from '@aglyn/shared-ui-jsx/components/site-sharing-field.component';
|
|
1
2
|
import { type CrmSharingObject, type CrmSharingSite } from '../model/crm-sharing';
|
|
2
3
|
import type { CrmTaskRouteScope } from '../model/task-routes';
|
|
3
4
|
export interface ShareRecordsDialogProps {
|
|
@@ -9,13 +10,26 @@ export interface ShareRecordsDialogProps {
|
|
|
9
10
|
scope: CrmTaskRouteScope | null;
|
|
10
11
|
sites: readonly CrmSharingSite[];
|
|
11
12
|
sitesReady: boolean;
|
|
12
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Sites that already hold the record. They are listed like every site, so
|
|
15
|
+
* what each choice reaches reads true, and the dialog says they keep it.
|
|
16
|
+
*/
|
|
13
17
|
heldHostIds?: readonly string[];
|
|
14
18
|
onShared?: (changed: number) => void;
|
|
15
19
|
}
|
|
16
20
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
21
|
+
* What `crm/sharing` `share` reads as `targets` for a choice (AGL-4047):
|
|
22
|
+
* `'all'`, the sites, or all sites except the ones left out.
|
|
23
|
+
*/
|
|
24
|
+
export declare function shareTargetsOfChoice(choice: SiteSharingValue): 'all' | string[] | {
|
|
25
|
+
mode: 'allExcept';
|
|
26
|
+
exceptHostIds: string[];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* "Share with sites…" (AGL-3336): All sites — which covers a site created
|
|
30
|
+
* later — the sites a manager picks, or all sites except the ones they leave
|
|
31
|
+
* out (AGL-4047), which a site created later also joins; and whether they
|
|
32
|
+
* may edit. Radios and a visible list, through the shared sharing field.
|
|
19
33
|
*
|
|
20
34
|
* Read-only is the default. The sentence under the choice is the guardrail
|
|
21
35
|
* a manager has to read before sharing: the other site sees the person and
|
|
@@ -15,16 +15,34 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ 'use client';
|
|
17
17
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
18
|
-
import {
|
|
18
|
+
import { sharingFromChoice } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
19
|
+
import { SiteSharingField } from "@aglyn/shared-ui-jsx/components/site-sharing-field.component";
|
|
19
20
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
20
21
|
import { useUser } from "@aglyn/tenant-feature-instance";
|
|
21
|
-
import { Button,
|
|
22
|
-
import { useEffect, useState } from "react";
|
|
23
|
-
import { CRM_SHARING_OBJECT_LABELS } from "../model/crm-sharing.js";
|
|
22
|
+
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, FormControlLabel, FormHelperText, FormLabel, Radio, RadioGroup, Stack, Typography } from "@mui/material";
|
|
23
|
+
import { useEffect, useMemo, useState } from "react";
|
|
24
|
+
import { CRM_SHARING_MAX_INCLUDED, CRM_SHARING_OBJECT_LABELS } from "../model/crm-sharing.js";
|
|
24
25
|
import { callCrmSharing } from "../model/crm-sharing-api.js";
|
|
25
26
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
27
|
+
* What `crm/sharing` `share` reads as `targets` for a choice (AGL-4047):
|
|
28
|
+
* `'all'`, the sites, or all sites except the ones left out.
|
|
29
|
+
*/ export function shareTargetsOfChoice(choice) {
|
|
30
|
+
if (choice.mode === 'all') return 'all';
|
|
31
|
+
if (choice.mode === 'selected') return [
|
|
32
|
+
...choice.hostIds
|
|
33
|
+
];
|
|
34
|
+
return {
|
|
35
|
+
mode: 'allExcept',
|
|
36
|
+
exceptHostIds: [
|
|
37
|
+
...choice.exceptHostIds
|
|
38
|
+
]
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* "Share with sites…" (AGL-3336): All sites — which covers a site created
|
|
43
|
+
* later — the sites a manager picks, or all sites except the ones they leave
|
|
44
|
+
* out (AGL-4047), which a site created later also joins; and whether they
|
|
45
|
+
* may edit. Radios and a visible list, through the shared sharing field.
|
|
28
46
|
*
|
|
29
47
|
* Read-only is the default. The sentence under the choice is the guardrail
|
|
30
48
|
* a manager has to read before sharing: the other site sees the person and
|
|
@@ -33,32 +51,45 @@ import { callCrmSharing } from "../model/crm-sharing-api.js";
|
|
|
33
51
|
const { open, onClose, object, ids, scope, sites, sitesReady, heldHostIds = [], onShared } = props;
|
|
34
52
|
const { data: user } = useUser();
|
|
35
53
|
const { enqueueSnackbar } = useSnackbar();
|
|
36
|
-
|
|
37
|
-
const [
|
|
54
|
+
// Nothing is chosen until the manager chooses.
|
|
55
|
+
const [choice, setChoice] = useState(null);
|
|
38
56
|
const [access, setAccess] = useState('read');
|
|
39
57
|
const [busy, setBusy] = useState(false);
|
|
40
58
|
useEffect(()=>{
|
|
41
59
|
if (!open) return;
|
|
42
|
-
|
|
43
|
-
setPicked([]);
|
|
60
|
+
setChoice(null);
|
|
44
61
|
setAccess('read');
|
|
45
62
|
}, [
|
|
46
63
|
open
|
|
47
64
|
]);
|
|
48
|
-
const
|
|
65
|
+
const holders = sites.filter((site)=>heldHostIds.includes(site.id)).map((site)=>site.name);
|
|
66
|
+
const others = sites.length - holders.length;
|
|
49
67
|
const label = CRM_SHARING_OBJECT_LABELS[object];
|
|
50
68
|
const what = ids.length === 1 ? `this ${label.one}` : `${ids.length} ${label.many.toLowerCase()}`;
|
|
51
|
-
|
|
52
|
-
|
|
69
|
+
// What the route will answer, from the same helper: the sites it reaches
|
|
70
|
+
// are worked out against every site of the workspace, held ones included.
|
|
71
|
+
const problem = useMemo(()=>{
|
|
72
|
+
if (!choice) return null;
|
|
73
|
+
if (choice.mode === 'selected' && !choice.hostIds.length) return 'Choose a site to share with.';
|
|
74
|
+
if (choice.mode === 'allExcept' && !sitesReady) return null;
|
|
75
|
+
return sharingFromChoice(choice, sites.map((site)=>site.id), {
|
|
76
|
+
maxIncluded: CRM_SHARING_MAX_INCLUDED
|
|
77
|
+
}).problem;
|
|
78
|
+
}, [
|
|
79
|
+
choice,
|
|
80
|
+
sites,
|
|
81
|
+
sitesReady
|
|
82
|
+
]);
|
|
83
|
+
const ready = Boolean(scope) && ids.length > 0 && Boolean(choice) && !problem;
|
|
53
84
|
const submit = async ()=>{
|
|
54
|
-
if (!scope || !ready) return;
|
|
85
|
+
if (!scope || !ready || !choice) return;
|
|
55
86
|
setBusy(true);
|
|
56
87
|
try {
|
|
57
88
|
var _answer_changed;
|
|
58
89
|
const answer = await callCrmSharing(user, scope, 'share', {
|
|
59
90
|
object,
|
|
60
91
|
ids,
|
|
61
|
-
targets:
|
|
92
|
+
targets: shareTargetsOfChoice(choice),
|
|
62
93
|
access
|
|
63
94
|
});
|
|
64
95
|
enqueueSnackbar(answer.changed ? `Shared ${answer.changed === 1 ? `one ${label.one}` : `${answer.changed} ${label.many.toLowerCase()}`}` : `Already shared that way`, {
|
|
@@ -94,37 +125,20 @@ import { callCrmSharing } from "../model/crm-sharing-api.js";
|
|
|
94
125
|
color: "text.secondary",
|
|
95
126
|
children: `The sites you pick see ${what} on their CRM lists and can log activity and tasks on it.`
|
|
96
127
|
}),
|
|
97
|
-
/*#__PURE__*/
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}),
|
|
106
|
-
offered.map((site)=>/*#__PURE__*/ _jsx(FormControlLabel, {
|
|
107
|
-
control: /*#__PURE__*/ _jsx(Checkbox, {
|
|
108
|
-
checked: allSites || picked.includes(site.id),
|
|
109
|
-
disabled: allSites,
|
|
110
|
-
onChange: (event)=>setPicked((current)=>event.target.checked ? [
|
|
111
|
-
...current,
|
|
112
|
-
site.id
|
|
113
|
-
] : current.filter((id)=>id !== site.id))
|
|
114
|
-
}),
|
|
115
|
-
label: site.name
|
|
116
|
-
}, site.id)),
|
|
117
|
-
!sitesReady ? /*#__PURE__*/ _jsx(FormHelperText, {
|
|
118
|
-
children: 'Loading your sites…'
|
|
119
|
-
}) : !offered.length ? /*#__PURE__*/ _jsx(FormHelperText, {
|
|
120
|
-
children: 'No other site to share with. All sites still covers sites added later.'
|
|
121
|
-
}) : null,
|
|
122
|
-
tooMany ? /*#__PURE__*/ _jsx(FormHelperText, {
|
|
123
|
-
error: true,
|
|
124
|
-
children: `Choose ${MAX_SCOPE_HOSTS} sites or fewer, or share with All sites.`
|
|
125
|
-
}) : null
|
|
126
|
-
]
|
|
128
|
+
/*#__PURE__*/ _jsx(SiteSharingField, {
|
|
129
|
+
label: "Share with",
|
|
130
|
+
value: choice,
|
|
131
|
+
onChange: setChoice,
|
|
132
|
+
sites: sites,
|
|
133
|
+
sitesReady: sitesReady,
|
|
134
|
+
maxIncluded: CRM_SHARING_MAX_INCLUDED,
|
|
135
|
+
problem: problem
|
|
127
136
|
}),
|
|
137
|
+
sitesReady && !others ? /*#__PURE__*/ _jsx(FormHelperText, {
|
|
138
|
+
children: 'No other site to share with. All sites still covers sites added later.'
|
|
139
|
+
}) : holders.length ? /*#__PURE__*/ _jsx(FormHelperText, {
|
|
140
|
+
children: `${holders.join(', ')} already ${holders.length === 1 ? 'holds' : 'hold'} ${what}, and ${holders.length === 1 ? 'keeps' : 'keep'} it whatever you choose.`
|
|
141
|
+
}) : null,
|
|
128
142
|
/*#__PURE__*/ _jsxs(FormControl, {
|
|
129
143
|
children: [
|
|
130
144
|
/*#__PURE__*/ _jsx(FormLabel, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/share-records-dialog.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 { MAX_SCOPE_HOSTS } from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControl,\n FormControlLabel,\n FormGroup,\n FormHelperText,\n FormLabel,\n Radio,\n RadioGroup,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport {\n CRM_SHARING_OBJECT_LABELS,\n type CrmShareAccess,\n type CrmSharingObject,\n type CrmSharingSite,\n} from '../model/crm-sharing'\nimport { callCrmSharing } from '../model/crm-sharing-api'\nimport type { CrmTaskRouteScope } from '../model/task-routes'\n\nexport interface ShareRecordsDialogProps {\n open: boolean\n onClose: () => void\n object: CrmSharingObject\n ids: readonly string[]\n /** The route scope the share is sent with. */\n scope: CrmTaskRouteScope | null\n sites: readonly CrmSharingSite[]\n sitesReady: boolean\n /** Sites that already hold the record — not offered, since they see it anyway. */\n heldHostIds?: readonly string[]\n onShared?: (changed: number) => void\n}\n\n/**\n * \"Share with sites…\" (AGL-3336): the sites a manager picks, or All sites —\n * which covers a site created later — and whether they may edit.\n *\n * Read-only is the default. The sentence under the choice is the guardrail\n * a manager has to read before sharing: the other site sees the person and\n * may work the record, and gains no permission to market to them.\n */\nexport function ShareRecordsDialog(props: ShareRecordsDialogProps) {\n const { open, onClose, object, ids, scope, sites, sitesReady, heldHostIds = [], onShared } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [allSites, setAllSites] = useState(false)\n const [picked, setPicked] = useState<string[]>([])\n const [access, setAccess] = useState<CrmShareAccess>('read')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (!open) return\n setAllSites(false)\n setPicked([])\n setAccess('read')\n }, [open])\n\n const offered = sites.filter((site) => !heldHostIds.includes(site.id))\n const label = CRM_SHARING_OBJECT_LABELS[object]\n const what = ids.length === 1 ? `this ${label.one}` : `${ids.length} ${label.many.toLowerCase()}`\n const tooMany = !allSites && picked.length > MAX_SCOPE_HOSTS\n const ready = Boolean(scope) && ids.length > 0 && (allSites || picked.length > 0) && !tooMany\n\n const submit = async () => {\n if (!scope || !ready) return\n setBusy(true)\n try {\n const answer = await callCrmSharing(user, scope, 'share', {\n object,\n ids,\n targets: allSites ? 'all' : picked,\n access,\n })\n enqueueSnackbar(\n answer.changed\n ? `Shared ${answer.changed === 1 ? `one ${label.one}` : `${answer.changed} ${label.many.toLowerCase()}`}`\n : `Already shared that way`,\n { variant: 'success', persist: false },\n )\n onShared?.(answer.changed ?? 0)\n onClose()\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle>{'Share with sites'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`The sites you pick see ${what} on their CRM lists and can log activity and tasks on it.`}\n </Typography>\n <FormGroup>\n <FormControlLabel\n control={\n <Checkbox\n checked={allSites}\n onChange={(event) => setAllSites(event.target.checked)}\n />\n }\n label=\"All sites, including sites added later\"\n />\n {offered.map((site) => (\n <FormControlLabel\n key={site.id}\n control={\n <Checkbox\n checked={allSites || picked.includes(site.id)}\n disabled={allSites}\n onChange={(event) =>\n setPicked((current) =>\n event.target.checked\n ? [...current, site.id]\n : current.filter((id) => id !== site.id),\n )\n }\n />\n }\n label={site.name}\n />\n ))}\n {!sitesReady ? (\n <FormHelperText>{'Loading your sites…'}</FormHelperText>\n ) : !offered.length ? (\n <FormHelperText>{'No other site to share with. All sites still covers sites added later.'}</FormHelperText>\n ) : null}\n {tooMany ? (\n <FormHelperText error>\n {`Choose ${MAX_SCOPE_HOSTS} sites or fewer, or share with All sites.`}\n </FormHelperText>\n ) : null}\n </FormGroup>\n <FormControl>\n <FormLabel>{'Access'}</FormLabel>\n <RadioGroup\n value={access}\n onChange={(event) => setAccess(event.target.value === 'edit' ? 'edit' : 'read')}\n >\n <FormControlLabel value=\"read\" control={<Radio size=\"small\" />} label=\"Read-only\" />\n <FormControlLabel value=\"edit\" control={<Radio size=\"small\" />} label=\"Read and edit\" />\n </RadioGroup>\n </FormControl>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Sharing is not consent. A site this is shared with cannot include the person ' +\n 'in a campaign, a list or a sequence unless the person gave that site consent.'}\n </Typography>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" onClick={() => void submit()} disabled={!ready || busy}>\n {'Share'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nShareRecordsDialog.displayName = 'ShareRecordsDialog'\n\nexport default ShareRecordsDialog\n"],"names":["MAX_SCOPE_HOSTS","useSnackbar","useUser","Button","Checkbox","Dialog","DialogActions","DialogContent","DialogTitle","FormControl","FormControlLabel","FormGroup","FormHelperText","FormLabel","Radio","RadioGroup","Stack","Typography","useEffect","useState","CRM_SHARING_OBJECT_LABELS","callCrmSharing","ShareRecordsDialog","props","open","onClose","object","ids","scope","sites","sitesReady","heldHostIds","onShared","data","user","enqueueSnackbar","allSites","setAllSites","picked","setPicked","access","setAccess","busy","setBusy","offered","filter","site","includes","id","label","what","length","one","many","toLowerCase","tooMany","ready","Boolean","submit","answer","targets","changed","variant","persist","error","message","allowDuplicate","undefined","fullWidth","maxWidth","spacing","color","control","checked","onChange","event","target","map","disabled","current","name","value","size","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,QAAQ,eAAc;AAC9C,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,WAAW,EACXC,gBAAgB,EAChBC,SAAS,EACTC,cAAc,EACdC,SAAS,EACTC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SACEC,yBAAyB,QAIpB,0BAAsB;AAC7B,SAASC,cAAc,QAAQ,8BAA0B;AAiBzD;;;;;;;CAOC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;IAC/D,MAAM,EAAEC,IAAI,EA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dXlC,KAAKE,EAAE;gCAiBf,CAAClB,2BACA,KAAClB;8CAAgB;qCACf,CAACgC,QAAQO,MAAM,iBACjB,KAACvC;8CAAgB;qCACf;gCACH2C,wBACC,KAAC3C;oCAAeoD,KAAK;8CAClB,CAAC,OAAO,EAAEhE,gBAAgB,yCAAyC,CAAC;qCAErE;;;sCAEN,MAACS;;8CACC,KAACI;8CAAW;;8CACZ,MAACE;oCACCkE,OAAOzC;oCACPkC,UAAU,CAACC,QAAUlC,UAAUkC,MAAMC,MAAM,CAACK,KAAK,KAAK,SAAS,SAAS;;sDAExE,KAACvE;4CAAiBuE,OAAM;4CAAOT,uBAAS,KAAC1D;gDAAMoE,MAAK;;4CAAYjC,OAAM;;sDACtE,KAACvC;4CAAiBuE,OAAM;4CAAOT,uBAAS,KAAC1D;gDAAMoE,MAAK;;4CAAYjC,OAAM;;;;;;sCAG1E,KAAChC;4BAAW6C,SAAQ;4BAAUS,OAAM;sCACjC,kFACC;;;;;0BAIR,MAACjE;;kCACC,KAACH;wBAAOgF,SAAS1D;wBAASqD,UAAUpC;kCACjC;;kCAEH,KAACvC;wBAAO2D,SAAQ;wBAAYqB,SAAS,IAAM,KAAKzB;wBAAUoB,UAAU,CAACtB,SAASd;kCAC3E;;;;;;AAKX;AACApB,mBAAmB8D,WAAW,GAAG;AAEjC,eAAe9D,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/share-records-dialog.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 { sharingFromChoice } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n SiteSharingField,\n type SiteSharingValue,\n} from '@aglyn/shared-ui-jsx/components/site-sharing-field.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControl,\n FormControlLabel,\n FormHelperText,\n FormLabel,\n Radio,\n RadioGroup,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useEffect, useMemo, useState } from 'react'\nimport {\n CRM_SHARING_MAX_INCLUDED,\n CRM_SHARING_OBJECT_LABELS,\n type CrmShareAccess,\n type CrmSharingObject,\n type CrmSharingSite,\n} from '../model/crm-sharing'\nimport { callCrmSharing } from '../model/crm-sharing-api'\nimport type { CrmTaskRouteScope } from '../model/task-routes'\n\nexport interface ShareRecordsDialogProps {\n open: boolean\n onClose: () => void\n object: CrmSharingObject\n ids: readonly string[]\n /** The route scope the share is sent with. */\n scope: CrmTaskRouteScope | null\n sites: readonly CrmSharingSite[]\n sitesReady: boolean\n /**\n * Sites that already hold the record. They are listed like every site, so\n * what each choice reaches reads true, and the dialog says they keep it.\n */\n heldHostIds?: readonly string[]\n onShared?: (changed: number) => void\n}\n\n/**\n * What `crm/sharing` `share` reads as `targets` for a choice (AGL-4047):\n * `'all'`, the sites, or all sites except the ones left out.\n */\nexport function shareTargetsOfChoice(\n choice: SiteSharingValue,\n): 'all' | string[] | { mode: 'allExcept'; exceptHostIds: string[] } {\n if (choice.mode === 'all') return 'all'\n if (choice.mode === 'selected') return [...choice.hostIds]\n return { mode: 'allExcept', exceptHostIds: [...choice.exceptHostIds] }\n}\n\n/**\n * \"Share with sites…\" (AGL-3336): All sites — which covers a site created\n * later — the sites a manager picks, or all sites except the ones they leave\n * out (AGL-4047), which a site created later also joins; and whether they\n * may edit. Radios and a visible list, through the shared sharing field.\n *\n * Read-only is the default. The sentence under the choice is the guardrail\n * a manager has to read before sharing: the other site sees the person and\n * may work the record, and gains no permission to market to them.\n */\nexport function ShareRecordsDialog(props: ShareRecordsDialogProps) {\n const { open, onClose, object, ids, scope, sites, sitesReady, heldHostIds = [], onShared } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n // Nothing is chosen until the manager chooses.\n const [choice, setChoice] = useState<SiteSharingValue | null>(null)\n const [access, setAccess] = useState<CrmShareAccess>('read')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (!open) return\n setChoice(null)\n setAccess('read')\n }, [open])\n\n const holders = sites.filter((site) => heldHostIds.includes(site.id)).map((site) => site.name)\n const others = sites.length - holders.length\n const label = CRM_SHARING_OBJECT_LABELS[object]\n const what = ids.length === 1 ? `this ${label.one}` : `${ids.length} ${label.many.toLowerCase()}`\n // What the route will answer, from the same helper: the sites it reaches\n // are worked out against every site of the workspace, held ones included.\n const problem = useMemo(() => {\n if (!choice) return null\n if (choice.mode === 'selected' && !choice.hostIds.length) return 'Choose a site to share with.'\n if (choice.mode === 'allExcept' && !sitesReady) return null\n return sharingFromChoice(\n choice,\n sites.map((site) => site.id),\n { maxIncluded: CRM_SHARING_MAX_INCLUDED },\n ).problem\n }, [choice, sites, sitesReady])\n const ready = Boolean(scope) && ids.length > 0 && Boolean(choice) && !problem\n\n const submit = async () => {\n if (!scope || !ready || !choice) return\n setBusy(true)\n try {\n const answer = await callCrmSharing(user, scope, 'share', {\n object,\n ids,\n targets: shareTargetsOfChoice(choice),\n access,\n })\n enqueueSnackbar(\n answer.changed\n ? `Shared ${answer.changed === 1 ? `one ${label.one}` : `${answer.changed} ${label.many.toLowerCase()}`}`\n : `Already shared that way`,\n { variant: 'success', persist: false },\n )\n onShared?.(answer.changed ?? 0)\n onClose()\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle>{'Share with sites'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`The sites you pick see ${what} on their CRM lists and can log activity and tasks on it.`}\n </Typography>\n <SiteSharingField\n label=\"Share with\"\n value={choice}\n onChange={setChoice}\n sites={sites}\n sitesReady={sitesReady}\n maxIncluded={CRM_SHARING_MAX_INCLUDED}\n problem={problem}\n />\n {sitesReady && !others ? (\n <FormHelperText>{'No other site to share with. All sites still covers sites added later.'}</FormHelperText>\n ) : holders.length ? (\n <FormHelperText>\n {`${holders.join(', ')} already ${holders.length === 1 ? 'holds' : 'hold'} ${what}, and ${\n holders.length === 1 ? 'keeps' : 'keep'\n } it whatever you choose.`}\n </FormHelperText>\n ) : null}\n <FormControl>\n <FormLabel>{'Access'}</FormLabel>\n <RadioGroup\n value={access}\n onChange={(event) => setAccess(event.target.value === 'edit' ? 'edit' : 'read')}\n >\n <FormControlLabel value=\"read\" control={<Radio size=\"small\" />} label=\"Read-only\" />\n <FormControlLabel value=\"edit\" control={<Radio size=\"small\" />} label=\"Read and edit\" />\n </RadioGroup>\n </FormControl>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Sharing is not consent. A site this is shared with cannot include the person ' +\n 'in a campaign, a list or a sequence unless the person gave that site consent.'}\n </Typography>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" onClick={() => void submit()} disabled={!ready || busy}>\n {'Share'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nShareRecordsDialog.displayName = 'ShareRecordsDialog'\n\nexport default ShareRecordsDialog\n"],"names":["sharingFromChoice","SiteSharingField","useSnackbar","useUser","Button","Dialog","DialogActions","DialogContent","DialogTitle","FormControl","FormControlLabel","FormHelperText","FormLabel","Radio","RadioGroup","Stack","Typography","useEffect","useMemo","useState","CRM_SHARING_MAX_INCLUDED","CRM_SHARING_OBJECT_LABELS","callCrmSharing","shareTargetsOfChoice","choice","mode","hostIds","exceptHostIds","ShareRecordsDialog","props","open","onClose","object","ids","scope","sites","sitesReady","heldHostIds","onShared","data","user","enqueueSnackbar","setChoice","access","setAccess","busy","setBusy","holders","filter","site","includes","id","map","name","others","length","label","what","one","many","toLowerCase","problem","maxIncluded","ready","Boolean","submit","answer","targets","changed","variant","persist","error","message","allowDuplicate","undefined","fullWidth","maxWidth","spacing","color","value","onChange","join","event","target","control","size","onClick","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,gBAAgB,QAEX,+DAA8D;AACrE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SACEC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,EACdC,SAAS,EACTC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpD,SACEC,wBAAwB,EACxBC,yBAAyB,QAIpB,0BAAsB;AAC7B,SAASC,cAAc,QAAQ,8BAA0B;AAoBzD;;;CAGC,GACD,OAAO,SAASC,qBACdC,MAAwB;IAExB,IAAIA,OAAOC,IAAI,KAAK,OAAO,OAAO;IAClC,IAAID,OAAOC,IAAI,KAAK,YAAY,OAAO;WAAID,OAAOE,OAAO;KAAC;IAC1D,OAAO;QAAED,MAAM;QAAaE,eAAe;eAAIH,OAAOG,aAAa;SAAC;IAAC;AACvE;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;IAC/D,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,MAAM,EAAEC,GAAG,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAEC,cAAc,EAAE,EAAEC,QAAQ,EAAE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