@aglyn/plugins-crm 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -14
  3. package/src/lib/components/add-to-list-dialog.js +7 -3
  4. package/src/lib/components/add-to-list-dialog.js.map +1 -1
  5. package/src/lib/components/company-contact-roles-card.d.ts +3 -0
  6. package/src/lib/components/company-contact-roles-card.js +4 -2
  7. package/src/lib/components/company-contact-roles-card.js.map +1 -1
  8. package/src/lib/components/company-detail-page.js +5 -3
  9. package/src/lib/components/company-detail-page.js.map +1 -1
  10. package/src/lib/components/company-edit-drawer.d.ts +3 -0
  11. package/src/lib/components/company-edit-drawer.js +2 -1
  12. package/src/lib/components/company-edit-drawer.js.map +1 -1
  13. package/src/lib/components/company-properties-card.d.ts +3 -0
  14. package/src/lib/components/company-properties-card.js.map +1 -1
  15. package/src/lib/components/contact-associations-card.d.ts +3 -0
  16. package/src/lib/components/contact-associations-card.js +3 -1
  17. package/src/lib/components/contact-associations-card.js.map +1 -1
  18. package/src/lib/components/contact-detail-page.js +5 -3
  19. package/src/lib/components/contact-detail-page.js.map +1 -1
  20. package/src/lib/components/contact-properties-card.d.ts +3 -0
  21. package/src/lib/components/contact-properties-card.js +3 -1
  22. package/src/lib/components/contact-properties-card.js.map +1 -1
  23. package/src/lib/components/deal-contact-roles-card.d.ts +3 -0
  24. package/src/lib/components/deal-contact-roles-card.js +4 -2
  25. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  26. package/src/lib/components/deal-detail-page.js +7 -4
  27. package/src/lib/components/deal-detail-page.js.map +1 -1
  28. package/src/lib/components/deal-edit-drawer.d.ts +3 -0
  29. package/src/lib/components/deal-edit-drawer.js +4 -2
  30. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  31. package/src/lib/components/deal-products-card.d.ts +3 -0
  32. package/src/lib/components/deal-products-card.js +4 -2
  33. package/src/lib/components/deal-products-card.js.map +1 -1
  34. package/src/lib/components/deals-section.js +1 -0
  35. package/src/lib/components/deals-section.js.map +1 -1
  36. package/src/lib/components/fields-section.js +7 -3
  37. package/src/lib/components/fields-section.js.map +1 -1
  38. package/src/lib/components/lead-campaigns-card.d.ts +3 -1
  39. package/src/lib/components/lead-campaigns-card.js +3 -2
  40. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  41. package/src/lib/components/lead-detail-page.js +3 -1
  42. package/src/lib/components/lead-detail-page.js.map +1 -1
  43. package/src/lib/components/lead-properties-card.d.ts +3 -1
  44. package/src/lib/components/lead-properties-card.js +3 -2
  45. package/src/lib/components/lead-properties-card.js.map +1 -1
  46. package/src/lib/components/picklist-values-card.js +4 -2
  47. package/src/lib/components/picklist-values-card.js.map +1 -1
  48. package/src/lib/components/pipeline-stages-dialog.d.ts +3 -0
  49. package/src/lib/components/pipeline-stages-dialog.js +43 -14
  50. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  51. package/src/lib/components/pipelines-dialog.d.ts +3 -0
  52. package/src/lib/components/pipelines-dialog.js +5 -2
  53. package/src/lib/components/pipelines-dialog.js.map +1 -1
  54. package/src/lib/components/record-tasks-card.js +3 -2
  55. package/src/lib/components/record-tasks-card.js.map +1 -1
  56. package/src/lib/components/task-edit-drawer.d.ts +2 -0
  57. package/src/lib/components/task-edit-drawer.js +2 -1
  58. package/src/lib/components/task-edit-drawer.js.map +1 -1
  59. package/src/lib/components/tasks-section.js +3 -2
  60. package/src/lib/components/tasks-section.js.map +1 -1
  61. package/src/lib/hooks/use-contact-field-definitions.d.ts +3 -0
  62. package/src/lib/hooks/use-contact-field-definitions.js +3 -2
  63. package/src/lib/hooks/use-contact-field-definitions.js.map +1 -1
  64. package/src/lib/hooks/use-crm-picklist.d.ts +3 -0
  65. package/src/lib/hooks/use-crm-picklist.js +5 -3
  66. package/src/lib/hooks/use-crm-picklist.js.map +1 -1
  67. package/src/lib/hooks/use-crm-tasks.d.ts +3 -0
  68. package/src/lib/hooks/use-crm-tasks.js +3 -1
  69. package/src/lib/hooks/use-crm-tasks.js.map +1 -1
  70. package/src/lib/hooks/use-lead-source-picklist.js +5 -3
  71. package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
  72. package/src/lib/hooks/use-lead-status-picklist.js +5 -3
  73. package/src/lib/hooks/use-lead-status-picklist.js.map +1 -1
  74. package/src/lib/hooks/use-pipeline.d.ts +3 -0
  75. package/src/lib/hooks/use-pipeline.js +3 -1
  76. package/src/lib/hooks/use-pipeline.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-detail-page.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 * as Aglyn from '@aglyn/aglyn'\nimport { CONTACT_LIFECYCLE_STAGE_LABELS, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n pluginRecordByEmailHref,\n pluginRecordHref,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiDeleteOutline, mdiMerge } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { Stack, Tooltip, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useParams, useRouter } from 'next/navigation'\nimport { useCallback, useMemo } from 'react'\nimport { useContactRemove } from '../hooks/use-contact-remove'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault, useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup, contactRecordFromDoc, contactRecordLabel } from '../model/contact-record'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport ContactAssociationsCard from './contact-associations-card'\nimport ContactDuplicatesCard from './contact-duplicates-card'\nimport ContactKnownByCard from './contact-known-by-card'\nimport ContactMergeDialog, { useContactMergeDialog } from './contact-merge-dialog'\nimport ContactPropertiesCard from './contact-properties-card'\nimport ContactTimelineCard from './contact-timeline-card'\nimport { AddToListButton } from './add-to-list-button'\nimport { useBookingDoor } from './crm-booking-zone'\nimport { CrmRecordEmailActionsZone } from './crm-email-actions-zone'\nimport { CrmRecordActionsZone } from './crm-record-actions-zone'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { ContactDealsCard } from './contact-deals-card'\nimport { CrmCallButton } from './crm-call-actions'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { CrmAccountLockChip, CrmEmailGatewayChip } from './crm-email-check'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { CrmSuiteNotice, crmSuiteIncluded, crmSuiteLockedReason } from './crm-suite-lock'\nimport { useErasePersonAction } from './erase-person-action'\nimport RecordFilesCard from './record-files-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { RecordTasksCard } from './record-tasks-card'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport { useOrgMembers } from './use-org-members'\n\nconst contactDocsHelp = pluginDocsHelp('contactRecord', { anchor: '#the-record-page' })\n\n/**\n * `/crm/contacts/{contactId}` — one person (AGL-2596).\n *\n * A ROUTE rather than the v1 drawer, because a person is the thing every\n * other CRM record points at: a deal, a task and an activity all name a\n * contact, and a link that opens a drawer on top of a list is not a link\n * anybody can paste.\n *\n * ## What this page reads\n *\n * ONE document, by id, through the scoped rules — a single-document get is\n * judged on that document's own `visibleTo`, so no `array-contains-any`\n * filter is needed here the way it is on the list. The row is then flattened\n * through the viewing group's facet ONCE (`contactRecordFromDoc`) and the\n * cards below read the flat record: none of them reaches into\n * `facets.{groupId}` for itself, which is what keeps a card from ever\n * showing another holder's notes.\n *\n * Beyond the document: the team roster (one request, for the owner picker)\n * and the site's campaigns (one listen, for the filing picker) — both paid\n * here because opening a record IS the ask for them, and neither is paid by\n * the list.\n *\n * ## The cards\n *\n * Each in its own file, so a card can grow without this page growing:\n * properties (the editable profile, with the org's custom fields under it),\n * the relationship (sources, attribution, consent, campaign filing) and the\n * timeline. Other CRM sections add a card here by inserting one import and\n * one line.\n *\n * ## Delete is a detach\n *\n * The row is shared by every site that has captured this person, so the\n * action in the overflow menu drops THIS group's facet, consent, attribution\n * and scope tokens, and deletes the document only when nobody else is left\n * holding it. `crm/contact-remove` decides which against the stored\n * document and keeps any marketing refusal the person gave (AGL-3338); the\n * rules refuse a client the write. Not the erasure path: a privacy erasure\n * removes the person regardless of who else holds them.\n */\nexport function ContactDetailPage(props: CrmDetailPageProps) {\n const { hostId, org, id, basePath } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root, the viewing group and what this viewer may list — the\n // merge search's and the duplicates query's one clause — from the one\n // scope hook (AGL-2614); at the organization level the group is `null`\n // and resolved per person below, and the listeners carry no clause\n // (AGL-2630).\n const {\n scope,\n orgId,\n consentGroup: viewingGroup,\n visibleTo,\n } = useCrmScope({ hostId, org })\n const mount = useCrmOrgMount()\n const merge = useContactMergeDialog()\n /*\n * THE CRM (AGL-2788). This page is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). What locks below — owner, stage\n * and company; tasks, deals, files and custom fields; a logged call or\n * activity; one-to-one email; a merge — draws only for an org whose plan\n * lacks the CRM. The shell mounted this page once the org had settled, so\n * this is the plan, not a paint of the org still loading.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n\n const {\n data: row,\n status,\n fromCache,\n } = useFirestoreDoc<Record<string, any>>(\n () => (scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null),\n [firestore, scope, id],\n { idField: '$id' },\n )\n /*\n * The controller this page is showing. Under a site: the sites declared\n * to be one sender, or this site alone — resolved from the org document\n * the shell already passed, so it costs no read. At the ORGANIZATION\n * level: the person's own PRIMARY holder, the first capturing site's\n * group, so an org-wide member reads the profile that site keeps and an\n * edit goes back to the same facet; the \"Known by\" card says which other\n * sites hold one.\n */\n const consentGroup = useMemo(\n () => viewingGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n [viewingGroup, row, org],\n )\n /**\n * The SITE the page acts as, for what needs one — the lead lookup, the\n * campaign filing, the site's activity feed: the mounted site, or the\n * primary holder's, or nothing for a row no site has captured.\n */\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const record = useMemo(\n () => (row ? contactRecordFromDoc(row, consentGroup) : null),\n [row, consentGroup],\n )\n const notFound = Boolean(scope) && status !== 'loading' && !row\n /** How the site the delete detaches from is named — see `handleRemove`. */\n const siteLabel = hostId\n ? 'this site'\n : siteHostId\n ? (mount?.siteName(siteHostId) ?? siteHostId)\n : 'its site'\n\n // The roster, for the owner picker and the owner's name — read because a\n // record page is the one place both are shown.\n const members = useOrgMembers(orgId, { enabled: Boolean(record) })\n /*\n * Where this person's ORDERS are read (AGL-2622): the site's orders list,\n * narrowed to their address, at the address the plugin that keeps orders\n * publishes. The count on the header is the number; the list is the rows.\n * Built from the route params already in the URL, so no document is read\n * to draw a link, and absent off a site — the org-level mount has no\n * orders list to point at — and where no plugin keeps orders.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const ordersHref =\n params?.orgSlug && params?.host && record?.email\n ? pluginRecordByEmailHref(\n 'order',\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n record.email,\n )\n : null\n /*\n * Where this person's BOOKINGS are read (AGL-2660): the site's Bookings\n * page narrowed to their address, under the same match rule the booking\n * row's own \"View in CRM\" uses. Offered only where the site has a booking\n * door — a site that never enabled Bookings should not carry the row. At\n * the organization level the capturing site's page, addressed through\n * the subdomain the mount knows it by.\n */\n const bookingDoor = useBookingDoor(siteHostId, org)\n const siteSlug = params?.host\n ? String(params.host)\n : siteHostId && mount\n ? mount.siteSubdomain(siteHostId)\n : null\n const bookingsHref =\n bookingDoor.open && params?.orgSlug && siteSlug && record?.email\n ? pluginRecordByEmailHref(\n 'booking',\n { orgSlug: String(params.orgSlug), host: siteSlug },\n record.email,\n )\n : null\n\n /*\n * Where a campaign entry on the timeline links to: the email's own report\n * (AGL-2616), at the address the plugin that keeps messages publishes as\n * `emailMessage` (AGL-3080). Only a campaign THIS site sent can be\n * addressed — a sibling site in the same consent group has pages of its\n * own under a subdomain this page does not know — so the builder answers\n * `null` for those, and where nothing publishes the kind, and the entry\n * draws unlinked.\n */\n const siteRoute = useSiteRouteContext()\n const campaignHref = useCallback(\n (email: Aglyn.ContactCampaignEmail) =>\n siteRoute && email.hostId === hostId\n ? pluginRecordHref('emailMessage', siteRoute, email.campaignId)\n : null,\n [siteRoute, hostId],\n )\n\n const contactRemove = useContactRemove(hostId)\n const handleRemove = useCallback(async () => {\n if (!row || !scope) return\n const confirmed = await confirm({\n title: 'Delete this contact?',\n description:\n `\"${record ? contactRecordLabel(record) : id}\" is removed from ${siteLabel}'s ` +\n 'Contacts, along with its notes, tags and timeline. Other sites ' +\n 'that captured the same person keep their own records. Their form ' +\n 'submissions, orders, bookings, and membership records are ' +\n 'separate — delete those from their own pages if the request ' +\n 'covers them.',\n confirmationText: 'Delete contact',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n // The route decides against the stored document, keeps any refusal,\n // and restamps what the Contacts list filters by (AGL-3338).\n const removed = await contactRemove.removeOne(id)\n // `siteLabel` and not \"this site\": at the organization level the line\n // lands in a feed that spans every site, so it has to name the one.\n logActivity(`Removed contact from ${siteLabel}`, {\n type: 'contact',\n id,\n name: record ? contactRecordLabel(record) : undefined,\n })\n enqueueSnackbar(\n removed === 'deleted'\n ? 'Contact deleted'\n : `Contact removed from ${siteLabel}`,\n { variant: 'success', persist: false },\n )\n router.push(routes.section('contacts'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n confirm,\n contactRemove,\n enqueueSnackbar,\n id,\n logActivity,\n record,\n router,\n routes,\n row,\n scope,\n siteLabel,\n ])\n\n const overflowItems: RowActionsMenuItem[] = [\n /*\n * Two records for one person become one (AGL-2625). Opened empty, to be\n * searched, with the OTHER record surviving: a reader on the record they\n * want gone says \"merge this into…\". The dialog lets them switch.\n */\n {\n key: 'merge',\n label: 'Merge into…',\n icon: <MdiIcon path={mdiMerge.path} size={0.8} />,\n disabled: !row || !suiteIncluded,\n disabledReason: suiteIncluded ? 'The contact has not loaded' : crmSuiteLockedReason(),\n onClick: () => merge.open(),\n },\n {\n key: 'remove',\n label: 'Delete contact',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !row,\n disabledReason: 'The contact has not loaded',\n onClick: () => void handleRemove(),\n },\n ]\n // The privacy erasure (AGL-2623): its item joins the overflow, its banner\n // sits under the header while a request waits, its dialog renders once.\n const erase = useErasePersonAction({\n // Filed as the site the page acts as — at the organization level the\n // person's primary holder (AGL-2630).\n hostId: siteHostId,\n orgId,\n subject: record ? { kind: 'contact', id, email: record.email } : null,\n requestedAtMs: Aglyn.readErasureRequestedAtMs(row),\n })\n\n if (notFound) {\n return (\n <CrmRecordHeader\n kind=\"Contact\"\n title={undefined}\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n >\n {/*\n * Not \"no data\". A contact that cannot be read is a different\n * situation from one with an empty profile — it may have been\n * removed from this site, or be held only by a site this reader\n * cannot see.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This contact could not be loaded. It may have been removed from this site.'}\n </Typography>\n </CrmRecordHeader>\n )\n }\n\n return (\n // A create opened from this page — a task, an activity, a deal — files\n // under the site that captured this person unless the reader says\n // otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={siteHostId}>\n <Stack spacing={3}>\n <CrmRecordHeader\n kind=\"Contact\"\n title={record ? contactRecordLabel(record) : undefined}\n // The identity, and the other addresses a merge folded into it.\n subtitle={\n record\n ? [record.email, ...record.alternateEmails.map((email) => `also ${email}`)]\n .filter(Boolean)\n .join(' · ')\n : undefined\n }\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n actions={\n record ? (\n <>\n {/* A list is for mail, and this person may not have an address yet. */}\n {record.email ? (\n <AddToListButton hostId={hostId} org={org} contactId={id} email={record.email} />\n ) : null}\n {/* Dial the number, and log the call it was (AGL-2661). */}\n <CrmCallButton\n hostId={siteHostId}\n org={org}\n link={{ contactId: id }}\n // The main number, or the mobile when that is all there is (AGL-3515).\n phone={record.phone || record.mobilePhone}\n doNotCall={record.doNotCall}\n suiteLocked={!suiteIncluded}\n />\n {/* An answer in a thread another plugin keeps with them (AGL-4020), ahead of a new message. */}\n <CrmRecordEmailActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n />\n {record.email ? (\n <CrmSendEmailButton\n hostId={siteHostId}\n org={org}\n contactId={id}\n email={record.email}\n name={record.name}\n emailState={record.emailState}\n suiteLocked={!suiteIncluded}\n />\n ) : null}\n {/* What another plugin does with the person, such as start a quote (AGL-4098). */}\n <CrmRecordActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n phone={record.phone || record.mobilePhone || ''}\n company={record.companyName || ''}\n />\n </>\n ) : null\n }\n menuItems={[...overflowItems, ...erase.menuItems]}\n // The booking door (AGL-2660): this site's services, or at the\n // organization level the capturing site's.\n booking={record ? { hostId: siteHostId, org, kind: 'contact', recordId: id } : undefined}\n loading={!record}\n chips={\n record ? (\n <>\n {/* The verdict on the address (AGL-3245), first: a bounce or a\n do-not-contact mark is what a person deciding to write must see. */}\n <CrmEmailStateChip state={record.emailState} />\n {/* Seen here only through a share (AGL-3336): who shared it. */}\n <CrmShareChipView chip={crmShareChipFor(row, viewingGroup?.hostIds ?? [])} org={org} />\n {/* The mail gateway in front of the address (AGL-3328). */}\n <CrmEmailGatewayChip\n hostId={siteHostId}\n email={record.email}\n emailState={record.emailState}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmAccountLockChip\n hostId={siteHostId}\n email={record.email}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmRecordChip\n label=\"Stage\"\n value={\n record.lifecycleStage\n ? CONTACT_LIFECYCLE_STAGE_LABELS[record.lifecycleStage]\n : undefined\n }\n />\n <CrmRecordChip\n label=\"Owner\"\n value={record.ownerUid ? members.memberName(record.ownerUid) : undefined}\n />\n {/*\n The last time they opened or clicked one of this site's\n campaigns (AGL-2616) — the relationship's pulse, beside the\n owner who keeps it.\n */}\n <CrmRecordChip\n label=\"Last engaged\"\n value={\n record.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(record.lastEmailEngagementAtMs).toLocaleString()}>\n <span>\n {Aglyn.activityTimeLabel(record.lastEmailEngagementAtMs, Date.now())}\n </span>\n </Tooltip>\n ) : undefined\n }\n />\n <CrmRecordChip\n label=\"Orders\"\n value={\n record.ordersCount > 0 ? (\n ordersHref ? (\n <AppLink href={ordersHref} color=\"inherit\" underline=\"hover\">\n {`${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`}\n </AppLink>\n ) : (\n `${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`\n )\n ) : undefined\n }\n />\n </>\n ) : null\n }\n >\n {erase.banner}\n </CrmRecordHeader>\n {record && row && scope ? (\n <>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Working this contact — the owner, stage and company, tasks, ' +\n 'deals, files and custom fields, logging a call or an activity, ' +\n 'one-to-one email and merging duplicates — is part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The cross-site fact, at the organization level only (AGL-2630):\n which sites know this person, and their consent for each. Under\n a site the page IS one site's view and the card would say so on\n every record.\n */}\n {/* What an assistant proposes about the person (AGL-2917), where the plan works a contact. */}\n {suiteIncluded ? (\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"contact\"\n recordId={id}\n name={contactRecordLabel(record)}\n taskLink={{ contactId: id }}\n />\n ) : null}\n {mount ? <ContactKnownByCard row={row} contactId={id} org={org} /> : null}\n {/* Where the person is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"contacts\"\n id={id}\n record={row}\n hostId={hostId ?? null}\n orgId={orgId}\n org={org}\n viewingHostIds={viewingGroup?.hostIds}\n />\n <ContactPropertiesCard\n hostId={hostId}\n org={org}\n record={record}\n orgId={orgId}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n members={members}\n suiteLocked={!suiteIncluded}\n />\n <ContactAssociationsCard\n hostId={siteHostId}\n record={record}\n row={row}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n basePath={basePath}\n bookingsHref={bookingsHref}\n />\n <ContactTimelineCard\n hostId={hostId}\n org={org}\n contactId={id}\n contact={row}\n campaignHref={campaignHref}\n suiteLocked={!suiteIncluded}\n />\n {/*\n On a plan without the CRM, the cards that only work a record —\n deals, tasks, files — are named in the notice above rather than\n drawn as upsells in a row.\n */}\n {suiteIncluded ? (\n <>\n <ContactDealsCard\n hostId={hostId}\n org={org}\n basePath={basePath}\n contactId={id}\n contactName={contactRecordLabel(record)}\n />\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} contactId={id} />\n {/*\n The files are the VIEWING holder's, like everything else on this\n page: the write is a facet path, so a contract one brand filed\n never appears on a sibling brand's copy of the person.\n */}\n <RecordFilesCard\n scope={scope}\n collection=\"contacts\"\n recordId={id}\n hostId={hostId}\n facetGroupId={consentGroup.groupId}\n mediaIds={record.mediaIds}\n topic=\"contactRecord\"\n />\n </>\n ) : null}\n <ContactDuplicatesCard\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n basePath={basePath}\n onMerge={(candidate) => merge.open({ other: candidate, keep: 'current' })}\n suiteLocked={!suiteIncluded}\n />\n <ContactMergeDialog\n {...merge.state}\n onClose={merge.close}\n hostId={siteHostId}\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n memberName={members.memberName}\n // The page's own record was folded away: its address now opens\n // the survivor, which is where the reader is taken.\n onMerged={(survivorId) => {\n if (survivorId !== id) router.replace(routes.contact(survivorId))\n }}\n />\n </>\n ) : null}\n {erase.dialog}\n </Stack>\n </CrmCreateSiteDefault>\n )\n}\nContactDetailPage.displayName = 'ContactDetailPage'\n\nexport default ContactDetailPage\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","pluginDocsHelp","pluginRecordByEmailHref","pluginRecordHref","mdiDeleteOutline","mdiMerge","AppLink","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","useFirestoreDoc","Stack","Tooltip","Typography","doc","useParams","useRouter","useCallback","useMemo","useContactRemove","useCrmActivityLogger","CrmCreateSiteDefault","useCrmOrgMount","crmShareChipFor","useCrmScope","contactPrimaryGroup","contactRecordFromDoc","contactRecordLabel","crmRoutes","ContactAssociationsCard","ContactDuplicatesCard","ContactKnownByCard","ContactMergeDialog","useContactMergeDialog","ContactPropertiesCard","ContactTimelineCard","AddToListButton","useBookingDoor","CrmRecordEmailActionsZone","CrmRecordActionsZone","CrmSendEmailButton","ContactDealsCard","CrmCallButton","CrmEmailStateChip","CrmAccountLockChip","CrmEmailGatewayChip","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","CrmSuiteNotice","crmSuiteIncluded","crmSuiteLockedReason","useErasePersonAction","RecordFilesCard","CrmShareChipView","RecordSharingCard","RecordTasksCard","useSiteRouteContext","useOrgMembers","contactDocsHelp","anchor","ContactDetailPage","props","hostId","org","id","basePath","routes","router","firestore","enqueueSnackbar","confirm","scope","orgId","consentGroup","viewingGroup","visibleTo","mount","merge","suiteIncluded","data","row","status","fromCache","idField","siteHostId","logActivity","record","notFound","Boolean","siteLabel","siteName","members","enabled","params","ordersHref","orgSlug","host","email","String","bookingDoor","siteSlug","siteSubdomain","bookingsHref","open","siteRoute","campaignHref","campaignId","contactRemove","handleRemove","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","removed","removeOne","type","name","undefined","variant","persist","push","section","error","console","allowDuplicate","overflowItems","key","label","icon","path","size","disabled","disabledReason","onClick","destructive","erase","subject","kind","requestedAtMs","readErasureRequestedAtMs","help","backHref","backLabel","spacing","subtitle","alternateEmails","map","filter","join","actions","contactId","link","phone","mobilePhone","doNotCall","suiteLocked","recordId","emailState","company","companyName","menuItems","booking","loading","chips","state","chip","hostIds","value","lifecycleStage","ownerUid","memberName","lastEmailEngagementAtMs","Date","toLocaleString","span","activityTimeLabel","now","ordersCount","href","underline","ltvCents","toFixed","banner","taskLink","object","viewingHostIds","seed","contact","contactName","collection","facetGroupId","groupId","mediaIds","topic","current","onMerge","candidate","other","keep","onClose","close","onMerged","survivorId","replace","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,8BAA8B,EAAEC,cAAc,QAAQ,eAAc;A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sB,QAAQA;oCACRC,KAAKA;oCACLE,UAAUA;oCACVyF,WAAW1F;oCACXgI,aAAatK,mBAAmB4D;;8CAElC,KAAC/B;oCAAgBO,QAAQA;oCAAQC,KAAKA;oCAAKE,UAAUA;oCAAUyF,WAAW1F;;8CAM1E,KAACZ;oCACCmB,OAAOA;oCACP0H,YAAW;oCACXjC,UAAUhG;oCACVF,QAAQA;oCACRoI,cAAczH,aAAa0H,OAAO;oCAClCC,UAAU9G,OAAO8G,QAAQ;oCACzBC,OAAM;;;6BAGR;sCACJ,KAACxK;4BACCyK,SAAS;gCAAEtI;gCAAInD,KAAKmE;4BAAI;4BACxBT,OAAOA;4BACPE,cAAcA;4BACdE,WAAWA;4BACXV,UAAUA;4BACVsI,SAAS,CAACC,YAAc3H,MAAM0B,IAAI,CAAC;oCAAEkG,OAAOD;oCAAWE,MAAM;gCAAU;4BACvE3C,aAAa,CAACjF;;sCAEhB,KAAC/C,iCACK8C,MAAM2F,KAAK;4BACfmC,SAAS9H,MAAM+H,KAAK;4BACpB9I,QAAQsB;4BACRkH,SAAS;gCAAEtI;gCAAInD,KAAKmE;4BAAI;4BACxBT,OAAOA;4BACPE,cAAcA;4BACdE,WAAWA;4BACXmG,YAAYnF,QAAQmF,UAAU;4BAC9B,+DAA+D;4BAC/D,oDAAoD;4BACpD+B,UAAU,CAACC;gCACT,IAAIA,eAAe9I,IAAIG,OAAO4I,OAAO,CAAC7I,OAAO6H,OAAO,CAACe;4BACvD;;;qBAGF;gBACHnE,MAAMqE,MAAM;;;;AAInB;AACApJ,kBAAkBqJ,WAAW,GAAG;AAEhC,eAAerJ,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-detail-page.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 * as Aglyn from '@aglyn/aglyn'\nimport { CONTACT_LIFECYCLE_STAGE_LABELS, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n pluginRecordByEmailHref,\n pluginRecordHref,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiDeleteOutline, mdiMerge } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { Stack, Tooltip, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useParams, useRouter } from 'next/navigation'\nimport { useCallback, useMemo } from 'react'\nimport { useContactRemove } from '../hooks/use-contact-remove'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault, useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup, contactRecordFromDoc, contactRecordLabel } from '../model/contact-record'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport ContactAssociationsCard from './contact-associations-card'\nimport ContactDuplicatesCard from './contact-duplicates-card'\nimport ContactKnownByCard from './contact-known-by-card'\nimport ContactMergeDialog, { useContactMergeDialog } from './contact-merge-dialog'\nimport ContactPropertiesCard from './contact-properties-card'\nimport ContactTimelineCard from './contact-timeline-card'\nimport { AddToListButton } from './add-to-list-button'\nimport { useBookingDoor } from './crm-booking-zone'\nimport { CrmRecordEmailActionsZone } from './crm-email-actions-zone'\nimport { CrmRecordActionsZone } from './crm-record-actions-zone'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { ContactDealsCard } from './contact-deals-card'\nimport { CrmCallButton } from './crm-call-actions'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { CrmAccountLockChip, CrmEmailGatewayChip } from './crm-email-check'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { CrmSuiteNotice, crmSuiteIncluded, crmSuiteLockedReason } from './crm-suite-lock'\nimport { useErasePersonAction } from './erase-person-action'\nimport RecordFilesCard from './record-files-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { RecordTasksCard } from './record-tasks-card'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport { useOrgMembers } from './use-org-members'\n\nconst contactDocsHelp = pluginDocsHelp('contactRecord', { anchor: '#the-record-page' })\n\n/**\n * `/crm/contacts/{contactId}` — one person (AGL-2596).\n *\n * A ROUTE rather than the v1 drawer, because a person is the thing every\n * other CRM record points at: a deal, a task and an activity all name a\n * contact, and a link that opens a drawer on top of a list is not a link\n * anybody can paste.\n *\n * ## What this page reads\n *\n * ONE document, by id, through the scoped rules — a single-document get is\n * judged on that document's own `visibleTo`, so no `array-contains-any`\n * filter is needed here the way it is on the list. The row is then flattened\n * through the viewing group's facet ONCE (`contactRecordFromDoc`) and the\n * cards below read the flat record: none of them reaches into\n * `facets.{groupId}` for itself, which is what keeps a card from ever\n * showing another holder's notes.\n *\n * Beyond the document: the team roster (one request, for the owner picker)\n * and the site's campaigns (one listen, for the filing picker) — both paid\n * here because opening a record IS the ask for them, and neither is paid by\n * the list.\n *\n * ## The cards\n *\n * Each in its own file, so a card can grow without this page growing:\n * properties (the editable profile, with the org's custom fields under it),\n * the relationship (sources, attribution, consent, campaign filing) and the\n * timeline. Other CRM sections add a card here by inserting one import and\n * one line.\n *\n * ## Delete is a detach\n *\n * The row is shared by every site that has captured this person, so the\n * action in the overflow menu drops THIS group's facet, consent, attribution\n * and scope tokens, and deletes the document only when nobody else is left\n * holding it. `crm/contact-remove` decides which against the stored\n * document and keeps any marketing refusal the person gave (AGL-3338); the\n * rules refuse a client the write. Not the erasure path: a privacy erasure\n * removes the person regardless of who else holds them.\n */\nexport function ContactDetailPage(props: CrmDetailPageProps) {\n const { hostId, org, id, basePath } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root, the viewing group and what this viewer may list — the\n // merge search's and the duplicates query's one clause — from the one\n // scope hook (AGL-2614); at the organization level the group is `null`\n // and resolved per person below, and the listeners carry no clause\n // (AGL-2630).\n const {\n scope,\n orgId,\n consentGroup: viewingGroup,\n visibleTo,\n } = useCrmScope({ hostId, org })\n const mount = useCrmOrgMount()\n const merge = useContactMergeDialog()\n /*\n * THE CRM (AGL-2788). This page is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). What locks below — owner, stage\n * and company; tasks, deals, files and custom fields; a logged call or\n * activity; one-to-one email; a merge — draws only for an org whose plan\n * lacks the CRM. The shell mounted this page once the org had settled, so\n * this is the plan, not a paint of the org still loading.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n\n const {\n data: row,\n status,\n fromCache,\n listen,\n } = useFirestoreDoc<Record<string, any>>(\n () => (scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null),\n [firestore, scope, id],\n { idField: '$id' },\n )\n /*\n * The controller this page is showing. Under a site: the sites declared\n * to be one sender, or this site alone — resolved from the org document\n * the shell already passed, so it costs no read. At the ORGANIZATION\n * level: the person's own PRIMARY holder, the first capturing site's\n * group, so an org-wide member reads the profile that site keeps and an\n * edit goes back to the same facet; the \"Known by\" card says which other\n * sites hold one.\n */\n const consentGroup = useMemo(\n () => viewingGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n [viewingGroup, row, org],\n )\n /**\n * The SITE the page acts as, for what needs one — the lead lookup, the\n * campaign filing, the site's activity feed: the mounted site, or the\n * primary holder's, or nothing for a row no site has captured.\n */\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const record = useMemo(\n () => (row ? contactRecordFromDoc(row, consentGroup) : null),\n [row, consentGroup],\n )\n const notFound = Boolean(scope) && status !== 'loading' && !row\n /** How the site the delete detaches from is named — see `handleRemove`. */\n const siteLabel = hostId\n ? 'this site'\n : siteHostId\n ? (mount?.siteName(siteHostId) ?? siteHostId)\n : 'its site'\n\n // The roster, for the owner picker and the owner's name — read because a\n // record page is the one place both are shown.\n const members = useOrgMembers(orgId, { enabled: Boolean(record) })\n /*\n * Where this person's ORDERS are read (AGL-2622): the site's orders list,\n * narrowed to their address, at the address the plugin that keeps orders\n * publishes. The count on the header is the number; the list is the rows.\n * Built from the route params already in the URL, so no document is read\n * to draw a link, and absent off a site — the org-level mount has no\n * orders list to point at — and where no plugin keeps orders.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const ordersHref =\n params?.orgSlug && params?.host && record?.email\n ? pluginRecordByEmailHref(\n 'order',\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n record.email,\n )\n : null\n /*\n * Where this person's BOOKINGS are read (AGL-2660): the site's Bookings\n * page narrowed to their address, under the same match rule the booking\n * row's own \"View in CRM\" uses. Offered only where the site has a booking\n * door — a site that never enabled Bookings should not carry the row. At\n * the organization level the capturing site's page, addressed through\n * the subdomain the mount knows it by.\n */\n const bookingDoor = useBookingDoor(siteHostId, org)\n const siteSlug = params?.host\n ? String(params.host)\n : siteHostId && mount\n ? mount.siteSubdomain(siteHostId)\n : null\n const bookingsHref =\n bookingDoor.open && params?.orgSlug && siteSlug && record?.email\n ? pluginRecordByEmailHref(\n 'booking',\n { orgSlug: String(params.orgSlug), host: siteSlug },\n record.email,\n )\n : null\n\n /*\n * Where a campaign entry on the timeline links to: the email's own report\n * (AGL-2616), at the address the plugin that keeps messages publishes as\n * `emailMessage` (AGL-3080). Only a campaign THIS site sent can be\n * addressed — a sibling site in the same consent group has pages of its\n * own under a subdomain this page does not know — so the builder answers\n * `null` for those, and where nothing publishes the kind, and the entry\n * draws unlinked.\n */\n const siteRoute = useSiteRouteContext()\n const campaignHref = useCallback(\n (email: Aglyn.ContactCampaignEmail) =>\n siteRoute && email.hostId === hostId\n ? pluginRecordHref('emailMessage', siteRoute, email.campaignId)\n : null,\n [siteRoute, hostId],\n )\n\n const contactRemove = useContactRemove(hostId)\n const handleRemove = useCallback(async () => {\n if (!row || !scope) return\n const confirmed = await confirm({\n title: 'Delete this contact?',\n description:\n `\"${record ? contactRecordLabel(record) : id}\" is removed from ${siteLabel}'s ` +\n 'Contacts, along with its notes, tags and timeline. Other sites ' +\n 'that captured the same person keep their own records. Their form ' +\n 'submissions, orders, bookings, and membership records are ' +\n 'separate — delete those from their own pages if the request ' +\n 'covers them.',\n confirmationText: 'Delete contact',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n // The route decides against the stored document, keeps any refusal,\n // and restamps what the Contacts list filters by (AGL-3338).\n const removed = await contactRemove.removeOne(id)\n // `siteLabel` and not \"this site\": at the organization level the line\n // lands in a feed that spans every site, so it has to name the one.\n logActivity(`Removed contact from ${siteLabel}`, {\n type: 'contact',\n id,\n name: record ? contactRecordLabel(record) : undefined,\n })\n enqueueSnackbar(\n removed === 'deleted'\n ? 'Contact deleted'\n : `Contact removed from ${siteLabel}`,\n { variant: 'success', persist: false },\n )\n router.push(routes.section('contacts'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n confirm,\n contactRemove,\n enqueueSnackbar,\n id,\n logActivity,\n record,\n router,\n routes,\n row,\n scope,\n siteLabel,\n ])\n\n const overflowItems: RowActionsMenuItem[] = [\n /*\n * Two records for one person become one (AGL-2625). Opened empty, to be\n * searched, with the OTHER record surviving: a reader on the record they\n * want gone says \"merge this into…\". The dialog lets them switch.\n */\n {\n key: 'merge',\n label: 'Merge into…',\n icon: <MdiIcon path={mdiMerge.path} size={0.8} />,\n disabled: !row || !suiteIncluded,\n disabledReason: suiteIncluded ? 'The contact has not loaded' : crmSuiteLockedReason(),\n onClick: () => merge.open(),\n },\n {\n key: 'remove',\n label: 'Delete contact',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !row,\n disabledReason: 'The contact has not loaded',\n onClick: () => void handleRemove(),\n },\n ]\n // The privacy erasure (AGL-2623): its item joins the overflow, its banner\n // sits under the header while a request waits, its dialog renders once.\n const erase = useErasePersonAction({\n // Filed as the site the page acts as — at the organization level the\n // person's primary holder (AGL-2630).\n hostId: siteHostId,\n orgId,\n subject: record ? { kind: 'contact', id, email: record.email } : null,\n requestedAtMs: Aglyn.readErasureRequestedAtMs(row),\n })\n\n if (notFound) {\n return (\n <CrmRecordHeader\n kind=\"Contact\"\n title={undefined}\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n >\n {/*\n * Not \"no data\". A contact that cannot be read is a different\n * situation from one with an empty profile — it may have been\n * removed from this site, or be held only by a site this reader\n * cannot see.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This contact could not be loaded. It may have been removed from this site.'}\n </Typography>\n </CrmRecordHeader>\n )\n }\n\n return (\n // A create opened from this page — a task, an activity, a deal — files\n // under the site that captured this person unless the reader says\n // otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={siteHostId}>\n <Stack spacing={3}>\n <CrmRecordHeader\n kind=\"Contact\"\n title={record ? contactRecordLabel(record) : undefined}\n // The identity, and the other addresses a merge folded into it.\n subtitle={\n record\n ? [record.email, ...record.alternateEmails.map((email) => `also ${email}`)]\n .filter(Boolean)\n .join(' · ')\n : undefined\n }\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n actions={\n record ? (\n <>\n {/* A list is for mail, and this person may not have an address yet. */}\n {record.email ? (\n <AddToListButton hostId={hostId} org={org} contactId={id} email={record.email} />\n ) : null}\n {/* Dial the number, and log the call it was (AGL-2661). */}\n <CrmCallButton\n hostId={siteHostId}\n org={org}\n link={{ contactId: id }}\n // The main number, or the mobile when that is all there is (AGL-3515).\n phone={record.phone || record.mobilePhone}\n doNotCall={record.doNotCall}\n suiteLocked={!suiteIncluded}\n />\n {/* An answer in a thread another plugin keeps with them (AGL-4020), ahead of a new message. */}\n <CrmRecordEmailActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n />\n {record.email ? (\n <CrmSendEmailButton\n hostId={siteHostId}\n org={org}\n contactId={id}\n email={record.email}\n name={record.name}\n emailState={record.emailState}\n suiteLocked={!suiteIncluded}\n />\n ) : null}\n {/* What another plugin does with the person, such as start a quote (AGL-4098). */}\n <CrmRecordActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n phone={record.phone || record.mobilePhone || ''}\n company={record.companyName || ''}\n />\n </>\n ) : null\n }\n menuItems={[...overflowItems, ...erase.menuItems]}\n // The booking door (AGL-2660): this site's services, or at the\n // organization level the capturing site's.\n booking={record ? { hostId: siteHostId, org, kind: 'contact', recordId: id } : undefined}\n loading={!record}\n chips={\n record ? (\n <>\n {/* The verdict on the address (AGL-3245), first: a bounce or a\n do-not-contact mark is what a person deciding to write must see. */}\n <CrmEmailStateChip state={record.emailState} />\n {/* Seen here only through a share (AGL-3336): who shared it. */}\n <CrmShareChipView chip={crmShareChipFor(row, viewingGroup?.hostIds ?? [])} org={org} />\n {/* The mail gateway in front of the address (AGL-3328). */}\n <CrmEmailGatewayChip\n hostId={siteHostId}\n email={record.email}\n emailState={record.emailState}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmAccountLockChip\n hostId={siteHostId}\n email={record.email}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmRecordChip\n label=\"Stage\"\n value={\n record.lifecycleStage\n ? CONTACT_LIFECYCLE_STAGE_LABELS[record.lifecycleStage]\n : undefined\n }\n />\n <CrmRecordChip\n label=\"Owner\"\n value={record.ownerUid ? members.memberName(record.ownerUid) : undefined}\n />\n {/*\n The last time they opened or clicked one of this site's\n campaigns (AGL-2616) — the relationship's pulse, beside the\n owner who keeps it.\n */}\n <CrmRecordChip\n label=\"Last engaged\"\n value={\n record.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(record.lastEmailEngagementAtMs).toLocaleString()}>\n <span>\n {Aglyn.activityTimeLabel(record.lastEmailEngagementAtMs, Date.now())}\n </span>\n </Tooltip>\n ) : undefined\n }\n />\n <CrmRecordChip\n label=\"Orders\"\n value={\n record.ordersCount > 0 ? (\n ordersHref ? (\n <AppLink href={ordersHref} color=\"inherit\" underline=\"hover\">\n {`${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`}\n </AppLink>\n ) : (\n `${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`\n )\n ) : undefined\n }\n />\n </>\n ) : null\n }\n >\n {erase.banner}\n </CrmRecordHeader>\n {record && row && scope ? (\n <>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Working this contact — the owner, stage and company, tasks, ' +\n 'deals, files and custom fields, logging a call or an activity, ' +\n 'one-to-one email and merging duplicates — is part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The cross-site fact, at the organization level only (AGL-2630):\n which sites know this person, and their consent for each. Under\n a site the page IS one site's view and the card would say so on\n every record.\n */}\n {/* What an assistant proposes about the person (AGL-2917), where the plan works a contact. */}\n {suiteIncluded ? (\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"contact\"\n recordId={id}\n name={contactRecordLabel(record)}\n taskLink={{ contactId: id }}\n />\n ) : null}\n {mount ? <ContactKnownByCard row={row} contactId={id} org={org} /> : null}\n {/* Where the person is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"contacts\"\n id={id}\n record={row}\n hostId={hostId ?? null}\n orgId={orgId}\n org={org}\n viewingHostIds={viewingGroup?.hostIds}\n />\n <ContactPropertiesCard\n hostId={hostId}\n org={org}\n record={record}\n orgId={orgId}\n consentGroup={consentGroup}\n seed={{ status, fromCache, listen }}\n members={members}\n suiteLocked={!suiteIncluded}\n />\n <ContactAssociationsCard\n hostId={siteHostId}\n record={record}\n row={row}\n consentGroup={consentGroup}\n seed={{ status, fromCache, listen }}\n basePath={basePath}\n bookingsHref={bookingsHref}\n />\n <ContactTimelineCard\n hostId={hostId}\n org={org}\n contactId={id}\n contact={row}\n campaignHref={campaignHref}\n suiteLocked={!suiteIncluded}\n />\n {/*\n On a plan without the CRM, the cards that only work a record —\n deals, tasks, files — are named in the notice above rather than\n drawn as upsells in a row.\n */}\n {suiteIncluded ? (\n <>\n <ContactDealsCard\n hostId={hostId}\n org={org}\n basePath={basePath}\n contactId={id}\n contactName={contactRecordLabel(record)}\n />\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} contactId={id} />\n {/*\n The files are the VIEWING holder's, like everything else on this\n page: the write is a facet path, so a contract one brand filed\n never appears on a sibling brand's copy of the person.\n */}\n <RecordFilesCard\n scope={scope}\n collection=\"contacts\"\n recordId={id}\n hostId={hostId}\n facetGroupId={consentGroup.groupId}\n mediaIds={record.mediaIds}\n topic=\"contactRecord\"\n />\n </>\n ) : null}\n <ContactDuplicatesCard\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n basePath={basePath}\n onMerge={(candidate) => merge.open({ other: candidate, keep: 'current' })}\n suiteLocked={!suiteIncluded}\n />\n <ContactMergeDialog\n {...merge.state}\n onClose={merge.close}\n hostId={siteHostId}\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n memberName={members.memberName}\n // The page's own record was folded away: its address now opens\n // the survivor, which is where the reader is taken.\n onMerged={(survivorId) => {\n if (survivorId !== id) router.replace(routes.contact(survivorId))\n }}\n />\n </>\n ) : null}\n {erase.dialog}\n </Stack>\n </CrmCreateSiteDefault>\n )\n}\nContactDetailPage.displayName = 'ContactDetailPage'\n\nexport default ContactDetailPage\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","pluginDocsHelp","pluginRecordByEmailHref","pluginRecordHref","mdiDeleteOutline","mdiMerge","AppLink","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","useFirestoreDoc","Stack","Tooltip","Typography","doc","useParams","useRouter","useCallback","useMemo","useContactRemove","useCrmActivityLogger","CrmCreateSiteDefault","useCrmOrgMount","crmShareChipFor","useCrmScope","contactPrimaryGroup","contactRecordFromDoc","contactRecordLabel","crmRoutes","ContactAssociationsCard","ContactDuplicatesCard","ContactKnownByCard","ContactMergeDialog","useContactMergeDialog","ContactPropertiesCard","ContactTimelineCard","AddToListButton","useBookingDoor","CrmRecordEmailActionsZone","CrmRecordActionsZone","CrmSendEmailButton","ContactDealsCard","CrmCallButton","CrmEmailStateChip","CrmAccountLockChip","CrmEmailGatewayChip","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","CrmSuiteNotice","crmSuiteIncluded","crmSuiteLockedReason","useErasePersonAction","RecordFilesCard","CrmShareChipView","RecordSharingCard","RecordTasksCard","useSiteRouteContext","useOrgMembers","contactDocsHelp","anchor","ContactDetailPage","props","hostId","org","id","basePath","routes","router","firestore","enqueueSnackbar","confirm","scope","orgId","consentGroup","viewingGroup","visibleTo","mount","merge","suiteIncluded","data","row","status","fromCache","listen","idField","siteHostId","logActivity","record","notFound","Boolean","siteLabel","siteName","members","enabled","params","ordersHref","orgSlug","host","email","String","bookingDoor","siteSlug","siteSubdomain","bookingsHref","open","siteRoute","campaignHref","campaignId","contactRemove","handleRemove","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","removed","removeOne","type","name","undefined","variant","persist","push","section","error","console","allowDuplicate","overflowItems","key","label","icon","path","size","disabled","disabledReason","onClick","destructive","erase","subject","kind","requestedAtMs","readErasureRequestedAtMs","help","backHref","backLabel","spacing","subtitle","alternateEmails","map","filter","join","actions","contactId","link","phone","mobilePhone","doNotCall","suiteLocked","recordId","emailState","company","companyName","menuItems","booking","loading","chips","state","chip","hostIds","value","lifecycleStage","ownerUid","memberName","lastEmailEngagementAtMs","Date","toLocaleString","span","activityTimeLabel","now","ordersCount","href","underline","ltvCents","toFixed","banner","taskLink","object","viewingHostIds","seed","contact","contactName","collection","facetGroupId","groupId","mediaIds","topic","current","onMerge","candidate","other","keep","onClose","close","onMerged","survivorId","replace","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,8BAA8B,EAAEC,cAAc,QAAQ,eAAc;AAC7E,SACEC,uBAAuB,EACvBC,gBAAgB,QACX,mDAAkD;AACzD,SAASC,gBAAgB,EAAEC,QAAQ,QAAQ,yBAAwB;AACnE,SAASC,OAAO,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAE/E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,eAAe,QAAQ,iCAAgC;AAC9E,SAASC,KAAK,EAAEC,OAAO,EAAEC,UAAU,QAAQ,gBAAe;AAC1D,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,SAAS,EAAEC,SAAS,QAAQ,kBAAiB;AACtD,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAO;AAC5C,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,oBAAoB,QAAQ,sCAAkC;AACvE,SAASC,oBAAoB,EAAEC,cAAc,QAAQ,gCAA4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AM;gCAAU;4BACvE3C,aAAa,CAAClF;;sCAEhB,KAAC/C,iCACK8C,MAAM4F,KAAK;4BACfmC,SAAS/H,MAAMgI,KAAK;4BACpB/I,QAAQuB;4BACRkH,SAAS;gCAAEvI;gCAAInD,KAAKmE;4BAAI;4BACxBT,OAAOA;4BACPE,cAAcA;4BACdE,WAAWA;4BACXoG,YAAYnF,QAAQmF,UAAU;4BAC9B,+DAA+D;4BAC/D,oDAAoD;4BACpD+B,UAAU,CAACC;gCACT,IAAIA,eAAe/I,IAAIG,OAAO6I,OAAO,CAAC9I,OAAO8H,OAAO,CAACe;4BACvD;;;qBAGF;gBACHnE,MAAMqE,MAAM;;;;AAInB;AACArJ,kBAAkBsJ,WAAW,GAAG;AAEhC,eAAetJ,kBAAiB"}
@@ -1,4 +1,5 @@
1
1
  import { type AglynOrgBilling, type ConsentGroup } from '@aglyn/aglyn';
2
+ import { type ListenHandle } from '@aglyn/tenant-feature-instance';
2
3
  import { type ContactRecord } from '../model/contact-record';
3
4
  import type { OrgMembers } from './use-org-members';
4
5
  export interface ContactPropertiesCardProps {
@@ -24,6 +25,8 @@ export interface ContactPropertiesCardProps {
24
25
  seed: {
25
26
  status: 'loading' | 'success' | 'error';
26
27
  fromCache: boolean;
28
+ /** The row's listener, so a save waits on that read alone (AGL-4135). */
29
+ listen?: ListenHandle | null;
27
30
  };
28
31
  /** The team, for the owner picker and the owner's name. */
29
32
  members: OrgMembers;
@@ -345,7 +345,8 @@ export function ContactPropertiesCard(props) {
345
345
  const verdict = await writeGuardedBySeed({
346
346
  subject: 'contact',
347
347
  unreadable: seed.status === 'error',
348
- fromCache: seed.fromCache
348
+ fromCache: seed.fromCache,
349
+ listen: seed.listen
349
350
  }, ()=>contactUpdate.updateOne(record.$id, set));
350
351
  if (!verdict.ok) {
351
352
  return void enqueueSnackbar(verdict.message, {
@@ -427,6 +428,7 @@ export function ContactPropertiesCard(props) {
427
428
  reportsTo,
428
429
  salutation,
429
430
  seed.fromCache,
431
+ seed.listen,
430
432
  seed.status,
431
433
  suiteLocked,
432
434
  tags,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-properties-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 * as Aglyn from '@aglyn/aglyn'\nimport {\n type AglynOrgBilling,\n composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_NAME_PART_MAX,\n CONTACT_PHONE_FIELD_LABELS,\n type ConsentGroup,\n type ContactLifecycleStage,\n CRM_SALUTATION_PICKLIST,\n crmTelHref,\n normalizeContactBirthdate,\n normalizeContactEmail,\n normalizePhone,\n} from '@aglyn/aglyn'\nimport { mdiPhoneOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser, writeGuardedBySeed } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormHelperText,\n Grid,\n IconButton,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { type ContactRecord, parseContactTags } from '../model/contact-record'\nimport type { ContactUpdateFields } from '../model/contact-update'\nimport { setContactStage } from '../model/crm-api'\nimport {\n type CrmCustomDraft,\n crmCustomDraftChanges,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n} from '../model/crm-custom-draft'\nimport {\n CompanyPicker,\n useCompanyOptions,\n useCreateCompany,\n} from './company-picker'\nimport {\n addressDraftFrom,\n ContactAddressFields,\n type AddressDraft,\n} from './contact-address-fields'\nimport { ContactReportsToField } from './contact-reports-to-field'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { crmSuiteLockedReason } from './crm-suite-lock'\nimport { LeadSourceSelect } from './lead-source-select'\nimport type { OrgMembers } from './use-org-members'\n\nexport interface ContactPropertiesCardProps {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed, for the company picker's scope. */\n org?: Partial<AglynOrgBilling> | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /**\n * The org the record belongs to, as the page resolved it — for the org's\n * lead source values (AGL-3298) and its custom contact fields (AGL-2601).\n * Null while it settles, when the select offers the starter list, no\n * custom field is drawn yet, and the save still sends only what changed.\n */\n orgId?: string | null\n /** The controller whose facet the edits are saved into. */\n consentGroup: ConsentGroup\n /**\n * The listener's verdict on the row the drafts were seeded from, for the\n * guard that refuses a save over an unconfirmed read.\n */\n seed: { status: 'loading' | 'success' | 'error'; fromCache: boolean }\n /** The team, for the owner picker and the owner's name. */\n members: OrgMembers\n /**\n * The org's plan lacks the CRM (AGL-2788), which the shell mounts no CRM\n * page for (AGL-2851). The owner, the lifecycle stage and the company\n * show, locked, and are left out of a save; `crm/contact-update` refuses\n * such a plan the rest of the profile, the tags and the notes too. The\n * custom fields are the CRM's as well, and are not drawn.\n */\n suiteLocked?: boolean\n}\n\n/**\n * THE RECORD ITSELF: every field a team keeps on a person, in one card with\n * one Save in its header (AGL-2596).\n *\n * ## Custom fields sit with the built-in ones\n *\n * The org's own contact fields (AGL-2601) are drawn under **More fields**,\n * after the built-in properties, the way Salesforce keeps custom fields in\n * the record's Details beside the standard ones — and they save with them.\n * An org with no active field draws no subsection at all.\n *\n * A custom value is THIS holder's (`facets.{group}.custom.{key}`), so the\n * draft holds only the keys the reader touched and the save sends only the\n * keys that changed: the route writes each at its own dotted path, and a\n * `custom` map sent whole would take every key this card did not touch out\n * with it. A cleared control sends `null`, the explicit \"cleared\" the model\n * keeps the key present with, and a required field left empty is refused\n * before anything is sent.\n *\n * ## One save, one request, one guard\n *\n * A field-at-a-time save would be nine requests and nine chances for the\n * stale-seed guard to refuse one of them — so the card holds a draft of the\n * whole profile and sends it once. The guard WRAPS the send: a row seeded\n * from the cache or from a failed read is refused with the message the guard\n * chooses, and what was typed stays in the fields, because a refusal that\n * also emptied the form would read as a save that worked.\n *\n * ## The server writes the facet (AGL-2804)\n *\n * Every field here lives in THIS holder's facet, and the Firestore rules\n * cannot tell one field of a facet from another, so the card writes nothing\n * itself. The draft goes to `crm/contact-update`, which writes each field by\n * dotted path into the holder's facet — never a nested object, which would\n * take every other holder's records with it — clears a blank field rather\n * than storing it empty, keeps the phone's and the company's search echoes\n * at the top of the document, and refuses every field to a plan without\n * the CRM. A refusal is shown in the route's own words.\n *\n * ## The stage goes to its own route\n *\n * The lifecycle stage is the one field an automation listens for:\n * `contactStageChanged` (AGL-2605) is emitted by `crm/contact-stage` after it\n * performs the write, and by nothing else. So when the stage the reader\n * picked differs from the one the record holds, it is sent to that route\n * once the rest of the profile has landed — the stage picked, or `null` for\n * \"Not placed yet\", which clears it and announces nothing. A refusal from\n * that route is reported on its own, with its sentence, after the fields that\n * did save.\n *\n * ## The name is an override\n *\n * The canonical name is shared by every site holding the person, so this\n * card never edits it. What it saves is this holder's own name for them,\n * and the helper says what a blank falls back to, so nobody clears the\n * field expecting the record to go nameless.\n *\n * ## Salesforce's sections (AGL-3515)\n *\n * The fields are grouped the way Salesforce's contact Details groups them —\n * Contact information, Phones, Addresses, Additional information — and every\n * one is still one draft and one Save. While the holder keeps a first or\n * last name the Name field shows their composition and is read-only; the\n * save sends the parts, and the route composes the name from them. The\n * salutation and the reports-to are sent only when they change, for the\n * lead source's reason: the route judges a sent one. Do not call is a hint\n * on every phone's call link, never a block.\n *\n * ## Company is a record, with its name kept beside it\n *\n * The Company field is the picker (AGL-2613): the link is `companyId` in\n * this holder's facet, mirrored into the top-level `companyIds` for the\n * company page's query, and the company's contacts count moves with it —\n * all planned by the route from the stored document, so this card never\n * reasons about another holder's link. The name is sent too, from the picked\n * company, because the list column and the global search read the name and\n * not the id; a record that carries a name with no link — an import, a save\n * from before the picker — keeps it as the label, and the picker offers it\n * as the company to link or create.\n */\n/** The phone fields the card edits, in the order the Phones section lists them. */\nconst PHONE_FIELDS = ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const\ntype PhoneField = (typeof PHONE_FIELDS)[number]\ntype PhoneDrafts = Record<PhoneField, string>\n\nconst phoneDraftsFrom = (record: ContactRecord): PhoneDrafts =>\n Object.fromEntries(\n PHONE_FIELDS.map((field) => [field, String(record[field] ?? '')]),\n ) as PhoneDrafts\n\n/** The phones as the route stores them, or the fields that cannot be read as numbers. */\nfunction readPhones(\n drafts: PhoneDrafts,\n): { ok: true; phones: PhoneDrafts } | { ok: false; errors: Partial<PhoneDrafts> } {\n const phones = {} as PhoneDrafts\n const errors: Partial<PhoneDrafts> = {}\n for (const field of PHONE_FIELDS) {\n const typed = drafts[field].trim()\n const normalized = typed ? normalizePhone(typed) : ''\n if (normalized === null) errors[field] = PHONE_HELP_ERROR\n else phones[field] = normalized\n }\n return Object.keys(errors).length ? { ok: false, errors } : { ok: true, phones }\n}\n\nconst PHONE_HELP = 'With the country code, like +1 512 555 0107'\nconst PHONE_HELP_ERROR = 'Enter it with its country code, like +1 512 555 0107.'\n\n/** A section heading inside the card — Salesforce's Details groups its fields the same way. */\nfunction SectionHeading(props: { children: string }) {\n return (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\" color=\"text.secondary\">\n {props.children}\n </Typography>\n </Grid>\n )\n}\n\nexport function ContactPropertiesCard(props: ContactPropertiesCardProps) {\n const {\n hostId,\n org,\n record,\n orgId = null,\n consentGroup,\n seed,\n members,\n suiteLocked = false,\n } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n // The site a stage move is routed through: the mounted one, or at the\n // organization level the holder's own (AGL-2630).\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const companies = useCompanyOptions({ hostId, org })\n const createCompany = useCreateCompany({ hostId, org })\n\n const [nameOverride, setNameOverride] = useState(record.nameOverride)\n const [salutation, setSalutation] = useState(record.salutation ?? '')\n const salutations = useCrmPicklist(CRM_SALUTATION_PICKLIST, orgId)\n const [firstName, setFirstName] = useState(record.firstName ?? '')\n const [lastName, setLastName] = useState(record.lastName ?? '')\n const [phones, setPhones] = useState<PhoneDrafts>(() => phoneDraftsFrom(record))\n const [doNotCall, setDoNotCall] = useState(record.doNotCall === true)\n const [email, setEmail] = useState(record.email)\n const [emailError, setEmailError] = useState('')\n const [jobTitle, setJobTitle] = useState(record.jobTitle)\n const [department, setDepartment] = useState(record.department ?? '')\n const [birthdate, setBirthdate] = useState(record.birthdate ?? '')\n const [assistantName, setAssistantName] = useState(record.assistantName ?? '')\n const [reportsTo, setReportsTo] = useState(record.reportsToContactId ?? '')\n // Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.\n const [leadSource, setLeadSource] = useState(record.leadSource)\n const leadSources = useLeadSourcePicklist(orgId)\n const [companyName, setCompanyName] = useState(record.companyName)\n const [companyId, setCompanyId] = useState<string | null>(\n record.companyId || null,\n )\n const [ownerUid, setOwnerUid] = useState(record.ownerUid)\n const [lifecycleStage, setLifecycleStage] = useState<ContactLifecycleStage | ''>(\n record.lifecycleStage,\n )\n const [tags, setTags] = useState(record.tags.join(', '))\n const [notes, setNotes] = useState(record.notes)\n const [address, setAddress] = useState<AddressDraft>(\n addressDraftFrom(record.address),\n )\n const [otherAddress, setOtherAddress] = useState<AddressDraft>(\n addressDraftFrom(record.otherAddress),\n )\n const [phoneErrors, setPhoneErrors] = useState<Partial<PhoneDrafts>>({})\n const [birthdateError, setBirthdateError] = useState('')\n const [saving, setSaving] = useState(false)\n /** The custom values the reader touched; every other key reads from the record. */\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /** Something was edited since the card was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const fields = useContactFieldDefinitions(suiteLocked ? null : orgId)\n // The custom fields are the CRM's; a plan without it draws and sends none.\n const customFields = suiteLocked ? [] : fields.active\n const storedCustom = useMemo(() => record.custom ?? {}, [record.custom])\n const customChanges = useMemo(\n () => crmCustomDraftChanges(storedCustom, custom),\n [storedCustom, custom],\n )\n const clearingRequired =\n crmCustomDraftMissingRequired(customFields, storedCustom, custom, 'edit').length > 0\n /*\n * The name the first and last names make (AGL-3515). While there is one,\n * it IS the name — the Name field shows it, read-only, and the save sends\n * the parts rather than a name the route would have to reconcile.\n */\n const composedName = composeContactName(firstName, lastName)\n\n /** One field's edit: the value, and the card now has something to save. */\n const change = useCallback(<T,>(set: (value: T) => void, value: T) => {\n set(value)\n setEdited(true)\n }, [])\n\n /** Every draft back to what the record holds — the seed, and Discard. */\n const reseed = () => {\n setNameOverride(record.nameOverride)\n setSalutation(record.salutation ?? '')\n setFirstName(record.firstName ?? '')\n setLastName(record.lastName ?? '')\n setPhones(phoneDraftsFrom(record))\n setDoNotCall(record.doNotCall === true)\n setEmail(record.email)\n setEmailError('')\n setJobTitle(record.jobTitle)\n setDepartment(record.department ?? '')\n setBirthdate(record.birthdate ?? '')\n setAssistantName(record.assistantName ?? '')\n setReportsTo(record.reportsToContactId ?? '')\n setLeadSource(record.leadSource)\n setCompanyName(record.companyName)\n setCompanyId(record.companyId || null)\n setOwnerUid(record.ownerUid)\n setLifecycleStage(record.lifecycleStage)\n setTags(record.tags.join(', '))\n setNotes(record.notes)\n setAddress(addressDraftFrom(record.address))\n setOtherAddress(addressDraftFrom(record.otherAddress))\n setPhoneErrors({})\n setBirthdateError('')\n setCustom({})\n setEdited(false)\n }\n\n /*\n * Re-seeded when the RECORD changes, not when it re-renders. The listener\n * delivers a fresh row on every snapshot, including the one this card's\n * own save produces; re-seeding on each would overwrite what somebody is\n * in the middle of typing with what the server last confirmed.\n */\n const recordId = record.$id\n useEffect(() => {\n reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n /*\n * And it follows the document until somebody edits it (AGL-4122). A page\n * drawn from the cache seeds these drafts from the cached row, and the\n * server's answer arrives a moment later with the newer one. Left alone, the\n * form kept the old values on screen with the seed reading confirmed, and the\n * next save wrote them back over the new ones without anyone having touched\n * those fields.\n */\n useEffect(() => {\n if (!edited) reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record])\n\n const handleSave = useCallback(async () => {\n if (clearingRequired) return\n const readPhonesResult = readPhones(phones)\n const storedBirthdate = normalizeContactBirthdate(birthdate)\n setPhoneErrors('errors' in readPhonesResult ? readPhonesResult.errors : {})\n setBirthdateError(storedBirthdate === null ? CONTACT_BIRTHDATE_REFUSAL : '')\n // The address, only when it moved. It can be filled in or replaced, never\n // emptied: a person who had one still answers to it (AGL-4122).\n const typedEmail = email.trim()\n const nextEmail = typedEmail === record.email ? null : normalizeContactEmail(typedEmail)\n const emailMoved = typedEmail !== record.email\n setEmailError(emailMoved && !nextEmail ? 'Enter a valid email address.' : '')\n if ('errors' in readPhonesResult || storedBirthdate === null) return\n if (emailMoved && !nextEmail) return\n // A stage that differs from the record's is the stage route's to write —\n // see the note above.\n const stageChanged = !suiteLocked && lifecycleStage !== record.lifecycleStage\n const set: ContactUpdateFields = {\n ...(nextEmail ? { email: nextEmail } : {}),\n // The name is the parts' while there are parts — see the note above.\n ...(composedName ? {} : { name: nameOverride.trim().slice(0, 120) }),\n firstName: firstName.trim(),\n lastName: lastName.trim(),\n ...readPhonesResult.phones,\n // Sent only when it moves: the route stores the flag as a fact about\n // the person, and an untouched card should not re-assert it.\n ...(doNotCall !== (record.doNotCall === true) ? { doNotCall } : {}),\n jobTitle: jobTitle.trim().slice(0, 120),\n department: department.trim().slice(0, 120),\n birthdate: storedBirthdate,\n assistantName: assistantName.trim().slice(0, 120),\n // Sent only when changed: the route judges a sent value against the\n // org's list, and an untouched one needs no judging. The reports-to\n // likewise, because the route checks a sent one for a loop.\n ...(leadSource !== record.leadSource ? { leadSource } : {}),\n ...(salutation !== (record.salutation ?? '') ? { salutation } : {}),\n ...(reportsTo !== (record.reportsToContactId ?? '')\n ? { reportsToContactId: reportsTo || null }\n : {}),\n address,\n otherAddress,\n tags: parseContactTags(tags),\n notes: notes.slice(0, 2000),\n // The owner and the company, sent only on a plan that carries the CRM.\n ...(suiteLocked\n ? {}\n : { ownerUid, companyId, companyName: companyName.trim().slice(0, 120) }),\n // Only the custom keys that changed — see the note above.\n ...(!suiteLocked && customChanges.length\n ? { custom: Object.fromEntries(customChanges) }\n : {}),\n }\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n },\n () => contactUpdate.updateOne(record.$id, set),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n logActivity('Updated contact', {\n type: 'contact',\n id: record.$id,\n name: record.name || email.trim() || record.phone,\n })\n // The custom values are stored; the controls read the record again.\n setCustom({})\n if (stageChanged) {\n try {\n // A person no site holds is staged at the organization (AGL-4122).\n await setContactStage(user, siteHostId, record.$id, lifecycleStage || null, {\n orgId,\n })\n } catch (error) {\n // The rest of the profile is saved; only the stage was refused, and\n // the route's own sentence says why.\n return void enqueueSnackbar(\n `Saved, but the stage could not be changed: ${\n error instanceof Error ? error.message : 'the request failed'\n }`,\n { variant: 'warning', persist: false },\n )\n }\n }\n setEdited(false)\n enqueueSnackbar('Contact saved', { variant: 'success', persist: false })\n } catch (error) {\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 } finally {\n setSaving(false)\n }\n }, [\n email,\n orgId,\n address,\n assistantName,\n birthdate,\n clearingRequired,\n companyId,\n companyName,\n composedName,\n contactUpdate,\n customChanges,\n department,\n doNotCall,\n enqueueSnackbar,\n firstName,\n siteHostId,\n jobTitle,\n lastName,\n leadSource,\n lifecycleStage,\n logActivity,\n nameOverride,\n notes,\n otherAddress,\n ownerUid,\n phones,\n record.$id,\n record.doNotCall,\n record.email,\n record.leadSource,\n record.lifecycleStage,\n record.name,\n record.reportsToContactId,\n record.salutation,\n reportsTo,\n salutation,\n seed.fromCache,\n seed.status,\n suiteLocked,\n tags,\n user,\n ])\n\n /*\n * An owner the roster no longer lists — somebody who left the team — is\n * still offered as the current value, named by their uid, so the select is\n * never handed a value it has no option for and the reader can see who it\n * was before reassigning.\n */\n const ownerKnown = members.options.some((option) => option.uid === ownerUid)\n\n /** One phone field, with click-to-call off what is IN the box (AGL-2661). */\n const phoneField = (field: PhoneField) => {\n const value = phones[field]\n const telHref = crmTelHref(value)\n const callLabel = doNotCall\n ? `Call ${value.trim()} — marked do not call`\n : `Call ${value.trim()}`\n return (\n <Grid key={field} size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label={CONTACT_PHONE_FIELD_LABELS[field]}\n value={value}\n onChange={(event) => change(setPhones, { ...phones, [field]: event.target.value })}\n error={Boolean(phoneErrors[field])}\n helperText={phoneErrors[field] || (field === 'phone' ? PHONE_HELP : undefined)}\n fullWidth\n slotProps={{\n input: {\n /*\n * The number on screen is the one a reader means to ring, and\n * `crmTelHref` withholds the link from anything half-typed. A\n * do-not-call person keeps the link — the rep decides — with\n * the request said in the tooltip and the icon's color.\n */\n endAdornment:\n telHref && field !== 'fax' ? (\n <InputAdornment position=\"end\">\n <Tooltip title={callLabel}>\n <IconButton\n component=\"a\"\n href={telHref}\n size=\"small\"\n edge=\"end\"\n color={doNotCall ? 'warning' : 'default'}\n aria-label={callLabel}\n >\n <MdiIcon path={mdiPhoneOutline.path} size={0.8} />\n </IconButton>\n </Tooltip>\n </InputAdornment>\n ) : null,\n },\n }}\n />\n </Grid>\n )\n }\n\n return (\n <CardDisplay\n header={'Properties'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#contact-properties' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n {edited ? (\n <Button size=\"small\" disabled={saving} onClick={reseed}>\n {'Discard changes'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={saving || !edited || clearingRequired}\n onClick={() => void handleSave()}\n >\n {saving ? 'Saving…' : 'Save'}\n </Button>\n </Stack>\n ),\n }}\n >\n <Grid container spacing={2}>\n <SectionHeading>{'Contact information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => change(setEmail, event.target.value)}\n error={Boolean(emailError)}\n helperText={\n emailError ||\n (record.email\n ? 'Every site shares this address, so changing it changes it for all of them.'\n : 'Add it whenever you have it.')\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CrmPicklistSelect\n picklistId={CRM_SALUTATION_PICKLIST}\n picklist={salutations.picklist}\n value={salutation}\n stored={record.salutation ?? ''}\n onChange={(value) => change(setSalutation, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"First name\"\n value={firstName}\n onChange={(event) => change(setFirstName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Last name\"\n value={lastName}\n onChange={(event) => change(setLastName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={composedName || nameOverride}\n onChange={(event) => change(setNameOverride, event.target.value)}\n slotProps={{\n htmlInput: { maxLength: 120 },\n input: { readOnly: Boolean(composedName) },\n }}\n helperText={\n composedName\n ? 'Made of the first and last name.'\n : record.canonicalName\n ? `Your own name for this person. Blank shows the name they gave: ${record.canonicalName}.`\n : 'Your own name for this person.'\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Job title\"\n value={jobTitle}\n onChange={(event) => change(setJobTitle, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Department\"\n value={department}\n onChange={(event) => change(setDepartment, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CompanyPicker\n options={companies.options}\n ready={companies.ready}\n truncated={companies.truncated}\n value={companyId}\n onChange={(id, company) => {\n change(setCompanyId, id)\n // The label follows the link: the picked name, or nothing\n // once the link is cleared. A company the list cannot name\n // keeps whatever label the record already had.\n setCompanyName(company ? company.name : id ? companyName : '')\n }}\n onCreate={createCompany}\n email={record.email}\n fallbackName={companyName}\n disabled={saving || suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <LeadSourceSelect\n picklist={leadSources.picklist}\n value={leadSource}\n stored={record.leadSource}\n onChange={(value) => change(setLeadSource, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Lifecycle stage\"\n value={lifecycleStage}\n onChange={(event) =>\n change(setLifecycleStage, event.target.value as ContactLifecycleStage | '')\n }\n disabled={suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n fullWidth\n >\n <MenuItem value=\"\">{'Not placed yet'}</MenuItem>\n {CONTACT_LIFECYCLE_STAGES.map((stage) => (\n <MenuItem key={stage} value={stage}>\n {CONTACT_LIFECYCLE_STAGE_LABELS[stage]}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={ownerUid}\n onChange={(event) => change(setOwnerUid, event.target.value)}\n disabled={suiteLocked}\n helperText={\n suiteLocked\n ? crmSuiteLockedReason()\n : members.ready && !members.options.length\n ? 'The team roster could not be read, so nobody can be picked yet.'\n : 'The team member responsible for this relationship'\n }\n fullWidth\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {ownerUid && !ownerKnown ? (\n <MenuItem value={ownerUid}>{members.memberName(ownerUid)}</MenuItem>\n ) : null}\n {members.options.map((owner) => (\n <MenuItem key={owner.uid} value={owner.uid}>\n {Aglyn.crmMemberPickerLabel(owner)}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"vip, beta\"\n helperText=\"Comma-separated\"\n value={tags}\n onChange={(event) => change(setTags, event.target.value)}\n fullWidth\n />\n </Grid>\n\n <SectionHeading>{'Phones'}</SectionHeading>\n {PHONE_FIELDS.filter((field) => field !== 'assistantPhone').map(phoneField)}\n <Grid size={{ xs: 12, sm: 6 }}>\n <FormControlLabel\n control={\n <Checkbox\n checked={doNotCall}\n onChange={(event) => change(setDoNotCall, event.target.checked)}\n />\n }\n label=\"Do not call\"\n />\n <FormHelperText>\n {'They asked not to be phoned. Every number still dials; the Call button says so.'}\n </FormHelperText>\n </Grid>\n\n <SectionHeading>{'Addresses'}</SectionHeading>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Mailing address'}</Typography>\n <ContactAddressFields\n value={address}\n onChange={(value) => change(setAddress, value)}\n />\n </Stack>\n </Grid>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Other address'}</Typography>\n <ContactAddressFields\n value={otherAddress}\n onChange={(value) => change(setOtherAddress, value)}\n />\n </Stack>\n </Grid>\n\n <SectionHeading>{'Additional information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n type=\"date\"\n label=\"Birthdate\"\n value={birthdate}\n onChange={(event) => change(setBirthdate, event.target.value)}\n error={Boolean(birthdateError)}\n helperText={birthdateError || undefined}\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <ContactReportsToField\n hostId={hostId}\n org={org}\n contactId={record.$id}\n groupId={consentGroup.groupId}\n value={reportsTo}\n onChange={(value) => change(setReportsTo, value)}\n disabled={saving}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Assistant\"\n value={assistantName}\n onChange={(event) => change(setAssistantName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n {phoneField('assistantPhone')}\n <Grid size={{ xs: 12 }}>\n <TextField\n size=\"small\"\n label=\"About\"\n value={notes}\n onChange={(event) => change(setNotes, event.target.value)}\n helperText=\"Notes for your team. Nobody outside this site's group can read them.\"\n multiline\n minRows={3}\n fullWidth\n />\n </Grid>\n {/*\n The org's own fields (AGL-2601), after the built-in ones and saved\n with them. Absent, not an empty box, while the org defines none.\n */}\n {customFields.length ? (\n <>\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\">{'More fields'}</Typography>\n </Grid>\n {customFields.map((definition) => (\n <Grid key={definition.$id} size={{ xs: 12, sm: 6 }}>\n <CrmCustomFieldControl\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n change(setCustom, { ...custom, [definition.key]: value })\n }\n disabled={saving}\n />\n </Grid>\n ))}\n {clearingRequired ? (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"caption\" color=\"error\">\n {'A required field cannot be left empty.'}\n </Typography>\n </Grid>\n ) : null}\n </>\n ) : null}\n </Grid>\n </CardDisplay>\n )\n}\nContactPropertiesCard.displayName = 'ContactPropertiesCard'\n\nexport default ContactPropertiesCard\n"],"names":["Aglyn","composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_NAME_PART_MAX","CONTACT_PHONE_FIELD_LABELS","CRM_SALUTATION_PICKLIST","crmTelHref","normalizeContactBirthdate","normalizeContactEmail","normalizePhone","mdiPhoneOutline","CardDisplay","MdiIcon","useSnackbar","useUser","writeGuardedBySeed","Button","Checkbox","FormControlLabel","FormHelperText","Grid","IconButton","InputAdornment","MenuItem","Stack","TextField","Tooltip","Typography","useCallback","useEffect","useMemo","useState","useContactFieldDefinitions","useContactUpdate","useCrmActivityLogger","useCrmPicklist","useLeadSourcePicklist","parseContactTags","setContactStage","crmCustomDraftChanges","crmCustomDraftMissingRequired","crmCustomDraftValue","CompanyPicker","useCompanyOptions","useCreateCompany","addressDraftFrom","ContactAddressFields","ContactReportsToField","CrmCustomFieldControl","CrmPicklistSelect","crmSuiteLockedReason","LeadSourceSelect","PHONE_FIELDS","phoneDraftsFrom","record","Object","fromEntries","map","field","String","readPhones","drafts","phones","errors","typed","trim","normalized","PHONE_HELP_ERROR","keys","length","ok","PHONE_HELP","SectionHeading","props","size","xs","variant","color","children","ContactPropertiesCard","hostId","org","orgId","consentGroup","seed","members","suiteLocked","data","user","enqueueSnackbar","contactUpdate","siteHostId","logActivity","companies","createCompany","nameOverride","setNameOverride","salutation","setSalutation","salutations","firstName","setFirstName","lastName","setLastName","setPhones","doNotCall","setDoNotCall","email","setEmail","emailError","setEmailError","jobTitle","setJobTitle","department","setDepartment","birthdate","setBirthdate","assistantName","setAssistantName","reportsTo","setReportsTo","reportsToContactId","leadSource","setLeadSource","leadSources","companyName","setCompanyName","companyId","setCompanyId","ownerUid","setOwnerUid","lifecycleStage","setLifecycleStage","tags","setTags","join","notes","setNotes","address","setAddress","otherAddress","setOtherAddress","phoneErrors","setPhoneErrors","birthdateError","setBirthdateError","saving","setSaving","custom","setCustom","edited","setEdited","fields","customFields","active","storedCustom","customChanges","clearingRequired","composedName","change","set","value","reseed","recordId","$id","handleSave","readPhonesResult","storedBirthdate","typedEmail","nextEmail","emailMoved","stageChanged","name","slice","verdict","subject","unreadable","status","fromCache","updateOne","message","persist","type","id","phone","error","Error","console","allowDuplicate","ownerKnown","options","some","option","uid","phoneField","telHref","callLabel","sm","label","onChange","event","target","Boolean","helperText","undefined","fullWidth","slotProps","input","endAdornment","position","title","component","href","edge","aria-label","path","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","disabled","onClick","container","picklistId","picklist","stored","htmlInput","maxLength","readOnly","canonicalName","ready","truncated","company","onCreate","fallbackName","select","stage","memberName","owner","crmMemberPickerLabel","placeholder","filter","control","checked","inputLabel","shrink","contactId","groupId","multiline","minRows","definition","key","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAEEC,kBAAkB,EAClBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,wBAAwB,EACxBC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AAenL,sBAAqB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-properties-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 * as Aglyn from '@aglyn/aglyn'\nimport {\n type AglynOrgBilling,\n composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_NAME_PART_MAX,\n CONTACT_PHONE_FIELD_LABELS,\n type ConsentGroup,\n type ContactLifecycleStage,\n CRM_SALUTATION_PICKLIST,\n crmTelHref,\n normalizeContactBirthdate,\n normalizeContactEmail,\n normalizePhone,\n} from '@aglyn/aglyn'\nimport { mdiPhoneOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormHelperText,\n Grid,\n IconButton,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { type ContactRecord, parseContactTags } from '../model/contact-record'\nimport type { ContactUpdateFields } from '../model/contact-update'\nimport { setContactStage } from '../model/crm-api'\nimport {\n type CrmCustomDraft,\n crmCustomDraftChanges,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n} from '../model/crm-custom-draft'\nimport {\n CompanyPicker,\n useCompanyOptions,\n useCreateCompany,\n} from './company-picker'\nimport {\n addressDraftFrom,\n ContactAddressFields,\n type AddressDraft,\n} from './contact-address-fields'\nimport { ContactReportsToField } from './contact-reports-to-field'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { crmSuiteLockedReason } from './crm-suite-lock'\nimport { LeadSourceSelect } from './lead-source-select'\nimport type { OrgMembers } from './use-org-members'\n\nexport interface ContactPropertiesCardProps {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed, for the company picker's scope. */\n org?: Partial<AglynOrgBilling> | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /**\n * The org the record belongs to, as the page resolved it — for the org's\n * lead source values (AGL-3298) and its custom contact fields (AGL-2601).\n * Null while it settles, when the select offers the starter list, no\n * custom field is drawn yet, and the save still sends only what changed.\n */\n orgId?: string | null\n /** The controller whose facet the edits are saved into. */\n consentGroup: ConsentGroup\n /**\n * The listener's verdict on the row the drafts were seeded from, for the\n * guard that refuses a save over an unconfirmed read.\n */\n seed: {\n status: 'loading' | 'success' | 'error'\n fromCache: boolean\n /** The row's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n }\n /** The team, for the owner picker and the owner's name. */\n members: OrgMembers\n /**\n * The org's plan lacks the CRM (AGL-2788), which the shell mounts no CRM\n * page for (AGL-2851). The owner, the lifecycle stage and the company\n * show, locked, and are left out of a save; `crm/contact-update` refuses\n * such a plan the rest of the profile, the tags and the notes too. The\n * custom fields are the CRM's as well, and are not drawn.\n */\n suiteLocked?: boolean\n}\n\n/**\n * THE RECORD ITSELF: every field a team keeps on a person, in one card with\n * one Save in its header (AGL-2596).\n *\n * ## Custom fields sit with the built-in ones\n *\n * The org's own contact fields (AGL-2601) are drawn under **More fields**,\n * after the built-in properties, the way Salesforce keeps custom fields in\n * the record's Details beside the standard ones — and they save with them.\n * An org with no active field draws no subsection at all.\n *\n * A custom value is THIS holder's (`facets.{group}.custom.{key}`), so the\n * draft holds only the keys the reader touched and the save sends only the\n * keys that changed: the route writes each at its own dotted path, and a\n * `custom` map sent whole would take every key this card did not touch out\n * with it. A cleared control sends `null`, the explicit \"cleared\" the model\n * keeps the key present with, and a required field left empty is refused\n * before anything is sent.\n *\n * ## One save, one request, one guard\n *\n * A field-at-a-time save would be nine requests and nine chances for the\n * stale-seed guard to refuse one of them — so the card holds a draft of the\n * whole profile and sends it once. The guard WRAPS the send: a row seeded\n * from the cache or from a failed read is refused with the message the guard\n * chooses, and what was typed stays in the fields, because a refusal that\n * also emptied the form would read as a save that worked.\n *\n * ## The server writes the facet (AGL-2804)\n *\n * Every field here lives in THIS holder's facet, and the Firestore rules\n * cannot tell one field of a facet from another, so the card writes nothing\n * itself. The draft goes to `crm/contact-update`, which writes each field by\n * dotted path into the holder's facet — never a nested object, which would\n * take every other holder's records with it — clears a blank field rather\n * than storing it empty, keeps the phone's and the company's search echoes\n * at the top of the document, and refuses every field to a plan without\n * the CRM. A refusal is shown in the route's own words.\n *\n * ## The stage goes to its own route\n *\n * The lifecycle stage is the one field an automation listens for:\n * `contactStageChanged` (AGL-2605) is emitted by `crm/contact-stage` after it\n * performs the write, and by nothing else. So when the stage the reader\n * picked differs from the one the record holds, it is sent to that route\n * once the rest of the profile has landed — the stage picked, or `null` for\n * \"Not placed yet\", which clears it and announces nothing. A refusal from\n * that route is reported on its own, with its sentence, after the fields that\n * did save.\n *\n * ## The name is an override\n *\n * The canonical name is shared by every site holding the person, so this\n * card never edits it. What it saves is this holder's own name for them,\n * and the helper says what a blank falls back to, so nobody clears the\n * field expecting the record to go nameless.\n *\n * ## Salesforce's sections (AGL-3515)\n *\n * The fields are grouped the way Salesforce's contact Details groups them —\n * Contact information, Phones, Addresses, Additional information — and every\n * one is still one draft and one Save. While the holder keeps a first or\n * last name the Name field shows their composition and is read-only; the\n * save sends the parts, and the route composes the name from them. The\n * salutation and the reports-to are sent only when they change, for the\n * lead source's reason: the route judges a sent one. Do not call is a hint\n * on every phone's call link, never a block.\n *\n * ## Company is a record, with its name kept beside it\n *\n * The Company field is the picker (AGL-2613): the link is `companyId` in\n * this holder's facet, mirrored into the top-level `companyIds` for the\n * company page's query, and the company's contacts count moves with it —\n * all planned by the route from the stored document, so this card never\n * reasons about another holder's link. The name is sent too, from the picked\n * company, because the list column and the global search read the name and\n * not the id; a record that carries a name with no link — an import, a save\n * from before the picker — keeps it as the label, and the picker offers it\n * as the company to link or create.\n */\n/** The phone fields the card edits, in the order the Phones section lists them. */\nconst PHONE_FIELDS = ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const\ntype PhoneField = (typeof PHONE_FIELDS)[number]\ntype PhoneDrafts = Record<PhoneField, string>\n\nconst phoneDraftsFrom = (record: ContactRecord): PhoneDrafts =>\n Object.fromEntries(\n PHONE_FIELDS.map((field) => [field, String(record[field] ?? '')]),\n ) as PhoneDrafts\n\n/** The phones as the route stores them, or the fields that cannot be read as numbers. */\nfunction readPhones(\n drafts: PhoneDrafts,\n): { ok: true; phones: PhoneDrafts } | { ok: false; errors: Partial<PhoneDrafts> } {\n const phones = {} as PhoneDrafts\n const errors: Partial<PhoneDrafts> = {}\n for (const field of PHONE_FIELDS) {\n const typed = drafts[field].trim()\n const normalized = typed ? normalizePhone(typed) : ''\n if (normalized === null) errors[field] = PHONE_HELP_ERROR\n else phones[field] = normalized\n }\n return Object.keys(errors).length ? { ok: false, errors } : { ok: true, phones }\n}\n\nconst PHONE_HELP = 'With the country code, like +1 512 555 0107'\nconst PHONE_HELP_ERROR = 'Enter it with its country code, like +1 512 555 0107.'\n\n/** A section heading inside the card — Salesforce's Details groups its fields the same way. */\nfunction SectionHeading(props: { children: string }) {\n return (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\" color=\"text.secondary\">\n {props.children}\n </Typography>\n </Grid>\n )\n}\n\nexport function ContactPropertiesCard(props: ContactPropertiesCardProps) {\n const {\n hostId,\n org,\n record,\n orgId = null,\n consentGroup,\n seed,\n members,\n suiteLocked = false,\n } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n // The site a stage move is routed through: the mounted one, or at the\n // organization level the holder's own (AGL-2630).\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const companies = useCompanyOptions({ hostId, org })\n const createCompany = useCreateCompany({ hostId, org })\n\n const [nameOverride, setNameOverride] = useState(record.nameOverride)\n const [salutation, setSalutation] = useState(record.salutation ?? '')\n const salutations = useCrmPicklist(CRM_SALUTATION_PICKLIST, orgId)\n const [firstName, setFirstName] = useState(record.firstName ?? '')\n const [lastName, setLastName] = useState(record.lastName ?? '')\n const [phones, setPhones] = useState<PhoneDrafts>(() => phoneDraftsFrom(record))\n const [doNotCall, setDoNotCall] = useState(record.doNotCall === true)\n const [email, setEmail] = useState(record.email)\n const [emailError, setEmailError] = useState('')\n const [jobTitle, setJobTitle] = useState(record.jobTitle)\n const [department, setDepartment] = useState(record.department ?? '')\n const [birthdate, setBirthdate] = useState(record.birthdate ?? '')\n const [assistantName, setAssistantName] = useState(record.assistantName ?? '')\n const [reportsTo, setReportsTo] = useState(record.reportsToContactId ?? '')\n // Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.\n const [leadSource, setLeadSource] = useState(record.leadSource)\n const leadSources = useLeadSourcePicklist(orgId)\n const [companyName, setCompanyName] = useState(record.companyName)\n const [companyId, setCompanyId] = useState<string | null>(\n record.companyId || null,\n )\n const [ownerUid, setOwnerUid] = useState(record.ownerUid)\n const [lifecycleStage, setLifecycleStage] = useState<ContactLifecycleStage | ''>(\n record.lifecycleStage,\n )\n const [tags, setTags] = useState(record.tags.join(', '))\n const [notes, setNotes] = useState(record.notes)\n const [address, setAddress] = useState<AddressDraft>(\n addressDraftFrom(record.address),\n )\n const [otherAddress, setOtherAddress] = useState<AddressDraft>(\n addressDraftFrom(record.otherAddress),\n )\n const [phoneErrors, setPhoneErrors] = useState<Partial<PhoneDrafts>>({})\n const [birthdateError, setBirthdateError] = useState('')\n const [saving, setSaving] = useState(false)\n /** The custom values the reader touched; every other key reads from the record. */\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /** Something was edited since the card was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const fields = useContactFieldDefinitions(suiteLocked ? null : orgId)\n // The custom fields are the CRM's; a plan without it draws and sends none.\n const customFields = suiteLocked ? [] : fields.active\n const storedCustom = useMemo(() => record.custom ?? {}, [record.custom])\n const customChanges = useMemo(\n () => crmCustomDraftChanges(storedCustom, custom),\n [storedCustom, custom],\n )\n const clearingRequired =\n crmCustomDraftMissingRequired(customFields, storedCustom, custom, 'edit').length > 0\n /*\n * The name the first and last names make (AGL-3515). While there is one,\n * it IS the name — the Name field shows it, read-only, and the save sends\n * the parts rather than a name the route would have to reconcile.\n */\n const composedName = composeContactName(firstName, lastName)\n\n /** One field's edit: the value, and the card now has something to save. */\n const change = useCallback(<T,>(set: (value: T) => void, value: T) => {\n set(value)\n setEdited(true)\n }, [])\n\n /** Every draft back to what the record holds — the seed, and Discard. */\n const reseed = () => {\n setNameOverride(record.nameOverride)\n setSalutation(record.salutation ?? '')\n setFirstName(record.firstName ?? '')\n setLastName(record.lastName ?? '')\n setPhones(phoneDraftsFrom(record))\n setDoNotCall(record.doNotCall === true)\n setEmail(record.email)\n setEmailError('')\n setJobTitle(record.jobTitle)\n setDepartment(record.department ?? '')\n setBirthdate(record.birthdate ?? '')\n setAssistantName(record.assistantName ?? '')\n setReportsTo(record.reportsToContactId ?? '')\n setLeadSource(record.leadSource)\n setCompanyName(record.companyName)\n setCompanyId(record.companyId || null)\n setOwnerUid(record.ownerUid)\n setLifecycleStage(record.lifecycleStage)\n setTags(record.tags.join(', '))\n setNotes(record.notes)\n setAddress(addressDraftFrom(record.address))\n setOtherAddress(addressDraftFrom(record.otherAddress))\n setPhoneErrors({})\n setBirthdateError('')\n setCustom({})\n setEdited(false)\n }\n\n /*\n * Re-seeded when the RECORD changes, not when it re-renders. The listener\n * delivers a fresh row on every snapshot, including the one this card's\n * own save produces; re-seeding on each would overwrite what somebody is\n * in the middle of typing with what the server last confirmed.\n */\n const recordId = record.$id\n useEffect(() => {\n reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n /*\n * And it follows the document until somebody edits it (AGL-4122). A page\n * drawn from the cache seeds these drafts from the cached row, and the\n * server's answer arrives a moment later with the newer one. Left alone, the\n * form kept the old values on screen with the seed reading confirmed, and the\n * next save wrote them back over the new ones without anyone having touched\n * those fields.\n */\n useEffect(() => {\n if (!edited) reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record])\n\n const handleSave = useCallback(async () => {\n if (clearingRequired) return\n const readPhonesResult = readPhones(phones)\n const storedBirthdate = normalizeContactBirthdate(birthdate)\n setPhoneErrors('errors' in readPhonesResult ? readPhonesResult.errors : {})\n setBirthdateError(storedBirthdate === null ? CONTACT_BIRTHDATE_REFUSAL : '')\n // The address, only when it moved. It can be filled in or replaced, never\n // emptied: a person who had one still answers to it (AGL-4122).\n const typedEmail = email.trim()\n const nextEmail = typedEmail === record.email ? null : normalizeContactEmail(typedEmail)\n const emailMoved = typedEmail !== record.email\n setEmailError(emailMoved && !nextEmail ? 'Enter a valid email address.' : '')\n if ('errors' in readPhonesResult || storedBirthdate === null) return\n if (emailMoved && !nextEmail) return\n // A stage that differs from the record's is the stage route's to write —\n // see the note above.\n const stageChanged = !suiteLocked && lifecycleStage !== record.lifecycleStage\n const set: ContactUpdateFields = {\n ...(nextEmail ? { email: nextEmail } : {}),\n // The name is the parts' while there are parts — see the note above.\n ...(composedName ? {} : { name: nameOverride.trim().slice(0, 120) }),\n firstName: firstName.trim(),\n lastName: lastName.trim(),\n ...readPhonesResult.phones,\n // Sent only when it moves: the route stores the flag as a fact about\n // the person, and an untouched card should not re-assert it.\n ...(doNotCall !== (record.doNotCall === true) ? { doNotCall } : {}),\n jobTitle: jobTitle.trim().slice(0, 120),\n department: department.trim().slice(0, 120),\n birthdate: storedBirthdate,\n assistantName: assistantName.trim().slice(0, 120),\n // Sent only when changed: the route judges a sent value against the\n // org's list, and an untouched one needs no judging. The reports-to\n // likewise, because the route checks a sent one for a loop.\n ...(leadSource !== record.leadSource ? { leadSource } : {}),\n ...(salutation !== (record.salutation ?? '') ? { salutation } : {}),\n ...(reportsTo !== (record.reportsToContactId ?? '')\n ? { reportsToContactId: reportsTo || null }\n : {}),\n address,\n otherAddress,\n tags: parseContactTags(tags),\n notes: notes.slice(0, 2000),\n // The owner and the company, sent only on a plan that carries the CRM.\n ...(suiteLocked\n ? {}\n : { ownerUid, companyId, companyName: companyName.trim().slice(0, 120) }),\n // Only the custom keys that changed — see the note above.\n ...(!suiteLocked && customChanges.length\n ? { custom: Object.fromEntries(customChanges) }\n : {}),\n }\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n listen: seed.listen,\n },\n () => contactUpdate.updateOne(record.$id, set),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n logActivity('Updated contact', {\n type: 'contact',\n id: record.$id,\n name: record.name || email.trim() || record.phone,\n })\n // The custom values are stored; the controls read the record again.\n setCustom({})\n if (stageChanged) {\n try {\n // A person no site holds is staged at the organization (AGL-4122).\n await setContactStage(user, siteHostId, record.$id, lifecycleStage || null, {\n orgId,\n })\n } catch (error) {\n // The rest of the profile is saved; only the stage was refused, and\n // the route's own sentence says why.\n return void enqueueSnackbar(\n `Saved, but the stage could not be changed: ${\n error instanceof Error ? error.message : 'the request failed'\n }`,\n { variant: 'warning', persist: false },\n )\n }\n }\n setEdited(false)\n enqueueSnackbar('Contact saved', { variant: 'success', persist: false })\n } catch (error) {\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 } finally {\n setSaving(false)\n }\n }, [\n email,\n orgId,\n address,\n assistantName,\n birthdate,\n clearingRequired,\n companyId,\n companyName,\n composedName,\n contactUpdate,\n customChanges,\n department,\n doNotCall,\n enqueueSnackbar,\n firstName,\n siteHostId,\n jobTitle,\n lastName,\n leadSource,\n lifecycleStage,\n logActivity,\n nameOverride,\n notes,\n otherAddress,\n ownerUid,\n phones,\n record.$id,\n record.doNotCall,\n record.email,\n record.leadSource,\n record.lifecycleStage,\n record.name,\n record.reportsToContactId,\n record.salutation,\n reportsTo,\n salutation,\n seed.fromCache,\n seed.listen,\n seed.status,\n suiteLocked,\n tags,\n user,\n ])\n\n /*\n * An owner the roster no longer lists — somebody who left the team — is\n * still offered as the current value, named by their uid, so the select is\n * never handed a value it has no option for and the reader can see who it\n * was before reassigning.\n */\n const ownerKnown = members.options.some((option) => option.uid === ownerUid)\n\n /** One phone field, with click-to-call off what is IN the box (AGL-2661). */\n const phoneField = (field: PhoneField) => {\n const value = phones[field]\n const telHref = crmTelHref(value)\n const callLabel = doNotCall\n ? `Call ${value.trim()} — marked do not call`\n : `Call ${value.trim()}`\n return (\n <Grid key={field} size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label={CONTACT_PHONE_FIELD_LABELS[field]}\n value={value}\n onChange={(event) => change(setPhones, { ...phones, [field]: event.target.value })}\n error={Boolean(phoneErrors[field])}\n helperText={phoneErrors[field] || (field === 'phone' ? PHONE_HELP : undefined)}\n fullWidth\n slotProps={{\n input: {\n /*\n * The number on screen is the one a reader means to ring, and\n * `crmTelHref` withholds the link from anything half-typed. A\n * do-not-call person keeps the link — the rep decides — with\n * the request said in the tooltip and the icon's color.\n */\n endAdornment:\n telHref && field !== 'fax' ? (\n <InputAdornment position=\"end\">\n <Tooltip title={callLabel}>\n <IconButton\n component=\"a\"\n href={telHref}\n size=\"small\"\n edge=\"end\"\n color={doNotCall ? 'warning' : 'default'}\n aria-label={callLabel}\n >\n <MdiIcon path={mdiPhoneOutline.path} size={0.8} />\n </IconButton>\n </Tooltip>\n </InputAdornment>\n ) : null,\n },\n }}\n />\n </Grid>\n )\n }\n\n return (\n <CardDisplay\n header={'Properties'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#contact-properties' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n {edited ? (\n <Button size=\"small\" disabled={saving} onClick={reseed}>\n {'Discard changes'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={saving || !edited || clearingRequired}\n onClick={() => void handleSave()}\n >\n {saving ? 'Saving…' : 'Save'}\n </Button>\n </Stack>\n ),\n }}\n >\n <Grid container spacing={2}>\n <SectionHeading>{'Contact information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => change(setEmail, event.target.value)}\n error={Boolean(emailError)}\n helperText={\n emailError ||\n (record.email\n ? 'Every site shares this address, so changing it changes it for all of them.'\n : 'Add it whenever you have it.')\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CrmPicklistSelect\n picklistId={CRM_SALUTATION_PICKLIST}\n picklist={salutations.picklist}\n value={salutation}\n stored={record.salutation ?? ''}\n onChange={(value) => change(setSalutation, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"First name\"\n value={firstName}\n onChange={(event) => change(setFirstName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Last name\"\n value={lastName}\n onChange={(event) => change(setLastName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={composedName || nameOverride}\n onChange={(event) => change(setNameOverride, event.target.value)}\n slotProps={{\n htmlInput: { maxLength: 120 },\n input: { readOnly: Boolean(composedName) },\n }}\n helperText={\n composedName\n ? 'Made of the first and last name.'\n : record.canonicalName\n ? `Your own name for this person. Blank shows the name they gave: ${record.canonicalName}.`\n : 'Your own name for this person.'\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Job title\"\n value={jobTitle}\n onChange={(event) => change(setJobTitle, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Department\"\n value={department}\n onChange={(event) => change(setDepartment, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CompanyPicker\n options={companies.options}\n ready={companies.ready}\n truncated={companies.truncated}\n value={companyId}\n onChange={(id, company) => {\n change(setCompanyId, id)\n // The label follows the link: the picked name, or nothing\n // once the link is cleared. A company the list cannot name\n // keeps whatever label the record already had.\n setCompanyName(company ? company.name : id ? companyName : '')\n }}\n onCreate={createCompany}\n email={record.email}\n fallbackName={companyName}\n disabled={saving || suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <LeadSourceSelect\n picklist={leadSources.picklist}\n value={leadSource}\n stored={record.leadSource}\n onChange={(value) => change(setLeadSource, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Lifecycle stage\"\n value={lifecycleStage}\n onChange={(event) =>\n change(setLifecycleStage, event.target.value as ContactLifecycleStage | '')\n }\n disabled={suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n fullWidth\n >\n <MenuItem value=\"\">{'Not placed yet'}</MenuItem>\n {CONTACT_LIFECYCLE_STAGES.map((stage) => (\n <MenuItem key={stage} value={stage}>\n {CONTACT_LIFECYCLE_STAGE_LABELS[stage]}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={ownerUid}\n onChange={(event) => change(setOwnerUid, event.target.value)}\n disabled={suiteLocked}\n helperText={\n suiteLocked\n ? crmSuiteLockedReason()\n : members.ready && !members.options.length\n ? 'The team roster could not be read, so nobody can be picked yet.'\n : 'The team member responsible for this relationship'\n }\n fullWidth\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {ownerUid && !ownerKnown ? (\n <MenuItem value={ownerUid}>{members.memberName(ownerUid)}</MenuItem>\n ) : null}\n {members.options.map((owner) => (\n <MenuItem key={owner.uid} value={owner.uid}>\n {Aglyn.crmMemberPickerLabel(owner)}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"vip, beta\"\n helperText=\"Comma-separated\"\n value={tags}\n onChange={(event) => change(setTags, event.target.value)}\n fullWidth\n />\n </Grid>\n\n <SectionHeading>{'Phones'}</SectionHeading>\n {PHONE_FIELDS.filter((field) => field !== 'assistantPhone').map(phoneField)}\n <Grid size={{ xs: 12, sm: 6 }}>\n <FormControlLabel\n control={\n <Checkbox\n checked={doNotCall}\n onChange={(event) => change(setDoNotCall, event.target.checked)}\n />\n }\n label=\"Do not call\"\n />\n <FormHelperText>\n {'They asked not to be phoned. Every number still dials; the Call button says so.'}\n </FormHelperText>\n </Grid>\n\n <SectionHeading>{'Addresses'}</SectionHeading>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Mailing address'}</Typography>\n <ContactAddressFields\n value={address}\n onChange={(value) => change(setAddress, value)}\n />\n </Stack>\n </Grid>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Other address'}</Typography>\n <ContactAddressFields\n value={otherAddress}\n onChange={(value) => change(setOtherAddress, value)}\n />\n </Stack>\n </Grid>\n\n <SectionHeading>{'Additional information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n type=\"date\"\n label=\"Birthdate\"\n value={birthdate}\n onChange={(event) => change(setBirthdate, event.target.value)}\n error={Boolean(birthdateError)}\n helperText={birthdateError || undefined}\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <ContactReportsToField\n hostId={hostId}\n org={org}\n contactId={record.$id}\n groupId={consentGroup.groupId}\n value={reportsTo}\n onChange={(value) => change(setReportsTo, value)}\n disabled={saving}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Assistant\"\n value={assistantName}\n onChange={(event) => change(setAssistantName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n {phoneField('assistantPhone')}\n <Grid size={{ xs: 12 }}>\n <TextField\n size=\"small\"\n label=\"About\"\n value={notes}\n onChange={(event) => change(setNotes, event.target.value)}\n helperText=\"Notes for your team. Nobody outside this site's group can read them.\"\n multiline\n minRows={3}\n fullWidth\n />\n </Grid>\n {/*\n The org's own fields (AGL-2601), after the built-in ones and saved\n with them. Absent, not an empty box, while the org defines none.\n */}\n {customFields.length ? (\n <>\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\">{'More fields'}</Typography>\n </Grid>\n {customFields.map((definition) => (\n <Grid key={definition.$id} size={{ xs: 12, sm: 6 }}>\n <CrmCustomFieldControl\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n change(setCustom, { ...custom, [definition.key]: value })\n }\n disabled={saving}\n />\n </Grid>\n ))}\n {clearingRequired ? (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"caption\" color=\"error\">\n {'A required field cannot be left empty.'}\n </Typography>\n </Grid>\n ) : null}\n </>\n ) : null}\n </Grid>\n </CardDisplay>\n )\n}\nContactPropertiesCard.displayName = 'ContactPropertiesCard'\n\nexport default ContactPropertiesCard\n"],"names":["Aglyn","composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_NAME_PART_MAX","CONTACT_PHONE_FIELD_LABELS","CRM_SALUTATION_PICKLIST","crmTelHref","normalizeContactBirthdate","normalizeContactEmail","normalizePhone","mdiPhoneOutline","CardDisplay","MdiIcon","useSnackbar","useUser","writeGuardedBySeed","Button","Checkbox","FormControlLabel","FormHelperText","Grid","IconButton","InputAdornment","MenuItem","Stack","TextField","Tooltip","Typography","useCallback","useEffect","useMemo","useState","useContactFieldDefinitions","useContactUpdate","useCrmActivityLogger","useCrmPicklist","useLeadSourcePicklist","parseContactTags","setContactStage","crmCustomDraftChanges","crmCustomDraftMissingRequired","crmCustomDraftValue","CompanyPicker","useCompanyOptions","useCreateCompany","addressDraftFrom","ContactAddressFields","ContactReportsToField","CrmCustomFieldControl","CrmPicklistSelect","crmSuiteLockedReason","LeadSourceSelect","PHONE_FIELDS","phoneDraftsFrom","record","Object","fromEntries","map","field","String","readPhones","drafts","phones","errors","typed","trim","normalized","PHONE_HELP_ERROR","keys","length","ok","PHONE_HELP","SectionHeading","props","size","xs","variant","color","children","ContactPropertiesCard","hostId","org","orgId","consentGroup","seed","members","suiteLocked","data","user","enqueueSnackbar","contactUpdate","siteHostId","logActivity","companies","createCompany","nameOverride","setNameOverride","salutation","setSalutation","salutations","firstName","setFirstName","lastName","setLastName","setPhones","doNotCall","setDoNotCall","email","setEmail","emailError","setEmailError","jobTitle","setJobTitle","department","setDepartment","birthdate","setBirthdate","assistantName","setAssistantName","reportsTo","setReportsTo","reportsToContactId","leadSource","setLeadSource","leadSources","companyName","setCompanyName","companyId","setCompanyId","ownerUid","setOwnerUid","lifecycleStage","setLifecycleStage","tags","setTags","join","notes","setNotes","address","setAddress","otherAddress","setOtherAddress","phoneErrors","setPhoneErrors","birthdateError","setBirthdateError","saving","setSaving","custom","setCustom","edited","setEdited","fields","customFields","active","storedCustom","customChanges","clearingRequired","composedName","change","set","value","reseed","recordId","$id","handleSave","readPhonesResult","storedBirthdate","typedEmail","nextEmail","emailMoved","stageChanged","name","slice","verdict","subject","unreadable","status","fromCache","listen","updateOne","message","persist","type","id","phone","error","Error","console","allowDuplicate","ownerKnown","options","some","option","uid","phoneField","telHref","callLabel","sm","label","onChange","event","target","Boolean","helperText","undefined","fullWidth","slotProps","input","endAdornment","position","title","component","href","edge","aria-label","path","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","disabled","onClick","container","picklistId","picklist","stored","htmlInput","maxLength","readOnly","canonicalName","ready","truncated","company","onCreate","fallbackName","select","stage","memberName","owner","crmMemberPickerLabel","placeholder","filter","control","checked","inputLabel","shrink","contactId","groupId","multiline","minRows","definition","key","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAEEC,kBAAkB,EAClBC,yBA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G;sCACnB,cAAA,KAAChD;gCAAWiD,SAAQ;gCAAUC,OAAM;0CACjC;;6BAGH;;qBAEJ;;;;AAIZ;AACAE,sBAAsBoL,WAAW,GAAG;AAEpC,eAAepL,sBAAqB"}
@@ -14,6 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ import { type ListenHandle } from '@aglyn/tenant-feature-instance';
17
18
  import { type CrmOrgDoc } from '../hooks/use-crm-scope';
18
19
  import type { CrmRoutes } from '../model/crm-routes';
19
20
  import type { DealDoc } from '../model/deal-board-model';
@@ -26,6 +27,8 @@ export interface DealContactRolesCardProps {
26
27
  /** The listener's verdict on the deal, for the stale-seed guard. */
27
28
  fromCache: boolean;
28
29
  unreadable: boolean;
30
+ /** The deal's listener, so a save waits on that read alone (AGL-4135). */
31
+ listen?: ListenHandle | null;
29
32
  }
30
33
  /**
31
34
  * Salesforce's Opportunity Contact Roles on a deal's page (AGL-3521): the
@@ -41,7 +41,7 @@ import { ContactRolesEditor } from "./contact-roles-editor.js";
41
41
  */ export function DealContactRolesCard(props) {
42
42
  var _ref;
43
43
  var _scope_consentGroup;
44
- const { deal, hostId, org, routes, fromCache, unreadable } = props;
44
+ const { deal, hostId, org, routes, fromCache, unreadable, listen } = props;
45
45
  const firestore = useFirestore();
46
46
  const { enqueueSnackbar } = useSnackbar();
47
47
  const scope = useCrmScope({
@@ -87,7 +87,8 @@ import { ContactRolesEditor } from "./contact-roles-editor.js";
87
87
  const written = await writeGuardedBySeed({
88
88
  subject: 'deal',
89
89
  unreadable,
90
- fromCache
90
+ fromCache,
91
+ listen
91
92
  }, async ()=>{
92
93
  await updateDoc(doc(firestore, 'orgs', scope.orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, patch, crmClientListFields('deals', deal, patch, CRM_DEAL_CONTACT_ROLE_LIST_FIELDS), {
93
94
  updatedAt: new Date()
@@ -122,6 +123,7 @@ import { ContactRolesEditor } from "./contact-roles-editor.js";
122
123
  nameOf,
123
124
  unreadable,
124
125
  fromCache,
126
+ listen,
125
127
  firestore,
126
128
  enqueueSnackbar
127
129
  ]);