@aglyn/plugins-crm 1.21.0 → 1.22.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 (43) hide show
  1. package/package.json +15 -15
  2. package/src/lib/components/company-edit-drawer.js +10 -4
  3. package/src/lib/components/company-edit-drawer.js.map +1 -1
  4. package/src/lib/components/contact-associations-card.js +13 -4
  5. package/src/lib/components/contact-associations-card.js.map +1 -1
  6. package/src/lib/components/contact-field-drawer.js +10 -4
  7. package/src/lib/components/contact-field-drawer.js.map +1 -1
  8. package/src/lib/components/contact-properties-card.js +13 -4
  9. package/src/lib/components/contact-properties-card.js.map +1 -1
  10. package/src/lib/components/contact-roles-editor.js +30 -12
  11. package/src/lib/components/contact-roles-editor.js.map +1 -1
  12. package/src/lib/components/crm-glance-card.js +1 -1
  13. package/src/lib/components/crm-glance-card.js.map +1 -1
  14. package/src/lib/components/deal-edit-drawer.js +14 -5
  15. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  16. package/src/lib/components/deal-products-card.js +22 -6
  17. package/src/lib/components/deal-products-card.js.map +1 -1
  18. package/src/lib/components/lead-campaigns-card.js +21 -11
  19. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  20. package/src/lib/components/lead-properties-card.js +13 -4
  21. package/src/lib/components/lead-properties-card.js.map +1 -1
  22. package/src/lib/components/picklist-values-card.js +14 -4
  23. package/src/lib/components/picklist-values-card.js.map +1 -1
  24. package/src/lib/components/pipeline-stages-dialog.js +13 -4
  25. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  26. package/src/lib/components/pipelines-dialog.js +27 -9
  27. package/src/lib/components/pipelines-dialog.js.map +1 -1
  28. package/src/lib/components/task-edit-drawer.js +14 -6
  29. package/src/lib/components/task-edit-drawer.js.map +1 -1
  30. package/src/lib/model/crm-reports.d.ts +2 -11
  31. package/src/lib/model/crm-reports.js +1 -14
  32. package/src/lib/model/crm-reports.js.map +1 -1
  33. package/src/lib/model/local-day-bounds.d.ts +31 -0
  34. package/src/lib/model/local-day-bounds.js +36 -0
  35. package/src/lib/model/local-day-bounds.js.map +1 -0
  36. package/src/lib/transfer/fields.d.ts +2 -8
  37. package/src/lib/transfer/fields.js +3 -9
  38. package/src/lib/transfer/fields.js.map +1 -1
  39. package/src/lib/transfer/resource-keys.d.ts +33 -0
  40. package/src/lib/transfer/resource-keys.js +33 -0
  41. package/src/lib/transfer/resource-keys.js.map +1 -0
  42. package/src/lib/transfer/ui.js +1 -1
  43. package/src/lib/transfer/ui.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-crm",
3
- "version": "1.21.0",
3
+ "version": "1.22.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,22 +25,22 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.21.0",
29
- "@aglyn/shared-data-enums": "1.21.0",
30
- "@aglyn/shared-data-mdi": "1.21.0",
31
- "@aglyn/shared-ui-jsx": "1.21.0",
32
- "@aglyn/shared-ui-next": "1.21.0",
33
- "@aglyn/shared-ui-snackstack": "1.21.0",
34
- "@aglyn/shared-util-email": "1.21.0",
35
- "@aglyn/shared-util-http": "1.21.0",
36
- "@aglyn/shared-util-timestamp": "1.21.0",
37
- "@aglyn/shared-util-tools": "1.21.0",
38
- "@aglyn/tenant-data-admin": "1.21.0",
39
- "@aglyn/tenant-feature-instance": "1.21.0",
40
- "@aglyn/tenant-runtime": "1.21.0",
28
+ "@aglyn/aglyn": "1.22.0",
29
+ "@aglyn/shared-data-enums": "1.22.0",
30
+ "@aglyn/shared-data-mdi": "1.22.0",
31
+ "@aglyn/shared-ui-jsx": "1.22.0",
32
+ "@aglyn/shared-ui-next": "1.22.0",
33
+ "@aglyn/shared-ui-snackstack": "1.22.0",
34
+ "@aglyn/shared-util-email": "1.22.0",
35
+ "@aglyn/shared-util-http": "1.22.0",
36
+ "@aglyn/shared-util-timestamp": "1.22.0",
37
+ "@aglyn/shared-util-tools": "1.22.0",
38
+ "@aglyn/tenant-data-admin": "1.22.0",
39
+ "@aglyn/tenant-feature-instance": "1.22.0",
40
+ "@aglyn/tenant-runtime": "1.22.0",
41
41
  "@dnd-kit/core": "^6.3.1",
42
42
  "@dnd-kit/utilities": "^3.2.2",
43
- "@swc/helpers": "0.5.23",
43
+ "@swc/helpers": "0.5.24",
44
44
  "notistack": "^3.0.2"
45
45
  },
46
46
  "peerDependencies": {
@@ -23,7 +23,7 @@ import { Container, HelpTip, MdiIcon, SrOnly } from "@aglyn/shared-ui-jsx";
23
23
  import { NavigationDrawerComponent } from "@aglyn/shared-ui-jsx/components/navigation-drawer.component";
24
24
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
25
25
  import { useFirestore, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
26
- import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
26
+ import { isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
27
27
  import { seedEditsBetween } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
28
28
  import { Alert, Button, IconButton, MenuItem, Stack, TextField, Typography } from "@mui/material";
29
29
  import { deleteField, doc, getDoc, serverTimestamp, setDoc, updateDoc } from "firebase/firestore";
@@ -380,6 +380,12 @@ const ADDRESS_FIELDS = [
380
380
  picklists.lists,
381
381
  readParent
382
382
  ]);
383
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
384
+ const held = useHeldSave(handleSave, {
385
+ checking: Boolean(checkingText),
386
+ subject: 'company',
387
+ onRefused: (message)=>setError(message)
388
+ });
383
389
  return /*#__PURE__*/ _jsx(NavigationDrawerComponent, {
384
390
  open: open,
385
391
  anchor: "right",
@@ -734,9 +740,9 @@ const ADDRESS_FIELDS = [
734
740
  variant: "contained",
735
741
  color: "primary",
736
742
  // A new company waits for its capturing site.
737
- disabled: busy || Boolean(checkingText) || !scope || !draft.name.trim() || !company && !createTokens.length,
738
- onClick: ()=>void handleSave(),
739
- children: busy ? 'Saving…' : company ? 'Save company' : 'Create company'
743
+ disabled: busy || !scope || !draft.name.trim() || !company && !createTokens.length || held.saving,
744
+ onClick: held.press,
745
+ children: busy || held.saving ? 'Saving…' : company ? 'Save company' : 'Create company'
740
746
  }),
741
747
  /*#__PURE__*/ _jsx(Button, {
742
748
  onClick: onClose,
@@ -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 type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { seedEditsBetween } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\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 /*\n * What was typed, kept as EDITS over the company (AGL-4047). The company\n * listen is live, so the server's copy arriving after the drawer opened on\n * the cache's replaces it under every field nobody touched, and Save is\n * held until it has (`checkingText`).\n */\n const draftSeed = useMemo<CompanyDraft>(\n () =>\n company\n ? companyDraftFrom(company)\n : { ...EMPTY_COMPANY_DRAFT, ownerUid: user?.uid ?? '' },\n [company, user?.uid],\n )\n const draftEdits = useSeedEdits<CompanyDraft>(draftSeed)\n const draft = draftEdits.values\n const { edit: editDraft, discard: discardDraft } = draftEdits\n const setDraft = useCallback(\n (build: (current: CompanyDraft) => CompanyDraft) =>\n editDraft((values) => seedEditsBetween(values, build(values))),\n [editDraft],\n )\n const checkingText =\n company && isSeedChecking({ fromCache: seed?.fromCache, unreadable: seed?.unreadable })\n ? seedCheckingText('company')\n : undefined\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 * The edits start empty when the drawer OPENS. The company listen is live,\n * and each snapshot moves only the fields nobody has typed in (the draft is\n * edits over it, above), so a snapshot, their own save's included, never\n * takes a field away from whoever is typing. The create case seeds the\n * owner to the person filing the record, which is the answer nine times in\n * ten and one click to change.\n */\n const companyId = company?.$id\n useEffect(() => {\n if (!open) return\n discardDraft()\n setCustom({})\n setError('')\n seededDefaults.current = false\n // Once per opening; `company` is a new object on every snapshot and must\n // not throw the edits away.\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, setDraft])\n\n const patch = useCallback(\n (field: keyof Omit<CompanyDraft, AddressDraftField>, value: string) =>\n setDraft((current) => ({ ...current, [field]: value })),\n [setDraft],\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 [setDraft],\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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : 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={\n busy ||\n Boolean(checkingText) ||\n !scope ||\n !draft.name.trim() ||\n (!company && !createTokens.length)\n }\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","isSeedChecking","seedCheckingText","useSeedEdits","seedEditsBetween","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","draftSeed","ownerUid","uid","draftEdits","draft","values","edit","editDraft","discard","discardDraft","setDraft","build","checkingText","fromCache","unreadable","undefined","busy","setBusy","error","setError","fields","storedCustom","custom","setCustom","records","bandFull","ready","quota","allowed","picklists","seededDefaults","companyOptions","enabled","parentOptions","options","filter","option","id","$id","companyId","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","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","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","role","Boolean","display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awer.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 isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { seedEditsBetween } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\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 /*\n * What was typed, kept as EDITS over the company (AGL-4047). The company\n * listen is live, so the server's copy arriving after the drawer opened on\n * the cache's replaces it under every field nobody touched, and Save is\n * held until it has (`checkingText`).\n */\n const draftSeed = useMemo<CompanyDraft>(\n () =>\n company\n ? companyDraftFrom(company)\n : { ...EMPTY_COMPANY_DRAFT, ownerUid: user?.uid ?? '' },\n [company, user?.uid],\n )\n const draftEdits = useSeedEdits<CompanyDraft>(draftSeed)\n const draft = draftEdits.values\n const { edit: editDraft, discard: discardDraft } = draftEdits\n const setDraft = useCallback(\n (build: (current: CompanyDraft) => CompanyDraft) =>\n editDraft((values) => seedEditsBetween(values, build(values))),\n [editDraft],\n )\n const checkingText =\n company && isSeedChecking({ fromCache: seed?.fromCache, unreadable: seed?.unreadable })\n ? seedCheckingText('company')\n : undefined\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 * The edits start empty when the drawer OPENS. The company listen is live,\n * and each snapshot moves only the fields nobody has typed in (the draft is\n * edits over it, above), so a snapshot, their own save's included, never\n * takes a field away from whoever is typing. The create case seeds the\n * owner to the person filing the record, which is the answer nine times in\n * ten and one click to change.\n */\n const companyId = company?.$id\n useEffect(() => {\n if (!open) return\n discardDraft()\n setCustom({})\n setError('')\n seededDefaults.current = false\n // Once per opening; `company` is a new object on every snapshot and must\n // not throw the edits away.\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, setDraft])\n\n const patch = useCallback(\n (field: keyof Omit<CompanyDraft, AddressDraftField>, value: string) =>\n setDraft((current) => ({ ...current, [field]: value })),\n [setDraft],\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 [setDraft],\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 // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking: Boolean(checkingText),\n subject: 'company',\n onRefused: (message) => setError(message),\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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : 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={\n busy ||\n !scope ||\n !draft.name.trim() ||\n (!company && !createTokens.length) ||\n held.saving\n }\n onClick={held.press}\n >\n {busy || held.saving\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","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","seedEditsBetween","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","draftSeed","ownerUid","uid","draftEdits","draft","values","edit","editDraft","discard","discardDraft","setDraft","build","checkingText","fromCache","unreadable","undefined","busy","setBusy","error","setError","fields","storedCustom","custom","setCustom","records","bandFull","ready","quota","allowed","picklists","seededDefaults","companyOptions","enabled","parentOptions","options","filter","option","id","$id","companyId","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","listen","cleared","Object","fromEntries","map","_rowId","stored","searchFields","updatedAt","message","variant","persist","visibleTo","createdByUid","createdAt","name","trim","caught","console","held","checking","Boolean","onRefused","anchor","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","gutterY","spacing","disabled","optional","helperText","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","role","saving","press","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,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K;wBAClBrC,UAAU,CAACC,QAAUlE,MAAM,SAASkE,MAAMC,MAAM,CAAClE,KAAK;wBACtDsG,SAAS;wBACTC,SAAS;;oBAEVnI,OAAO4C,MAAM,CAACC,MAAM,iBACnB;;0CACE,KAACpI;gCAAWoJ,SAAQ;0CAAa;;4BAChC7D,OAAO4C,MAAM,CAACW,GAAG,CAAC,CAAC6E,2BAClB,KAAC/L;oCAEC+L,YAAYA;oCACZxG,OAAOzF,oBAAoB8D,cAAcC,QAAQkI,WAAW9K,GAAG;oCAC/DsI,UAAU,CAAChE,QACTzB,UAAU,CAACiB,UAAa,aAAKA;gDAAS,CAACgH,WAAW9K,GAAG,CAAC,EAAEsE;;oCAE1D0D,UAAU1F;mCANLwI,WAAWlH,GAAG;;yBAUvB;oBACHpB,sBAAQ,KAAC3F;wBAAMsL,UAAS;kCAAW3F;yBAAiB;oBACpDN,6BACC,KAAC/E;wBAAWoJ,SAAQ;wBAAQe,OAAM;wBAAiByD,MAAK;kCACrD7I;yBAED;kCACJ,MAACjF;wBAAMsM,WAAU;wBAAMxB,SAAS;;0CAC9B,KAACjL;gCACCyJ,SAAQ;gCACRe,OAAM;gCACN,8CAA8C;gCAC9CU,UACE1F,QACA,CAACtB,SACD,CAACU,MAAMkF,IAAI,CAACC,IAAI,MACf,CAACpG,WAAW,CAACQ,aAAasE,MAAM,IACjCyB,KAAKgE,MAAM;gCAEbvD,SAAST,KAAKiE,KAAK;0CAElB3I,QAAQ0E,KAAKgE,MAAM,GAChB,YACAvK,UACE,iBACA;;0CAER,KAAC3D;gCAAO2K,SAASnH;gCAAS0H,UAAU1F;0CACjC;;;;;;;;AAOf;AACApC,kBAAkBgL,WAAW,GAAG;AAEhC,eAAehL,kBAAiB"}
@@ -29,7 +29,7 @@ import ContainerPicker from "@aglyn/tenant-feature-instance/components/container
29
29
  import { AppLink, CardDisplay } from "@aglyn/shared-ui-jsx";
30
30
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
31
31
  import { useFirestore, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
32
- import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
32
+ import { isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
33
33
  import { Button, Chip, Divider, Stack, Typography } from "@mui/material";
34
34
  import { doc, getDoc } from "firebase/firestore";
35
35
  import { useCallback, useEffect, useMemo, useState } from "react";
@@ -199,6 +199,15 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
199
199
  consent.assertedBy === 'operator' ? 'entered by your team' : null,
200
200
  consent.otherGrant === 'other-host' ? 'opted in to another site in this workspace' : null
201
201
  ].filter(Boolean);
202
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
203
+ const held = useHeldSave(handleSaveFiling, {
204
+ checking: Boolean(checkingText),
205
+ subject: 'contact',
206
+ onRefused: (message)=>enqueueSnackbar(message, {
207
+ variant: 'warning',
208
+ persist: false
209
+ })
210
+ });
202
211
  return /*#__PURE__*/ _jsx(CardDisplay, {
203
212
  header: 'Relationship',
204
213
  help: Aglyn.pluginDocsHelp('contactRecord', {
@@ -210,9 +219,9 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
210
219
  action: /*#__PURE__*/ _jsx(Button, {
211
220
  size: "small",
212
221
  variant: "outlined",
213
- disabled: saving || Boolean(checkingText) || siteCampaigns.ready && !siteCampaigns.options.length,
214
- onClick: ()=>void handleSaveFiling(),
215
- children: saving ? 'Saving…' : 'Save filing'
222
+ disabled: saving || siteCampaigns.ready && !siteCampaigns.options.length || held.saving,
223
+ onClick: held.press,
224
+ children: held.saving ? 'Saving…' : 'Save filing'
216
225
  })
217
226
  },
218
227
  children: /*#__PURE__*/ _jsxs(Stack, {
@@ -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 type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 /*\n * Save is held while the contact read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). The filing follows the document until it is edited, so what\n * is ticked meanwhile stays.\n */\n const checkingText = isSeedChecking({\n fromCache: seed.fromCache,\n unreadable: seed.status === 'error',\n })\n ? seedCheckingText('contact')\n : undefined\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={\n saving ||\n Boolean(checkingText) ||\n (siteCampaigns.ready && !siteCampaigns.options.length)\n }\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n {edited && checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\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","isSeedChecking","seedCheckingText","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","checkingText","fromCache","unreadable","status","handleSaveFiling","verdict","subject","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","color","role","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","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,QAEb,iCAAgC;AACvC,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,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;AA+B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;QAoH7CC;IAnH5B,MAAM,EAAEC,MAAM,EAAED,MAAM,EAAEE,GAAG,EAAEC,YAAY,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,YAAY,EAAE,GAAGP;IAC5E,0EAA0E;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,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 {\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 /*\n * Save is held while the contact read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). The filing follows the document until it is edited, so what\n * is ticked meanwhile stays.\n */\n const checkingText = isSeedChecking({\n fromCache: seed.fromCache,\n unreadable: seed.status === 'error',\n })\n ? seedCheckingText('contact')\n : undefined\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 // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSaveFiling, {\n checking: Boolean(checkingText),\n subject: 'contact',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\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={\n saving ||\n (siteCampaigns.ready && !siteCampaigns.options.length) ||\n held.saving\n }\n onClick={held.press}\n >\n {held.saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n {edited && checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\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","isSeedChecking","seedCheckingText","useHeldSave","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","checkingText","fromCache","unreadable","status","handleSaveFiling","verdict","subject","listen","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","held","checking","onRefused","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","press","spacing","color","role","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","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,QAEb,iCAAgC;AACvC,SACEC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,QACN,sDAAqD;AAC5D,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,S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,GAAG;;;sCAE9D,KAAClH;4BAAW0D,SAAQ;4BAAUoC,OAAM;sCACjCjD,QAAQoE,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACdjG,aAAamG,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAACrH;8BACD,KAACX;oBACCiI,MAAK;oBACL3B,SAAS9C,cAAc8C,OAAO;oBAC9B4B,OAAOnF;oBACPoF,UAAU,CAACC;wBACTpF,aAAaoF;wBACb/E,UAAU;oBACZ;oBACA+D,OAAM;oBACNiB,YAAW;oBACXC,OAAO9E,cAAc6C,KAAK,IAAI,CAAC7C,cAAc8C,OAAO,CAACC,MAAM;oBAC3DgC,WAAW5G,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwBgH,WAAW,GAAG;AAEtC,eAAehH,wBAAuB"}
@@ -18,7 +18,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
18
18
  import { CONTACT_FIELD_TYPE_LABELS, CONTACT_FIELD_TYPES, customFieldCurrency, isContactFieldType, normalizeContactFieldKey } from "@aglyn/aglyn";
19
19
  import { Button, Drawer, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
20
20
  import { useCallback, useEffect, useMemo, useState } from "react";
21
- import { useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
21
+ import { useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
22
22
  import { CRM_FIELD_LABEL_MAX_LENGTH, crmFieldOptions } from "../model/crm-setup-content.js";
23
23
  import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
24
24
  /** How the object reads in the drawer's own sentences — singular, lowercase. */ const OBJECT_NOUN = {
@@ -172,6 +172,12 @@ import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
172
172
  currency,
173
173
  required
174
174
  ]);
175
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
176
+ const held = useHeldSave(handleSubmit, {
177
+ checking: Boolean(checkingText),
178
+ subject: 'field',
179
+ onRefused: (message)=>setError(message)
180
+ });
175
181
  return /*#__PURE__*/ _jsx(Drawer, {
176
182
  anchor: "right",
177
183
  open: open,
@@ -296,9 +302,9 @@ import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
296
302
  /*#__PURE__*/ _jsx(Button, {
297
303
  variant: "contained",
298
304
  color: "primary",
299
- disabled: !canSubmit || Boolean(checkingText),
300
- onClick: handleSubmit,
301
- children: editing ? 'Save' : 'Create field'
305
+ disabled: !canSubmit || held.saving,
306
+ onClick: held.press,
307
+ children: held.saving ? 'Saving…' : editing ? 'Save' : 'Create field'
302
308
  }),
303
309
  /*#__PURE__*/ _jsx(Button, {
304
310
  onClick: onClose,