@aglyn/plugins-crm 1.0.0-beta.246 → 1.0.0-beta.249
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/README.md +1 -1
- package/package.json +14 -14
- package/src/lib/components/contact-custom-columns.d.ts +15 -6
- package/src/lib/components/contact-custom-columns.js +27 -7
- package/src/lib/components/contact-custom-columns.js.map +1 -1
- package/src/lib/components/contact-field-drawer.d.ts +2 -0
- package/src/lib/components/contact-field-drawer.js +25 -1
- package/src/lib/components/contact-field-drawer.js.map +1 -1
- package/src/lib/components/contacts-section.js +9 -3
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-custom-field-control.d.ts +4 -2
- package/src/lib/components/crm-custom-field-control.js +53 -1
- package/src/lib/components/crm-custom-field-control.js.map +1 -1
- package/src/lib/components/fields-section.js +4 -2
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/form-contact-fields-card.js +2 -0
- package/src/lib/components/form-contact-fields-card.js.map +1 -1
- package/src/lib/constants/contact-filters.d.ts +7 -0
- package/src/lib/constants/contact-filters.js +8 -1
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/declarations.console-server.d.ts +2 -0
- package/src/lib/declarations.console-server.js +5 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/crm-picklist-setup-content.d.ts +121 -0
- package/src/lib/model/crm-picklist-setup-content.js +262 -0
- package/src/lib/model/crm-picklist-setup-content.js.map +1 -0
- package/src/lib/model/crm-record-routes.js +6 -0
- package/src/lib/model/crm-record-routes.js.map +1 -1
- package/src/lib/model/crm-setup-content.d.ts +4 -1
- package/src/lib/model/crm-setup-content.js +15 -4
- package/src/lib/model/crm-setup-content.js.map +1 -1
- package/src/lib/server/crm-setup-ai-capabilities.d.ts +13 -0
- package/src/lib/server/crm-setup-ai-capabilities.js +94 -2
- package/src/lib/server/crm-setup-ai-capabilities.js.map +1 -1
- package/src/lib/server/crm-setup-writers.server.d.ts +28 -0
- package/src/lib/server/crm-setup-writers.server.js +181 -4
- package/src/lib/server/crm-setup-writers.server.js.map +1 -1
- package/src/lib/server/picklist-regroup.d.ts +30 -0
- package/src/lib/server/picklist-regroup.js +61 -0
- package/src/lib/server/picklist-regroup.js.map +1 -0
- package/src/lib/server/picklist-values.d.ts +2 -14
- package/src/lib/server/picklist-values.js +3 -40
- package/src/lib/server/picklist-values.js.map +1 -1
- package/src/lib/transfer/common.d.ts +4 -2
- package/src/lib/transfer/common.js +14 -3
- package/src/lib/transfer/common.js.map +1 -1
- package/src/lib/transfer/fields.js +10 -1
- package/src/lib/transfer/fields.js.map +1 -1
- package/src/lib/transfer/pipelines.js +4 -2
- package/src/lib/transfer/pipelines.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/fields-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 { CrmExportButton } from './crm-transfer-buttons'\nimport { CRM_FIELDS_RESOURCE } from '../transfer/fields'\nimport {\n CONTACT_FIELD_TYPE_LABELS,\n CONTACT_FIELD_TYPES,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ConsolePluginPageProps,\n createResourceUid,\n CRM_COLLECTIONS,\n crmFieldListFields,\n type CrmFieldObject,\n CRM_PICKLIST_OBJECT_LABELS,\n CRM_PICKLIST_OBJECTS,\n type CrmPicklistId,\n type CrmPicklistObject,\n crmPicklistDefinitionsFor,\n isCrmPicklistObject,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport {\n mdiArchiveArrowUpOutline,\n mdiArchiveOutline,\n mdiArrowDown,\n mdiArrowUp,\n mdiDeleteOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n CardDisplay,\n MdiIcon,\n SrOnly,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport {\n type ListFilterOption,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { ceilingedWindow } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n IconButton,\n Stack,\n Tab,\n Tabs,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport type { GridColDef, GridSortModel } from '@mui/x-data-grid'\nimport {\n collection,\n deleteDoc,\n doc,\n limit,\n query,\n setDoc,\n updateDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n type ContactFieldDefinitionDoc,\n useContactFieldDefinitions,\n} from '../hooks/use-contact-field-definitions'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_FIELD_LIST_QUERY, crmFieldListBase } from '../constants/field-list-query'\nimport ContactFieldDrawer, { type ContactFieldDraft } from './contact-field-drawer'\nimport { PicklistValuesCard } from './picklist-values-card'\nimport { recomputeAllCrmNextActivity } from '../model/next-activity-api'\nimport { crmTaskCallScope } from '../model/task-routes'\n\nexport type ContactsFieldsSectionProps = Pick<ConsolePluginPageProps, 'hostId' | 'org'>\n\n/** What each tab says the fields are for, above its list. */\nconst OBJECT_INTRO: Record<CrmFieldObject, string> = {\n contact:\n 'The custom fields on a contact — text, number, date, choice, ' +\n 'checkbox or link. They show on every contact, as columns on the ' +\n 'list, and a form field can save into one.',\n company:\n 'The custom fields on a company. They show on every company’s page ' +\n 'and its edit form, as columns on the companies list, and a CSV ' +\n 'import can fill them.',\n deal:\n 'The custom fields on a deal. They show on every deal’s page and ' +\n 'its edit form, and as columns on the deals table.',\n lead:\n 'The custom fields on a lead. They show on every lead’s page and the ' +\n 'New lead drawer, and as columns on the leads list. They stay on the ' +\n 'lead when it converts — a contact’s fields are its own.',\n}\n\n/**\n * The Tasks tab's intro (AGL-3517): a task has standard picklists and no\n * custom fields, so the tab is its picklist cards alone.\n */\nconst TASKS_INTRO =\n 'A task’s standard picklists — its Status, Priority and Type, and the ' +\n 'subjects its title suggests. Status, Priority and Type each mean one of ' +\n 'the CRM’s own values, which reminders, due dates and automations read; ' +\n 'the labels are your organization’s. Tasks have no custom fields.'\n\n/** The noun each tab's empty state and captions use. */\nconst OBJECT_NOUN: Record<CrmFieldObject, string> = {\n contact: 'contact',\n company: 'company',\n deal: 'deal',\n lead: 'lead',\n}\n\n/** One definition as the list table draws it. */\ninterface FieldRow {\n $id: string\n label: string\n key: string\n type: string\n /** `true` or `false`, the value the Required filter picks. */\n required: 'true' | 'false'\n /** Where the stored order puts it, from zero. */\n position: number\n definition: ContactFieldDefinitionDoc\n}\n\n/** What the grid's Filters panel offers: the type and whether it is required, on the query. */\nconst FIELD_FILTER_FIELDS = CRM_FIELD_LIST_QUERY.fields\nconst FIELD_FILTER_HEADERS: Readonly<Record<string, string>> = {\n type: 'Type',\n required: 'Required',\n}\nconst FIELD_FILTER_OPTIONS: Readonly<Record<string, readonly ListFilterOption[]>> = {\n type: CONTACT_FIELD_TYPES.map((type) => ({\n value: type,\n label: CONTACT_FIELD_TYPE_LABELS[type],\n })),\n required: [\n { value: 'true', label: 'Required' },\n { value: 'false', label: 'Optional' },\n ],\n}\n\n/** Why the arrows are off while the list is not in its stored order. */\nexport const FIELD_REORDER_LOCKED_REASON = 'Clear sorting and filters to reorder'\n\nconst typeLabel = (type: unknown) =>\n CONTACT_FIELD_TYPE_LABELS[type as keyof typeof CONTACT_FIELD_TYPE_LABELS] ?? String(type ?? '')\n\ninterface FieldsTableProps {\n /** The organization whose definitions these are; `null` reads nothing. */\n orgId: string | null\n /** The tab: which record the definitions describe. */\n object: CrmFieldObject\n /** One tab's definitions, in the stored order. */\n definitions: readonly ContactFieldDefinitionDoc[]\n /** A field being written; every arrow waits for it. */\n busyId: string\n onMove: (definition: ContactFieldDefinitionDoc, direction: -1 | 1) => void\n rowActions: (definition: ContactFieldDefinitionDoc) => RowActionsMenuItem[]\n}\n\n/**\n * One tab's field definitions in the console's list table (AGL-3335): the\n * toolbar's columns, filters, export and search, sorting by Field, Key and\n * Type, and the shared footer.\n *\n * ## Order is data, not a sort\n *\n * The stored `order` is where each field appears on every record and form,\n * so the arrows that move it are kept, and are live only while the table\n * shows that order: no sort, no filter and no search. Under any of them the\n * row above a field on screen is not the field above it in the stored\n * order, and a move would land somewhere the reader cannot see; the arrows\n * say so rather than disappear.\n *\n * The panel and the search are asked of Firestore (AGL-3321): a clause or\n * a search word reads the tab's definitions that match it\n * (`CRM_FIELD_LIST_QUERY`), and never narrows the rows already on screen.\n * That answer is every match, at most `CONTACT_FIELDS_MAX_PER_ORG`, so the\n * grid sorts and pages it whole; a read that reaches the ceiling says so.\n */\nfunction FieldsTable(props: FieldsTableProps) {\n const { orgId, object, definitions, busyId, onMove, rowActions } = props\n const firestore = useFirestore()\n const gridFilter = useListGridFilter({ selectFields: ['type', 'required'] })\n const [sortModel, setSortModel] = useState<GridSortModel>([])\n const searching = gridFilter.searchWords.some((word) => word.trim() !== '')\n const reorderLocked =\n sortModel.length > 0 || gridFilter.clauses.length > 0 || searching\n\n const narrowed = gridFilter.clauses.length > 0 || searching\n const plan = useMemo(\n () =>\n planListQuery(\n CRM_FIELD_LIST_QUERY,\n {\n clauses: gridFilter.clauses,\n search: gridFilter.searchWords,\n base: crmFieldListBase(object),\n },\n nameSearchNormalizers,\n ),\n // The words are a new array each render; their text is their identity.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [object, gridFilter.clauses, gridFilter.searchWords.join(' ')],\n )\n const planKey = JSON.stringify({ filters: plan.filters, orderBy: plan.orderBy })\n /*\n * Read only while something narrows the tab. Unnarrowed, the table is the\n * shared definitions read every CRM surface already holds, in its stored\n * order — the same fields, with no second read.\n */\n const matched = useFirestoreCollection<ContactFieldDefinitionDoc>(\n () =>\n narrowed && orgId\n ? query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.contactFields),\n ...listQueryConstraints(plan),\n limit(CONTACT_FIELDS_MAX_PER_ORG + 1),\n )\n : null,\n [firestore, orgId, narrowed, planKey],\n { idField: '$id' },\n )\n const answer = useMemo(\n () => ceilingedWindow(matched.data, CONTACT_FIELDS_MAX_PER_ORG),\n [matched.data],\n )\n const positions = useMemo(\n () => new Map(definitions.map((definition, position) => [definition.$id, position])),\n [definitions],\n )\n const rows = useMemo<FieldRow[]>(() => {\n const shown = narrowed\n ? [...answer.rows].sort(\n (a, b) =>\n (positions.get(a.$id) ?? Number.MAX_SAFE_INTEGER) -\n (positions.get(b.$id) ?? Number.MAX_SAFE_INTEGER),\n )\n : definitions\n return shown.map((definition) => ({\n $id: definition.$id,\n label: definition.label,\n key: definition.key,\n type: definition.type,\n required: definition.required ? 'true' : 'false',\n position: positions.get(definition.$id) ?? 0,\n definition,\n }))\n }, [narrowed, answer.rows, definitions, positions])\n const refused = useMemo(\n () =>\n listQueryRefusals(plan.refused, {\n fields: FIELD_FILTER_FIELDS,\n headers: FIELD_FILTER_HEADERS,\n options: FIELD_FILTER_OPTIONS,\n }),\n [plan.refused],\n )\n\n const columns = useMemo<GridColDef[]>(\n () =>\n listFilterGridColumns(\n [\n {\n field: 'position',\n headerName: 'Order',\n width: 132,\n sortable: false,\n filterable: false,\n hideable: false,\n disableColumnMenu: true,\n renderCell: ({ row }: { row: FieldRow }) => {\n const arrows = (\n <Stack direction=\"row\" spacing={0} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ minWidth: 24, textAlign: 'right', mr: 0.5 }}\n >\n {row.position + 1}\n </Typography>\n <IconButton\n size=\"small\"\n disabled={reorderLocked || row.position === 0 || Boolean(busyId)}\n onClick={() => onMove(row.definition, -1)}\n >\n <MdiIcon path={mdiArrowUp.path} size={0.7} />\n <SrOnly>{`Move ${row.label} up`}</SrOnly>\n </IconButton>\n <IconButton\n size=\"small\"\n disabled={\n reorderLocked || row.position === definitions.length - 1 || Boolean(busyId)\n }\n onClick={() => onMove(row.definition, 1)}\n >\n <MdiIcon path={mdiArrowDown.path} size={0.7} />\n <SrOnly>{`Move ${row.label} down`}</SrOnly>\n </IconButton>\n </Stack>\n )\n return reorderLocked ? (\n <Tooltip title={FIELD_REORDER_LOCKED_REASON}>\n {/* A disabled button emits no events; the span carries the tooltip. */}\n <span>{arrows}</span>\n </Tooltip>\n ) : (\n arrows\n )\n },\n },\n {\n field: 'label',\n headerName: 'Field',\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Stack\n useFlexGap\n direction=\"row\"\n spacing={1}\n sx={{ flexWrap: 'wrap', alignItems: 'center' }}\n >\n <Typography variant=\"body2\">{row.label}</Typography>\n {row.definition.retiredAt ? (\n <Chip size=\"small\" variant=\"outlined\" color=\"warning\" label=\"Retired\" />\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'key',\n headerName: 'Key',\n flex: 1,\n minWidth: 160,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ fontFamily: 'monospace' }}\n >\n {row.key}\n </Typography>\n ),\n },\n {\n field: 'type',\n headerName: 'Type',\n width: 170,\n // By what the type reads as, not by its stored key.\n sortComparator: (a: unknown, b: unknown) =>\n typeLabel(a).localeCompare(typeLabel(b)),\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography variant=\"body2\">\n {typeLabel(row.type)}\n {row.definition.type === 'select' && row.definition.options?.length\n ? ` · ${row.definition.options.length} choices`\n : ''}\n </Typography>\n ),\n },\n {\n field: 'required',\n headerName: 'Required',\n width: 120,\n sortable: false,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {row.required === 'true' ? 'Yes' : '—'}\n </Typography>\n ),\n },\n listActionsColumn(\n (row: FieldRow) => (\n <ListRowActions label={row.label} items={rowActions(row.definition)} />\n ),\n { width: 72 },\n ),\n ],\n FIELD_FILTER_FIELDS,\n FIELD_FILTER_OPTIONS,\n FIELD_FILTER_HEADERS,\n ),\n [reorderLocked, busyId, onMove, rowActions, definitions.length],\n )\n\n return (\n <Stack spacing={1}>\n <ListFilterChips\n fields={FIELD_FILTER_FIELDS}\n headers={FIELD_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={FIELD_FILTER_OPTIONS}\n marksServed={false}\n />\n <ListQueryNotices refused={refused} notices={plan.notices} />\n {narrowed && answer.truncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Showing the first ${CONTACT_FIELDS_MAX_PER_ORG} matching fields.`}\n </Typography>\n ) : null}\n <ListTable\n aria-label=\"Fields\"\n rows={rows}\n loading={narrowed && matched.status === 'loading'}\n columns={columns}\n sortModel={sortModel}\n onSortModelChange={setSortModel}\n // Firestore narrowed the rows above; the grid only draws them.\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n noRowsLabel=\"No fields match these filters\"\n getRowClassName={({ row }: { row: FieldRow }) =>\n row.definition.retiredAt ? 'field-retired' : ''\n }\n sx={{ '& .field-retired': { opacity: 0.6 } }}\n />\n </Stack>\n )\n}\nFieldsTable.displayName = 'FieldsTable'\n\n/**\n * `/crm/fields` — the custom fields a holder keeps on a person (AGL-2601),\n * since AGL-2661 on a company and a deal too, and since AGL-3272 on a lead:\n * one tab each, and every CRM record describable in the org's own words.\n *\n * Definitions live in `orgs/{orgId}/contactFields`, one document per field,\n * and the VALUES live under each contact facet's `custom` keyed by the\n * definition's `key`. That split decides everything this section does:\n *\n * - A field is RETIRED, not deleted, while values may exist under it. A\n * retired field leaves every form and every column, but an export can\n * still read what was written, and a restore brings it back intact.\n * Delete is offered only on a retired field, because retiring is the step\n * where the author had to look at what they were losing.\n * - The KEY never changes. It is the map key every value sits under; a\n * rename is a new field and a retire.\n * - Order is a stored `order` on each document, moved with the arrows here,\n * and every reader sorts by it — the profile card, the columns, an export.\n * The list table sorts, filters and searches a tab too (AGL-3335), and\n * the arrows wait while it does — see `FieldsTable`.\n *\n * ## What is NOT on this page\n *\n * How many contacts carry a value under each field. That count is a read of\n * every contact document in the org — the expensive-read shape this codebase\n * has a standing rule against — and it would be paid on every visit to a\n * settings page. The list says so rather than showing a number it cannot\n * afford to keep true.\n *\n * Definitions are ORG-WIDE (`visibleTo: ['org']`): a field is a fact about\n * how this business describes people, and every site in the org files\n * people into the same address book. `hostId` records which site defined it.\n */\nexport function ContactsFieldsSection(props: ContactsFieldsSectionProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root from the one scope hook (AGL-2614), which also answers at\n // the organization level (AGL-2630). A definition is org-wide either way;\n // the defining site it records is the mounted one, or the picked one, or\n // none for a field defined over the whole org before any pick.\n const { scope, ready: scopeReady, createHostId } = useCrmScope({ hostId, org })\n const orgId = scope?.[1] ?? null\n /*\n * ONE TAB PER OBJECT (AGL-2661). The list, the drawer and every write\n * below are about the tab's object: the hook narrows the org's one\n * definition list to it, a new field is stamped with it, and the drawer\n * refuses a key only against the keys THIS object already uses — a\n * company and a contact may both define `region`.\n */\n const [tab, setTab] = useState<CrmPicklistObject>('contact')\n // The Tasks tab has no custom fields (AGL-3517): no read, no New field.\n const tasksTab = tab === 'task'\n const object: CrmFieldObject = tab === 'task' ? 'contact' : tab\n const { definitions, ready, fromCache } = useContactFieldDefinitions(\n tasksTab ? null : orgId,\n object,\n )\n const noun = OBJECT_NOUN[object]\n\n /*\n * MAINTENANCE: recompute every record's next activity (AGL-2661). The\n * figure is kept by every task write, so this is for the records written\n * before it existed and for whatever a write that could not reach the\n * route left behind. A console action rather than a script, because the\n * person who notices a stale column is the person who should be able to\n * fix it.\n */\n const { data: user } = useUser()\n const [recomputing, setRecomputing] = useState(false)\n const recomputeNextActivity = useCallback(async () => {\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope || recomputing) return\n const confirmed = await confirm({\n title: 'Recompute next activity?',\n description:\n 'Every contact, company and deal in this organization gets its ' +\n '\"Next activity\" recomputed from its open tasks. Safe to run any time; ' +\n 'it only rewrites a figure the task list already implies.',\n confirmationText: 'Recompute',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setRecomputing(true)\n try {\n const result = await recomputeAllCrmNextActivity(user, callScope)\n enqueueSnackbar(\n `Next activity recomputed: ${result.records.toLocaleString()} record${result.records === 1 ? '' : 's'} ` +\n `from ${(result.tasks ?? 0).toLocaleString()} open task${result.tasks === 1 ? '' : 's'}` +\n (result.truncated\n ? ' — the first batch of open tasks only; nothing stale was cleared'\n : ''),\n { variant: 'success' },\n )\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The next activity could not be recomputed.',\n { variant: 'warning' },\n )\n } finally {\n setRecomputing(false)\n }\n }, [hostId, orgId, recomputing, confirm, user, enqueueSnackbar])\n\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [editing, setEditing] = useState<ContactFieldDefinitionDoc | null>(null)\n const [busyId, setBusyId] = useState('')\n\n const fieldRef = useCallback(\n (id: string) => {\n if (!scope) throw new Error('a contact field needs an organization')\n return doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.contactFields, id)\n },\n [firestore, scope],\n )\n\n const openCreate = useCallback(() => {\n setEditing(null)\n setDrawerOpen(true)\n }, [])\n const openEdit = useCallback((definition: ContactFieldDefinitionDoc) => {\n setEditing(definition)\n setDrawerOpen(true)\n }, [])\n\n /**\n * Create, or save the editable half of an existing field.\n *\n * On create the document carries everything a reader expects: the key,\n * an `order` past every existing one so it lands last, an explicit\n * `retiredAt: null` so a `where('retiredAt', '==', null)` can find it, the\n * defining site, and the org-wide scope stamp the rules require. On edit\n * only the label, the choices and the required flag move — the key and\n * the type are the drawer's disabled inputs, and this writer does not\n * take them either.\n */\n const handleSubmit = useCallback(\n async (draft: ContactFieldDraft) => {\n if (!scope) return\n const now = new Date()\n if (editing) {\n const verdict = await writeGuardedBySeed(\n { subject: 'field', fromCache },\n async () => {\n await updateDoc(fieldRef(editing.$id), {\n label: draft.label,\n ...(editing.type === 'select' ? { options: draft.options } : {}),\n // The Fields table's query fields (AGL-3335), from the new name —\n // and a definition written before them gains them here.\n ...crmFieldListFields({ ...editing, label: draft.label, required: draft.required }),\n updatedAt: now,\n })\n },\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n enqueueSnackbar('Field saved', { variant: 'success', persist: false })\n } else {\n const order =\n definitions.reduce(\n (highest, definition) => Math.max(highest, Number(definition.order) || 0),\n -1,\n ) + 1\n await setDoc(\n doc(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.contactFields),\n createResourceUid(),\n ),\n {\n key: draft.key,\n label: draft.label,\n type: draft.type,\n ...(draft.type === 'select' ? { options: draft.options } : {}),\n required: draft.required,\n order,\n retiredAt: null,\n // Which record the field describes — the tab it was made on —\n // with the Fields table's query fields (AGL-3335).\n ...crmFieldListFields({ key: draft.key, label: draft.label, required: draft.required, object }),\n hostId: createHostId,\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n createdAt: now,\n updatedAt: now,\n },\n )\n enqueueSnackbar(`Field \"${draft.label}\" added`, {\n variant: 'success',\n persist: false,\n })\n }\n setDrawerOpen(false)\n setEditing(null)\n },\n [scope, editing, fromCache, fieldRef, enqueueSnackbar, definitions, firestore, createHostId, object],\n )\n\n /**\n * Move a field one place up or down.\n *\n * Writes `order` as the POSITION for every row whose stored order is not\n * already its position, in one batch. Swapping two numbers would be enough\n * on a list whose orders are already distinct, and wrong on one where they\n * are not — every field created before this section existed carries the\n * same `order`, and a swap of two equal numbers moves nothing. Renumbering\n * what is out of place makes the first move on such a list also the one\n * that normalizes it, at the cost of a batch that is at most the list.\n */\n const move = useCallback(\n async (definition: ContactFieldDefinitionDoc, direction: -1 | 1) => {\n if (!scope || busyId) return\n const index = definitions.findIndex((entry) => entry.$id === definition.$id)\n const target = index + direction\n if (index < 0 || target < 0 || target >= definitions.length) return\n const next = [...definitions]\n next[index] = definitions[target]\n next[target] = definitions[index]\n setBusyId(definition.$id)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'field order', fromCache },\n async () => {\n const batch = writeBatch(firestore)\n const now = new Date()\n next.forEach((entry, position) => {\n if (entry.order === position) return\n batch.update(fieldRef(entry.$id), { order: position, updatedAt: now })\n })\n await batch.commit()\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, definitions, fromCache, firestore, fieldRef, enqueueSnackbar],\n )\n\n /**\n * Retire a field, or bring one back.\n *\n * Retiring is asked about because it takes a control off every contact\n * form and a column off the list; restoring is not, because it puts a\n * choice back and is undone by retiring again. Neither touches a value.\n */\n const toggleRetired = useCallback(\n async (definition: ContactFieldDefinitionDoc) => {\n if (!scope || busyId) return\n if (!definition.retiredAt) {\n const accepted = await confirm({\n title: `Retire “${definition.label}”?`,\n description:\n `It leaves every ${noun} form, column and form-field mapping. ` +\n 'Values already saved under it are kept and still export, and ' +\n 'you can restore the field at any time.',\n confirmationText: 'Retire',\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating\n // on the resolved value alone would always fall through.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setBusyId(definition.$id)\n try {\n await updateDoc(fieldRef(definition.$id), {\n retiredAt: definition.retiredAt ? null : Date.now(),\n updatedAt: new Date(),\n })\n enqueueSnackbar(definition.retiredAt ? 'Field restored' : 'Field retired', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, confirm, fieldRef, enqueueSnackbar, noun],\n )\n\n /**\n * Delete a RETIRED field's definition.\n *\n * The values under its key are not touched — they sit on contact documents\n * this page does not read — so what is destroyed is the ability to show\n * them anywhere. The dialog says exactly that, and the key stays taken for\n * as long as the list can see it, which after this write it cannot; a new\n * field with the same key would read the orphaned values back as its own.\n */\n const handleDelete = useCallback(\n async (definition: ContactFieldDefinitionDoc) => {\n if (!scope || busyId || !definition.retiredAt) return\n const accepted = await confirm({\n title: `Delete “${definition.label}”?`,\n description:\n 'The definition is removed for good. Values saved under its key ' +\n `(${definition.key}) stay on the ${noun}s that carry them but ` +\n 'nothing will show them again — and a new field created with the ' +\n 'same key would read them as its own.',\n confirmationText: 'Delete field',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setBusyId(definition.$id)\n try {\n await deleteDoc(fieldRef(definition.$id))\n enqueueSnackbar('Field deleted', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, confirm, fieldRef, enqueueSnackbar, noun],\n )\n\n /*\n * Stable across renders, as the table's columns are built from them: a\n * fresh function each render would rebuild every column on every render.\n */\n const rowActions = useCallback(\n (definition: ContactFieldDefinitionDoc): RowActionsMenuItem[] => [\n {\n key: 'edit',\n label: 'Edit field',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n onClick: () => openEdit(definition),\n },\n {\n key: 'retire',\n label: definition.retiredAt ? 'Restore' : 'Retire',\n icon: (\n <MdiIcon\n path={definition.retiredAt ? mdiArchiveArrowUpOutline.path : mdiArchiveOutline.path}\n size={0.8}\n />\n ),\n destructive: !definition.retiredAt,\n disabled: Boolean(busyId),\n disabledReason: busyId ? 'Another field is being saved' : undefined,\n onClick: () => void toggleRetired(definition),\n },\n ...(definition.retiredAt\n ? [\n {\n key: 'delete',\n label: 'Delete',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: Boolean(busyId),\n disabledReason: busyId ? 'Another field is being saved' : undefined,\n onClick: () => void handleDelete(definition),\n } satisfies RowActionsMenuItem,\n ]\n : []),\n ],\n [openEdit, toggleRetired, handleDelete, busyId],\n )\n const onMove = useCallback(\n (definition: ContactFieldDefinitionDoc, direction: -1 | 1) =>\n void move(definition, direction),\n [move],\n )\n\n return (\n <CardDisplay\n header={'Fields'}\n help={pluginDocsHelp('contactFields', { anchor: '#define-a-field' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: scope ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n {/* Every custom field, as a file (AGL-3528). */}\n <CrmExportButton resource={CRM_FIELDS_RESOURCE} hostId={hostId ?? null} />\n <Button size=\"small\" onClick={() => void recomputeNextActivity()} disabled={recomputing}>\n {recomputing ? 'Recomputing…' : 'Recompute next activity'}\n </Button>\n {tasksTab ? null : (\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n )}\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n <Tabs\n value={tab}\n onChange={(_event, next) => {\n if (isCrmPicklistObject(next)) setTab(next)\n }}\n aria-label=\"Fields by record\"\n variant=\"scrollable\"\n scrollButtons=\"auto\"\n allowScrollButtonsMobile\n >\n {CRM_PICKLIST_OBJECTS.map((entry) => (\n <Tab key={entry} value={entry} label={CRM_PICKLIST_OBJECT_LABELS[entry]} />\n ))}\n </Tabs>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${tasksTab ? TASKS_INTRO : OBJECT_INTRO[object]} Fields are shared across every site in this ` +\n 'organization, like the records themselves.'}\n </Typography>\n {tasksTab ? null : scopeReady && !scope ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`This site has no organization, so it has no ${noun} fields.`}\n </Typography>\n ) : !ready ? null : definitions.length === 0 ? (\n <EmptyStateComponent\n label={`No custom ${noun} fields yet`}\n description={`A field you define here is kept on every ${noun} and shows on its page.`}\n action={\n scope ? (\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n ) : undefined\n }\n />\n ) : (\n /*\n Keyed by the tab, so a sort, a filter or a search made on one\n record's fields does not follow the reader onto another's.\n */\n <FieldsTable\n key={object}\n orgId={orgId}\n object={object}\n definitions={definitions}\n busyId={busyId}\n onMove={onMove}\n rowActions={rowActions}\n />\n )}\n {definitions.length && !tasksTab ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`How many ${noun}s carry a value under each field is not ` +\n `counted — that would read every ${noun} in the organization ` +\n 'each time this page opened.'}\n </Typography>\n ) : null}\n {/*\n The tab's standard picklists (AGL-3298, AGL-3510) — standard fields\n whose CHOICES are the org's, Salesforce's picklist value sets — one\n card each, beside the custom fields of the same record.\n */}\n {scope\n ? crmPicklistDefinitionsFor(tab).map((definition) => (\n <PicklistValuesCard\n key={definition.id}\n picklistId={definition.id as CrmPicklistId}\n hostId={hostId}\n orgId={orgId}\n createHostId={createHostId}\n />\n ))\n : null}\n </Stack>\n <ContactFieldDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n definition={editing}\n object={object}\n takenKeys={definitions.map((definition) => definition.key)}\n onSubmit={handleSubmit}\n />\n </CardDisplay>\n )\n}\nContactsFieldsSection.displayName = 'ContactsFieldsSection'\n\nexport default ContactsFieldsSection\n"],"names":["CrmExportButton","CRM_FIELDS_RESOURCE","CONTACT_FIELD_TYPE_LABELS","CONTACT_FIELD_TYPES","CONTACT_FIELDS_MAX_PER_ORG","createResourceUid","CRM_COLLECTIONS","crmFieldListFields","CRM_PICKLIST_OBJECT_LABELS","CRM_PICKLIST_OBJECTS","crmPicklistDefinitionsFor","isCrmPicklistObject","newResourceScopeFields","ORG_SCOPE_TOKEN","pluginDocsHelp","EmptyStateComponent","ListFilterChips","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","mdiArchiveArrowUpOutline","mdiArchiveOutline","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","mdiPencilOutline","CardDisplay","MdiIcon","SrOnly","useConfirmationContext","listFilterGridColumns","planListQuery","useListGridFilter","nameSearchNormalizers","useSnackbar","ceilingedWindow","listQueryConstraints","useFirestore","useFirestoreCollection","useUser","writeGuardedBySeed","Button","Chip","IconButton","Stack","Tab","Tabs","Tooltip","Typography","collection","deleteDoc","doc","limit","query","setDoc","updateDoc","writeBatch","useCallback","useMemo","useState","useContactFieldDefinitions","useCrmScope","CRM_FIELD_LIST_QUERY","crmFieldListBase","ContactFieldDrawer","PicklistValuesCard","recomputeAllCrmNextActivity","crmTaskCallScope","OBJECT_INTRO","contact","company","deal","lead","TASKS_INTRO","OBJECT_NOUN","FIELD_FILTER_FIELDS","fields","FIELD_FILTER_HEADERS","type","required","FIELD_FILTER_OPTIONS","map","value","label","FIELD_REORDER_LOCKED_REASON","typeLabel","String","FieldsTable","props","orgId","object","definitions","busyId","onMove","rowActions","firestore","gridFilter","selectFields","sortModel","setSortModel","searching","searchWords","some","word","trim","reorderLocked","length","clauses","narrowed","plan","search","base","join","planKey","JSON","stringify","filters","orderBy","matched","contactFields","idField","answer","data","positions","Map","definition","position","$id","rows","shown","sort","a","b","get","Number","MAX_SAFE_INTEGER","key","refused","headers","options","columns","field","headerName","width","sortable","filterable","hideable","disableColumnMenu","renderCell","row","arrows","direction","spacing","sx","alignItems","variant","color","minWidth","textAlign","mr","size","disabled","Boolean","onClick","path","title","span","flex","useFlexGap","flexWrap","retiredAt","fontFamily","sortComparator","localeCompare","items","onChange","setClauses","marksServed","notices","truncated","aria-label","loading","status","onSortModelChange","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","getRowClassName","opacity","displayName","ContactsFieldsSection","hostId","org","enqueueSnackbar","confirm","scope","ready","scopeReady","createHostId","tab","setTab","tasksTab","fromCache","noun","user","recomputing","setRecomputing","recomputeNextActivity","callScope","confirmed","description","confirmationText","then","catch","result","records","toLocaleString","tasks","cause","Error","message","drawerOpen","setDrawerOpen","editing","setEditing","setBusyId","fieldRef","id","openCreate","openEdit","handleSubmit","draft","now","Date","verdict","subject","updatedAt","ok","persist","order","reduce","highest","Math","max","createdAt","move","index","findIndex","entry","target","next","batch","forEach","update","commit","error","console","allowDuplicate","toggleRetired","accepted","handleDelete","confirmationButtonProps","icon","destructive","disabledReason","undefined","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","resource","_event","scrollButtons","allowScrollButtonsMobile","picklistId","open","onClose","takenKeys","onSubmit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,eAAe,QAAQ,4BAAwB;AACxD,SAASC,mBAAmB,QAAQ,wBAAoB;AACxD,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,0BAA0B,EAE1BC,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wBAAUC,OAAM;kCACjC,CAAC,SAAS,EAAEiD,KAAK,wCAAwC,CAAC,GACzD,CAAC,gCAAgC,EAAEA,KAAK,qBAAqB,CAAC,GAC9D;yBAEF;oBAMHR,QACG7L,0BAA0BiM,KAAKxH,GAAG,CAAC,CAAC4C,2BAClC,KAAC5D;4BAECuN,YAAY3J,WAAWwG,EAAE;4BACzBpC,QAAQA;4BACRxG,OAAOA;4BACP+G,cAAcA;2BAJT3E,WAAWwG,EAAE,KAOtB;;;0BAEN,KAACrK;gBACCyN,MAAM1D;gBACN2D,SAAS,IAAM1D,cAAc;gBAC7BnG,YAAYoG;gBACZvI,QAAQA;gBACRiM,WAAWhM,YAAYV,GAAG,CAAC,CAAC4C,aAAeA,WAAWW,GAAG;gBACzDoJ,UAAUpD;;;;AAIlB;AACAxC,sBAAsBD,WAAW,GAAG;AAEpC,eAAeC,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/fields-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 { CrmExportButton } from './crm-transfer-buttons'\nimport { CRM_FIELDS_RESOURCE } from '../transfer/fields'\nimport {\n CONTACT_FIELD_TYPE_LABELS,\n CONTACT_FIELD_TYPES,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ConsolePluginPageProps,\n createResourceUid,\n CRM_COLLECTIONS,\n crmFieldListFields,\n type CrmFieldObject,\n CRM_PICKLIST_OBJECT_LABELS,\n CRM_PICKLIST_OBJECTS,\n type CrmPicklistId,\n type CrmPicklistObject,\n crmPicklistDefinitionsFor,\n isCrmPicklistObject,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport {\n mdiArchiveArrowUpOutline,\n mdiArchiveOutline,\n mdiArrowDown,\n mdiArrowUp,\n mdiDeleteOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n CardDisplay,\n MdiIcon,\n SrOnly,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport {\n type ListFilterOption,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { ceilingedWindow } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n IconButton,\n Stack,\n Tab,\n Tabs,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport type { GridColDef, GridSortModel } from '@mui/x-data-grid'\nimport {\n collection,\n deleteDoc,\n doc,\n limit,\n query,\n setDoc,\n updateDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n type ContactFieldDefinitionDoc,\n useContactFieldDefinitions,\n} from '../hooks/use-contact-field-definitions'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_FIELD_LIST_QUERY, crmFieldListBase } from '../constants/field-list-query'\nimport ContactFieldDrawer, { type ContactFieldDraft } from './contact-field-drawer'\nimport { PicklistValuesCard } from './picklist-values-card'\nimport { recomputeAllCrmNextActivity } from '../model/next-activity-api'\nimport { crmTaskCallScope } from '../model/task-routes'\n\nexport type ContactsFieldsSectionProps = Pick<ConsolePluginPageProps, 'hostId' | 'org'>\n\n/** What each tab says the fields are for, above its list. */\nconst OBJECT_INTRO: Record<CrmFieldObject, string> = {\n contact:\n 'The custom fields on a contact — text, number, date, choice, ' +\n 'checkbox, link or currency. They show on every contact, as columns on the ' +\n 'list, and a form field can save into one.',\n company:\n 'The custom fields on a company. They show on every company’s page ' +\n 'and its edit form, as columns on the companies list, and a CSV ' +\n 'import can fill them.',\n deal:\n 'The custom fields on a deal. They show on every deal’s page and ' +\n 'its edit form, and as columns on the deals table.',\n lead:\n 'The custom fields on a lead. They show on every lead’s page and the ' +\n 'New lead drawer, and as columns on the leads list. They stay on the ' +\n 'lead when it converts — a contact’s fields are its own.',\n}\n\n/**\n * The Tasks tab's intro (AGL-3517): a task has standard picklists and no\n * custom fields, so the tab is its picklist cards alone.\n */\nconst TASKS_INTRO =\n 'A task’s standard picklists — its Status, Priority and Type, and the ' +\n 'subjects its title suggests. Status, Priority and Type each mean one of ' +\n 'the CRM’s own values, which reminders, due dates and automations read; ' +\n 'the labels are your organization’s. Tasks have no custom fields.'\n\n/** The noun each tab's empty state and captions use. */\nconst OBJECT_NOUN: Record<CrmFieldObject, string> = {\n contact: 'contact',\n company: 'company',\n deal: 'deal',\n lead: 'lead',\n}\n\n/** One definition as the list table draws it. */\ninterface FieldRow {\n $id: string\n label: string\n key: string\n type: string\n /** `true` or `false`, the value the Required filter picks. */\n required: 'true' | 'false'\n /** Where the stored order puts it, from zero. */\n position: number\n definition: ContactFieldDefinitionDoc\n}\n\n/** What the grid's Filters panel offers: the type and whether it is required, on the query. */\nconst FIELD_FILTER_FIELDS = CRM_FIELD_LIST_QUERY.fields\nconst FIELD_FILTER_HEADERS: Readonly<Record<string, string>> = {\n type: 'Type',\n required: 'Required',\n}\nconst FIELD_FILTER_OPTIONS: Readonly<Record<string, readonly ListFilterOption[]>> = {\n type: CONTACT_FIELD_TYPES.map((type) => ({\n value: type,\n label: CONTACT_FIELD_TYPE_LABELS[type],\n })),\n required: [\n { value: 'true', label: 'Required' },\n { value: 'false', label: 'Optional' },\n ],\n}\n\n/** Why the arrows are off while the list is not in its stored order. */\nexport const FIELD_REORDER_LOCKED_REASON = 'Clear sorting and filters to reorder'\n\nconst typeLabel = (type: unknown) =>\n CONTACT_FIELD_TYPE_LABELS[type as keyof typeof CONTACT_FIELD_TYPE_LABELS] ?? String(type ?? '')\n\ninterface FieldsTableProps {\n /** The organization whose definitions these are; `null` reads nothing. */\n orgId: string | null\n /** The tab: which record the definitions describe. */\n object: CrmFieldObject\n /** One tab's definitions, in the stored order. */\n definitions: readonly ContactFieldDefinitionDoc[]\n /** A field being written; every arrow waits for it. */\n busyId: string\n onMove: (definition: ContactFieldDefinitionDoc, direction: -1 | 1) => void\n rowActions: (definition: ContactFieldDefinitionDoc) => RowActionsMenuItem[]\n}\n\n/**\n * One tab's field definitions in the console's list table (AGL-3335): the\n * toolbar's columns, filters, export and search, sorting by Field, Key and\n * Type, and the shared footer.\n *\n * ## Order is data, not a sort\n *\n * The stored `order` is where each field appears on every record and form,\n * so the arrows that move it are kept, and are live only while the table\n * shows that order: no sort, no filter and no search. Under any of them the\n * row above a field on screen is not the field above it in the stored\n * order, and a move would land somewhere the reader cannot see; the arrows\n * say so rather than disappear.\n *\n * The panel and the search are asked of Firestore (AGL-3321): a clause or\n * a search word reads the tab's definitions that match it\n * (`CRM_FIELD_LIST_QUERY`), and never narrows the rows already on screen.\n * That answer is every match, at most `CONTACT_FIELDS_MAX_PER_ORG`, so the\n * grid sorts and pages it whole; a read that reaches the ceiling says so.\n */\nfunction FieldsTable(props: FieldsTableProps) {\n const { orgId, object, definitions, busyId, onMove, rowActions } = props\n const firestore = useFirestore()\n const gridFilter = useListGridFilter({ selectFields: ['type', 'required'] })\n const [sortModel, setSortModel] = useState<GridSortModel>([])\n const searching = gridFilter.searchWords.some((word) => word.trim() !== '')\n const reorderLocked =\n sortModel.length > 0 || gridFilter.clauses.length > 0 || searching\n\n const narrowed = gridFilter.clauses.length > 0 || searching\n const plan = useMemo(\n () =>\n planListQuery(\n CRM_FIELD_LIST_QUERY,\n {\n clauses: gridFilter.clauses,\n search: gridFilter.searchWords,\n base: crmFieldListBase(object),\n },\n nameSearchNormalizers,\n ),\n // The words are a new array each render; their text is their identity.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [object, gridFilter.clauses, gridFilter.searchWords.join(' ')],\n )\n const planKey = JSON.stringify({ filters: plan.filters, orderBy: plan.orderBy })\n /*\n * Read only while something narrows the tab. Unnarrowed, the table is the\n * shared definitions read every CRM surface already holds, in its stored\n * order — the same fields, with no second read.\n */\n const matched = useFirestoreCollection<ContactFieldDefinitionDoc>(\n () =>\n narrowed && orgId\n ? query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.contactFields),\n ...listQueryConstraints(plan),\n limit(CONTACT_FIELDS_MAX_PER_ORG + 1),\n )\n : null,\n [firestore, orgId, narrowed, planKey],\n { idField: '$id' },\n )\n const answer = useMemo(\n () => ceilingedWindow(matched.data, CONTACT_FIELDS_MAX_PER_ORG),\n [matched.data],\n )\n const positions = useMemo(\n () => new Map(definitions.map((definition, position) => [definition.$id, position])),\n [definitions],\n )\n const rows = useMemo<FieldRow[]>(() => {\n const shown = narrowed\n ? [...answer.rows].sort(\n (a, b) =>\n (positions.get(a.$id) ?? Number.MAX_SAFE_INTEGER) -\n (positions.get(b.$id) ?? Number.MAX_SAFE_INTEGER),\n )\n : definitions\n return shown.map((definition) => ({\n $id: definition.$id,\n label: definition.label,\n key: definition.key,\n type: definition.type,\n required: definition.required ? 'true' : 'false',\n position: positions.get(definition.$id) ?? 0,\n definition,\n }))\n }, [narrowed, answer.rows, definitions, positions])\n const refused = useMemo(\n () =>\n listQueryRefusals(plan.refused, {\n fields: FIELD_FILTER_FIELDS,\n headers: FIELD_FILTER_HEADERS,\n options: FIELD_FILTER_OPTIONS,\n }),\n [plan.refused],\n )\n\n const columns = useMemo<GridColDef[]>(\n () =>\n listFilterGridColumns(\n [\n {\n field: 'position',\n headerName: 'Order',\n width: 132,\n sortable: false,\n filterable: false,\n hideable: false,\n disableColumnMenu: true,\n renderCell: ({ row }: { row: FieldRow }) => {\n const arrows = (\n <Stack direction=\"row\" spacing={0} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ minWidth: 24, textAlign: 'right', mr: 0.5 }}\n >\n {row.position + 1}\n </Typography>\n <IconButton\n size=\"small\"\n disabled={reorderLocked || row.position === 0 || Boolean(busyId)}\n onClick={() => onMove(row.definition, -1)}\n >\n <MdiIcon path={mdiArrowUp.path} size={0.7} />\n <SrOnly>{`Move ${row.label} up`}</SrOnly>\n </IconButton>\n <IconButton\n size=\"small\"\n disabled={\n reorderLocked || row.position === definitions.length - 1 || Boolean(busyId)\n }\n onClick={() => onMove(row.definition, 1)}\n >\n <MdiIcon path={mdiArrowDown.path} size={0.7} />\n <SrOnly>{`Move ${row.label} down`}</SrOnly>\n </IconButton>\n </Stack>\n )\n return reorderLocked ? (\n <Tooltip title={FIELD_REORDER_LOCKED_REASON}>\n {/* A disabled button emits no events; the span carries the tooltip. */}\n <span>{arrows}</span>\n </Tooltip>\n ) : (\n arrows\n )\n },\n },\n {\n field: 'label',\n headerName: 'Field',\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Stack\n useFlexGap\n direction=\"row\"\n spacing={1}\n sx={{ flexWrap: 'wrap', alignItems: 'center' }}\n >\n <Typography variant=\"body2\">{row.label}</Typography>\n {row.definition.retiredAt ? (\n <Chip size=\"small\" variant=\"outlined\" color=\"warning\" label=\"Retired\" />\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'key',\n headerName: 'Key',\n flex: 1,\n minWidth: 160,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ fontFamily: 'monospace' }}\n >\n {row.key}\n </Typography>\n ),\n },\n {\n field: 'type',\n headerName: 'Type',\n width: 170,\n // By what the type reads as, not by its stored key.\n sortComparator: (a: unknown, b: unknown) =>\n typeLabel(a).localeCompare(typeLabel(b)),\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography variant=\"body2\">\n {typeLabel(row.type)}\n {row.definition.type === 'currency'\n ? ` · ${String(row.definition.currency || 'usd').toUpperCase()}`\n : row.definition.type === 'select' && row.definition.options?.length\n ? ` · ${row.definition.options.length} choices`\n : ''}\n </Typography>\n ),\n },\n {\n field: 'required',\n headerName: 'Required',\n width: 120,\n sortable: false,\n renderCell: ({ row }: { row: FieldRow }) => (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {row.required === 'true' ? 'Yes' : '—'}\n </Typography>\n ),\n },\n listActionsColumn(\n (row: FieldRow) => (\n <ListRowActions label={row.label} items={rowActions(row.definition)} />\n ),\n { width: 72 },\n ),\n ],\n FIELD_FILTER_FIELDS,\n FIELD_FILTER_OPTIONS,\n FIELD_FILTER_HEADERS,\n ),\n [reorderLocked, busyId, onMove, rowActions, definitions.length],\n )\n\n return (\n <Stack spacing={1}>\n <ListFilterChips\n fields={FIELD_FILTER_FIELDS}\n headers={FIELD_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={FIELD_FILTER_OPTIONS}\n marksServed={false}\n />\n <ListQueryNotices refused={refused} notices={plan.notices} />\n {narrowed && answer.truncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Showing the first ${CONTACT_FIELDS_MAX_PER_ORG} matching fields.`}\n </Typography>\n ) : null}\n <ListTable\n aria-label=\"Fields\"\n rows={rows}\n loading={narrowed && matched.status === 'loading'}\n columns={columns}\n sortModel={sortModel}\n onSortModelChange={setSortModel}\n // Firestore narrowed the rows above; the grid only draws them.\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n noRowsLabel=\"No fields match these filters\"\n getRowClassName={({ row }: { row: FieldRow }) =>\n row.definition.retiredAt ? 'field-retired' : ''\n }\n sx={{ '& .field-retired': { opacity: 0.6 } }}\n />\n </Stack>\n )\n}\nFieldsTable.displayName = 'FieldsTable'\n\n/**\n * `/crm/fields` — the custom fields a holder keeps on a person (AGL-2601),\n * since AGL-2661 on a company and a deal too, and since AGL-3272 on a lead:\n * one tab each, and every CRM record describable in the org's own words.\n *\n * Definitions live in `orgs/{orgId}/contactFields`, one document per field,\n * and the VALUES live under each contact facet's `custom` keyed by the\n * definition's `key`. That split decides everything this section does:\n *\n * - A field is RETIRED, not deleted, while values may exist under it. A\n * retired field leaves every form and every column, but an export can\n * still read what was written, and a restore brings it back intact.\n * Delete is offered only on a retired field, because retiring is the step\n * where the author had to look at what they were losing.\n * - The KEY never changes. It is the map key every value sits under; a\n * rename is a new field and a retire.\n * - Order is a stored `order` on each document, moved with the arrows here,\n * and every reader sorts by it — the profile card, the columns, an export.\n * The list table sorts, filters and searches a tab too (AGL-3335), and\n * the arrows wait while it does — see `FieldsTable`.\n *\n * ## What is NOT on this page\n *\n * How many contacts carry a value under each field. That count is a read of\n * every contact document in the org — the expensive-read shape this codebase\n * has a standing rule against — and it would be paid on every visit to a\n * settings page. The list says so rather than showing a number it cannot\n * afford to keep true.\n *\n * Definitions are ORG-WIDE (`visibleTo: ['org']`): a field is a fact about\n * how this business describes people, and every site in the org files\n * people into the same address book. `hostId` records which site defined it.\n */\nexport function ContactsFieldsSection(props: ContactsFieldsSectionProps) {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root from the one scope hook (AGL-2614), which also answers at\n // the organization level (AGL-2630). A definition is org-wide either way;\n // the defining site it records is the mounted one, or the picked one, or\n // none for a field defined over the whole org before any pick.\n const { scope, ready: scopeReady, createHostId } = useCrmScope({ hostId, org })\n const orgId = scope?.[1] ?? null\n /*\n * ONE TAB PER OBJECT (AGL-2661). The list, the drawer and every write\n * below are about the tab's object: the hook narrows the org's one\n * definition list to it, a new field is stamped with it, and the drawer\n * refuses a key only against the keys THIS object already uses — a\n * company and a contact may both define `region`.\n */\n const [tab, setTab] = useState<CrmPicklistObject>('contact')\n // The Tasks tab has no custom fields (AGL-3517): no read, no New field.\n const tasksTab = tab === 'task'\n const object: CrmFieldObject = tab === 'task' ? 'contact' : tab\n const { definitions, ready, fromCache } = useContactFieldDefinitions(\n tasksTab ? null : orgId,\n object,\n )\n const noun = OBJECT_NOUN[object]\n\n /*\n * MAINTENANCE: recompute every record's next activity (AGL-2661). The\n * figure is kept by every task write, so this is for the records written\n * before it existed and for whatever a write that could not reach the\n * route left behind. A console action rather than a script, because the\n * person who notices a stale column is the person who should be able to\n * fix it.\n */\n const { data: user } = useUser()\n const [recomputing, setRecomputing] = useState(false)\n const recomputeNextActivity = useCallback(async () => {\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope || recomputing) return\n const confirmed = await confirm({\n title: 'Recompute next activity?',\n description:\n 'Every contact, company and deal in this organization gets its ' +\n '\"Next activity\" recomputed from its open tasks. Safe to run any time; ' +\n 'it only rewrites a figure the task list already implies.',\n confirmationText: 'Recompute',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setRecomputing(true)\n try {\n const result = await recomputeAllCrmNextActivity(user, callScope)\n enqueueSnackbar(\n `Next activity recomputed: ${result.records.toLocaleString()} record${result.records === 1 ? '' : 's'} ` +\n `from ${(result.tasks ?? 0).toLocaleString()} open task${result.tasks === 1 ? '' : 's'}` +\n (result.truncated\n ? ' — the first batch of open tasks only; nothing stale was cleared'\n : ''),\n { variant: 'success' },\n )\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The next activity could not be recomputed.',\n { variant: 'warning' },\n )\n } finally {\n setRecomputing(false)\n }\n }, [hostId, orgId, recomputing, confirm, user, enqueueSnackbar])\n\n const [drawerOpen, setDrawerOpen] = useState(false)\n const [editing, setEditing] = useState<ContactFieldDefinitionDoc | null>(null)\n const [busyId, setBusyId] = useState('')\n\n const fieldRef = useCallback(\n (id: string) => {\n if (!scope) throw new Error('a contact field needs an organization')\n return doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.contactFields, id)\n },\n [firestore, scope],\n )\n\n const openCreate = useCallback(() => {\n setEditing(null)\n setDrawerOpen(true)\n }, [])\n const openEdit = useCallback((definition: ContactFieldDefinitionDoc) => {\n setEditing(definition)\n setDrawerOpen(true)\n }, [])\n\n /**\n * Create, or save the editable half of an existing field.\n *\n * On create the document carries everything a reader expects: the key,\n * an `order` past every existing one so it lands last, an explicit\n * `retiredAt: null` so a `where('retiredAt', '==', null)` can find it, the\n * defining site, and the org-wide scope stamp the rules require. On edit\n * only the label, the choices and the required flag move — the key and\n * the type are the drawer's disabled inputs, and this writer does not\n * take them either.\n */\n const handleSubmit = useCallback(\n async (draft: ContactFieldDraft) => {\n if (!scope) return\n const now = new Date()\n if (editing) {\n const verdict = await writeGuardedBySeed(\n { subject: 'field', fromCache },\n async () => {\n await updateDoc(fieldRef(editing.$id), {\n label: draft.label,\n ...(editing.type === 'select' ? { options: draft.options } : {}),\n // The Fields table's query fields (AGL-3335), from the new name —\n // and a definition written before them gains them here.\n ...crmFieldListFields({ ...editing, label: draft.label, required: draft.required }),\n updatedAt: now,\n })\n },\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n enqueueSnackbar('Field saved', { variant: 'success', persist: false })\n } else {\n const order =\n definitions.reduce(\n (highest, definition) => Math.max(highest, Number(definition.order) || 0),\n -1,\n ) + 1\n await setDoc(\n doc(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.contactFields),\n createResourceUid(),\n ),\n {\n key: draft.key,\n label: draft.label,\n type: draft.type,\n ...(draft.type === 'select' ? { options: draft.options } : {}),\n ...(draft.type === 'currency' && draft.currency ? { currency: draft.currency } : {}),\n required: draft.required,\n order,\n retiredAt: null,\n // Which record the field describes — the tab it was made on —\n // with the Fields table's query fields (AGL-3335).\n ...crmFieldListFields({ key: draft.key, label: draft.label, required: draft.required, object }),\n hostId: createHostId,\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n createdAt: now,\n updatedAt: now,\n },\n )\n enqueueSnackbar(`Field \"${draft.label}\" added`, {\n variant: 'success',\n persist: false,\n })\n }\n setDrawerOpen(false)\n setEditing(null)\n },\n [scope, editing, fromCache, fieldRef, enqueueSnackbar, definitions, firestore, createHostId, object],\n )\n\n /**\n * Move a field one place up or down.\n *\n * Writes `order` as the POSITION for every row whose stored order is not\n * already its position, in one batch. Swapping two numbers would be enough\n * on a list whose orders are already distinct, and wrong on one where they\n * are not — every field created before this section existed carries the\n * same `order`, and a swap of two equal numbers moves nothing. Renumbering\n * what is out of place makes the first move on such a list also the one\n * that normalizes it, at the cost of a batch that is at most the list.\n */\n const move = useCallback(\n async (definition: ContactFieldDefinitionDoc, direction: -1 | 1) => {\n if (!scope || busyId) return\n const index = definitions.findIndex((entry) => entry.$id === definition.$id)\n const target = index + direction\n if (index < 0 || target < 0 || target >= definitions.length) return\n const next = [...definitions]\n next[index] = definitions[target]\n next[target] = definitions[index]\n setBusyId(definition.$id)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'field order', fromCache },\n async () => {\n const batch = writeBatch(firestore)\n const now = new Date()\n next.forEach((entry, position) => {\n if (entry.order === position) return\n batch.update(fieldRef(entry.$id), { order: position, updatedAt: now })\n })\n await batch.commit()\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, definitions, fromCache, firestore, fieldRef, enqueueSnackbar],\n )\n\n /**\n * Retire a field, or bring one back.\n *\n * Retiring is asked about because it takes a control off every contact\n * form and a column off the list; restoring is not, because it puts a\n * choice back and is undone by retiring again. Neither touches a value.\n */\n const toggleRetired = useCallback(\n async (definition: ContactFieldDefinitionDoc) => {\n if (!scope || busyId) return\n if (!definition.retiredAt) {\n const accepted = await confirm({\n title: `Retire “${definition.label}”?`,\n description:\n `It leaves every ${noun} form, column and form-field mapping. ` +\n 'Values already saved under it are kept and still export, and ' +\n 'you can restore the field at any time.',\n confirmationText: 'Retire',\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating\n // on the resolved value alone would always fall through.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setBusyId(definition.$id)\n try {\n await updateDoc(fieldRef(definition.$id), {\n retiredAt: definition.retiredAt ? null : Date.now(),\n updatedAt: new Date(),\n })\n enqueueSnackbar(definition.retiredAt ? 'Field restored' : 'Field retired', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, confirm, fieldRef, enqueueSnackbar, noun],\n )\n\n /**\n * Delete a RETIRED field's definition.\n *\n * The values under its key are not touched — they sit on contact documents\n * this page does not read — so what is destroyed is the ability to show\n * them anywhere. The dialog says exactly that, and the key stays taken for\n * as long as the list can see it, which after this write it cannot; a new\n * field with the same key would read the orphaned values back as its own.\n */\n const handleDelete = useCallback(\n async (definition: ContactFieldDefinitionDoc) => {\n if (!scope || busyId || !definition.retiredAt) return\n const accepted = await confirm({\n title: `Delete “${definition.label}”?`,\n description:\n 'The definition is removed for good. Values saved under its key ' +\n `(${definition.key}) stay on the ${noun}s that carry them but ` +\n 'nothing will show them again — and a new field created with the ' +\n 'same key would read them as its own.',\n confirmationText: 'Delete field',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setBusyId(definition.$id)\n try {\n await deleteDoc(fieldRef(definition.$id))\n enqueueSnackbar('Field deleted', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setBusyId('')\n }\n },\n [scope, busyId, confirm, fieldRef, enqueueSnackbar, noun],\n )\n\n /*\n * Stable across renders, as the table's columns are built from them: a\n * fresh function each render would rebuild every column on every render.\n */\n const rowActions = useCallback(\n (definition: ContactFieldDefinitionDoc): RowActionsMenuItem[] => [\n {\n key: 'edit',\n label: 'Edit field',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n onClick: () => openEdit(definition),\n },\n {\n key: 'retire',\n label: definition.retiredAt ? 'Restore' : 'Retire',\n icon: (\n <MdiIcon\n path={definition.retiredAt ? mdiArchiveArrowUpOutline.path : mdiArchiveOutline.path}\n size={0.8}\n />\n ),\n destructive: !definition.retiredAt,\n disabled: Boolean(busyId),\n disabledReason: busyId ? 'Another field is being saved' : undefined,\n onClick: () => void toggleRetired(definition),\n },\n ...(definition.retiredAt\n ? [\n {\n key: 'delete',\n label: 'Delete',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: Boolean(busyId),\n disabledReason: busyId ? 'Another field is being saved' : undefined,\n onClick: () => void handleDelete(definition),\n } satisfies RowActionsMenuItem,\n ]\n : []),\n ],\n [openEdit, toggleRetired, handleDelete, busyId],\n )\n const onMove = useCallback(\n (definition: ContactFieldDefinitionDoc, direction: -1 | 1) =>\n void move(definition, direction),\n [move],\n )\n\n return (\n <CardDisplay\n header={'Fields'}\n help={pluginDocsHelp('contactFields', { anchor: '#define-a-field' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: scope ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n {/* Every custom field, as a file (AGL-3528). */}\n <CrmExportButton resource={CRM_FIELDS_RESOURCE} hostId={hostId ?? null} />\n <Button size=\"small\" onClick={() => void recomputeNextActivity()} disabled={recomputing}>\n {recomputing ? 'Recomputing…' : 'Recompute next activity'}\n </Button>\n {tasksTab ? null : (\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n )}\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n <Tabs\n value={tab}\n onChange={(_event, next) => {\n if (isCrmPicklistObject(next)) setTab(next)\n }}\n aria-label=\"Fields by record\"\n variant=\"scrollable\"\n scrollButtons=\"auto\"\n allowScrollButtonsMobile\n >\n {CRM_PICKLIST_OBJECTS.map((entry) => (\n <Tab key={entry} value={entry} label={CRM_PICKLIST_OBJECT_LABELS[entry]} />\n ))}\n </Tabs>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${tasksTab ? TASKS_INTRO : OBJECT_INTRO[object]} Fields are shared across every site in this ` +\n 'organization, like the records themselves.'}\n </Typography>\n {tasksTab ? null : scopeReady && !scope ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`This site has no organization, so it has no ${noun} fields.`}\n </Typography>\n ) : !ready ? null : definitions.length === 0 ? (\n <EmptyStateComponent\n label={`No custom ${noun} fields yet`}\n description={`A field you define here is kept on every ${noun} and shows on its page.`}\n action={\n scope ? (\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n ) : undefined\n }\n />\n ) : (\n /*\n Keyed by the tab, so a sort, a filter or a search made on one\n record's fields does not follow the reader onto another's.\n */\n <FieldsTable\n key={object}\n orgId={orgId}\n object={object}\n definitions={definitions}\n busyId={busyId}\n onMove={onMove}\n rowActions={rowActions}\n />\n )}\n {definitions.length && !tasksTab ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`How many ${noun}s carry a value under each field is not ` +\n `counted — that would read every ${noun} in the organization ` +\n 'each time this page opened.'}\n </Typography>\n ) : null}\n {/*\n The tab's standard picklists (AGL-3298, AGL-3510) — standard fields\n whose CHOICES are the org's, Salesforce's picklist value sets — one\n card each, beside the custom fields of the same record.\n */}\n {scope\n ? crmPicklistDefinitionsFor(tab).map((definition) => (\n <PicklistValuesCard\n key={definition.id}\n picklistId={definition.id as CrmPicklistId}\n hostId={hostId}\n orgId={orgId}\n createHostId={createHostId}\n />\n ))\n : null}\n </Stack>\n <ContactFieldDrawer\n open={drawerOpen}\n onClose={() => setDrawerOpen(false)}\n definition={editing}\n object={object}\n takenKeys={definitions.map((definition) => definition.key)}\n onSubmit={handleSubmit}\n />\n </CardDisplay>\n )\n}\nContactsFieldsSection.displayName = 'ContactsFieldsSection'\n\nexport default ContactsFieldsSection\n"],"names":["CrmExportButton","CRM_FIELDS_RESOURCE","CONTACT_FIELD_TYPE_LABELS","CONTACT_FIELD_TYPES","CONTACT_FIELDS_MAX_PER_ORG","createResourceUid","CRM_COLLECTIONS","crmFieldListFields","CRM_PICKLIST_OBJECT_LABELS","CRM_PICKLIST_OBJECTS","crmPicklistDefinitionsFor","isCrmPicklistObject","newResourceScopeFields","ORG_SCOPE_TOKEN","pluginDocsHelp","EmptyStateComponent","ListFilterChips","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","mdiArchiveArrowUpOutline","mdiArchiveOutline","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","mdiPencilOutline","CardDisplay","MdiIcon","SrOnly","useConfirmationContext","listFilterGridColumns","planListQuery","useListGridFilter","nameSearchNormalizers","useSnackbar","ceilingedWindow","listQueryConstraints","useFirestore","useFirestoreCollection","useUser","writeGuardedBySeed","Button","Chip","IconButton","Stack","Tab","Tabs","Tooltip","Typography","collection","deleteDoc","doc","limit","query","setDoc","updateDoc","writeBatch","useCallback","useMemo","useState","useContactFieldDefinitions","useCrmScope","CRM_FIELD_LIST_QUERY","crmFieldListBase","ContactFieldDrawer","PicklistValuesCard","recomputeAllCrmNextActivity","crmTaskCallScope","OBJECT_INTRO","contact","company","deal","lead","TASKS_INTRO","OBJECT_NOUN","FIELD_FILTER_FIELDS","fields","FIELD_FILTER_HEADERS","type","required","FIELD_FILTER_OPTIONS","map","value","label","FIELD_REORDER_LOCKED_REASON","typeLabel","String","FieldsTable","props","orgId","object","definitions","busyId","onMove","rowActions","firestore","gridFilter","selectFields","sortModel","setSortModel","searching","searchWords","some","word","trim","reorderLocked","length","clauses","narrowed","plan","search","base","join","planKey","JSON","stringify","filters","orderBy","matched","contactFields","idField","answer","data","positions","Map","definition","position","$id","rows","shown","sort","a","b","get","Number","MAX_SAFE_INTEGER","key","refused","headers","options","columns","field","headerName","width","sortable","filterable","hideable","disableColumnMenu","renderCell","row","arrows","direction","spacing","sx","alignItems","variant","color","minWidth","textAlign","mr","size","disabled","Boolean","onClick","path","title","span","flex","useFlexGap","flexWrap","retiredAt","fontFamily","sortComparator","localeCompare","currency","toUpperCase","items","onChange","setClauses","marksServed","notices","truncated","aria-label","loading","status","onSortModelChange","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","getRowClassName","opacity","displayName","ContactsFieldsSection","hostId","org","enqueueSnackbar","confirm","scope","ready","scopeReady","createHostId","tab","setTab","tasksTab","fromCache","noun","user","recomputing","setRecomputing","recomputeNextActivity","callScope","confirmed","description","confirmationText","then","catch","result","records","toLocaleString","tasks","cause","Error","message","drawerOpen","setDrawerOpen","editing","setEditing","setBusyId","fieldRef","id","openCreate","openEdit","handleSubmit","draft","now","Date","verdict","subject","updatedAt","ok","persist","order","reduce","highest","Math","max","createdAt","move","index","findIndex","entry","target","next","batch","forEach","update","commit","error","console","allowDuplicate","toggleRetired","accepted","handleDelete","confirmationButtonProps","icon","destructive","disabledReason","undefined","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","resource","_event","scrollButtons","allowScrollButtonsMobile","picklistId","open","onClose","takenK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C;yBAE9D,CAACP,QAAQ,OAAO7G,YAAYe,MAAM,KAAK,kBACzC,KAAC7F;wBACCsE,OAAO,CAAC,UAAU,EAAE4H,KAAK,WAAW,CAAC;wBACrCO,aAAa,CAAC,yCAAyC,EAAEP,KAAK,uBAAuB,CAAC;wBACtFsE,QACE9E,sBACE,KAAC9J;4BAAOkH,SAAQ;4BAAYQ,SAASqE;sCAClC;6BAEDqC;yBAIR;;;UAGA,iBACA,KAACtL;wBAECE,OAAOA;wBACPC,QAAQA;wBACRC,aAAaA;wBACbC,QAAQA;wBACRC,QAAQA;wBACRC,YAAYA;uBANPJ;oBASRC,YAAYe,MAAM,IAAI,CAACmG,yBACtB,KAAC7J;wBAAW2G,SAAQ;wBAAUC,OAAM;kCACjC,CAAC,SAAS,EAAEmD,KAAK,wCAAwC,CAAC,GACzD,CAAC,gCAAgC,EAAEA,KAAK,qBAAqB,CAAC,GAC9D;yBAEF;oBAMHR,QACG/L,0BAA0BmM,KAAK1H,GAAG,CAAC,CAAC4C,2BAClC,KAAC5D;4BAECyN,YAAY7J,WAAW0G,EAAE;4BACzBpC,QAAQA;4BACR1G,OAAOA;4BACPiH,cAAcA;2BAJT7E,WAAW0G,EAAE,KAOtB;;;0BAEN,KAACvK;gBACC2N,MAAM1D;gBACN2D,SAAS,IAAM1D,cAAc;gBAC7BrG,YAAYsG;gBACZzI,QAAQA;gBACRmM,WAAWlM,YAAYV,GAAG,CAAC,CAAC4C,aAAeA,WAAWW,GAAG;gBACzDsJ,UAAUpD;;;;AAIlB;AACAxC,sBAAsBD,WAAW,GAAG;AAEpC,eAAeC,sBAAqB"}
|
|
@@ -126,6 +126,8 @@ import { useCallback, useMemo, useState } from "react";
|
|
|
126
126
|
switch(definition.type){
|
|
127
127
|
case 'number':
|
|
128
128
|
return 'Stored as a number; an answer that is not one number is dropped.';
|
|
129
|
+
case 'currency':
|
|
130
|
+
return `Stored as an amount in ${String(definition.currency || 'usd').toUpperCase()}; an answer that is not one amount is dropped.`;
|
|
129
131
|
case 'date':
|
|
130
132
|
return 'Stored as a date, whichever way the visitor types it.';
|
|
131
133
|
case 'checkbox':
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/form-contact-fields-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n CONTACT_FIELD_TYPE_LABELS,\n type FormFieldDecl,\n pluginDocsHelp,\n withContactFieldMapping,\n} from '@aglyn/aglyn'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useOrgDataScope } from '@aglyn/tenant-feature-instance'\nimport { Button, MenuItem, Stack, TextField, Typography } from '@mui/material'\nimport { useCallback, useMemo, useState } from 'react'\n\nexport interface FormContactFieldsCardProps {\n hostId: string\n formId: string\n /** The PUBLISHED declaration, as stored on the form document. */\n fields: readonly FormFieldDecl[]\n /** True while the form document is still being read. */\n loading?: boolean\n /**\n * Writes the declaration back. The form document is the forms plugin's, so\n * its page does the write; this card decides what the array should be.\n */\n saveFields: (fields: FormFieldDecl[]) => Promise<void>\n}\n\n/** The choice that saves nowhere — a `MenuItem` value has to be a string. */\nconst NONE = ''\n\n/**\n * Where each of a form's fields saves on the contact (AGL-2601).\n *\n * The declaration a submission is judged against comes off the DESIGN at\n * publish — names, types, options — and knows nothing about where a field\n * saves to, because that is a fact about the contact, not the canvas. So it\n * is edited here — drawn by the CRM in the zone the form's own page hosts,\n * beside routing and the consent field — and written onto the stored\n * declaration as `contactFieldKey`;\n * `carryContactFieldMappings` keeps it across the next publish by field\n * name. The destinations are the org's custom field definitions, read\n * through the same hook every other surface uses, so a field retired under\n * CRM → Fields leaves this list at the same moment it leaves the columns.\n *\n * Only the org's OWN fields are offered. The sender's name and email are\n * recognized from the field name at submission (`name`, `email`) and need no\n * mapping; a control that offered them here would promise a second way to\n * say the same thing, and the built-in `role` on a declaration is read by\n * nothing at the door today — a choice that writes it would be a choice\n * that does nothing.\n *\n * Save hands the whole `fields` array to the page, which writes it — it is\n * one array on the form document, the document is the forms plugin's, and\n * Firestore has no per-element update — with the picked keys\n * applied through `withContactFieldMapping`, which deletes an unmapped key\n * rather than leaving an `undefined` the array write would refuse.\n */\nexport function FormContactFieldsCard(props: FormContactFieldsCardProps) {\n const { hostId, fields, loading, saveFields } = props\n const { enqueueSnackbar } = useSnackbar()\n const { scope, ready: scopeReady } = useOrgDataScope({ hostId })\n const { active, definitions, ready } = useContactFieldDefinitions(scope?.[1] ?? null)\n\n /**\n * The destinations picked on screen, by field name — only the fields the\n * reader touched. Everything else reads from the stored declaration, so a\n * write from elsewhere (a publish, another tab) shows through untouched.\n */\n const [draft, setDraft] = useState<Record<string, string>>({})\n const [saving, setSaving] = useState(false)\n\n const storedKey = useCallback((decl: FormFieldDecl) => decl.contactFieldKey ?? NONE, [])\n const shownKey = useCallback(\n (decl: FormFieldDecl) => (decl.fieldName in draft ? draft[decl.fieldName] : storedKey(decl)),\n [draft, storedKey],\n )\n const changed = useMemo(\n () =>\n fields.filter(\n (decl) => decl.fieldName in draft && draft[decl.fieldName] !== storedKey(decl),\n ),\n [fields, draft, storedKey],\n )\n\n /** Active definitions by key, for the hint under a mapped field. */\n const activeByKey = useMemo(\n () => new Map(active.map((definition) => [definition.key, definition])),\n [active],\n )\n\n const handleSave = useCallback(async () => {\n if (!changed.length || saving) return\n setSaving(true)\n try {\n const next = changed.reduce<FormFieldDecl[]>(\n (decls, decl) =>\n withContactFieldMapping(decls, decl.fieldName, draft[decl.fieldName] || null),\n [...fields],\n )\n await saveFields(next)\n setDraft({})\n enqueueSnackbar('Form saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setSaving(false)\n }\n }, [changed, saving, fields, draft, saveFields, enqueueSnackbar])\n\n /**\n * What the picked destination does with an answer — the type's rule, in a\n * sentence, so the author learns it here rather than from a value that\n * never arrived.\n */\n const hint = (key: string): string | undefined => {\n if (key === NONE) return undefined\n const definition = activeByKey.get(key)\n if (!definition) {\n return definitions.some((entry) => entry.key === key)\n ? 'This field is retired, so the answer is no longer saved. Pick another or clear it.'\n : 'This field no longer exists, so the answer is not saved. Pick another or clear it.'\n }\n switch (definition.type) {\n case 'number':\n return 'Stored as a number; an answer that is not one number is dropped.'\n case 'date':\n return 'Stored as a date, whichever way the visitor types it.'\n case 'checkbox':\n return 'Stored as yes or no, from a ticked or unticked box.'\n case 'select':\n return `Stored only when the answer is one of: ${(definition.options ?? []).join(', ')}.`\n case 'url':\n return 'Stored when the answer is an http(s) link.'\n default:\n return 'Stored as text.'\n }\n }\n\n /**\n * A stored key no active definition answers to — retired, or deleted —\n * still has to be an option, or the control could not show what the\n * declaration says and the author could not clear it.\n */\n const orphanOption = (key: string) => {\n if (key === NONE || activeByKey.has(key)) return null\n const retired = definitions.some((entry) => entry.key === key)\n return (\n <MenuItem key={key} value={key}>\n {`${key} — ${retired ? 'retired field' : 'no such field'}`}\n </MenuItem>\n )\n }\n\n const settled = scopeReady && !loading && (!scope || ready)\n const anyMapped = fields.some((decl) => decl.contactFieldKey)\n // The mapping is offered once there is something to map, and saved from the header.\n const mapping =\n settled && Boolean(scope) && fields.length > 0 && (active.length > 0 || anyMapped)\n\n return (\n <CardDisplay\n header=\"Saves to contact fields\"\n help={pluginDocsHelp('contactFields', { anchor: '#save-a-form-field' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: mapping ? (\n <Stack direction=\"row\" spacing={1}>\n {changed.length ? (\n <Button size=\"small\" onClick={() => setDraft({})} disabled={saving}>\n {'Discard'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!changed.length || saving}\n onClick={handleSave}\n >\n {'Save'}\n </Button>\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n {!settled ? null : !scope ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This site has no organization, so it has no contact fields to save into.'}\n </Typography>\n ) : fields.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Publish a version to declare this form’s fields; then choose where each one saves.'}\n </Typography>\n ) : active.length === 0 && !anyMapped ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No custom contact fields are defined yet. Define them under CRM → Fields and ' +\n 'each form field can save into one.'}\n </Typography>\n ) : (\n <>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Each answer is stored on the contact the submission creates or updates, ' +\n 'converted by the field’s type. A blank answer writes nothing.'}\n </Typography>\n {fields.map((decl) => {\n const key = shownKey(decl)\n return (\n <TextField\n key={decl.fieldName}\n select\n size=\"small\"\n label={decl.label ? `${decl.label} (${decl.fieldName})` : decl.fieldName}\n value={key}\n onChange={(event) =>\n setDraft((current) => ({ ...current, [decl.fieldName]: event.target.value }))\n }\n helperText={hint(key)}\n // `displayEmpty`, or the \"saves nowhere\" choice renders as\n // a blank control and reads as a field left unset; the label\n // shrinks with it so the two do not overlap.\n slotProps={{\n select: { displayEmpty: true },\n inputLabel: { shrink: true },\n }}\n fullWidth\n >\n <MenuItem value={NONE}>{'Not saved to a contact field'}</MenuItem>\n {orphanOption(key)}\n {active.map((definition) => (\n <MenuItem key={definition.key} value={definition.key}>\n {`${definition.label} · ${CONTACT_FIELD_TYPE_LABELS[definition.type]}`}\n </MenuItem>\n ))}\n </TextField>\n )\n })}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The sender’s name and email are read from fields named name and email, ' +\n 'so they never need mapping.'}\n </Typography>\n </>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nFormContactFieldsCard.displayName = 'FormContactFieldsCard'\n\nexport default FormContactFieldsCard\n"],"names":["CONTACT_FIELD_TYPE_LABELS","pluginDocsHelp","withContactFieldMapping","useContactFieldDefinitions","CardDisplay","useSnackbar","useOrgDataScope","Button","MenuItem","Stack","TextField","Typography","useCallback","useMemo","useState","NONE","FormContactFieldsCard","props","hostId","fields","loading","saveFields","enqueueSnackbar","scope","ready","scopeReady","active","definitions","draft","setDraft","saving","setSaving","storedKey","decl","contactFieldKey","shownKey","fieldName","changed","filter","activeByKey","Map","map","definition","key","handleSave","length","next","reduce","decls","variant","persist","error","console","allowDuplicate","hint","undefined","get","some","entry","type","options","join","orphanOption","has","retired","value","settled","anyMapped","mapping","Boolean","header","help","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","size","onClick","disabled","color","select","label","onChange","event","current","target","helperText","slotProps","displayEmpty","inputLabel","shrink","fullWidth","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,yBAAyB,EAEzBC,cAAc,EACdC,uBAAuB,QAClB,eAAc;AACrB,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAe;AAC9E,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAgBtD,2EAA2E,GAC3E,MAAMC,OAAO;AAEb;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,SAASC,sBAAsBC,KAAiC;;IACrE,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,UAAU,EAAE,GA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C0D,UAAa,aAAKA;wCAAS,CAACtD,KAAKG,SAAS,CAAC,EAAEkD,MAAME,MAAM,CAACvB,KAAK;;4BAE3EwB,YAAYnC,KAAKX;4BACjB,2DAA2D;4BAC3D,6DAA6D;4BAC7D,6CAA6C;4BAC7C+C,WAAW;gCACTP,QAAQ;oCAAEQ,cAAc;gCAAK;gCAC7BC,YAAY;oCAAEC,QAAQ;gCAAK;4BAC7B;4BACAC,SAAS;;8CAET,KAACtF;oCAASyD,OAAOlD;8CAAO;;gCACvB+C,aAAanB;gCACbjB,OAAOe,GAAG,CAAC,CAACC,2BACX,KAAClC;wCAA8ByD,OAAOvB,WAAWC,GAAG;kDACjD,GAAGD,WAAW0C,KAAK,CAAC,GAAG,EAAEpF,yBAAyB,CAAC0C,WAAWiB,IAAI,CAAC,EAAE;uCADzDjB,WAAWC,GAAG;;2BArB1BV,KAAKG,SAAS;oBA2BzB;kCACA,KAACzB;wBAAWsC,SAAQ;wBAAUiC,OAAM;kCACjC,4EACC;;;;;;AAOhB;AACAlE,sBAAsB+E,WAAW,GAAG;AAEpC,eAAe/E,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/form-contact-fields-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n CONTACT_FIELD_TYPE_LABELS,\n type FormFieldDecl,\n pluginDocsHelp,\n withContactFieldMapping,\n} from '@aglyn/aglyn'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useOrgDataScope } from '@aglyn/tenant-feature-instance'\nimport { Button, MenuItem, Stack, TextField, Typography } from '@mui/material'\nimport { useCallback, useMemo, useState } from 'react'\n\nexport interface FormContactFieldsCardProps {\n hostId: string\n formId: string\n /** The PUBLISHED declaration, as stored on the form document. */\n fields: readonly FormFieldDecl[]\n /** True while the form document is still being read. */\n loading?: boolean\n /**\n * Writes the declaration back. The form document is the forms plugin's, so\n * its page does the write; this card decides what the array should be.\n */\n saveFields: (fields: FormFieldDecl[]) => Promise<void>\n}\n\n/** The choice that saves nowhere — a `MenuItem` value has to be a string. */\nconst NONE = ''\n\n/**\n * Where each of a form's fields saves on the contact (AGL-2601).\n *\n * The declaration a submission is judged against comes off the DESIGN at\n * publish — names, types, options — and knows nothing about where a field\n * saves to, because that is a fact about the contact, not the canvas. So it\n * is edited here — drawn by the CRM in the zone the form's own page hosts,\n * beside routing and the consent field — and written onto the stored\n * declaration as `contactFieldKey`;\n * `carryContactFieldMappings` keeps it across the next publish by field\n * name. The destinations are the org's custom field definitions, read\n * through the same hook every other surface uses, so a field retired under\n * CRM → Fields leaves this list at the same moment it leaves the columns.\n *\n * Only the org's OWN fields are offered. The sender's name and email are\n * recognized from the field name at submission (`name`, `email`) and need no\n * mapping; a control that offered them here would promise a second way to\n * say the same thing, and the built-in `role` on a declaration is read by\n * nothing at the door today — a choice that writes it would be a choice\n * that does nothing.\n *\n * Save hands the whole `fields` array to the page, which writes it — it is\n * one array on the form document, the document is the forms plugin's, and\n * Firestore has no per-element update — with the picked keys\n * applied through `withContactFieldMapping`, which deletes an unmapped key\n * rather than leaving an `undefined` the array write would refuse.\n */\nexport function FormContactFieldsCard(props: FormContactFieldsCardProps) {\n const { hostId, fields, loading, saveFields } = props\n const { enqueueSnackbar } = useSnackbar()\n const { scope, ready: scopeReady } = useOrgDataScope({ hostId })\n const { active, definitions, ready } = useContactFieldDefinitions(scope?.[1] ?? null)\n\n /**\n * The destinations picked on screen, by field name — only the fields the\n * reader touched. Everything else reads from the stored declaration, so a\n * write from elsewhere (a publish, another tab) shows through untouched.\n */\n const [draft, setDraft] = useState<Record<string, string>>({})\n const [saving, setSaving] = useState(false)\n\n const storedKey = useCallback((decl: FormFieldDecl) => decl.contactFieldKey ?? NONE, [])\n const shownKey = useCallback(\n (decl: FormFieldDecl) => (decl.fieldName in draft ? draft[decl.fieldName] : storedKey(decl)),\n [draft, storedKey],\n )\n const changed = useMemo(\n () =>\n fields.filter(\n (decl) => decl.fieldName in draft && draft[decl.fieldName] !== storedKey(decl),\n ),\n [fields, draft, storedKey],\n )\n\n /** Active definitions by key, for the hint under a mapped field. */\n const activeByKey = useMemo(\n () => new Map(active.map((definition) => [definition.key, definition])),\n [active],\n )\n\n const handleSave = useCallback(async () => {\n if (!changed.length || saving) return\n setSaving(true)\n try {\n const next = changed.reduce<FormFieldDecl[]>(\n (decls, decl) =>\n withContactFieldMapping(decls, decl.fieldName, draft[decl.fieldName] || null),\n [...fields],\n )\n await saveFields(next)\n setDraft({})\n enqueueSnackbar('Form saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n } finally {\n setSaving(false)\n }\n }, [changed, saving, fields, draft, saveFields, enqueueSnackbar])\n\n /**\n * What the picked destination does with an answer — the type's rule, in a\n * sentence, so the author learns it here rather than from a value that\n * never arrived.\n */\n const hint = (key: string): string | undefined => {\n if (key === NONE) return undefined\n const definition = activeByKey.get(key)\n if (!definition) {\n return definitions.some((entry) => entry.key === key)\n ? 'This field is retired, so the answer is no longer saved. Pick another or clear it.'\n : 'This field no longer exists, so the answer is not saved. Pick another or clear it.'\n }\n switch (definition.type) {\n case 'number':\n return 'Stored as a number; an answer that is not one number is dropped.'\n case 'currency':\n return `Stored as an amount in ${String(definition.currency || 'usd').toUpperCase()}; an answer that is not one amount is dropped.`\n case 'date':\n return 'Stored as a date, whichever way the visitor types it.'\n case 'checkbox':\n return 'Stored as yes or no, from a ticked or unticked box.'\n case 'select':\n return `Stored only when the answer is one of: ${(definition.options ?? []).join(', ')}.`\n case 'url':\n return 'Stored when the answer is an http(s) link.'\n default:\n return 'Stored as text.'\n }\n }\n\n /**\n * A stored key no active definition answers to — retired, or deleted —\n * still has to be an option, or the control could not show what the\n * declaration says and the author could not clear it.\n */\n const orphanOption = (key: string) => {\n if (key === NONE || activeByKey.has(key)) return null\n const retired = definitions.some((entry) => entry.key === key)\n return (\n <MenuItem key={key} value={key}>\n {`${key} — ${retired ? 'retired field' : 'no such field'}`}\n </MenuItem>\n )\n }\n\n const settled = scopeReady && !loading && (!scope || ready)\n const anyMapped = fields.some((decl) => decl.contactFieldKey)\n // The mapping is offered once there is something to map, and saved from the header.\n const mapping =\n settled && Boolean(scope) && fields.length > 0 && (active.length > 0 || anyMapped)\n\n return (\n <CardDisplay\n header=\"Saves to contact fields\"\n help={pluginDocsHelp('contactFields', { anchor: '#save-a-form-field' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: mapping ? (\n <Stack direction=\"row\" spacing={1}>\n {changed.length ? (\n <Button size=\"small\" onClick={() => setDraft({})} disabled={saving}>\n {'Discard'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!changed.length || saving}\n onClick={handleSave}\n >\n {'Save'}\n </Button>\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n {!settled ? null : !scope ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This site has no organization, so it has no contact fields to save into.'}\n </Typography>\n ) : fields.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Publish a version to declare this form’s fields; then choose where each one saves.'}\n </Typography>\n ) : active.length === 0 && !anyMapped ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No custom contact fields are defined yet. Define them under CRM → Fields and ' +\n 'each form field can save into one.'}\n </Typography>\n ) : (\n <>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Each answer is stored on the contact the submission creates or updates, ' +\n 'converted by the field’s type. A blank answer writes nothing.'}\n </Typography>\n {fields.map((decl) => {\n const key = shownKey(decl)\n return (\n <TextField\n key={decl.fieldName}\n select\n size=\"small\"\n label={decl.label ? `${decl.label} (${decl.fieldName})` : decl.fieldName}\n value={key}\n onChange={(event) =>\n setDraft((current) => ({ ...current, [decl.fieldName]: event.target.value }))\n }\n helperText={hint(key)}\n // `displayEmpty`, or the \"saves nowhere\" choice renders as\n // a blank control and reads as a field left unset; the label\n // shrinks with it so the two do not overlap.\n slotProps={{\n select: { displayEmpty: true },\n inputLabel: { shrink: true },\n }}\n fullWidth\n >\n <MenuItem value={NONE}>{'Not saved to a contact field'}</MenuItem>\n {orphanOption(key)}\n {active.map((definition) => (\n <MenuItem key={definition.key} value={definition.key}>\n {`${definition.label} · ${CONTACT_FIELD_TYPE_LABELS[definition.type]}`}\n </MenuItem>\n ))}\n </TextField>\n )\n })}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The sender’s name and email are read from fields named name and email, ' +\n 'so they never need mapping.'}\n </Typography>\n </>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nFormContactFieldsCard.displayName = 'FormContactFieldsCard'\n\nexport default FormContactFieldsCard\n"],"names":["CONTACT_FIELD_TYPE_LABELS","pluginDocsHelp","withContactFieldMapping","useContactFieldDefinitions","CardDisplay","useSnackbar","useOrgDataScope","Button","MenuItem","Stack","TextField","Typography","useCallback","useMemo","useState","NONE","FormContactFieldsCard","props","hostId","fields","loading","saveFields","enqueueSnackbar","scope","ready","scopeReady","active","definitions","draft","setDraft","saving","setSaving","storedKey","decl","contactFieldKey","shownKey","fieldName","changed","filter","activeByKey","Map","map","definition","key","handleSave","length","next","reduce","decls","variant","persist","error","console","allowDuplicate","hint","undefined","get","some","entry","type","String","currency","toUpperCase","options","join","orphanOption","has","retired","value","settled","anyMapped","mapping","Boolean","header","help","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","size","onClick","disabled","color","select","label","onChange","event","current","target","helperText","slotProps","displayEmpty","inputLabel","shrink","fullWidth","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,yBAAyB,EAEzBC,cAAc,EACdC,uBAAuB,QAClB,eAAc;AACrB,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAe;AAC9E,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAgBtD,2EAA2E,GAC3E,MAAMC,OAAO;AAEb;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,SAASC,sBAAsBC,KAAiC;;IACrE,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,UAAU,EAAE,GAAGJ;IAChD,MAAM,EAAEK,eAAe,EAAE,GAAGjB;IAC5B,MAAM,EAAEkB,KAAK,EAAEC,OAAOC,UAAU,EAAE,GAAGnB,gBAAgB;QAAEY;IAAO;IAC9D,MAAM,EAAEQ,MAAM,EAAEC,WAAW,EAAEH,KAAK,EAAE,GAAGrB,mCAA2BoB,yBAAAA,KAAO,CAAC,EAAE,mBAAI;IAEhF;;;;GAIC,GACD,MAAM,CAACK,OAAOC,SAAS,GAAGf,SAAiC,CAAC;IAC5D,MAAM,CAACgB,QAAQC,UAAU,GAAGjB,SAAS;IAErC,MAAMkB,YAAYpB,YAAY,CAACqB;YAAwBA;gBAAAA,wBAAAA,KAAKC,eAAe,YAApBD,wBAAwBlB;OAAM,EAAE;IACvF,MAAMoB,WAAWvB,YACf,CAACqB,OAAyBA,KAAKG,SAAS,IAAIR,QAAQA,KAAK,CAACK,KAAKG,SAAS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C,GAAG,EAAEvF,yBAAyB,CAAC0C,WAAWiB,IAAI,CAAC,EAAE;uCADzDjB,WAAWC,GAAG;;2BArB1BV,KAAKG,SAAS;oBA2BzB;kCACA,KAACzB;wBAAWsC,SAAQ;wBAAUoC,OAAM;kCACjC,4EACC;;;;;;AAOhB;AACArE,sBAAsBkF,WAAW,GAAG;AAEpC,eAAelF,sBAAqB"}
|
|
@@ -78,6 +78,13 @@ export interface ContactQueryReader {
|
|
|
78
78
|
* level, where there is no scope clause.
|
|
79
79
|
*/
|
|
80
80
|
foldsScope: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* How each custom CURRENCY column reads a typed amount, by column
|
|
83
|
+
* (AGL-3756): its `=` is typed in major units and asked as the minor units
|
|
84
|
+
* the facet key holds, or `null` when it is not one amount. The web side
|
|
85
|
+
* builds it (`contactCustomAmountReaders`), so this module stays pure.
|
|
86
|
+
*/
|
|
87
|
+
amounts?: Readonly<Record<string, (typed: string) => number | null>>;
|
|
81
88
|
}
|
|
82
89
|
/**
|
|
83
90
|
* One grid clause as the clause the Contacts query asks — see the block at
|
|
@@ -268,6 +268,9 @@ import { CRM_LIST_SEARCH, crmAnyOf, crmClauseValues } from "../model/crm-list-qu
|
|
|
268
268
|
const path = `custom.${definition.key}`;
|
|
269
269
|
switch(definition.type){
|
|
270
270
|
case 'number':
|
|
271
|
+
// An amount is typed in major units and asked as the minor units it
|
|
272
|
+
// is stored in — `ContactQueryReader.currencies` (AGL-3756).
|
|
273
|
+
case 'currency':
|
|
271
274
|
return {
|
|
272
275
|
column,
|
|
273
276
|
kind: 'number',
|
|
@@ -522,6 +525,7 @@ export const CONTACT_LIST_DECLARATION = {
|
|
|
522
525
|
* name, never matched over the rows a page loaded.
|
|
523
526
|
*/ export function contactQueryClause(clause, reader) {
|
|
524
527
|
var _reader_groupId;
|
|
528
|
+
var _reader_amounts;
|
|
525
529
|
if (AS_STORED.has(clause.field)) {
|
|
526
530
|
if (clause.field === 'formIds' && !reader.foldsScope) return {
|
|
527
531
|
refused: LIMITED_ACCESS
|
|
@@ -563,8 +567,11 @@ export const CONTACT_LIST_DECLARATION = {
|
|
|
563
567
|
};
|
|
564
568
|
}
|
|
565
569
|
const keys = [];
|
|
570
|
+
const amount = (_reader_amounts = reader.amounts) == null ? void 0 : _reader_amounts[clause.field];
|
|
566
571
|
for (const value of crmClauseValues(clause)){
|
|
567
|
-
|
|
572
|
+
var _amount;
|
|
573
|
+
const asked = clause.op !== '=' ? value : amount ? (_amount = amount(value)) != null ? _amount : Number.NaN : Number(value);
|
|
574
|
+
const key = crmFacetKeyValue(asked);
|
|
568
575
|
if (key === null) return {
|
|
569
576
|
refused: 'no value yet'
|
|
570
577
|
};
|