@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/company-edit-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n type AglynPostalAddress,\n createResourceUid,\n CRM_COLLECTIONS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n CRM_COMPANY_PICKLIST_FIELDS,\n CRM_COMPANY_TEXT_MAX,\n type CrmCompany,\n type CrmCompanyPicklistField,\n crmCompanyParentId,\n crmCompanyParentRefusal,\n crmNewRecordListFields,\n crmPicklistDefaultLabel,\n pluginDocsHelp,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, HelpTip, MdiIcon, SrOnly } from '@aglyn/shared-ui-jsx'\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n deleteField,\n doc,\n getDoc,\n serverTimestamp,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCompanyPicklists } from '../hooks/use-company-picklists'\nimport { DEAL_CURRENCIES } from '../model/deal-board-model'\nimport { CompanyPicker, useCompanyOptions } from './company-picker'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport type { OrgMemberOptions } from '../hooks/use-org-member-options'\nimport {\n type CompanyDraft,\n companyDraftFields,\n companyDraftFrom,\n EMPTY_COMPANY_DRAFT,\n} from '../model/companies'\nimport {\n type CrmCustomDraft,\n crmCustomDraftDocument,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n crmCustomDraftWrites,\n} from '../model/crm-custom-draft'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmSitePicker } from './crm-site-picker'\nimport {\n CRM_CLIENT_SEARCH_FIELDS,\n CRM_CLIENT_SORT_FIELDS,\n crmClientListFields,\n} from '../model/crm-list-query'\n\n/**\n * The list fields a client edit of a company rewrites: the search tokens,\n * and the key beside each picklist field the Companies list filters by\n * (AGL-3514).\n */\nconst COMPANY_CLIENT_LIST_FIELDS = [\n ...CRM_CLIENT_SEARCH_FIELDS,\n // Any header sort key the edit's inputs move (AGL-3680).\n ...CRM_CLIENT_SORT_FIELDS,\n ...CRM_COMPANY_PICKLIST_FIELDS.flatMap((entry) => ('keyField' in entry ? [entry.keyField] : [])),\n]\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\nexport interface CompanyEditDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The site the drawer is opened under, or `null` at the organization\n * level (AGL-2630), where a NEW company asks which site captures it and\n * an edit keeps the company's own.\n */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n /**\n * The company being EDITED, or nothing to create one.\n *\n * The two modes differ in what the fields start as and in which write\n * runs: an edit opens on the stored values and updates the document, a\n * create opens empty and stamps the scope, provenance and timestamps a new\n * record must carry.\n */\n company?: (Partial<CrmCompany> & { $id: string }) | null\n /**\n * Whether the stored values the edit opened on can be trusted.\n *\n * Every optional field is written on every save — a blank one is a\n * DELETE — so a form seeded from a cached read would write the cache's\n * blanks over the server's values. The card that holds the listen reports\n * its own `fromCache` and `status`; the drawer refuses to save on a seed\n * the server never confirmed, and says so.\n */\n seed?: { fromCache: boolean; unreadable: boolean }\n /**\n * The team, for the owner picker.\n *\n * Handed in rather than fetched here, because the surface opening this\n * drawer already holds the roster to name owners in its rows, and one\n * fetch per surface is the bargain.\n */\n members: OrgMemberOptions\n /** Called with the record's id after a successful write. */\n onSaved: (companyId: string) => void\n}\n\ntype AddressDraftField = 'address' | 'shippingAddress'\n\n/** How each picklist field is labeled on a company. */\nconst COMPANY_PICKLIST_LABELS: Record<CrmCompanyPicklistField, string> = {\n type: 'Type',\n industry: 'Industry',\n rating: 'Rating',\n ownership: 'Ownership',\n accountSource: 'Account source',\n}\n\nconst ADDRESS_FIELDS: ReadonlyArray<{\n key: keyof AglynPostalAddress\n label: string\n}> = [\n { key: 'line1', label: 'Address line 1' },\n { key: 'line2', label: 'Address line 2' },\n { key: 'city', label: 'City' },\n { key: 'state', label: 'State or region' },\n { key: 'postalCode', label: 'Postal code' },\n { key: 'country', label: 'Country (two-letter code)' },\n]\n\n/**\n * ONE COMPANY, created or edited (AGL-2597).\n *\n * A drawer rather than a form above the list, and the same drawer for both\n * jobs: a company is eight fields and an address, which is too much to wedge\n * over a table and exactly the same set whether the record exists yet. The\n * list opens it empty; the company's page opens it on the record.\n *\n * Nothing is written per keystroke. The draft is held here and turned into a\n * document by `companyDraftFields` on Save, which is where a domain typed as\n * `acme` or a phone number with no country code is refused — as a message\n * beside the button, with the typed values left where they are.\n */\nexport function CompanyEditDrawer(props: CompanyEditDrawerProps) {\n const { open, onClose, hostId, org, company, seed, members, onSaved } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { scope, createTokens, createHostId, createNeedsSite } = useCrmScope({ hostId, org })\n // A client-direct write owes the org's sharing rules a re-evaluation (AGL-3336).\n const followUpSharing = useCrmSharingFollowUp(hostId, scope?.[1] ?? null)\n // The feed the act is logged in is the level it was PERFORMED at\n // (AGL-2738): this site's under a site, the organization's at the org\n // hub. `createHostId` is where the record is STAMPED, which at the hub is\n // a site the reader picked and may hold no role on — a different question\n // from where the line belongs, and a gate the record write never faced.\n const logActivity = useCrmActivityLogger(hostId)\n\n const [draft, setDraft] = useState<CompanyDraft>(EMPTY_COMPANY_DRAFT)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n /*\n * THE CUSTOM FIELDS (AGL-2661): the org's company definitions, and the\n * keys the reader has touched over what the company stores. Saved as the\n * difference — see `crm-custom-draft` — beside the fixed fields, in the\n * same write, so a company is never half-saved.\n */\n const fields = useContactFieldDefinitions(scope?.[1] ?? null, 'company')\n const storedCustom = useMemo(() => company?.custom ?? {}, [company?.custom])\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /*\n * THE RECORDS BAND (AGL-2611), read only for a CREATE: a company is a\n * record of the band the contacts list is banded by, and on an org at a\n * full hard band this drawer refuses the way `upsertHostContact` refuses a\n * capture — same number, same sentence. An edit is not a record and pays\n * for no aggregate. Only a SETTLED refusal refuses: three reads that have\n * not answered are not a full band.\n */\n const records = useCrmRecordsQuota(open && !company ? scope : null, org)\n const bandFull = !company && records.ready && !records.quota.allowed\n /*\n * SALESFORCE'S ACCOUNT FIELDS (AGL-3514): the org's lists behind Type,\n * Industry, Rating, Ownership and Account Source, and the companies a\n * parent may be chosen from — every one the reader can see but this one.\n */\n const picklists = useCompanyPicklists(scope?.[1] ?? null)\n const seededDefaults = useRef(false)\n const companyOptions = useCompanyOptions({ hostId, org, enabled: open })\n const parentOptions = useMemo(\n () => companyOptions.options.filter((option) => option.id !== company?.$id),\n [companyOptions.options, company?.$id],\n )\n\n /*\n * Seeded when the drawer OPENS, and not on every render of the card\n * behind it: the company listen is live, so re-seeding on each snapshot\n * would take a field away from whoever is typing in it — including on the\n * snapshot their own save produces. The create case seeds the owner to the\n * person filing the record, which is the answer nine times in ten and one\n * click to change.\n */\n const companyId = company?.$id\n useEffect(() => {\n if (!open) return\n setDraft(\n company\n ? companyDraftFrom(company)\n : { ...EMPTY_COMPANY_DRAFT, ownerUid: user?.uid ?? '' },\n )\n setCustom({})\n setError('')\n seededDefaults.current = false\n // The stored fields are read once per opening; `company` is a new object\n // on every snapshot and must not re-seed.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open, companyId])\n /*\n * A NEW company starts each picklist on the org's default, once the\n * lists have answered — Salesforce's form opens on it too — and only a\n * field nobody has picked a value for yet.\n */\n useEffect(() => {\n if (!open || company || !picklists.ready || seededDefaults.current) return\n seededDefaults.current = true\n setDraft((current) => {\n const next = { ...current }\n for (const { field, picklistId } of CRM_COMPANY_PICKLIST_FIELDS) {\n const list = picklists.lists[picklistId]\n const fallback = list ? crmPicklistDefaultLabel(list) : null\n if (!next[field] && fallback) next[field] = fallback\n }\n return next\n })\n }, [open, company, picklists])\n\n const patch = useCallback(\n (field: keyof Omit<CompanyDraft, AddressDraftField>, value: string) =>\n setDraft((current) => ({ ...current, [field]: value })),\n [],\n )\n const patchAddress = useCallback(\n (which: AddressDraftField, field: keyof AglynPostalAddress, value: string) =>\n setDraft((current) => ({\n ...current,\n [which]: { ...current[which], [field]: value },\n })),\n [],\n )\n /** The parent's own parent, as the cycle guard walks it; `null` for one this reader cannot see. */\n const readParent = useCallback(\n async (id: string) => {\n if (!scope) return null\n try {\n const snapshot = await getDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n )\n return snapshot.exists()\n ? { parentCompanyId: crmCompanyParentId(snapshot.get('parentCompanyId')) }\n : null\n } catch {\n return null\n }\n },\n [firestore, scope],\n )\n\n const handleSave = useCallback(async () => {\n if (busy || !scope) return\n const result = companyDraftFields(draft, { lists: picklists.lists, current: company })\n if (result.ok === false) return setError(result.error)\n // A parent is never this company, nor one already under it (AGL-3514).\n const parentId = crmCompanyParentId(result.set['parentCompanyId'])\n if (parentId && parentId !== crmCompanyParentId(company?.parentCompanyId)) {\n const refusal = await crmCompanyParentRefusal(company?.$id ?? null, parentId, readParent)\n if (refusal) return setError(refusal)\n }\n const missing = crmCustomDraftMissingRequired(\n fields.active,\n storedCustom,\n custom,\n company ? 'edit' : 'create',\n )\n if (missing.length) return setError(`${missing.join(', ')} is required.`)\n const customDocument = crmCustomDraftDocument(custom)\n setError('')\n setBusy(true)\n try {\n if (company) {\n const ref = doc(\n firestore,\n scope[0],\n scope[1],\n CRM_COLLECTIONS.companies,\n company.$id,\n )\n // The guard WRAPS the write — an early return is a shape you can\n // keep while losing the protection.\n const verdict = await writeGuardedBySeed(\n {\n subject: 'company',\n unreadable: seed?.unreadable ?? false,\n fromCache: seed?.fromCache ?? false,\n },\n async () => {\n const cleared = Object.fromEntries(\n result.cleared.map((field) => [field, deleteField()]),\n )\n // The stored record the list fields are computed from: the row\n // without the id the listener stamped on it.\n const { $id: _rowId, ...stored } = company\n const searchFields = crmClientListFields(\n 'companies',\n stored,\n { ...result.set, ...cleared },\n COMPANY_CLIENT_LIST_FIELDS,\n )\n await updateDoc(ref, {\n ...result.set,\n // A blank optional field is a DELETE on an edit, or the old\n // domain would stay stored and keep matching people by email.\n ...cleared,\n // The name and domain are what the Companies list searches\n // (AGL-3321), and the picklist keys what it filters by\n // (AGL-3514), from the listener's row with the edit over it.\n ...searchFields,\n // The custom keys that changed, merged into the stored map.\n ...crmCustomDraftWrites(storedCustom, custom),\n updatedAt: serverTimestamp(),\n })\n },\n )\n if (!verdict.ok) return setError(verdict.message)\n followUpSharing('companies', [company.$id])\n enqueueSnackbar('Company saved', { variant: 'success', persist: false })\n onSaved(company.$id)\n } else {\n if (bandFull) return setError(CRM_RECORDS_BAND_FULL_MESSAGE)\n const id = createResourceUid()\n // Held by the button until it knows who may see the company — the\n // whole org, or a picked site's group where the org keeps its sites\n // apart; checked again here because a callback can outlive the render\n // that held it.\n if (!createTokens.length) return\n await setDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n {\n ...result.set,\n ...(customDocument ? { custom: customDocument } : {}),\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', {\n ...result.set,\n visibleTo: [...createTokens],\n }),\n /*\n * The scope every CRM creator stamps: the whole org when the org\n * shares by default, and otherwise the sites that present as one\n * sender. Without it the record is seen by NOBODY — an absent\n * `visibleTo` matches no reader's predicate — and the rules\n * refuse a scoped member creating outside their own tokens.\n */\n visibleTo: [...createTokens],\n // Provenance: the site whose console filed it, never rewritten.\n hostId: createHostId,\n createdByUid: user?.uid ?? '',\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n },\n )\n // Setup → Activity shows CRM work (AGL-2622): the company is org\n // data, but the act happened in this site's console and belongs in\n // its feed. Creation only — an edit is a save the card reports.\n followUpSharing('companies', [id])\n logActivity('Added company', { type: 'company', id, name: draft.name.trim() })\n enqueueSnackbar(`Company \"${draft.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n onSaved(id)\n }\n onClose()\n } catch (caught) {\n console.error(caught)\n setError('The company could not be saved.')\n } finally {\n setBusy(false)\n }\n }, [\n busy,\n scope,\n followUpSharing,\n draft,\n company,\n bandFull,\n firestore,\n seed,\n createTokens,\n createHostId,\n user,\n logActivity,\n enqueueSnackbar,\n onSaved,\n onClose,\n fields.active,\n storedCustom,\n custom,\n picklists.lists,\n readParent,\n ])\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={onClose}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>{'close drawer'}</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {company ? 'Edit company' : 'New company'}\n </Typography>\n <HelpTip\n {...pluginDocsHelp('companies', { anchor: '#create-a-company' })}\n />\n </>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n {/*\n First, because the scope of everything below follows from it: at\n the organization level a new company names the site it came\n from — required where the org keeps its sites apart, optional\n where every site sees it. Nothing under a site, and nothing on an\n edit — a company keeps the site it was made on (AGL-2630).\n */}\n {company ? null : (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n optional={!createNeedsSite}\n helperText={\n createNeedsSite\n ? 'The site this company belongs to — it decides which of your sites may see it.'\n : undefined\n }\n />\n )}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The organization behind one or more of your contacts. The ' +\n 'domain is what suggests this company for a person from their ' +\n 'email address, so enter the bare hostname.'}\n </Typography>\n {bandFull ? (\n <Alert severity=\"warning\">{CRM_RECORDS_BAND_FULL_MESSAGE}</Alert>\n ) : null}\n {/*\n Grouped as Salesforce's Account page groups them (AGL-3514):\n what the company is, where it is, and what the team knows.\n */}\n <Typography variant=\"subtitle2\">{'Account information'}</Typography>\n <TextField\n size=\"small\"\n label=\"Name\"\n required\n value={draft.name}\n onChange={(event) => patch('name', event.target.value)}\n autoFocus\n />\n <CompanyPicker\n label=\"Parent company\"\n options={parentOptions}\n value={draft.parentCompanyId || null}\n onChange={(id) => patch('parentCompanyId', id ?? '')}\n ready={companyOptions.ready}\n truncated={companyOptions.truncated}\n disabled={busy}\n helperText=\"The company this one belongs to, such as a subsidiary's group.\"\n />\n <TextField\n size=\"small\"\n label=\"Domain\"\n placeholder=\"example.com\"\n value={draft.domain}\n onChange={(event) => patch('domain', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Website\"\n placeholder=\"https://www.example.com\"\n value={draft.website}\n onChange={(event) => patch('website', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Phone\"\n placeholder=\"+1 512 555 0123\"\n value={draft.phone}\n onChange={(event) => patch('phone', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Fax\"\n placeholder=\"+1 512 555 0124\"\n value={draft.fax}\n onChange={(event) => patch('fax', event.target.value)}\n />\n {CRM_COMPANY_PICKLIST_FIELDS.map(({ field, picklistId }) => {\n const list = picklists.lists[picklistId]\n return list ? (\n <CrmPicklistSelect\n key={field}\n picklistId={picklistId}\n picklist={list}\n label={COMPANY_PICKLIST_LABELS[field]}\n value={draft[field]}\n stored={company ? String(company[field] ?? '') : undefined}\n onChange={(label) => patch(field, label)}\n disabled={busy}\n />\n ) : null\n })}\n <TextField\n size=\"small\"\n label=\"Account number\"\n value={draft.accountNumber}\n onChange={(event) => patch('accountNumber', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.accountNumber } }}\n />\n <TextField\n size=\"small\"\n label=\"Account site\"\n placeholder=\"Headquarters\"\n helperText=\"Which of the company's locations this record is.\"\n value={draft.site}\n onChange={(event) => patch('site', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.site } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n size=\"small\"\n label=\"Ticker symbol\"\n value={draft.tickerSymbol}\n onChange={(event) => patch('tickerSymbol', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.tickerSymbol } }}\n sx={{ flex: 1 }}\n />\n <TextField\n size=\"small\"\n label=\"SIC code\"\n value={draft.sicCode}\n onChange={(event) => patch('sicCode', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.sicCode } }}\n sx={{ flex: 1 }}\n />\n </Stack>\n <TextField\n size=\"small\"\n label=\"Employees\"\n value={draft.numberOfEmployees}\n onChange={(event) => patch('numberOfEmployees', event.target.value)}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n size=\"small\"\n label=\"Annual revenue\"\n placeholder=\"0.00\"\n value={draft.annualRevenue}\n onChange={(event) => patch('annualRevenue', event.target.value)}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n sx={{ flex: 1 }}\n />\n <TextField\n select\n size=\"small\"\n label=\"Currency\"\n value={draft.currency}\n onChange={(event) => patch('currency', event.target.value)}\n sx={{ width: 120 }}\n >\n {/* A stored code outside the short list stays selectable as itself. */}\n {[...new Set<string>([...DEAL_CURRENCIES, draft.currency])].map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n {/*\n The owner is chosen from the team, never typed: the value is a\n uid, and a picker that is still loading says so rather than\n offering an empty list that reads as \"nobody can own this\".\n */}\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={draft.ownerUid}\n disabled={!members.ready}\n helperText={\n !members.ready\n ? 'Loading your team…'\n : (members.error ?? 'The team member responsible for this account.')\n }\n onChange={(event) => patch('ownerUid', event.target.value)}\n >\n <MenuItem value=\"\">{'Nobody yet'}</MenuItem>\n {draft.ownerUid &&\n !members.options.some((option) => option.uid === draft.ownerUid) ? (\n <MenuItem value={draft.ownerUid}>\n {members.labelFor(draft.ownerUid)}\n </MenuItem>\n ) : null}\n {members.options.map((option) => (\n <MenuItem key={option.uid} value={option.uid}>\n {crmMemberPickerLabel(option)}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"enterprise, west\"\n helperText=\"Comma-separated, lowercased — the same tags the bulk bar adds\"\n value={draft.tags}\n onChange={(event) => patch('tags', event.target.value)}\n />\n <Typography variant=\"subtitle2\">{'Address information'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Billing address'}\n </Typography>\n {ADDRESS_FIELDS.map((field) => (\n <TextField\n key={`address.${field.key}`}\n size=\"small\"\n label={field.label}\n value={draft.address[field.key] ?? ''}\n onChange={(event) => patchAddress('address', field.key, event.target.value)}\n />\n ))}\n <Stack direction=\"row\" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Shipping address'}\n </Typography>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() =>\n setDraft((current) => ({ ...current, shippingAddress: { ...current.address } }))\n }\n >\n {'Copy billing address'}\n </Button>\n </Stack>\n {ADDRESS_FIELDS.map((field) => (\n <TextField\n key={`shippingAddress.${field.key}`}\n size=\"small\"\n label={field.label}\n value={draft.shippingAddress[field.key] ?? ''}\n onChange={(event) => patchAddress('shippingAddress', field.key, event.target.value)}\n />\n ))}\n <Typography variant=\"subtitle2\">{'Description information'}</Typography>\n <TextField\n size=\"small\"\n label=\"Notes\"\n value={draft.notes}\n onChange={(event) => patch('notes', event.target.value)}\n multiline\n minRows={3}\n />\n {fields.active.length ? (\n <>\n <Typography variant=\"subtitle2\">{'Custom fields'}</Typography>\n {fields.active.map((definition) => (\n <CrmCustomFieldControl\n key={definition.$id}\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n setCustom((current) => ({ ...current, [definition.key]: value }))\n }\n disabled={busy}\n />\n ))}\n </>\n ) : null}\n {error ? <Alert severity=\"warning\">{error}</Alert> : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n // A new company waits for its capturing site.\n disabled={busy || !scope || !draft.name.trim() || (!company && !createTokens.length)}\n onClick={() => void handleSave()}\n >\n {busy\n ? 'Saving…'\n : company\n ? 'Save company'\n : 'Create company'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nCompanyEditDrawer.displayName = 'CompanyEditDrawer'\n\nexport default CompanyEditDrawer\n"],"names":["createResourceUid","CRM_COLLECTIONS","CRM_RECORDS_BAND_FULL_MESSAGE","CRM_COMPANY_PICKLIST_FIELDS","CRM_COMPANY_TEXT_MAX","crmCompanyParentId","crmCompanyParentRefusal","crmNewRecordListFields","crmPicklistDefaultLabel","pluginDocsHelp","crmMemberPickerLabel","ICON_VARIANT_CLOSE","Container","HelpTip","MdiIcon","SrOnly","NavigationDrawerComponent","useSnackbar","useFirestore","useUser","writeGuardedBySeed","Alert","Button","IconButton","MenuItem","Stack","TextField","Typography","deleteField","doc","getDoc","serverTimestamp","setDoc","updateDoc","useCallback","useEffect","useMemo","useRef","useState","useCompanyPicklists","DEAL_CURRENCIES","CompanyPicker","useCompanyOptions","CrmPicklistSelect","useContactFieldDefinitions","useCrmActivityLogger","useCrmRecordsQuota","useCrmScope","companyDraftFields","companyDraftFrom","EMPTY_COMPANY_DRAFT","crmCustomDraftDocument","crmCustomDraftMissingRequired","crmCustomDraftValue","crmCustomDraftWrites","CrmCustomFieldControl","CrmSitePicker","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","crmClientListFields","COMPANY_CLIENT_LIST_FIELDS","flatMap","entry","keyField","useCrmSharingFollowUp","COMPANY_PICKLIST_LABELS","type","industry","rating","ownership","accountSource","ADDRESS_FIELDS","key","label","CompanyEditDrawer","props","members","open","onClose","hostId","org","company","seed","onSaved","firestore","data","user","enqueueSnackbar","scope","createTokens","createHostId","createNeedsSite","followUpSharing","logActivity","draft","setDraft","busy","setBusy","error","setError","fields","storedCustom","custom","setCustom","records","bandFull","ready","quota","allowed","picklists","seededDefaults","companyOptions","enabled","parentOptions","options","filter","option","id","$id","companyId","ownerUid","uid","current","next","field","picklistId","list","lists","fallback","patch","value","patchAddress","which","readParent","snapshot","companies","exists","parentCompanyId","get","handleSave","result","ok","parentId","set","refusal","missing","active","length","join","customDocument","ref","verdict","subject","unreadable","fromCache","cleared","Object","fromEntries","map","_rowId","stored","searchFields","updatedAt","message","variant","persist","visibleTo","createdByUid","createdAt","name","trim","caught","console","anchor","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","gutterY","spacing","disabled","optional","helperText","undefined","severity","size","required","onChange","event","target","autoFocus","truncated","placeholder","domain","website","phone","fax","picklist","String","accountNumber","slotProps","htmlInput","maxLength","site","direction","tickerSymbol","flex","sicCode","numberOfEmployees","inputMode","annualRevenue","select","currency","width","Set","code","toUpperCase","some","labelFor","tags","address","alignItems","justifyContent","shippingAddress","notes","multiline","minRows","definition","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAGEA,iBAAiB,EACjBC,eAAe,EACfC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,oBAAoB,EAGpBC,kBAAkB,EAClBC,uBAAuB,EACvBC,sBAAsB,EACtBC,uBAAuB,EACvBC,cAAc,EACdC,oBAAoB,QACf,eAAc;AACrB,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,SAAS,EAAEC,OAAO,EAAEC,OAAO,EAAEC,MAAM,QAAQ,uBAAsB;AAC1E,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AACvC,SACEC,KAAK,EACLC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,WAAW,EACXC,GAAG,EACHC,MAAM,EACNC,eAAe,EACfC,MAAM,EACNC,SAAS,QACJ,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACzE,SAASC,mBAAmB,QAAQ,oCAAgC;AACpE,SAASC,eAAe,QAAQ,+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AAS;;oBAEVnI,OAAO8C,MAAM,CAACC,MAAM,iBACnB;;0CACE,KAACxH;gCAAWyI,SAAQ;0CAAa;;4BAChChE,OAAO8C,MAAM,CAACY,GAAG,CAAC,CAAC0E,2BAClB,KAACjL;oCAECiL,YAAYA;oCACZtG,OAAO7E,oBAAoBgD,cAAcC,QAAQkI,WAAWhK,GAAG;oCAC/DwH,UAAU,CAAC9D,QACT3B,UAAU,CAACmB,UAAa,aAAKA;gDAAS,CAAC8G,WAAWhK,GAAG,CAAC,EAAE0D;;oCAE1DuD,UAAUzF;mCANLwI,WAAWlH,GAAG;;yBAUvB;oBACHpB,sBAAQ,KAAC7E;wBAAMwK,UAAS;kCAAW3F;yBAAiB;kCACrD,MAACzE;wBAAMwL,WAAU;wBAAMzB,SAAS;;0CAC9B,KAAClK;gCACC8I,SAAQ;gCACRW,OAAM;gCACN,8CAA8C;gCAC9CU,UAAUzF,QAAQ,CAACR,SAAS,CAACM,MAAM2E,IAAI,CAACC,IAAI,MAAO,CAACzF,WAAW,CAACQ,aAAa0D,MAAM;gCACnF+B,SAAS,IAAM,KAAKvC;0CAEnB3C,OACG,YACAf,UACE,iBACA;;0CAER,KAAC3D;gCAAO4J,SAASpG;gCAAS2G,UAAUzF;0CACjC;;;;;;;;AAOf;AACAtB,kBAAkB+J,WAAW,GAAG;AAEhC,eAAe/J,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/company-edit-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n type AglynPostalAddress,\n createResourceUid,\n CRM_COLLECTIONS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n CRM_COMPANY_PICKLIST_FIELDS,\n CRM_COMPANY_TEXT_MAX,\n type CrmCompany,\n type CrmCompanyPicklistField,\n crmCompanyParentId,\n crmCompanyParentRefusal,\n crmNewRecordListFields,\n crmPicklistDefaultLabel,\n pluginDocsHelp,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, HelpTip, MdiIcon, SrOnly } from '@aglyn/shared-ui-jsx'\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n deleteField,\n doc,\n getDoc,\n serverTimestamp,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCompanyPicklists } from '../hooks/use-company-picklists'\nimport { DEAL_CURRENCIES } from '../model/deal-board-model'\nimport { CompanyPicker, useCompanyOptions } from './company-picker'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport type { OrgMemberOptions } from '../hooks/use-org-member-options'\nimport {\n type CompanyDraft,\n companyDraftFields,\n companyDraftFrom,\n EMPTY_COMPANY_DRAFT,\n} from '../model/companies'\nimport {\n type CrmCustomDraft,\n crmCustomDraftDocument,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n crmCustomDraftWrites,\n} from '../model/crm-custom-draft'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmSitePicker } from './crm-site-picker'\nimport {\n CRM_CLIENT_SEARCH_FIELDS,\n CRM_CLIENT_SORT_FIELDS,\n crmClientListFields,\n} from '../model/crm-list-query'\n\n/**\n * The list fields a client edit of a company rewrites: the search tokens,\n * and the key beside each picklist field the Companies list filters by\n * (AGL-3514).\n */\nconst COMPANY_CLIENT_LIST_FIELDS = [\n ...CRM_CLIENT_SEARCH_FIELDS,\n // Any header sort key the edit's inputs move (AGL-3680).\n ...CRM_CLIENT_SORT_FIELDS,\n ...CRM_COMPANY_PICKLIST_FIELDS.flatMap((entry) => ('keyField' in entry ? [entry.keyField] : [])),\n]\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\nexport interface CompanyEditDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The site the drawer is opened under, or `null` at the organization\n * level (AGL-2630), where a NEW company asks which site captures it and\n * an edit keeps the company's own.\n */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n /**\n * The company being EDITED, or nothing to create one.\n *\n * The two modes differ in what the fields start as and in which write\n * runs: an edit opens on the stored values and updates the document, a\n * create opens empty and stamps the scope, provenance and timestamps a new\n * record must carry.\n */\n company?: (Partial<CrmCompany> & { $id: string }) | null\n /**\n * Whether the stored values the edit opened on can be trusted.\n *\n * Every optional field is written on every save — a blank one is a\n * DELETE — so a form seeded from a cached read would write the cache's\n * blanks over the server's values. The card that holds the listen reports\n * its own `fromCache` and `status`; the drawer refuses to save on a seed\n * the server never confirmed, and says so.\n */\n seed?: {\n fromCache: boolean\n unreadable: boolean\n /** The company's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n }\n /**\n * The team, for the owner picker.\n *\n * Handed in rather than fetched here, because the surface opening this\n * drawer already holds the roster to name owners in its rows, and one\n * fetch per surface is the bargain.\n */\n members: OrgMemberOptions\n /** Called with the record's id after a successful write. */\n onSaved: (companyId: string) => void\n}\n\ntype AddressDraftField = 'address' | 'shippingAddress'\n\n/** How each picklist field is labeled on a company. */\nconst COMPANY_PICKLIST_LABELS: Record<CrmCompanyPicklistField, string> = {\n type: 'Type',\n industry: 'Industry',\n rating: 'Rating',\n ownership: 'Ownership',\n accountSource: 'Account source',\n}\n\nconst ADDRESS_FIELDS: ReadonlyArray<{\n key: keyof AglynPostalAddress\n label: string\n}> = [\n { key: 'line1', label: 'Address line 1' },\n { key: 'line2', label: 'Address line 2' },\n { key: 'city', label: 'City' },\n { key: 'state', label: 'State or region' },\n { key: 'postalCode', label: 'Postal code' },\n { key: 'country', label: 'Country (two-letter code)' },\n]\n\n/**\n * ONE COMPANY, created or edited (AGL-2597).\n *\n * A drawer rather than a form above the list, and the same drawer for both\n * jobs: a company is eight fields and an address, which is too much to wedge\n * over a table and exactly the same set whether the record exists yet. The\n * list opens it empty; the company's page opens it on the record.\n *\n * Nothing is written per keystroke. The draft is held here and turned into a\n * document by `companyDraftFields` on Save, which is where a domain typed as\n * `acme` or a phone number with no country code is refused — as a message\n * beside the button, with the typed values left where they are.\n */\nexport function CompanyEditDrawer(props: CompanyEditDrawerProps) {\n const { open, onClose, hostId, org, company, seed, members, onSaved } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { scope, createTokens, createHostId, createNeedsSite } = useCrmScope({ hostId, org })\n // A client-direct write owes the org's sharing rules a re-evaluation (AGL-3336).\n const followUpSharing = useCrmSharingFollowUp(hostId, scope?.[1] ?? null)\n // The feed the act is logged in is the level it was PERFORMED at\n // (AGL-2738): this site's under a site, the organization's at the org\n // hub. `createHostId` is where the record is STAMPED, which at the hub is\n // a site the reader picked and may hold no role on — a different question\n // from where the line belongs, and a gate the record write never faced.\n const logActivity = useCrmActivityLogger(hostId)\n\n const [draft, setDraft] = useState<CompanyDraft>(EMPTY_COMPANY_DRAFT)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n /*\n * THE CUSTOM FIELDS (AGL-2661): the org's company definitions, and the\n * keys the reader has touched over what the company stores. Saved as the\n * difference — see `crm-custom-draft` — beside the fixed fields, in the\n * same write, so a company is never half-saved.\n */\n const fields = useContactFieldDefinitions(scope?.[1] ?? null, 'company')\n const storedCustom = useMemo(() => company?.custom ?? {}, [company?.custom])\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /*\n * THE RECORDS BAND (AGL-2611), read only for a CREATE: a company is a\n * record of the band the contacts list is banded by, and on an org at a\n * full hard band this drawer refuses the way `upsertHostContact` refuses a\n * capture — same number, same sentence. An edit is not a record and pays\n * for no aggregate. Only a SETTLED refusal refuses: three reads that have\n * not answered are not a full band.\n */\n const records = useCrmRecordsQuota(open && !company ? scope : null, org)\n const bandFull = !company && records.ready && !records.quota.allowed\n /*\n * SALESFORCE'S ACCOUNT FIELDS (AGL-3514): the org's lists behind Type,\n * Industry, Rating, Ownership and Account Source, and the companies a\n * parent may be chosen from — every one the reader can see but this one.\n */\n const picklists = useCompanyPicklists(scope?.[1] ?? null)\n const seededDefaults = useRef(false)\n const companyOptions = useCompanyOptions({ hostId, org, enabled: open })\n const parentOptions = useMemo(\n () => companyOptions.options.filter((option) => option.id !== company?.$id),\n [companyOptions.options, company?.$id],\n )\n\n /*\n * Seeded when the drawer OPENS, and not on every render of the card\n * behind it: the company listen is live, so re-seeding on each snapshot\n * would take a field away from whoever is typing in it — including on the\n * snapshot their own save produces. The create case seeds the owner to the\n * person filing the record, which is the answer nine times in ten and one\n * click to change.\n */\n const companyId = company?.$id\n useEffect(() => {\n if (!open) return\n setDraft(\n company\n ? companyDraftFrom(company)\n : { ...EMPTY_COMPANY_DRAFT, ownerUid: user?.uid ?? '' },\n )\n setCustom({})\n setError('')\n seededDefaults.current = false\n // The stored fields are read once per opening; `company` is a new object\n // on every snapshot and must not re-seed.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open, companyId])\n /*\n * A NEW company starts each picklist on the org's default, once the\n * lists have answered — Salesforce's form opens on it too — and only a\n * field nobody has picked a value for yet.\n */\n useEffect(() => {\n if (!open || company || !picklists.ready || seededDefaults.current) return\n seededDefaults.current = true\n setDraft((current) => {\n const next = { ...current }\n for (const { field, picklistId } of CRM_COMPANY_PICKLIST_FIELDS) {\n const list = picklists.lists[picklistId]\n const fallback = list ? crmPicklistDefaultLabel(list) : null\n if (!next[field] && fallback) next[field] = fallback\n }\n return next\n })\n }, [open, company, picklists])\n\n const patch = useCallback(\n (field: keyof Omit<CompanyDraft, AddressDraftField>, value: string) =>\n setDraft((current) => ({ ...current, [field]: value })),\n [],\n )\n const patchAddress = useCallback(\n (which: AddressDraftField, field: keyof AglynPostalAddress, value: string) =>\n setDraft((current) => ({\n ...current,\n [which]: { ...current[which], [field]: value },\n })),\n [],\n )\n /** The parent's own parent, as the cycle guard walks it; `null` for one this reader cannot see. */\n const readParent = useCallback(\n async (id: string) => {\n if (!scope) return null\n try {\n const snapshot = await getDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n )\n return snapshot.exists()\n ? { parentCompanyId: crmCompanyParentId(snapshot.get('parentCompanyId')) }\n : null\n } catch {\n return null\n }\n },\n [firestore, scope],\n )\n\n const handleSave = useCallback(async () => {\n if (busy || !scope) return\n const result = companyDraftFields(draft, { lists: picklists.lists, current: company })\n if (result.ok === false) return setError(result.error)\n // A parent is never this company, nor one already under it (AGL-3514).\n const parentId = crmCompanyParentId(result.set['parentCompanyId'])\n if (parentId && parentId !== crmCompanyParentId(company?.parentCompanyId)) {\n const refusal = await crmCompanyParentRefusal(company?.$id ?? null, parentId, readParent)\n if (refusal) return setError(refusal)\n }\n const missing = crmCustomDraftMissingRequired(\n fields.active,\n storedCustom,\n custom,\n company ? 'edit' : 'create',\n )\n if (missing.length) return setError(`${missing.join(', ')} is required.`)\n const customDocument = crmCustomDraftDocument(custom)\n setError('')\n setBusy(true)\n try {\n if (company) {\n const ref = doc(\n firestore,\n scope[0],\n scope[1],\n CRM_COLLECTIONS.companies,\n company.$id,\n )\n // The guard WRAPS the write — an early return is a shape you can\n // keep while losing the protection.\n const verdict = await writeGuardedBySeed(\n {\n subject: 'company',\n unreadable: seed?.unreadable ?? false,\n fromCache: seed?.fromCache ?? false,\n listen: seed?.listen,\n },\n async () => {\n const cleared = Object.fromEntries(\n result.cleared.map((field) => [field, deleteField()]),\n )\n // The stored record the list fields are computed from: the row\n // without the id the listener stamped on it.\n const { $id: _rowId, ...stored } = company\n const searchFields = crmClientListFields(\n 'companies',\n stored,\n { ...result.set, ...cleared },\n COMPANY_CLIENT_LIST_FIELDS,\n )\n await updateDoc(ref, {\n ...result.set,\n // A blank optional field is a DELETE on an edit, or the old\n // domain would stay stored and keep matching people by email.\n ...cleared,\n // The name and domain are what the Companies list searches\n // (AGL-3321), and the picklist keys what it filters by\n // (AGL-3514), from the listener's row with the edit over it.\n ...searchFields,\n // The custom keys that changed, merged into the stored map.\n ...crmCustomDraftWrites(storedCustom, custom),\n updatedAt: serverTimestamp(),\n })\n },\n )\n if (!verdict.ok) return setError(verdict.message)\n followUpSharing('companies', [company.$id])\n enqueueSnackbar('Company saved', { variant: 'success', persist: false })\n onSaved(company.$id)\n } else {\n if (bandFull) return setError(CRM_RECORDS_BAND_FULL_MESSAGE)\n const id = createResourceUid()\n // Held by the button until it knows who may see the company — the\n // whole org, or a picked site's group where the org keeps its sites\n // apart; checked again here because a callback can outlive the render\n // that held it.\n if (!createTokens.length) return\n await setDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n {\n ...result.set,\n ...(customDocument ? { custom: customDocument } : {}),\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', {\n ...result.set,\n visibleTo: [...createTokens],\n }),\n /*\n * The scope every CRM creator stamps: the whole org when the org\n * shares by default, and otherwise the sites that present as one\n * sender. Without it the record is seen by NOBODY — an absent\n * `visibleTo` matches no reader's predicate — and the rules\n * refuse a scoped member creating outside their own tokens.\n */\n visibleTo: [...createTokens],\n // Provenance: the site whose console filed it, never rewritten.\n hostId: createHostId,\n createdByUid: user?.uid ?? '',\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n },\n )\n // Setup → Activity shows CRM work (AGL-2622): the company is org\n // data, but the act happened in this site's console and belongs in\n // its feed. Creation only — an edit is a save the card reports.\n followUpSharing('companies', [id])\n logActivity('Added company', { type: 'company', id, name: draft.name.trim() })\n enqueueSnackbar(`Company \"${draft.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n onSaved(id)\n }\n onClose()\n } catch (caught) {\n console.error(caught)\n setError('The company could not be saved.')\n } finally {\n setBusy(false)\n }\n }, [\n busy,\n scope,\n followUpSharing,\n draft,\n company,\n bandFull,\n firestore,\n seed,\n createTokens,\n createHostId,\n user,\n logActivity,\n enqueueSnackbar,\n onSaved,\n onClose,\n fields.active,\n storedCustom,\n custom,\n picklists.lists,\n readParent,\n ])\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={onClose}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>{'close drawer'}</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {company ? 'Edit company' : 'New company'}\n </Typography>\n <HelpTip\n {...pluginDocsHelp('companies', { anchor: '#create-a-company' })}\n />\n </>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n {/*\n First, because the scope of everything below follows from it: at\n the organization level a new company names the site it came\n from — required where the org keeps its sites apart, optional\n where every site sees it. Nothing under a site, and nothing on an\n edit — a company keeps the site it was made on (AGL-2630).\n */}\n {company ? null : (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n optional={!createNeedsSite}\n helperText={\n createNeedsSite\n ? 'The site this company belongs to — it decides which of your sites may see it.'\n : undefined\n }\n />\n )}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The organization behind one or more of your contacts. The ' +\n 'domain is what suggests this company for a person from their ' +\n 'email address, so enter the bare hostname.'}\n </Typography>\n {bandFull ? (\n <Alert severity=\"warning\">{CRM_RECORDS_BAND_FULL_MESSAGE}</Alert>\n ) : null}\n {/*\n Grouped as Salesforce's Account page groups them (AGL-3514):\n what the company is, where it is, and what the team knows.\n */}\n <Typography variant=\"subtitle2\">{'Account information'}</Typography>\n <TextField\n size=\"small\"\n label=\"Name\"\n required\n value={draft.name}\n onChange={(event) => patch('name', event.target.value)}\n autoFocus\n />\n <CompanyPicker\n label=\"Parent company\"\n options={parentOptions}\n value={draft.parentCompanyId || null}\n onChange={(id) => patch('parentCompanyId', id ?? '')}\n ready={companyOptions.ready}\n truncated={companyOptions.truncated}\n disabled={busy}\n helperText=\"The company this one belongs to, such as a subsidiary's group.\"\n />\n <TextField\n size=\"small\"\n label=\"Domain\"\n placeholder=\"example.com\"\n value={draft.domain}\n onChange={(event) => patch('domain', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Website\"\n placeholder=\"https://www.example.com\"\n value={draft.website}\n onChange={(event) => patch('website', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Phone\"\n placeholder=\"+1 512 555 0123\"\n value={draft.phone}\n onChange={(event) => patch('phone', event.target.value)}\n />\n <TextField\n size=\"small\"\n label=\"Fax\"\n placeholder=\"+1 512 555 0124\"\n value={draft.fax}\n onChange={(event) => patch('fax', event.target.value)}\n />\n {CRM_COMPANY_PICKLIST_FIELDS.map(({ field, picklistId }) => {\n const list = picklists.lists[picklistId]\n return list ? (\n <CrmPicklistSelect\n key={field}\n picklistId={picklistId}\n picklist={list}\n label={COMPANY_PICKLIST_LABELS[field]}\n value={draft[field]}\n stored={company ? String(company[field] ?? '') : undefined}\n onChange={(label) => patch(field, label)}\n disabled={busy}\n />\n ) : null\n })}\n <TextField\n size=\"small\"\n label=\"Account number\"\n value={draft.accountNumber}\n onChange={(event) => patch('accountNumber', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.accountNumber } }}\n />\n <TextField\n size=\"small\"\n label=\"Account site\"\n placeholder=\"Headquarters\"\n helperText=\"Which of the company's locations this record is.\"\n value={draft.site}\n onChange={(event) => patch('site', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.site } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n size=\"small\"\n label=\"Ticker symbol\"\n value={draft.tickerSymbol}\n onChange={(event) => patch('tickerSymbol', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.tickerSymbol } }}\n sx={{ flex: 1 }}\n />\n <TextField\n size=\"small\"\n label=\"SIC code\"\n value={draft.sicCode}\n onChange={(event) => patch('sicCode', event.target.value)}\n slotProps={{ htmlInput: { maxLength: CRM_COMPANY_TEXT_MAX.sicCode } }}\n sx={{ flex: 1 }}\n />\n </Stack>\n <TextField\n size=\"small\"\n label=\"Employees\"\n value={draft.numberOfEmployees}\n onChange={(event) => patch('numberOfEmployees', event.target.value)}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n size=\"small\"\n label=\"Annual revenue\"\n placeholder=\"0.00\"\n value={draft.annualRevenue}\n onChange={(event) => patch('annualRevenue', event.target.value)}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n sx={{ flex: 1 }}\n />\n <TextField\n select\n size=\"small\"\n label=\"Currency\"\n value={draft.currency}\n onChange={(event) => patch('currency', event.target.value)}\n sx={{ width: 120 }}\n >\n {/* A stored code outside the short list stays selectable as itself. */}\n {[...new Set<string>([...DEAL_CURRENCIES, draft.currency])].map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n {/*\n The owner is chosen from the team, never typed: the value is a\n uid, and a picker that is still loading says so rather than\n offering an empty list that reads as \"nobody can own this\".\n */}\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={draft.ownerUid}\n disabled={!members.ready}\n helperText={\n !members.ready\n ? 'Loading your team…'\n : (members.error ?? 'The team member responsible for this account.')\n }\n onChange={(event) => patch('ownerUid', event.target.value)}\n >\n <MenuItem value=\"\">{'Nobody yet'}</MenuItem>\n {draft.ownerUid &&\n !members.options.some((option) => option.uid === draft.ownerUid) ? (\n <MenuItem value={draft.ownerUid}>\n {members.labelFor(draft.ownerUid)}\n </MenuItem>\n ) : null}\n {members.options.map((option) => (\n <MenuItem key={option.uid} value={option.uid}>\n {crmMemberPickerLabel(option)}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"enterprise, west\"\n helperText=\"Comma-separated, lowercased — the same tags the bulk bar adds\"\n value={draft.tags}\n onChange={(event) => patch('tags', event.target.value)}\n />\n <Typography variant=\"subtitle2\">{'Address information'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Billing address'}\n </Typography>\n {ADDRESS_FIELDS.map((field) => (\n <TextField\n key={`address.${field.key}`}\n size=\"small\"\n label={field.label}\n value={draft.address[field.key] ?? ''}\n onChange={(event) => patchAddress('address', field.key, event.target.value)}\n />\n ))}\n <Stack direction=\"row\" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Shipping address'}\n </Typography>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() =>\n setDraft((current) => ({ ...current, shippingAddress: { ...current.address } }))\n }\n >\n {'Copy billing address'}\n </Button>\n </Stack>\n {ADDRESS_FIELDS.map((field) => (\n <TextField\n key={`shippingAddress.${field.key}`}\n size=\"small\"\n label={field.label}\n value={draft.shippingAddress[field.key] ?? ''}\n onChange={(event) => patchAddress('shippingAddress', field.key, event.target.value)}\n />\n ))}\n <Typography variant=\"subtitle2\">{'Description information'}</Typography>\n <TextField\n size=\"small\"\n label=\"Notes\"\n value={draft.notes}\n onChange={(event) => patch('notes', event.target.value)}\n multiline\n minRows={3}\n />\n {fields.active.length ? (\n <>\n <Typography variant=\"subtitle2\">{'Custom fields'}</Typography>\n {fields.active.map((definition) => (\n <CrmCustomFieldControl\n key={definition.$id}\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n setCustom((current) => ({ ...current, [definition.key]: value }))\n }\n disabled={busy}\n />\n ))}\n </>\n ) : null}\n {error ? <Alert severity=\"warning\">{error}</Alert> : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n // A new company waits for its capturing site.\n disabled={busy || !scope || !draft.name.trim() || (!company && !createTokens.length)}\n onClick={() => void handleSave()}\n >\n {busy\n ? 'Saving…'\n : company\n ? 'Save company'\n : 'Create company'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nCompanyEditDrawer.displayName = 'CompanyEditDrawer'\n\nexport default CompanyEditDrawer\n"],"names":["createResourceUid","CRM_COLLECTIONS","CRM_RECORDS_BAND_FULL_MESSAGE","CRM_COMPANY_PICKLIST_FIELDS","CRM_COMPANY_TEXT_MAX","crmCompanyParentId","crmCompanyParentRefusal","crmNewRecordListFields","crmPicklistDefaultLabel","pluginDocsHelp","crmMemberPickerLabel","ICON_VARIANT_CLOSE","Container","HelpTip","MdiIcon","SrOnly","NavigationDrawerComponent","useSnackbar","useFirestore","useUser","writeGuardedBySeed","Alert","Button","IconButton","MenuItem","Stack","TextField","Typography","deleteField","doc","getDoc","serverTimestamp","setDoc","updateDoc","useCallback","useEffect","useMemo","useRef","useState","useCompanyPicklists","DEAL_CURRENCIES","CompanyPicker","useCompanyOptions","CrmPicklistSelect","useContactFieldDefinitions","useCrmActivityLogger","useCrmRecordsQuota","useCrmScope","companyDraftFields","companyDraftFrom","EMPTY_COMPANY_DRAFT","crmCustomDraftDocument","crmCustomDraftMissingRequired","crmCustomDraftValue","crmCustomDraftWrites","CrmCustomFieldControl","CrmSitePicker","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","crmClientListFields","COMPANY_CLIENT_LIST_FIELDS","flatMap","entry","keyField","useCrmSharingFollowUp","COMPANY_PICKLIST_LABELS","type","industry","rating","ownership","accountSource","ADDRESS_FIELDS","key","label","CompanyEditDrawer","props","members","open","onClose","hostId","org","company","seed","onSaved","firestore","data","user","enqueueSnackbar","scope","createTokens","createHostId","createNeedsSite","followUpSharing","logActivity","draft","setDraft","busy","setBusy","error","setError","fields","storedCustom","custom","setCustom","records","bandFull","ready","quota","allowed","picklists","seededDefaults","companyOptions","enabled","parentOptions","options","filter","option","id","$id","companyId","ownerUid","uid","current","next","field","picklistId","list","lists","fallback","patch","value","patchAddress","which","readParent","snapshot","companies","exists","parentCompanyId","get","handleSave","result","ok","parentId","set","refusal","missing","active","length","join","customDocument","ref","verdict","subject","unreadable","fromCache","listen","cleared","Object","fromEntries","map","_rowId","stored","searchFields","updatedAt","message","variant","persist","visibleTo","createdByUid","createdAt","name","trim","caught","console","anchor","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","gutterY","spacing","disabled","optional","helperText","undefined","severity","size","required","onChange","event","target","autoFocus","truncated","placeholder","domain","website","phone","fax","picklist","String","accountNumber","slotProps","htmlInput","maxLength","site","direction","tickerSymbol","flex","sicCode","numberOfEmployees","inputMode","annualRevenue","select","currency","width","Set","code","toUpperCase","some","labelFor","tags","address","alignItems","justifyContent","shippingAddress","notes","multiline","minRows","definition","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAGEA,iBAAiB,EACjBC,eAAe,EACfC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,oBAAoB,EAGpBC,kBAAkB,EAClBC,uBAAuB,EACvBC,sBAAsB,EACtBC,uBAAuB,EACvBC,cAAc,EACdC,oBAAoB,QACf,eA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M4E,IAAI,CAACC,IAAI,MAAO,CAAC1F,WAAW,CAACQ,aAAa0D,MAAM;gCACnFgC,SAAS,IAAM,KAAKxC;0CAEnB3C,OACG,YACAf,UACE,iBACA;;0CAER,KAAC3D;gCAAO6J,SAASrG;gCAAS4G,UAAU1F;0CACjC;;;;;;;;AAOf;AACAtB,kBAAkBgK,WAAW,GAAG;AAEhC,eAAehK,kBAAiB"}
@@ -1,4 +1,5 @@
1
1
  import { type AglynOrgBilling, type CrmCompany } from '@aglyn/aglyn';
2
+ import type { ListenHandle } from '@aglyn/tenant-feature-instance';
2
3
  import { type ReactNode } from 'react';
3
4
  import type { CrmScope } from '../hooks/use-crm-scope';
4
5
  import type { OrgMemberOptions } from '../hooks/use-org-member-options';
@@ -21,6 +22,8 @@ export interface CompanyPropertiesCardProps {
21
22
  seed: {
22
23
  fromCache: boolean;
23
24
  unreadable: boolean;
25
+ /** The company's listener, so a save waits on that read alone (AGL-4135). */
26
+ listen?: ListenHandle | null;
24
27
  };
25
28
  /** The site the record is read under, or `null` at the organization level. */
26
29
  hostId: string | null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/company-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 {\n type AglynOrgBilling,\n type AglynPostalAddress,\n type CrmCompany,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Button, Link, Stack, Typography } from '@mui/material'\nimport { type ReactNode, useCallback, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport type { CrmScope } from '../hooks/use-crm-scope'\nimport type { OrgMemberOptions } from '../hooks/use-org-member-options'\nimport { COMPANY_DETACH_LIMIT } from '../model/companies'\nimport {\n companyDeleteFailureMessage,\n deleteCompanyThroughRoute,\n} from '../model/company-delete'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport { formatMoney } from '../model/deal-board-model'\nimport CompanyEditDrawer from './company-edit-drawer'\nimport { formatContactCustomValue } from './contact-custom-columns'\nimport { CrmCallButton, CrmPhoneLink } from './crm-call-actions'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { useCrmApi } from './use-crm-api'\n\n/**\n * The help on a company's header card — one card, so the page's\n * not-found branch carries the same link as the loaded one.\n */\nexport const COMPANY_PAGE_HELP = pluginDocsHelp('companies', { anchor: '#a-companys-page' })\n\nexport interface CompanyPropertiesCardProps {\n company: Partial<CrmCompany> & { $id: string }\n /** Whether the document the card holds is server-confirmed. */\n seed: { fromCache: boolean; unreadable: boolean }\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling>\n crmScope: CrmScope\n members: OrgMemberOptions\n routes: CrmRoutes\n /** Called once the record is gone, so the page can leave it. */\n onDeleted: () => void\n}\n\n/** A postal address on one line, or nothing. */\nfunction formatAddress(address: AglynPostalAddress | null | undefined): string {\n if (!address) return ''\n return [\n address.line1,\n address.line2,\n [address.city, address.state].filter(Boolean).join(', '),\n address.postalCode,\n address.country,\n ]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n .join(' · ')\n}\n\n/**\n * WHAT A COMPANY IS: its fields, read off the one document the page holds,\n * with the edit and the delete beside them (AGL-2597).\n *\n * ## Edit is the create drawer\n *\n * The same form the list creates with, opened on the record. One form means\n * one set of refusals — a domain that is not a domain is refused the same\n * way on day one and on a rename — and one place to add a field.\n *\n * ## Delete is a DETACH first\n *\n * `crm/company-delete` — the route the bulk bar calls per row as well —\n * unlinks the contacts that name this company before removing it, bounded\n * at {@link COMPANY_DETACH_LIMIT} per pass and honest past it: the company\n * stands, and the person is told more remain. The unlink clears each\n * holder's facet that named the company, which is the server's to write\n * (AGL-2804). What this card adds is the confirm, the sentence for each\n * outcome, and leaving the page once the record is gone.\n */\nexport function CompanyPropertiesCard(props: CompanyPropertiesCardProps) {\n const {\n company,\n seed,\n hostId,\n org,\n crmScope,\n members,\n routes,\n onDeleted,\n } = props\n const { scope } = crmScope\n const callCrm = useCrmApi(hostId)\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // The feed the act is logged in, decided by the level it was performed\n // at (AGL-2738): this site's under a site, the organization's at the org\n // hub, where a client-direct append to the company's own site would face\n // a gate the record write never had to pass.\n const logActivity = useCrmActivityLogger(hostId)\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n // The org's company fields (AGL-2661): one row each under the fixed\n // ones, read by type the way the list's columns read them.\n const fields = useContactFieldDefinitions(crmScope.orgId, 'company')\n\n const handleDelete = useCallback(async () => {\n if (!scope || deleting) return\n const name = String(company.name ?? company.$id)\n const accepted = await confirm({\n title: 'Delete this company?',\n description:\n `\"${name}\" is removed from Companies and unlinked from every ` +\n 'contact at it. The contacts themselves are kept, and so is ' +\n 'anything else filed against the company.',\n confirmationText: 'Delete company',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating\n // on the resolved value alone would make this always return.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setDeleting(true)\n try {\n const outcome = await deleteCompanyThroughRoute(callCrm, company.$id)\n if (!outcome.deleted) {\n enqueueSnackbar(\n `${COMPANY_DETACH_LIMIT.toLocaleString()} contacts were unlinked ` +\n `from \"${name}\" and more remain. Delete again to continue.`,\n { variant: 'warning' },\n )\n return\n }\n // Setup → Activity shows CRM work (AGL-2622): the company is org\n // data, but the act happened in this site's console and belongs in\n // its feed.\n logActivity('Deleted company', { type: 'company', id: company.$id, name })\n enqueueSnackbar(\n outcome.detached\n ? `Company deleted and unlinked from ${outcome.detached.toLocaleString()} ` +\n `contact${outcome.detached === 1 ? '' : 's'}`\n : 'Company deleted',\n { variant: 'success', persist: false },\n )\n onDeleted()\n } catch (error) {\n console.error(error)\n enqueueSnackbar(companyDeleteFailureMessage(error), {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeleting(false)\n }\n }, [scope, deleting, company, confirm, callCrm, logActivity, enqueueSnackbar, onDeleted])\n\n // The parent company by name (AGL-3514), resolved once and cached.\n const parentId = company.parentCompanyId || null\n const recordName = useCrmRecordNames({\n orgId: crmScope.orgId,\n groupId: null,\n records: parentId ? [{ kind: 'company', id: parentId }] : [],\n })\n /*\n * Grouped as Salesforce's Account page groups them (AGL-3514): what the\n * company is, where it is, and what the team knows. The domain, the\n * industry, the type, the rating and the owner read on the header — the\n * subtitle and the chip row — so the rows list what is left.\n */\n const rows: Array<{ label: string; value: ReactNode }> = [\n {\n label: 'Parent company',\n value: parentId ? (\n <AppLink href={routes.company(parentId)}>\n {recordName('company', parentId) || 'Open company'}\n </AppLink>\n ) : null,\n },\n {\n label: 'Website',\n value: company.website ? (\n <Link href={company.website} target=\"_blank\" rel=\"noreferrer noopener\">\n {company.website}\n </Link>\n ) : null,\n },\n // Callable in one tap (AGL-2661); plain text for a value no dialer takes.\n { label: 'Phone', value: <CrmPhoneLink phone={company.phone} /> },\n { label: 'Fax', value: company.fax },\n { label: 'Ownership', value: company.ownership },\n { label: 'Account source', value: company.accountSource },\n { label: 'Account number', value: company.accountNumber },\n { label: 'Account site', value: company.site },\n { label: 'Ticker symbol', value: company.tickerSymbol },\n { label: 'SIC code', value: company.sicCode },\n {\n label: 'Employees',\n value:\n typeof company.numberOfEmployees === 'number'\n ? company.numberOfEmployees.toLocaleString()\n : null,\n },\n {\n label: 'Annual revenue',\n value:\n typeof company.annualRevenueCents === 'number'\n ? formatMoney(company.annualRevenueCents, company.currency)\n : null,\n },\n { label: 'Tags', value: (company.tags ?? []).join(', ') },\n ]\n const addressRows: Array<{ label: string; value: ReactNode }> = [\n { label: 'Billing address', value: formatAddress(company.address) },\n { label: 'Shipping address', value: formatAddress(company.shippingAddress) },\n ]\n const descriptionRows: Array<{ label: string; value: ReactNode }> = [\n { label: 'Notes', value: company.notes },\n ]\n // The org's own company fields (AGL-2661), after the built-in ones under\n // \"More fields\", as a record's Details keep them; none defined, none drawn.\n const moreRows: Array<{ label: string; value: ReactNode }> = fields.active.map(\n (definition) => {\n const text = formatContactCustomValue(definition, company.custom?.[definition.key])\n return {\n label: definition.label || definition.key,\n value:\n text && definition.type === 'url' ? (\n <Link href={text} target=\"_blank\" rel=\"noreferrer noopener\">\n {text}\n </Link>\n ) : (\n text\n ),\n }\n },\n )\n const factRows = (list: Array<{ label: string; value: ReactNode }>) =>\n list.map((row) => (\n <Stack\n key={row.label}\n direction=\"row\"\n spacing={2}\n sx={{ alignItems: 'baseline' }}\n >\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ minWidth: 96, flexShrink: 0 }}\n >\n {row.label}\n </Typography>\n <Typography\n variant=\"body2\"\n color={row.value ? 'text.primary' : 'text.secondary'}\n sx={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}\n >\n {row.value || '—'}\n </Typography>\n </Stack>\n ))\n\n return (\n <CrmRecordHeader\n kind=\"Company\"\n title={String(company.name || company.$id)}\n subtitle={company.domain}\n help={COMPANY_PAGE_HELP}\n backHref={routes.section('companies')}\n backLabel=\"Back to companies\"\n actions={\n <>\n <CrmCallButton\n hostId={hostId}\n org={org}\n link={{ companyId: company.$id }}\n phone={company.phone}\n />\n <Button\n size=\"small\"\n color=\"primary\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiPencilOutline.path} size={0.8} />}\n onClick={() => setEditing(true)}\n >\n {'Edit'}\n </Button>\n </>\n }\n menuItems={[\n {\n key: 'delete',\n label: deleting ? 'Deleting…' : 'Delete company',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !scope || deleting,\n disabledReason: deleting ? 'The company is being deleted' : 'The organization has not loaded',\n onClick: () => void handleDelete(),\n },\n ]}\n chips={\n <>\n <CrmRecordChip label=\"Type\" value={company.type ?? undefined} />\n <CrmRecordChip label=\"Industry\" value={company.industry} />\n <CrmRecordChip label=\"Rating\" value={company.rating ?? undefined} />\n <CrmRecordChip\n label=\"Owner\"\n value={\n company.ownerUid\n ? members.ready\n ? members.labelFor(company.ownerUid)\n : '…'\n : undefined\n }\n />\n </>\n }\n >\n <Stack spacing={1}>\n {factRows(rows)}\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'Address information'}\n </Typography>\n {factRows(addressRows)}\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'Description information'}\n </Typography>\n {factRows(descriptionRows)}\n {moreRows.length ? (\n <>\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'More fields'}\n </Typography>\n {factRows(moreRows)}\n </>\n ) : null}\n </Stack>\n {editing ? (\n <CompanyEditDrawer\n open\n onClose={() => setEditing(false)}\n hostId={hostId}\n org={org}\n company={company}\n seed={seed}\n members={members}\n onSaved={() => setEditing(false)}\n />\n ) : null}\n </CrmRecordHeader>\n )\n}\nCompanyPropertiesCard.displayName = 'CompanyPropertiesCard'\n\nexport default CompanyPropertiesCard\n"],"names":["pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","AppLink","MdiIcon","useConfirmationContext","useSnackbar","Button","Link","Stack","Typography","useCallback","useState","useContactFieldDefinitions","useCrmActivityLogger","useCrmRecordNames","COMPANY_DETACH_LIMIT","companyDeleteFailureMessage","deleteCompanyThroughRoute","formatMoney","CompanyEditDrawer","formatContactCustomValue","CrmCallButton","CrmPhoneLink","CrmRecordChip","CrmRecordHeader","useCrmApi","COMPANY_PAGE_HELP","anchor","formatAddress","address","line1","line2","city","state","filter","Boolean","join","postalCode","country","map","part","String","trim","CompanyPropertiesCard","props","company","seed","hostId","org","crmScope","members","routes","onDeleted","scope","callCrm","confirm","enqueueSnackbar","logActivity","editing","setEditing","deleting","setDeleting","fields","orgId","handleDelete","name","$id","accepted","title","description","confirmationText","confirmationButtonProps","color","then","catch","outcome","deleted","toLocaleString","variant","type","id","detached","persist","error","console","allowDuplicate","parentId","parentCompanyId","recordName","groupId","records","kind","rows","label","value","href","website","target","rel","phone","fax","ownership","accountSource","accountNumber","site","tickerSymbol","sicCode","numberOfEmployees","annualRevenueCents","currency","tags","addressRows","shippingAddress","descriptionRows","notes","moreRows","active","definition","text","custom","key","factRows","list","row","direction","spacing","sx","alignItems","minWidth","flexShrink","whiteSpace","overflowWrap","subtitle","domain","help","backHref","section","backLabel","actions","link","companyId","size","startIcon","path","onClick","menuItems","icon","destructive","disabled","disabledReason","chips","undefined","industry","rating","ownerUid","ready","labelFor","pt","length","open","onClose","onSaved","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAIEA,cAAc,QACT,eAAc;AACrB,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,yBAAwB;AAC3E,SAASC,OAAO,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC/E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAC/D,SAAyBC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7D,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,oBAAoB,QAAQ,sCAAkC;AACvE,SAASC,iBAAiB,QAAQ,mCAA+B;AAGjE,SAASC,oBAAoB,QAAQ,wBAAo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0G;;8BACvD,KAAChI;oBACCsE,OAAM;oBACNC,OACEjD,QAAQ6G,QAAQ,GACZxG,QAAQyG,KAAK,GACXzG,QAAQ0G,QAAQ,CAAC/G,QAAQ6G,QAAQ,IACjC,MACFH;;;;;0BAMZ,MAAC/I;gBAAMqH,SAAS;;oBACbJ,SAAS7B;kCACV,KAACnF;wBAAWqE,SAAQ;wBAAYgD,IAAI;4BAAE+B,IAAI;wBAAE;kCACzC;;oBAEFpC,SAASV;kCACV,KAACtG;wBAAWqE,SAAQ;wBAAYgD,IAAI;4BAAE+B,IAAI;wBAAE;kCACzC;;oBAEFpC,SAASR;oBACTE,SAAS2C,MAAM,iBACd;;0CACE,KAACrJ;gCAAWqE,SAAQ;gCAAYgD,IAAI;oCAAE+B,IAAI;gCAAE;0CACzC;;4BAEFpC,SAASN;;yBAEV;;;YAELzD,wBACC,KAACvC;gBACC4I,IAAI;gBACJC,SAAS,IAAMrG,WAAW;gBAC1BZ,QAAQA;gBACRC,KAAKA;gBACLH,SAASA;gBACTC,MAAMA;gBACNI,SAASA;gBACT+G,SAAS,IAAMtG,WAAW;iBAE1B;;;AAGV;AACAhB,sBAAsBuH,WAAW,GAAG;AAEpC,eAAevH,sBAAqB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/company-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 {\n type AglynOrgBilling,\n type AglynPostalAddress,\n type CrmCompany,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport type { ListenHandle } from '@aglyn/tenant-feature-instance'\nimport { Button, Link, Stack, Typography } from '@mui/material'\nimport { type ReactNode, useCallback, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport type { CrmScope } from '../hooks/use-crm-scope'\nimport type { OrgMemberOptions } from '../hooks/use-org-member-options'\nimport { COMPANY_DETACH_LIMIT } from '../model/companies'\nimport {\n companyDeleteFailureMessage,\n deleteCompanyThroughRoute,\n} from '../model/company-delete'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport { formatMoney } from '../model/deal-board-model'\nimport CompanyEditDrawer from './company-edit-drawer'\nimport { formatContactCustomValue } from './contact-custom-columns'\nimport { CrmCallButton, CrmPhoneLink } from './crm-call-actions'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { useCrmApi } from './use-crm-api'\n\n/**\n * The help on a company's header card — one card, so the page's\n * not-found branch carries the same link as the loaded one.\n */\nexport const COMPANY_PAGE_HELP = pluginDocsHelp('companies', { anchor: '#a-companys-page' })\n\nexport interface CompanyPropertiesCardProps {\n company: Partial<CrmCompany> & { $id: string }\n /** Whether the document the card holds is server-confirmed. */\n seed: {\n fromCache: boolean\n unreadable: boolean\n /** The company's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n }\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling>\n crmScope: CrmScope\n members: OrgMemberOptions\n routes: CrmRoutes\n /** Called once the record is gone, so the page can leave it. */\n onDeleted: () => void\n}\n\n/** A postal address on one line, or nothing. */\nfunction formatAddress(address: AglynPostalAddress | null | undefined): string {\n if (!address) return ''\n return [\n address.line1,\n address.line2,\n [address.city, address.state].filter(Boolean).join(', '),\n address.postalCode,\n address.country,\n ]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n .join(' · ')\n}\n\n/**\n * WHAT A COMPANY IS: its fields, read off the one document the page holds,\n * with the edit and the delete beside them (AGL-2597).\n *\n * ## Edit is the create drawer\n *\n * The same form the list creates with, opened on the record. One form means\n * one set of refusals — a domain that is not a domain is refused the same\n * way on day one and on a rename — and one place to add a field.\n *\n * ## Delete is a DETACH first\n *\n * `crm/company-delete` — the route the bulk bar calls per row as well —\n * unlinks the contacts that name this company before removing it, bounded\n * at {@link COMPANY_DETACH_LIMIT} per pass and honest past it: the company\n * stands, and the person is told more remain. The unlink clears each\n * holder's facet that named the company, which is the server's to write\n * (AGL-2804). What this card adds is the confirm, the sentence for each\n * outcome, and leaving the page once the record is gone.\n */\nexport function CompanyPropertiesCard(props: CompanyPropertiesCardProps) {\n const {\n company,\n seed,\n hostId,\n org,\n crmScope,\n members,\n routes,\n onDeleted,\n } = props\n const { scope } = crmScope\n const callCrm = useCrmApi(hostId)\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // The feed the act is logged in, decided by the level it was performed\n // at (AGL-2738): this site's under a site, the organization's at the org\n // hub, where a client-direct append to the company's own site would face\n // a gate the record write never had to pass.\n const logActivity = useCrmActivityLogger(hostId)\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n // The org's company fields (AGL-2661): one row each under the fixed\n // ones, read by type the way the list's columns read them.\n const fields = useContactFieldDefinitions(crmScope.orgId, 'company')\n\n const handleDelete = useCallback(async () => {\n if (!scope || deleting) return\n const name = String(company.name ?? company.$id)\n const accepted = await confirm({\n title: 'Delete this company?',\n description:\n `\"${name}\" is removed from Companies and unlinked from every ` +\n 'contact at it. The contacts themselves are kept, and so is ' +\n 'anything else filed against the company.',\n confirmationText: 'Delete company',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating\n // on the resolved value alone would make this always return.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setDeleting(true)\n try {\n const outcome = await deleteCompanyThroughRoute(callCrm, company.$id)\n if (!outcome.deleted) {\n enqueueSnackbar(\n `${COMPANY_DETACH_LIMIT.toLocaleString()} contacts were unlinked ` +\n `from \"${name}\" and more remain. Delete again to continue.`,\n { variant: 'warning' },\n )\n return\n }\n // Setup → Activity shows CRM work (AGL-2622): the company is org\n // data, but the act happened in this site's console and belongs in\n // its feed.\n logActivity('Deleted company', { type: 'company', id: company.$id, name })\n enqueueSnackbar(\n outcome.detached\n ? `Company deleted and unlinked from ${outcome.detached.toLocaleString()} ` +\n `contact${outcome.detached === 1 ? '' : 's'}`\n : 'Company deleted',\n { variant: 'success', persist: false },\n )\n onDeleted()\n } catch (error) {\n console.error(error)\n enqueueSnackbar(companyDeleteFailureMessage(error), {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeleting(false)\n }\n }, [scope, deleting, company, confirm, callCrm, logActivity, enqueueSnackbar, onDeleted])\n\n // The parent company by name (AGL-3514), resolved once and cached.\n const parentId = company.parentCompanyId || null\n const recordName = useCrmRecordNames({\n orgId: crmScope.orgId,\n groupId: null,\n records: parentId ? [{ kind: 'company', id: parentId }] : [],\n })\n /*\n * Grouped as Salesforce's Account page groups them (AGL-3514): what the\n * company is, where it is, and what the team knows. The domain, the\n * industry, the type, the rating and the owner read on the header — the\n * subtitle and the chip row — so the rows list what is left.\n */\n const rows: Array<{ label: string; value: ReactNode }> = [\n {\n label: 'Parent company',\n value: parentId ? (\n <AppLink href={routes.company(parentId)}>\n {recordName('company', parentId) || 'Open company'}\n </AppLink>\n ) : null,\n },\n {\n label: 'Website',\n value: company.website ? (\n <Link href={company.website} target=\"_blank\" rel=\"noreferrer noopener\">\n {company.website}\n </Link>\n ) : null,\n },\n // Callable in one tap (AGL-2661); plain text for a value no dialer takes.\n { label: 'Phone', value: <CrmPhoneLink phone={company.phone} /> },\n { label: 'Fax', value: company.fax },\n { label: 'Ownership', value: company.ownership },\n { label: 'Account source', value: company.accountSource },\n { label: 'Account number', value: company.accountNumber },\n { label: 'Account site', value: company.site },\n { label: 'Ticker symbol', value: company.tickerSymbol },\n { label: 'SIC code', value: company.sicCode },\n {\n label: 'Employees',\n value:\n typeof company.numberOfEmployees === 'number'\n ? company.numberOfEmployees.toLocaleString()\n : null,\n },\n {\n label: 'Annual revenue',\n value:\n typeof company.annualRevenueCents === 'number'\n ? formatMoney(company.annualRevenueCents, company.currency)\n : null,\n },\n { label: 'Tags', value: (company.tags ?? []).join(', ') },\n ]\n const addressRows: Array<{ label: string; value: ReactNode }> = [\n { label: 'Billing address', value: formatAddress(company.address) },\n { label: 'Shipping address', value: formatAddress(company.shippingAddress) },\n ]\n const descriptionRows: Array<{ label: string; value: ReactNode }> = [\n { label: 'Notes', value: company.notes },\n ]\n // The org's own company fields (AGL-2661), after the built-in ones under\n // \"More fields\", as a record's Details keep them; none defined, none drawn.\n const moreRows: Array<{ label: string; value: ReactNode }> = fields.active.map(\n (definition) => {\n const text = formatContactCustomValue(definition, company.custom?.[definition.key])\n return {\n label: definition.label || definition.key,\n value:\n text && definition.type === 'url' ? (\n <Link href={text} target=\"_blank\" rel=\"noreferrer noopener\">\n {text}\n </Link>\n ) : (\n text\n ),\n }\n },\n )\n const factRows = (list: Array<{ label: string; value: ReactNode }>) =>\n list.map((row) => (\n <Stack\n key={row.label}\n direction=\"row\"\n spacing={2}\n sx={{ alignItems: 'baseline' }}\n >\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ minWidth: 96, flexShrink: 0 }}\n >\n {row.label}\n </Typography>\n <Typography\n variant=\"body2\"\n color={row.value ? 'text.primary' : 'text.secondary'}\n sx={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}\n >\n {row.value || '—'}\n </Typography>\n </Stack>\n ))\n\n return (\n <CrmRecordHeader\n kind=\"Company\"\n title={String(company.name || company.$id)}\n subtitle={company.domain}\n help={COMPANY_PAGE_HELP}\n backHref={routes.section('companies')}\n backLabel=\"Back to companies\"\n actions={\n <>\n <CrmCallButton\n hostId={hostId}\n org={org}\n link={{ companyId: company.$id }}\n phone={company.phone}\n />\n <Button\n size=\"small\"\n color=\"primary\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiPencilOutline.path} size={0.8} />}\n onClick={() => setEditing(true)}\n >\n {'Edit'}\n </Button>\n </>\n }\n menuItems={[\n {\n key: 'delete',\n label: deleting ? 'Deleting…' : 'Delete company',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !scope || deleting,\n disabledReason: deleting ? 'The company is being deleted' : 'The organization has not loaded',\n onClick: () => void handleDelete(),\n },\n ]}\n chips={\n <>\n <CrmRecordChip label=\"Type\" value={company.type ?? undefined} />\n <CrmRecordChip label=\"Industry\" value={company.industry} />\n <CrmRecordChip label=\"Rating\" value={company.rating ?? undefined} />\n <CrmRecordChip\n label=\"Owner\"\n value={\n company.ownerUid\n ? members.ready\n ? members.labelFor(company.ownerUid)\n : '…'\n : undefined\n }\n />\n </>\n }\n >\n <Stack spacing={1}>\n {factRows(rows)}\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'Address information'}\n </Typography>\n {factRows(addressRows)}\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'Description information'}\n </Typography>\n {factRows(descriptionRows)}\n {moreRows.length ? (\n <>\n <Typography variant=\"subtitle2\" sx={{ pt: 1 }}>\n {'More fields'}\n </Typography>\n {factRows(moreRows)}\n </>\n ) : null}\n </Stack>\n {editing ? (\n <CompanyEditDrawer\n open\n onClose={() => setEditing(false)}\n hostId={hostId}\n org={org}\n company={company}\n seed={seed}\n members={members}\n onSaved={() => setEditing(false)}\n />\n ) : null}\n </CrmRecordHeader>\n )\n}\nCompanyPropertiesCard.displayName = 'CompanyPropertiesCard'\n\nexport default CompanyPropertiesCard\n"],"names":["pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","AppLink","MdiIcon","useConfirmationContext","useSnackbar","Button","Link","Stack","Typography","useCallback","useState","useContactFieldDefinitions","useCrmActivityLogger","useCrmRecordNames","COMPANY_DETACH_LIMIT","companyDeleteFailureMessage","deleteCompanyThroughRoute","formatMoney","CompanyEditDrawer","formatContactCustomValue","CrmCallButton","CrmPhoneLink","CrmRecordChip","CrmRecordHeader","useCrmApi","COMPANY_PAGE_HELP","anchor","formatAddress","address","line1","line2","city","state","filter","Boolean","join","postalCode","country","map","part","String","trim","CompanyPropertiesCard","props","company","seed","hostId","org","crmScope","members","routes","onDeleted","scope","callCrm","confirm","enqueueSnackbar","logActivity","editing","setEditing","deleting","setDeleting","fields","orgId","handleDelete","name","$id","accepted","title","description","confirmationText","confirmationButtonProps","color","then","catch","outcome","deleted","toLocaleString","variant","type","id","detached","persist","error","console","allowDuplicate","parentId","parentCompanyId","recordName","groupId","records","kind","rows","label","value","href","website","target","rel","phone","fax","ownership","accountSource","accountNumber","site","tickerSymbol","sicCode","numberOfEmployees","annualRevenueCents","currency","tags","addressRows","shippingAddress","descriptionRows","notes","moreRows","active","definition","text","custom","key","factRows","list","row","direction","spacing","sx","alignItems","minWidth","flexShrink","whiteSpace","overflowWrap","subtitle","domain","help","backHref","section","backLabel","actions","link","companyId","size","startIcon","path","onClick","menuItems","icon","destructive","disabled","disabledReason","chips","undefined","industry","rating","ownerUid","ready","labelFor","pt","length","open","onClose","onSaved","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAIEA,cAAc,QACT,eAAc;AACrB,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,yBAAwB;AAC3E,SAASC,OAAO,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC/E,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,SAASC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAC/D,SAAyBC,WAAW,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lC,gBAAgB0G;;8BACnD,KAAChI;oBAAcsE,OAAM;oBAAWC,OAAOjD,QAAQ2G,QAAQ;;8BACvD,KAACjI;oBAAcsE,OAAM;oBAASC,KAAK,GAAEjD,kBAAAA,QAAQ4G,MAAM,YAAd5G,kBAAkB0G;;8BACvD,KAAChI;oBACCsE,OAAM;oBACNC,OACEjD,QAAQ6G,QAAQ,GACZxG,QAAQyG,KAAK,GACXzG,QAAQ0G,QAAQ,CAAC/G,QAAQ6G,QAAQ,IACjC,MACFH;;;;;0BAMZ,MAAC/I;gBAAMqH,SAAS;;oBACbJ,SAAS7B;kCACV,KAACnF;wBAAWqE,SAAQ;wBAAYgD,IAAI;4BAAE+B,IAAI;wBAAE;kCACzC;;oBAEFpC,SAASV;kCACV,KAACtG;wBAAWqE,SAAQ;wBAAYgD,IAAI;4BAAE+B,IAAI;wBAAE;kCACzC;;oBAEFpC,SAASR;oBACTE,SAAS2C,MAAM,iBACd;;0CACE,KAACrJ;gCAAWqE,SAAQ;gCAAYgD,IAAI;oCAAE+B,IAAI;gCAAE;0CACzC;;4BAEFpC,SAASN;;yBAEV;;;YAELzD,wBACC,KAACvC;gBACC4I,IAAI;gBACJC,SAAS,IAAMrG,WAAW;gBAC1BZ,QAAQA;gBACRC,KAAKA;gBACLH,SAASA;gBACTC,MAAMA;gBACNI,SAASA;gBACT+G,SAAS,IAAMtG,WAAW;iBAE1B;;;AAGV;AACAhB,sBAAsBuH,WAAW,GAAG;AAEpC,eAAevH,sBAAqB"}
@@ -1,4 +1,5 @@
1
1
  import { 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
  export interface ContactAssociationsCardProps {
4
5
  /**
@@ -16,6 +17,8 @@ export interface ContactAssociationsCardProps {
16
17
  seed: {
17
18
  status: 'loading' | 'success' | 'error';
18
19
  fromCache: boolean;
20
+ /** The row's listener, so a save waits on that read alone (AGL-4135). */
21
+ listen?: ListenHandle | null;
19
22
  };
20
23
  /** The hub's own path, for the link to this person's lead. */
21
24
  basePath: string;
@@ -146,7 +146,8 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
146
146
  const verdict = await writeGuardedBySeed({
147
147
  subject: 'contact',
148
148
  unreadable: seed.status === 'error',
149
- fromCache: seed.fromCache
149
+ fromCache: seed.fromCache,
150
+ listen: seed.listen
150
151
  }, // An empty selection is sent as an empty list rather than left out,
151
152
  // so "filed under no campaign" has one shape here and in the pass
152
153
  // that detaches a deleted campaign.
@@ -179,6 +180,7 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
179
180
  enqueueSnackbar,
180
181
  record.$id,
181
182
  seed.fromCache,
183
+ seed.listen,
182
184
  seed.status
183
185
  ]);
184
186
  const sources = Object.keys((_record_sources = record.sources) != null ? _record_sources : {});
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-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 ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\n seed: { status: 'loading' | 'success' | 'error'; fromCache: boolean }\n /** The hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n /** The filing was edited since it was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n setEdited(false)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n // The draft follows the document until it is edited (AGL-4122): a page drawn\n // from the cache must not hold on to the cached filing once the server answers.\n useEffect(() => {\n if (!edited) setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record.campaignIds])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n const handleSaveFiling = useCallback(async () => {\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 // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setEdited(false)\n enqueueSnackbar('Filing 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 }, [campaigns, contactUpdate, enqueueSnackbar, record.$id, seed.fromCache, seed.status])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || (siteCampaigns.ready && !siteCampaigns.options.length)}\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={(next) => {\n setCampaigns(next)\n setEdited(true)\n }}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","edited","setEdited","recordId","$id","siteCampaigns","enabled","consent","handleSaveFiling","verdict","subject","unreadable","status","fromCache","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","color","recordKind","basis","join","declared","kind","value","onChange","next","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D;;;;CAIC,GACD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,OAAOC,qBAAqB,6DAA4D;AACxF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACxE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,gBAAgB,QAAQ,iCAA6B;AAE9D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,eAAe,QAAQ,gCAA4B;AA0B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;QA8F7CC;IA7F5B,MAAM,EAAEC,MAAM,EAAED,MAAM,E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,cAAA,KAACjE;gCAAQ4G,MAAMhF;0CAAe;;;sCAEhC,KAACnB;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC;;;qBAGH;gBACH1F,uBACC,MAACf;oBAAMwF,SAAS;;sCACd,KAAClG;4BACCyB,QAAQA;4BACR2F,YAAW;4BACXhE,UAAU5B,OAAO6B,GAAG;;sCAItB,KAAC1C;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC;;;qBAGH;8BACJ,MAACzG;oBAAMwF,SAAS;;sCACd,KAACvF;4BAAWwD,SAAQ;sCAAa;;sCACjC,MAACxD;4BAAWwD,SAAQ;;gCACjBvE,sBAAsB,CAAC4D,QAAQ6D,KAAK,CAAC;gCACrCzC,cAAcoB,MAAM,GAAG,CAAC,GAAG,EAAEpB,cAAc0C,IAAI,CAAC,QAAQ,GAAG;;;sCAE9D,KAAC3G;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC3D,QAAQ6D,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACd1F,aAAa4F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAAC9G;8BACD,KAACR;oBACCuH,MAAK;oBACLzB,SAASzC,cAAcyC,OAAO;oBAC9B0B,OAAO5E;oBACP6E,UAAU,CAACC;wBACT7E,aAAa6E;wBACbxE,UAAU;oBACZ;oBACAuD,OAAM;oBACNkB,YAAW;oBACXC,OAAOvE,cAAcwC,KAAK,IAAI,CAACxC,cAAcyC,OAAO,CAACC,MAAM;oBAC3D8B,WAAWrG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwByG,WAAW,GAAG;AAEtC,eAAezG,wBAAuB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-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 ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\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 hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n /** The filing was edited since it was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n setEdited(false)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n // The draft follows the document until it is edited (AGL-4122): a page drawn\n // from the cache must not hold on to the cached filing once the server answers.\n useEffect(() => {\n if (!edited) setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record.campaignIds])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n const handleSaveFiling = useCallback(async () => {\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 // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setEdited(false)\n enqueueSnackbar('Filing 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 campaigns,\n contactUpdate,\n enqueueSnackbar,\n record.$id,\n seed.fromCache,\n seed.listen,\n seed.status,\n ])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || (siteCampaigns.ready && !siteCampaigns.options.length)}\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={(next) => {\n setCampaigns(next)\n setEdited(true)\n }}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","edited","setEdited","recordId","$id","siteCampaigns","enabled","consent","handleSaveFiling","verdict","subject","unreadable","status","fromCache","listen","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","color","recordKind","basis","join","declared","kind","value","onChange","next","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D;;;;CAIC,GACD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,OAAOC,qBAAqB,6DAA4D;AACxF,SAASC,OAA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AQ8D,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACd3F,aAAa6F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAAC/G;8BACD,KAACR;oBACCwH,MAAK;oBACLzB,SAAS1C,cAAc0C,OAAO;oBAC9B0B,OAAO7E;oBACP8E,UAAU,CAACC;wBACT9E,aAAa8E;wBACbzE,UAAU;oBACZ;oBACAwD,OAAM;oBACNkB,YAAW;oBACXC,OAAOxE,cAAcyC,KAAK,IAAI,CAACzC,cAAc0C,OAAO,CAACC,MAAM;oBAC3D8B,WAAWtG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwB0G,WAAW,GAAG;AAEtC,eAAe1G,wBAAuB"}
@@ -128,7 +128,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
128
128
  * lacks the CRM. The shell mounted this page once the org had settled, so
129
129
  * this is the plan, not a paint of the org still loading.
130
130
  */ const suiteIncluded = crmSuiteIncluded(org);
131
- const { data: row, status, fromCache } = useFirestoreDoc(()=>scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null, [
131
+ const { data: row, status, fromCache, listen } = useFirestoreDoc(()=>scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null, [
132
132
  firestore,
133
133
  scope,
134
134
  id
@@ -480,7 +480,8 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
480
480
  consentGroup: consentGroup,
481
481
  seed: {
482
482
  status,
483
- fromCache
483
+ fromCache,
484
+ listen
484
485
  },
485
486
  members: members,
486
487
  suiteLocked: !suiteIncluded
@@ -492,7 +493,8 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
492
493
  consentGroup: consentGroup,
493
494
  seed: {
494
495
  status,
495
- fromCache
496
+ fromCache,
497
+ listen
496
498
  },
497
499
  basePath: basePath,
498
500
  bookingsHref: bookingsHref