@aglyn/plugins-crm 1.0.0-beta.200 → 1.0.0-beta.202
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/activity-list.d.ts +36 -5
- package/src/lib/components/activity-list.js +159 -137
- package/src/lib/components/activity-list.js.map +1 -1
- package/src/lib/components/activity-timeline.d.ts +84 -0
- package/src/lib/components/activity-timeline.js +224 -0
- package/src/lib/components/activity-timeline.js.map +1 -0
- package/src/lib/components/company-properties-card.js +53 -36
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-associations-card.d.ts +3 -2
- package/src/lib/components/contact-associations-card.js +12 -12
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.d.ts +4 -3
- package/src/lib/components/contact-detail-page.js +4 -10
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +21 -4
- package/src/lib/components/contact-properties-card.js +129 -29
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-timeline-card.d.ts +12 -6
- package/src/lib/components/contact-timeline-card.js +132 -174
- package/src/lib/components/contact-timeline-card.js.map +1 -1
- package/src/lib/components/contacts-section.js +197 -198
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-email-state-chip.js +4 -1
- package/src/lib/components/crm-email-state-chip.js.map +1 -1
- package/src/lib/components/deal-products-card.js +15 -13
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/deal-properties-card.js +7 -0
- package/src/lib/components/deal-properties-card.js.map +1 -1
- package/src/lib/components/deal-stage-card.js +31 -29
- package/src/lib/components/deal-stage-card.js.map +1 -1
- package/src/lib/components/deals-section.js +9 -14
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.d.ts +4 -0
- package/src/lib/components/fields-section.js +368 -154
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/form-contact-fields-card.js +24 -20
- package/src/lib/components/form-contact-fields-card.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.d.ts +1 -1
- package/src/lib/components/lead-campaigns-card.js +32 -35
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-properties-card.d.ts +14 -6
- package/src/lib/components/lead-properties-card.js +317 -313
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/lead-surfaces-note.js +13 -2
- package/src/lib/components/lead-surfaces-note.js.map +1 -1
- package/src/lib/components/linked-deals-card.js +12 -10
- package/src/lib/components/linked-deals-card.js.map +1 -1
- package/src/lib/components/recent-activity-feed.d.ts +12 -8
- package/src/lib/components/recent-activity-feed.js +54 -29
- package/src/lib/components/recent-activity-feed.js.map +1 -1
- package/src/lib/components/record-activity-card.d.ts +4 -2
- package/src/lib/components/record-activity-card.js +29 -11
- package/src/lib/components/record-activity-card.js.map +1 -1
- package/src/lib/components/reports/activity-card.js +18 -12
- package/src/lib/components/reports/activity-card.js.map +1 -1
- package/src/lib/components/reports/lead-funnel-card.js +47 -37
- package/src/lib/components/reports/lead-funnel-card.js.map +1 -1
- package/src/lib/components/reports/pipeline-card.js +22 -16
- package/src/lib/components/reports/pipeline-card.js.map +1 -1
- package/src/lib/components/reports/report-export.d.ts +4 -11
- package/src/lib/components/reports/report-export.js +16 -33
- package/src/lib/components/reports/report-export.js.map +1 -1
- package/src/lib/components/reports/source-conversion-card.js +18 -12
- package/src/lib/components/reports/source-conversion-card.js.map +1 -1
- package/src/lib/components/reports/tasks-card.js +35 -25
- package/src/lib/components/reports/tasks-card.js.map +1 -1
- package/src/lib/components/tasks-section.js +23 -23
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/constants/field-list-query.d.ts +23 -0
- package/src/lib/constants/field-list-query.js +80 -0
- package/src/lib/constants/field-list-query.js.map +1 -0
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/capture-contact.js +7 -5
- package/src/lib/server/capture-contact.js.map +1 -1
- package/src/lib/components/contact-custom-fields-card.d.ts +0 -39
- package/src/lib/components/contact-custom-fields-card.js +0 -204
- package/src/lib/components/contact-custom-fields-card.js.map +0 -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 {\n CONTACT_FIELD_TYPE_LABELS,\n type ConsolePluginPageProps,\n createResourceUid,\n CRM_COLLECTIONS,\n CRM_FIELD_OBJECT_LABELS,\n CRM_FIELD_OBJECTS,\n type CrmFieldObject,\n isCrmFieldObject,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.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 RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n IconButton,\n Stack,\n Tab,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Tabs,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n doc,\n setDoc,\n updateDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport {\n type ContactFieldDefinitionDoc,\n useContactFieldDefinitions,\n} from '../hooks/use-contact-field-definitions'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport ContactFieldDrawer, { type ContactFieldDraft } from './contact-field-drawer'\nimport { LeadSourceValuesCard } from './lead-source-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/** 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/**\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 *\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 [object, setObject] = useState<CrmFieldObject>('contact')\n const { definitions, ready, fromCache } = useContactFieldDefinitions(orgId, object)\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 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 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 const rowActions = (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\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 <Button size=\"small\" onClick={() => void recomputeNextActivity()} disabled={recomputing}>\n {recomputing ? 'Recomputing…' : 'Recompute next activity'}\n </Button>\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n <Tabs\n value={object}\n onChange={(_event, next) => {\n if (isCrmFieldObject(next)) setObject(next)\n }}\n aria-label=\"Fields by record\"\n >\n {CRM_FIELD_OBJECTS.map((entry) => (\n <Tab key={entry} value={entry} label={CRM_FIELD_OBJECT_LABELS[entry]} />\n ))}\n </Tabs>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${OBJECT_INTRO[object]} Fields are shared across every site in this ` +\n 'organization, like the records themselves.'}\n </Typography>\n {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 <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell sx={{ width: 96 }}>{'Order'}</TableCell>\n <TableCell>{'Field'}</TableCell>\n <TableCell>{'Key'}</TableCell>\n <TableCell>{'Type'}</TableCell>\n <TableCell>{'Required'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {definitions.map((definition, index) => (\n <TableRow\n key={definition.$id}\n hover\n sx={definition.retiredAt ? { opacity: 0.6 } : undefined}\n >\n <TableCell>\n <Stack direction=\"row\" spacing={0}>\n <IconButton\n size=\"small\"\n disabled={index === 0 || Boolean(busyId)}\n onClick={() => void move(definition, -1)}\n >\n <MdiIcon path={mdiArrowUp.path} size={0.7} />\n <SrOnly>{`Move ${definition.label} up`}</SrOnly>\n </IconButton>\n <IconButton\n size=\"small\"\n disabled={index === definitions.length - 1 || Boolean(busyId)}\n onClick={() => void move(definition, 1)}\n >\n <MdiIcon path={mdiArrowDown.path} size={0.7} />\n <SrOnly>{`Move ${definition.label} down`}</SrOnly>\n </IconButton>\n </Stack>\n </TableCell>\n <TableCell>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ flexWrap: 'wrap', alignItems: 'center' }}\n >\n <Typography variant=\"body2\">{definition.label}</Typography>\n {definition.retiredAt ? (\n <Chip size=\"small\" variant=\"outlined\" color=\"warning\" label=\"Retired\" />\n ) : null}\n </Stack>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ fontFamily: 'monospace' }}>\n {definition.key}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\">\n {CONTACT_FIELD_TYPE_LABELS[definition.type] ?? definition.type}\n {definition.type === 'select' && definition.options?.length\n ? ` · ${definition.options.length} choices`\n : ''}\n </Typography>\n </TableCell>\n <TableCell>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {definition.required ? 'Yes' : '—'}\n </Typography>\n </TableCell>\n <TableCell align=\"right\" sx={{ width: 56 }}>\n <RowActionsMenu label={definition.label} items={rowActions(definition)} />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n {definitions.length ? (\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 Lead source (AGL-3298) — a standard lead field whose CHOICES are the\n org's, Salesforce's Lead Source picklist — kept on the Leads tab\n beside the custom lead fields.\n */}\n {object === 'lead' && scope ? (\n <LeadSourceValuesCard hostId={hostId} orgId={orgId} createHostId={createHostId} />\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":["CONTACT_FIELD_TYPE_LABELS","createResourceUid","CRM_COLLECTIONS","CRM_FIELD_OBJECT_LABELS","CRM_FIELD_OBJECTS","isCrmFieldObject","newResourceScopeFields","ORG_SCOPE_TOKEN","pluginDocsHelp","EmptyStateComponent","mdiArchiveArrowUpOutline","mdiArchiveOutline","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","mdiPencilOutline","CardDisplay","MdiIcon","SrOnly","useConfirmationContext","RowActionsMenu","ScrollTable","useSnackbar","useFirestore","useUser","writeGuardedBySeed","Button","Chip","IconButton","Stack","Tab","TableBody","TableCell","TableHead","TableRow","Tabs","Typography","collection","deleteDoc","doc","setDoc","updateDoc","writeBatch","useCallback","useState","useContactFieldDefinitions","useCrmScope","ContactFieldDrawer","LeadSourceValuesCard","recomputeAllCrmNextActivity","crmTaskCallScope","OBJECT_INTRO","contact","company","deal","lead","OBJECT_NOUN","ContactsFieldsSection","props","hostId","org","firestore","enqueueSnackbar","confirm","scope","ready","scopeReady","createHostId","orgId","object","setObject","definitions","fromCache","noun","data","user","recomputing","setRecomputing","recomputeNextActivity","callScope","confirmed","title","description","confirmationText","then","catch","result","records","toLocaleString","tasks","truncated","variant","cause","Error","message","drawerOpen","setDrawerOpen","editing","setEditing","busyId","setBusyId","fieldRef","id","contactFields","openCreate","openEdit","definition","handleSubmit","draft","now","Date","verdict","subject","$id","label","type","options","required","updatedAt","ok","persist","order","reduce","highest","Math","max","Number","key","retiredAt","createdAt","move","direction","index","findIndex","entry","target","length","next","batch","forEach","position","update","commit","error","console","allowDuplicate","toggleRetired","accepted","handleDelete","confirmationButtonProps","color","rowActions","icon","path","size","onClick","destructive","disabled","Boolean","disabledReason","undefined","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","spacing","sx","alignItems","value","onChange","_event","aria-label","map","width","align","hover","opacity","flexWrap","fontFamily","items","open","onClose","takenKeys","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,yBAAyB,EAEzBC,iBAAiB,EACjBC,eAAe,EACfC,uBAAuB,EACvBC,iBAAiB,EAEjBC,gBAAgB,EAChBC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,QACT,eAAc;AACrB,OAAOC,yBAAyB,wDAAuD;AACvF,SACEC,wBAAwB,EACxBC,iBAAiB,EACjBC,YAAY,EACZC,UAAU,EACVC,gBAAgB,EAChBC,gBAAgB,QACX,yBAAwB;AAC/B,SACEC,WAAW,EACXC,OAAO,EACPC,MAAM,EACNC,sBAAsB,QACjB,uBAAsB;AAC7B,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AACvC,SACEC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,IAAI,EACJC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,SAAS,EACTC,GAAG,EACHC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAEEC,0BAA0B,QACrB,4CAAwC;AAC/C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,OAAOC,wBAAoD,4BAAwB;AACnF,SAASC,oBAAoB,QAAQ,+BAA2B;AAChE,SAASC,2BAA2B,QAAQ,gCAA4B;AACxE,SAASC,gBAAgB,QAAQ,0BAAsB;AAIvD,2DAA2D,GAC3D,MAAM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,GAAG,CAAC,CAACtE,aAAeA,WAAWqB,GAAG;gBACzD4D,UAAUhF;;;;AAIlB;AACAlD,sBAAsBmI,WAAW,GAAG;AAEpC,eAAenI,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 {\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 CRM_FIELD_OBJECT_LABELS,\n CRM_FIELD_OBJECTS,\n type CrmFieldObject,\n isCrmFieldObject,\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 { LeadSourceValuesCard } from './lead-source-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/** 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 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 [object, setObject] = useState<CrmFieldObject>('contact')\n const { definitions, ready, fromCache } = useContactFieldDefinitions(orgId, object)\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 <Button size=\"small\" onClick={() => void recomputeNextActivity()} disabled={recomputing}>\n {recomputing ? 'Recomputing…' : 'Recompute next activity'}\n </Button>\n <Button variant=\"contained\" onClick={openCreate}>\n {'New field'}\n </Button>\n </Stack>\n ) : null,\n }}\n >\n <Stack spacing={2}>\n <Tabs\n value={object}\n onChange={(_event, next) => {\n if (isCrmFieldObject(next)) setObject(next)\n }}\n aria-label=\"Fields by record\"\n >\n {CRM_FIELD_OBJECTS.map((entry) => (\n <Tab key={entry} value={entry} label={CRM_FIELD_OBJECT_LABELS[entry]} />\n ))}\n </Tabs>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${OBJECT_INTRO[object]} Fields are shared across every site in this ` +\n 'organization, like the records themselves.'}\n </Typography>\n {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 ? (\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 Lead source (AGL-3298) — a standard lead field whose CHOICES are the\n org's, Salesforce's Lead Source picklist — kept on the Leads tab\n beside the custom lead fields.\n */}\n {object === 'lead' && scope ? (\n <LeadSourceValuesCard hostId={hostId} orgId={orgId} createHostId={createHostId} />\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":["CONTACT_FIELD_TYPE_LABELS","CONTACT_FIELD_TYPES","CONTACT_FIELDS_MAX_PER_ORG","createResourceUid","CRM_COLLECTIONS","crmFieldListFields","CRM_FIELD_OBJECT_LABELS","CRM_FIELD_OBJECTS","isCrmFieldObject","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","LeadSourceValuesCard","recomputeAllCrmNextActivity","crmTaskCallScope","OBJECT_INTRO","contact","company","deal","lead","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","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","setObject","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","_event","open","onClose","takenKeys","onSubmit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,yBAAyB,EACzBC,mBAAmB,EACnBC,0BAA0B,EAE1BC,iBAAiB,EACjBC,eAAe,EACfC,kBAAkB,EAClBC,uBAAuB,EACvBC,iBAA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tC,sBAAsBD,WAAW,GAAG;AAEpC,eAAeC,sBAAqB"}
|
|
@@ -153,6 +153,8 @@ import { useCallback, useMemo, useState } from "react";
|
|
|
153
153
|
};
|
|
154
154
|
const settled = scopeReady && !loading && (!scope || ready);
|
|
155
155
|
const anyMapped = fields.some((decl)=>decl.contactFieldKey);
|
|
156
|
+
// The mapping is offered once there is something to map, and saved from the header.
|
|
157
|
+
const mapping = settled && Boolean(scope) && fields.length > 0 && (active.length > 0 || anyMapped);
|
|
156
158
|
return /*#__PURE__*/ _jsx(CardDisplay, {
|
|
157
159
|
header: "Saves to contact fields",
|
|
158
160
|
help: pluginDocsHelp('contactFields', {
|
|
@@ -160,6 +162,28 @@ import { useCallback, useMemo, useState } from "react";
|
|
|
160
162
|
}),
|
|
161
163
|
contentGutterX: true,
|
|
162
164
|
contentGutterY: true,
|
|
165
|
+
HeaderProps: {
|
|
166
|
+
action: mapping ? /*#__PURE__*/ _jsxs(Stack, {
|
|
167
|
+
direction: "row",
|
|
168
|
+
spacing: 1,
|
|
169
|
+
children: [
|
|
170
|
+
changed.length ? /*#__PURE__*/ _jsx(Button, {
|
|
171
|
+
size: "small",
|
|
172
|
+
onClick: ()=>setDraft({}),
|
|
173
|
+
disabled: saving,
|
|
174
|
+
children: 'Discard'
|
|
175
|
+
}) : null,
|
|
176
|
+
/*#__PURE__*/ _jsx(Button, {
|
|
177
|
+
variant: "contained",
|
|
178
|
+
color: "primary",
|
|
179
|
+
size: "small",
|
|
180
|
+
disabled: !changed.length || saving,
|
|
181
|
+
onClick: handleSave,
|
|
182
|
+
children: 'Save'
|
|
183
|
+
})
|
|
184
|
+
]
|
|
185
|
+
}) : null
|
|
186
|
+
},
|
|
163
187
|
children: /*#__PURE__*/ _jsx(Stack, {
|
|
164
188
|
spacing: 2,
|
|
165
189
|
children: !settled ? null : !scope ? /*#__PURE__*/ _jsx(Typography, {
|
|
@@ -221,26 +245,6 @@ import { useCallback, useMemo, useState } from "react";
|
|
|
221
245
|
variant: "caption",
|
|
222
246
|
color: "text.secondary",
|
|
223
247
|
children: 'The sender’s name and email are read from fields named name and email, ' + 'so they never need mapping.'
|
|
224
|
-
}),
|
|
225
|
-
/*#__PURE__*/ _jsxs(Stack, {
|
|
226
|
-
direction: "row",
|
|
227
|
-
spacing: 1,
|
|
228
|
-
children: [
|
|
229
|
-
/*#__PURE__*/ _jsx(Button, {
|
|
230
|
-
variant: "contained",
|
|
231
|
-
color: "primary",
|
|
232
|
-
size: "small",
|
|
233
|
-
disabled: !changed.length || saving,
|
|
234
|
-
onClick: handleSave,
|
|
235
|
-
children: 'Save'
|
|
236
|
-
}),
|
|
237
|
-
changed.length ? /*#__PURE__*/ _jsx(Button, {
|
|
238
|
-
size: "small",
|
|
239
|
-
onClick: ()=>setDraft({}),
|
|
240
|
-
disabled: saving,
|
|
241
|
-
children: 'Discard'
|
|
242
|
-
}) : null
|
|
243
|
-
]
|
|
244
248
|
})
|
|
245
249
|
]
|
|
246
250
|
})
|
|
@@ -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\n return (\n <CardDisplay\n header=\"Saves to contact fields\"\n help={pluginDocsHelp('contactFields', { anchor: '#save-a-form-field' })}\n contentGutterX\n contentGutterY\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 <Stack direction=\"row\" spacing={1}>\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 {changed.length ? (\n <Button size=\"small\" onClick={() => setDraft({})} disabled={saving}>\n {'Discard'}\n </Button>\n ) : null}\n </Stack>\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","header","help","anchor","contentGutterX","contentGutterY","spacing","color","select","size","label","onChange","event","current","target","helperText","slotProps","displayEmpty","inputLabel","shrink","fullWidth","direction","disabled","onClick","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,QA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KAAK;;4BAE3EiB,YAAY5B,KAAKX;4BACjB,2DAA2D;4BAC3D,6DAA6D;4BAC7D,6CAA6C;4BAC7CwC,WAAW;gCACTR,QAAQ;oCAAES,cAAc;gCAAK;gCAC7BC,YAAY;oCAAEC,QAAQ;gCAAK;4BAC7B;4BACAC,SAAS;;8CAET,KAAC/E;oCAASyD,OAAOlD;8CAAO;;gCACvB+C,aAAanB;gCACbjB,OAAOe,GAAG,CAAC,CAACC,2BACX,KAAClC;wCAA8ByD,OAAOvB,WAAWC,GAAG;kDACjD,GAAGD,WAAWmC,KAAK,CAAC,GAAG,EAAE7E,yBAAyB,CAAC0C,WAAWiB,IAAI,CAAC,EAAE;uCADzDjB,WAAWC,GAAG;;2BArB1BV,KAAKG,SAAS;oBA2BzB;kCACA,KAACzB;wBAAWsC,SAAQ;wBAAUyB,OAAM;kCACjC,4EACC;;kCAEJ,MAACjE;wBAAM+E,WAAU;wBAAMf,SAAS;;0CAC9B,KAAClE;gCACC0C,SAAQ;gCACRyB,OAAM;gCACNE,MAAK;gCACLa,UAAU,CAACpD,QAAQQ,MAAM,IAAIf;gCAC7B4D,SAAS9C;0CAER;;4BAEFP,QAAQQ,MAAM,iBACb,KAACtC;gCAAOqE,MAAK;gCAAQc,SAAS,IAAM7D,SAAS,CAAC;gCAAI4D,UAAU3D;0CACzD;iCAED;;;;;;;AAOlB;AACAd,sBAAsB2E,WAAW,GAAG;AAEpC,eAAe3E,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 '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,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,eAA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W0C,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"}
|
|
@@ -52,7 +52,7 @@ export interface LeadCampaignsCardProps {
|
|
|
52
52
|
* `hosts/{hostId}/leads`, as the properties card writes status and notes —
|
|
53
53
|
* guarded by the seed like every draft edited over a cached read, and
|
|
54
54
|
* `campaignMembershipUnchanged` keeps Save quiet while the picker only
|
|
55
|
-
* reorders what is stored.
|
|
55
|
+
* reorders what is stored. **Save filing** sits in the card header.
|
|
56
56
|
*
|
|
57
57
|
* It is FILING, not audience: the helper says so, in the sentence the
|
|
58
58
|
* contact card uses, because a reader who finds a campaign picker on a
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ 'use client';
|
|
17
17
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
-
import { jsx as _jsx
|
|
18
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
19
19
|
import { campaignMembershipUnchanged, campaignMembershipValue, pluginDocsHelp, readCampaignIds } from "@aglyn/aglyn";
|
|
20
20
|
import CampaignPicker from "@aglyn/shared-ui-email-campaigns/components/campaign-picker.component";
|
|
21
21
|
import { CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
@@ -58,7 +58,7 @@ import { crmClientListFields } from "../model/crm-list-query.js";
|
|
|
58
58
|
* `hosts/{hostId}/leads`, as the properties card writes status and notes —
|
|
59
59
|
* guarded by the seed like every draft edited over a cached read, and
|
|
60
60
|
* `campaignMembershipUnchanged` keeps Save quiet while the picker only
|
|
61
|
-
* reorders what is stored.
|
|
61
|
+
* reorders what is stored. **Save filing** sits in the card header.
|
|
62
62
|
*
|
|
63
63
|
* It is FILING, not audience: the helper says so, in the sentence the
|
|
64
64
|
* contact card uses, because a reader who finds a campaign picker on a
|
|
@@ -138,40 +138,37 @@ import { crmClientListFields } from "../model/crm-list-query.js";
|
|
|
138
138
|
}),
|
|
139
139
|
contentGutterX: true,
|
|
140
140
|
contentGutterY: true,
|
|
141
|
-
|
|
141
|
+
HeaderProps: {
|
|
142
|
+
action: empty ? null : /*#__PURE__*/ _jsx(Button, {
|
|
143
|
+
size: "small",
|
|
144
|
+
variant: "outlined",
|
|
145
|
+
disabled: saving || unchanged,
|
|
146
|
+
onClick: ()=>void save().catch((error)=>{
|
|
147
|
+
console.error(error);
|
|
148
|
+
enqueueSnackbar(error instanceof Error && error.message ? error.message : 'An error has occurred', {
|
|
149
|
+
variant: 'error',
|
|
150
|
+
allowDuplicate: true
|
|
151
|
+
});
|
|
152
|
+
setSaving(false);
|
|
153
|
+
}),
|
|
154
|
+
children: saving ? 'Saving…' : 'Save filing'
|
|
155
|
+
})
|
|
156
|
+
},
|
|
157
|
+
children: /*#__PURE__*/ _jsx(Stack, {
|
|
142
158
|
spacing: 2,
|
|
143
|
-
children:
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}),
|
|
157
|
-
empty ? null : /*#__PURE__*/ _jsx(Stack, {
|
|
158
|
-
direction: "row",
|
|
159
|
-
children: /*#__PURE__*/ _jsx(Button, {
|
|
160
|
-
size: "small",
|
|
161
|
-
variant: "outlined",
|
|
162
|
-
disabled: saving || unchanged,
|
|
163
|
-
onClick: ()=>void save().catch((error)=>{
|
|
164
|
-
console.error(error);
|
|
165
|
-
enqueueSnackbar(error instanceof Error && error.message ? error.message : 'An error has occurred', {
|
|
166
|
-
variant: 'error',
|
|
167
|
-
allowDuplicate: true
|
|
168
|
-
});
|
|
169
|
-
setSaving(false);
|
|
170
|
-
}),
|
|
171
|
-
children: saving ? 'Saving…' : 'Save filing'
|
|
172
|
-
})
|
|
173
|
-
})
|
|
174
|
-
]
|
|
159
|
+
children: /*#__PURE__*/ _jsx(CampaignPicker, {
|
|
160
|
+
options: options,
|
|
161
|
+
value: selected,
|
|
162
|
+
onChange: (next)=>{
|
|
163
|
+
setSelected(next);
|
|
164
|
+
setDirty(true);
|
|
165
|
+
},
|
|
166
|
+
label: "Filed under campaigns",
|
|
167
|
+
helperText: LEAD_CAMPAIGNS_HELPER_TEXT,
|
|
168
|
+
disabled: saving,
|
|
169
|
+
empty: empty,
|
|
170
|
+
emptyText: "There are no campaigns to file this lead under yet. Create one from Marketing."
|
|
171
|
+
})
|
|
175
172
|
})
|
|
176
173
|
});
|
|
177
174
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/lead-campaigns-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 campaignMembershipUnchanged,\n campaignMembershipValue,\n pluginDocsHelp,\n readCampaignIds,\n} from '@aglyn/aglyn'\nimport CampaignPicker, {\n type CampaignPickerOption,\n} from '@aglyn/shared-ui-email-campaigns/components/campaign-picker.component'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n type FirestoreDocStatus,\n useFirestore,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Stack } from '@mui/material'\nimport { doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { crmClientListFields } from '../model/crm-list-query'\n\n/** The list field a campaign filing moves (AGL-3321). */\nconst LEAD_CAMPAIGN_LIST_FIELDS = ['scopedCampaignIds'] as const\n\n/** The helper line under the picker — the contact card's, word for word. */\nexport const LEAD_CAMPAIGNS_HELPER_TEXT =\n 'Your own filing. It never adds anyone to a send — a campaign mails its lists.'\n\n/**\n * The campaigns a lead is filed under, as NAMES for the record header.\n *\n * Resolved from the site's containers; an id with no live container — a\n * campaign the console deleted, or one still loading — is left out rather\n * than shown, because a document id on a chip tells a reader nothing and\n * looks like a fault. The picker below keeps such an id visible as itself,\n * so the filing is never silently lost; the header only ever names.\n */\nexport function leadCampaignNames(\n lead: Record<string, unknown> | null | undefined,\n options: readonly CampaignPickerOption[],\n): string[] {\n const labels = new Map(options.map((option) => [option.value, option.label]))\n return readCampaignIds(lead)\n .map((id) => labels.get(id))\n .filter((name): name is string => Boolean(name))\n}\n\nexport interface LeadCampaignsCardProps {\n /**\n * The lead's own site, or `null` at the organization level for a lead no\n * site captured (AGL-3278). Read for the org root alone — the containers\n * themselves are handed down as `options` — so the card serves both\n * levels; the org-level mount answers the same org without a site.\n */\n hostId: string | null\n leadId: string\n lead: Record<string, unknown>\n leadStatus: FirestoreDocStatus\n /** The listener has not confirmed this document with the server yet. */\n fromCache: boolean\n /** The site's campaigns, read once by the page for this card and the header. */\n options: readonly CampaignPickerOption[]\n /** The campaign read has answered — false while it settles. */\n optionsReady: boolean\n /**\n * What a saved filing changed, once it has landed: the ids added to and\n * removed from the lead's membership. The page files the activity\n * entries (AGL-3274); the card only knows the document.\n */\n onFiled?: (change: { added: string[]; removed: string[] }) => void\n}\n\n/**\n * WHICH CAMPAIGNS THIS LEAD IS FILED UNDER (AGL-3274).\n *\n * The contact's Relationship card has carried this picker since AGL-2596;\n * the lead's page had none, so a lead filed under a campaign by the New\n * lead drawer, the bulk bar or a sequence's enroll showed nothing of it —\n * the one field on the record the reader had no way to see or change.\n *\n * The same control, the same value helper, the same helper line. The save\n * is the lead's own client door — a one-field `update` on\n * `hosts/{hostId}/leads`, as the properties card writes status and notes —\n * guarded by the seed like every draft edited over a cached read, and\n * `campaignMembershipUnchanged` keeps Save quiet while the picker only\n * reorders what is stored.\n *\n * It is FILING, not audience: the helper says so, in the sentence the\n * contact card uses, because a reader who finds a campaign picker on a\n * person's page assumes the opposite.\n */\nexport function LeadCampaignsCard(props: LeadCampaignsCardProps) {\n const { hostId, leadId, lead, leadStatus, fromCache, options, optionsReady, onFiled } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const stored = readCampaignIds(lead)\n const [selected, setSelected] = useState<string[]>(stored)\n const [dirty, setDirty] = useState(false)\n const [saving, setSaving] = useState(false)\n // A newer membership from the server replaces an UNEDITED selection — a\n // sequence's enroll or a bulk add lands while the page is open — and an\n // edited one is the reader's, decided by the guard on save.\n const storedKey = stored.join(',')\n useEffect(() => {\n if (!dirty) setSelected(stored)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storedKey, dirty])\n\n const unchanged = campaignMembershipUnchanged(stored, selected)\n const empty = optionsReady && !options.length\n\n const save = async () => {\n if (unchanged) return\n if (!orgId) {\n enqueueSnackbar('Still loading this workspace — try again in a moment.', {\n variant: 'warning',\n persist: false,\n })\n return\n }\n setSaving(true)\n const next = campaignMembershipValue(selected)\n const verdict = await writeGuardedBySeed(\n { subject: 'lead', fromCache, unreadable: leadStatus === 'error' },\n async () => {\n await updateDoc(doc(firestore, 'orgs', orgId, 'leads', leadId), {\n campaignIds: next,\n // The Leads list's Campaign filter under a site reads these\n // (AGL-3321), from the lead with its new campaigns.\n ...crmClientListFields('leads', lead, { campaignIds: next }, LEAD_CAMPAIGN_LIST_FIELDS),\n updatedAt: serverTimestamp(),\n })\n },\n )\n setSaving(false)\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message ?? 'The filing could not be saved.', { variant: 'warning' })\n return\n }\n setDirty(false)\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n onFiled?.({\n added: next.filter((id) => !stored.includes(id)),\n removed: stored.filter((id) => !next.includes(id)),\n })\n }\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('crmLeads', { anchor: '#a-leads-page' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <CampaignPicker\n options={options}\n value={selected}\n onChange={(next) => {\n setSelected(next)\n setDirty(true)\n }}\n label=\"Filed under campaigns\"\n helperText={LEAD_CAMPAIGNS_HELPER_TEXT}\n disabled={saving}\n empty={empty}\n emptyText=\"There are no campaigns to file this lead under yet. Create one from Marketing.\"\n />\n {empty ? null : (\n <Stack direction=\"row\">\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || unchanged}\n onClick={() => void save().catch((error: unknown) => {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n setSaving(false)\n })}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n </Stack>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nLeadCampaignsCard.displayName = 'LeadCampaignsCard'\n\nexport default LeadCampaignsCard\n"],"names":["campaignMembershipUnchanged","campaignMembershipValue","pluginDocsHelp","readCampaignIds","CampaignPicker","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Stack","doc","serverTimestamp","updateDoc","useEffect","useState","useCrmScope","crmClientListFields","LEAD_CAMPAIGN_LIST_FIELDS","LEAD_CAMPAIGNS_HELPER_TEXT","leadCampaignNames","lead","options","labels","Map","map","option","value","label","id","get","filter","name","Boolean","LeadCampaignsCard","props","hostId","leadId","leadStatus","fromCache","optionsReady","onFiled","orgId","firestore","enqueueSnackbar","stored","selected","setSelected","dirty","setDirty","saving","setSaving","storedKey","join","unchanged","empty","length","save","variant","persist","next","verdict","subject","unreadable","campaignIds","updatedAt","ok","message","added","includes","removed","header","help","anchor","contentGutterX","contentGutterY","spacing","onChange","helperText","disabled","emptyText","direction","size","onClick","catch","error","console","Error","allowDuplicate","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,2BAA2B,EAC3BC,uBAAuB,EACvBC,cAAc,EACdC,eAAe,QACV,eAAc;AACrB,OAAOC,oBAEA,wEAAuE;AAC9E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAEEC,YAAY,EACZC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,KAAK,QAAQ,gBAAe;AAC7C,SAASC,GAAG,EAAEC,eAAe,EAAEC,SAAS,QAAQ,qBAAoB;AACpE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D,uDAAuD,GACvD,MAAMC,4BAA4B;IAAC;CAAoB;AAEvD,0EAA0E,GAC1E,OAAO,MAAMC,6BACX,gFAA+E;AAEjF;;;;;;;;CAQC,GACD,OAAO,SAASC,kBACdC,IAAgD,EAChDC,OAAwC;IAExC,MAAMC,SAAS,IAAIC,IAAIF,QAAQG,GAAG,CAAC,CAACC,SAAW;YAACA,OAAOC,KAAK;YAAED,OAAOE,KAAK;SAAC;IAC3E,OAAOzB,gBAAgBkB,MACpBI,GAAG,CAAC,CAACI,KAAON,OAAOO,GAAG,CAACD,KACvBE,MAAM,CAAC,CAACC,OAAyBC,QAAQD;AAC9C;AA2BA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASE,kBAAkBC,KAA6B;IAC7D,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAEhB,IAAI,EAAEiB,UAAU,E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AEH,SAAS;YAAU;YAC1F;QACF;QACAT,SAAS;QACTL,gBAAgB,gBAAgB;YAAEc,SAAS;YAAWC,SAAS;QAAM;QACrElB,2BAAAA,QAAU;YACR2B,OAAOR,KAAK7B,MAAM,CAAC,CAACF,KAAO,CAACgB,OAAOwB,QAAQ,CAACxC;YAC5CyC,SAASzB,OAAOd,MAAM,CAAC,CAACF,KAAO,CAAC+B,KAAKS,QAAQ,CAACxC;QAChD;IACF;IAEA,qBACE,KAACxB;QACCkE,QAAQ;QACRC,MAAMtE,eAAe,YAAY;YAAEuE,QAAQ;QAAgB;QAC3DC,cAAc;QACdC,cAAc;kBAEd,cAAA,MAACjE;YAAMkE,SAAS;;8BACd,KAACxE;oBACCkB,SAASA;oBACTK,OAAOmB;oBACP+B,UAAU,CAACjB;wBACTb,YAAYa;wBACZX,SAAS;oBACX;oBACArB,OAAM;oBACNkD,YAAY3D;oBACZ4D,UAAU7B;oBACVK,OAAOA;oBACPyB,WAAU;;gBAEXzB,QAAQ,qBACP,KAAC7C;oBAAMuE,WAAU;8BACf,cAAA,KAACxE;wBACCyE,MAAK;wBACLxB,SAAQ;wBACRqB,UAAU7B,UAAUI;wBACpB6B,SAAS,IAAM,KAAK1B,OAAO2B,KAAK,CAAC,CAACC;gCAChCC,QAAQD,KAAK,CAACA;gCACdzC,gBACEyC,iBAAiBE,SAASF,MAAMlB,OAAO,GAAGkB,MAAMlB,OAAO,GAAG,yBAC1D;oCAAET,SAAS;oCAAS8B,gBAAgB;gCAAK;gCAE3CrC,UAAU;4BACZ;kCAECD,SAAS,YAAY;;;;;;AAOpC;AACAhB,kBAAkBuD,WAAW,GAAG;AAEhC,eAAevD,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/lead-campaigns-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 campaignMembershipUnchanged,\n campaignMembershipValue,\n pluginDocsHelp,\n readCampaignIds,\n} from '@aglyn/aglyn'\nimport CampaignPicker, {\n type CampaignPickerOption,\n} from '@aglyn/shared-ui-email-campaigns/components/campaign-picker.component'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n type FirestoreDocStatus,\n useFirestore,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Stack } from '@mui/material'\nimport { doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { crmClientListFields } from '../model/crm-list-query'\n\n/** The list field a campaign filing moves (AGL-3321). */\nconst LEAD_CAMPAIGN_LIST_FIELDS = ['scopedCampaignIds'] as const\n\n/** The helper line under the picker — the contact card's, word for word. */\nexport const LEAD_CAMPAIGNS_HELPER_TEXT =\n 'Your own filing. It never adds anyone to a send — a campaign mails its lists.'\n\n/**\n * The campaigns a lead is filed under, as NAMES for the record header.\n *\n * Resolved from the site's containers; an id with no live container — a\n * campaign the console deleted, or one still loading — is left out rather\n * than shown, because a document id on a chip tells a reader nothing and\n * looks like a fault. The picker below keeps such an id visible as itself,\n * so the filing is never silently lost; the header only ever names.\n */\nexport function leadCampaignNames(\n lead: Record<string, unknown> | null | undefined,\n options: readonly CampaignPickerOption[],\n): string[] {\n const labels = new Map(options.map((option) => [option.value, option.label]))\n return readCampaignIds(lead)\n .map((id) => labels.get(id))\n .filter((name): name is string => Boolean(name))\n}\n\nexport interface LeadCampaignsCardProps {\n /**\n * The lead's own site, or `null` at the organization level for a lead no\n * site captured (AGL-3278). Read for the org root alone — the containers\n * themselves are handed down as `options` — so the card serves both\n * levels; the org-level mount answers the same org without a site.\n */\n hostId: string | null\n leadId: string\n lead: Record<string, unknown>\n leadStatus: FirestoreDocStatus\n /** The listener has not confirmed this document with the server yet. */\n fromCache: boolean\n /** The site's campaigns, read once by the page for this card and the header. */\n options: readonly CampaignPickerOption[]\n /** The campaign read has answered — false while it settles. */\n optionsReady: boolean\n /**\n * What a saved filing changed, once it has landed: the ids added to and\n * removed from the lead's membership. The page files the activity\n * entries (AGL-3274); the card only knows the document.\n */\n onFiled?: (change: { added: string[]; removed: string[] }) => void\n}\n\n/**\n * WHICH CAMPAIGNS THIS LEAD IS FILED UNDER (AGL-3274).\n *\n * The contact's Relationship card has carried this picker since AGL-2596;\n * the lead's page had none, so a lead filed under a campaign by the New\n * lead drawer, the bulk bar or a sequence's enroll showed nothing of it —\n * the one field on the record the reader had no way to see or change.\n *\n * The same control, the same value helper, the same helper line. The save\n * is the lead's own client door — a one-field `update` on\n * `hosts/{hostId}/leads`, as the properties card writes status and notes —\n * guarded by the seed like every draft edited over a cached read, and\n * `campaignMembershipUnchanged` keeps Save quiet while the picker only\n * reorders what is stored. **Save filing** sits in the card header.\n *\n * It is FILING, not audience: the helper says so, in the sentence the\n * contact card uses, because a reader who finds a campaign picker on a\n * person's page assumes the opposite.\n */\nexport function LeadCampaignsCard(props: LeadCampaignsCardProps) {\n const { hostId, leadId, lead, leadStatus, fromCache, options, optionsReady, onFiled } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const stored = readCampaignIds(lead)\n const [selected, setSelected] = useState<string[]>(stored)\n const [dirty, setDirty] = useState(false)\n const [saving, setSaving] = useState(false)\n // A newer membership from the server replaces an UNEDITED selection — a\n // sequence's enroll or a bulk add lands while the page is open — and an\n // edited one is the reader's, decided by the guard on save.\n const storedKey = stored.join(',')\n useEffect(() => {\n if (!dirty) setSelected(stored)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storedKey, dirty])\n\n const unchanged = campaignMembershipUnchanged(stored, selected)\n const empty = optionsReady && !options.length\n\n const save = async () => {\n if (unchanged) return\n if (!orgId) {\n enqueueSnackbar('Still loading this workspace — try again in a moment.', {\n variant: 'warning',\n persist: false,\n })\n return\n }\n setSaving(true)\n const next = campaignMembershipValue(selected)\n const verdict = await writeGuardedBySeed(\n { subject: 'lead', fromCache, unreadable: leadStatus === 'error' },\n async () => {\n await updateDoc(doc(firestore, 'orgs', orgId, 'leads', leadId), {\n campaignIds: next,\n // The Leads list's Campaign filter under a site reads these\n // (AGL-3321), from the lead with its new campaigns.\n ...crmClientListFields('leads', lead, { campaignIds: next }, LEAD_CAMPAIGN_LIST_FIELDS),\n updatedAt: serverTimestamp(),\n })\n },\n )\n setSaving(false)\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message ?? 'The filing could not be saved.', { variant: 'warning' })\n return\n }\n setDirty(false)\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n onFiled?.({\n added: next.filter((id) => !stored.includes(id)),\n removed: stored.filter((id) => !next.includes(id)),\n })\n }\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('crmLeads', { anchor: '#a-leads-page' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: empty ? null : (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || unchanged}\n onClick={() => void save().catch((error: unknown) => {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n setSaving(false)\n })}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <CampaignPicker\n options={options}\n value={selected}\n onChange={(next) => {\n setSelected(next)\n setDirty(true)\n }}\n label=\"Filed under campaigns\"\n helperText={LEAD_CAMPAIGNS_HELPER_TEXT}\n disabled={saving}\n empty={empty}\n emptyText=\"There are no campaigns to file this lead under yet. Create one from Marketing.\"\n />\n </Stack>\n </CardDisplay>\n )\n}\nLeadCampaignsCard.displayName = 'LeadCampaignsCard'\n\nexport default LeadCampaignsCard\n"],"names":["campaignMembershipUnchanged","campaignMembershipValue","pluginDocsHelp","readCampaignIds","CampaignPicker","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Stack","doc","serverTimestamp","updateDoc","useEffect","useState","useCrmScope","crmClientListFields","LEAD_CAMPAIGN_LIST_FIELDS","LEAD_CAMPAIGNS_HELPER_TEXT","leadCampaignNames","lead","options","labels","Map","map","option","value","label","id","get","filter","name","Boolean","LeadCampaignsCard","props","hostId","leadId","leadStatus","fromCache","optionsReady","onFiled","orgId","firestore","enqueueSnackbar","stored","selected","setSelected","dirty","setDirty","saving","setSaving","storedKey","join","unchanged","empty","length","save","variant","persist","next","verdict","subject","unreadable","campaignIds","updatedAt","ok","message","added","includes","removed","header","help","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","onClick","catch","error","console","Error","allowDuplicate","spacing","onChange","helperText","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,2BAA2B,EAC3BC,uBAAuB,EACvBC,cAAc,EACdC,eAAe,QACV,eAAc;AACrB,OAAOC,oBAEA,wEAAuE;AAC9E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAEEC,YAAY,EACZC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,KAAK,QAAQ,gBAAe;AAC7C,SAASC,GAAG,EAAEC,eAAe,EAAEC,SAAS,QAAQ,qBAAoB;AACpE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,mBAAmB,QAAQ,6BAAyB;AAE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AAK;wBAE3ClC,UAAU;oBACZ;0BAECD,SAAS,YAAY;;QAG5B;kBAEA,cAAA,KAACxC;YAAM4E,SAAS;sBACd,cAAA,KAAClF;gBACCkB,SAASA;gBACTK,OAAOmB;gBACPyC,UAAU,CAAC3B;oBACTb,YAAYa;oBACZX,SAAS;gBACX;gBACArB,OAAM;gBACN4D,YAAYrE;gBACZ4D,UAAU7B;gBACVK,OAAOA;gBACPkC,WAAU;;;;AAKpB;AACAvD,kBAAkBwD,WAAW,GAAG;AAEhC,eAAexD,kBAAiB"}
|
|
@@ -70,15 +70,23 @@ export interface LeadPropertiesCardProps {
|
|
|
70
70
|
* What the team knows and decides about a lead: status, owner, notes, and
|
|
71
71
|
* the identity and consent the capture recorded (AGL-2608).
|
|
72
72
|
*
|
|
73
|
+
* Two cards. The record's header carries the identity, the status and owner,
|
|
74
|
+
* the consent the capture recorded and the record's actions. **Details**
|
|
75
|
+
* under it carries the profile, the org's own lead fields under **More
|
|
76
|
+
* fields**, and the notes — one card with one Save in its header, the way
|
|
77
|
+
* Salesforce keeps a record's standard and custom fields in one Details
|
|
78
|
+
* section.
|
|
79
|
+
*
|
|
73
80
|
* Status and owner are single-field client writes — the rules let a site
|
|
74
81
|
* admin, editor or author update `hosts/{hostId}/leads`, and a one-field
|
|
75
|
-
* `update` cannot roll anything else back.
|
|
76
|
-
* from the document, so
|
|
77
|
-
* edited over a cached read would otherwise overwrite a newer note
|
|
78
|
-
*
|
|
82
|
+
* `update` cannot roll anything else back. The details are drafts seeded
|
|
83
|
+
* from the document, so their save goes through `writeGuardedBySeed`: a
|
|
84
|
+
* draft edited over a cached read would otherwise overwrite a newer note or
|
|
85
|
+
* profile with an older one.
|
|
79
86
|
*
|
|
80
|
-
* Converted leads are read-only here. Their status is the
|
|
81
|
-
* the actions become links to what the conversion
|
|
87
|
+
* Converted leads are read-only here, but for the notes. Their status is the
|
|
88
|
+
* conversion, and the header's actions become links to what the conversion
|
|
89
|
+
* made.
|
|
82
90
|
*/
|
|
83
91
|
export declare function LeadPropertiesCard(props: LeadPropertiesCardProps): import("react").JSX.Element;
|
|
84
92
|
export declare namespace LeadPropertiesCard {
|