@aglyn/plugins-crm 1.4.0 → 1.6.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 (81) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/add-to-list-dialog.js +7 -3
  3. package/src/lib/components/add-to-list-dialog.js.map +1 -1
  4. package/src/lib/components/company-contact-roles-card.d.ts +3 -0
  5. package/src/lib/components/company-contact-roles-card.js +4 -2
  6. package/src/lib/components/company-contact-roles-card.js.map +1 -1
  7. package/src/lib/components/company-detail-page.js +5 -3
  8. package/src/lib/components/company-detail-page.js.map +1 -1
  9. package/src/lib/components/company-edit-drawer.d.ts +3 -0
  10. package/src/lib/components/company-edit-drawer.js +2 -1
  11. package/src/lib/components/company-edit-drawer.js.map +1 -1
  12. package/src/lib/components/company-properties-card.d.ts +3 -0
  13. package/src/lib/components/company-properties-card.js.map +1 -1
  14. package/src/lib/components/contact-associations-card.d.ts +3 -0
  15. package/src/lib/components/contact-associations-card.js +3 -1
  16. package/src/lib/components/contact-associations-card.js.map +1 -1
  17. package/src/lib/components/contact-detail-page.js +5 -3
  18. package/src/lib/components/contact-detail-page.js.map +1 -1
  19. package/src/lib/components/contact-properties-card.d.ts +3 -0
  20. package/src/lib/components/contact-properties-card.js +3 -1
  21. package/src/lib/components/contact-properties-card.js.map +1 -1
  22. package/src/lib/components/deal-contact-roles-card.d.ts +3 -0
  23. package/src/lib/components/deal-contact-roles-card.js +4 -2
  24. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  25. package/src/lib/components/deal-detail-page.js +7 -4
  26. package/src/lib/components/deal-detail-page.js.map +1 -1
  27. package/src/lib/components/deal-edit-drawer.d.ts +12 -1
  28. package/src/lib/components/deal-edit-drawer.js +150 -53
  29. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  30. package/src/lib/components/deal-products-card.d.ts +3 -0
  31. package/src/lib/components/deal-products-card.js +4 -2
  32. package/src/lib/components/deal-products-card.js.map +1 -1
  33. package/src/lib/components/deals-section.js +1 -0
  34. package/src/lib/components/deals-section.js.map +1 -1
  35. package/src/lib/components/fields-section.js +7 -3
  36. package/src/lib/components/fields-section.js.map +1 -1
  37. package/src/lib/components/lead-campaigns-card.d.ts +3 -1
  38. package/src/lib/components/lead-campaigns-card.js +3 -2
  39. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  40. package/src/lib/components/lead-detail-page.js +3 -1
  41. package/src/lib/components/lead-detail-page.js.map +1 -1
  42. package/src/lib/components/lead-properties-card.d.ts +3 -1
  43. package/src/lib/components/lead-properties-card.js +3 -2
  44. package/src/lib/components/lead-properties-card.js.map +1 -1
  45. package/src/lib/components/picklist-values-card.js +4 -2
  46. package/src/lib/components/picklist-values-card.js.map +1 -1
  47. package/src/lib/components/pipeline-stages-dialog.d.ts +3 -0
  48. package/src/lib/components/pipeline-stages-dialog.js +43 -14
  49. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  50. package/src/lib/components/pipelines-dialog.d.ts +3 -0
  51. package/src/lib/components/pipelines-dialog.js +5 -2
  52. package/src/lib/components/pipelines-dialog.js.map +1 -1
  53. package/src/lib/components/record-tasks-card.js +3 -2
  54. package/src/lib/components/record-tasks-card.js.map +1 -1
  55. package/src/lib/components/task-edit-drawer.d.ts +2 -0
  56. package/src/lib/components/task-edit-drawer.js +2 -1
  57. package/src/lib/components/task-edit-drawer.js.map +1 -1
  58. package/src/lib/components/tasks-section.js +3 -2
  59. package/src/lib/components/tasks-section.js.map +1 -1
  60. package/src/lib/hooks/use-contact-field-definitions.d.ts +3 -0
  61. package/src/lib/hooks/use-contact-field-definitions.js +3 -2
  62. package/src/lib/hooks/use-contact-field-definitions.js.map +1 -1
  63. package/src/lib/hooks/use-crm-picklist.d.ts +3 -0
  64. package/src/lib/hooks/use-crm-picklist.js +5 -3
  65. package/src/lib/hooks/use-crm-picklist.js.map +1 -1
  66. package/src/lib/hooks/use-crm-tasks.d.ts +3 -0
  67. package/src/lib/hooks/use-crm-tasks.js +3 -1
  68. package/src/lib/hooks/use-crm-tasks.js.map +1 -1
  69. package/src/lib/hooks/use-lead-source-picklist.js +5 -3
  70. package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
  71. package/src/lib/hooks/use-lead-status-picklist.js +5 -3
  72. package/src/lib/hooks/use-lead-status-picklist.js.map +1 -1
  73. package/src/lib/hooks/use-pipeline.d.ts +3 -0
  74. package/src/lib/hooks/use-pipeline.js +3 -1
  75. package/src/lib/hooks/use-pipeline.js.map +1 -1
  76. package/src/lib/model/crm-list-query.d.ts +7 -0
  77. package/src/lib/model/crm-list-query.js +10 -0
  78. package/src/lib/model/crm-list-query.js.map +1 -1
  79. package/src/lib/model/deal-form-model.d.ts +35 -0
  80. package/src/lib/model/deal-form-model.js +103 -0
  81. package/src/lib/model/deal-form-model.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-contact-roles-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\n'use client'\n\nimport {\n CRM_COLLECTIONS,\n type CrmDealContactRole,\n dealContactRolesOf,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, writeGuardedBySeed } from '@aglyn/tenant-feature-instance'\nimport { deleteField, doc, updateDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from '../model/crm-list-query'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport type { DealDoc } from '../model/deal-board-model'\nimport { dealContactRolesSave } from '../model/deal-contact-roles'\nimport { ContactRolesEditor } from './contact-roles-editor'\n\nexport interface DealContactRolesCardProps {\n deal: DealDoc\n /** The site the page is read under, or `null` at the organization level. */\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\n /** The listener's verdict on the deal, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n}\n\n/**\n * Salesforce's Opportunity Contact Roles on a deal's page (AGL-3521): the\n * people on the deal, the part each plays, and which one is Primary.\n *\n * Every edit is one client-direct write of the whole list beside the\n * `contactId` its Primary names — the field every reader that came before\n * roles still reads — and the list fields a contact's page finds the deal\n * by. A role is one of the org's `opportunityContactRole` values, kept on\n * the Deals tab of Fields; a contact keeps the role it holds even once that\n * value is deactivated. Adding opens a dialog rather than a row of fields\n * above the list.\n */\nexport function DealContactRolesCard(props: DealContactRolesCardProps) {\n const { deal, hostId, org, routes, fromCache, unreadable } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const scope = useCrmScope({ hostId, org })\n const groupId = scope.consentGroup?.groupId ?? null\n const roles = useMemo(() => dealContactRolesOf(deal), [deal])\n const roleList = useCrmPicklist('opportunityContactRole', scope.orgId)\n const nameOf = useCrmRecordNames({\n orgId: scope.orgId,\n groupId,\n org: (org ?? null) as Record<string, unknown> | null,\n records: roles.map((row) => ({ kind: 'contact' as const, id: row.contactId })),\n })\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n\n /** The one write: the list, its Primary as `contactId`, and the list fields. */\n const save = useCallback(\n async (next: CrmDealContactRole[], done: string) => {\n if (!scope.orgId) return false\n const verdict = dealContactRolesSave(deal, next, roleList.picklist)\n if (verdict.ok === false) {\n enqueueSnackbar(verdict.error, { variant: 'warning', persist: false })\n return false\n }\n const primaryName = verdict.contactId ? nameOf('contact', verdict.contactId) : undefined\n const patch: Record<string, unknown> = {\n contactRoles: verdict.contactRoles,\n contactId: verdict.contactId ?? deleteField(),\n // The name the drawer copies beside `contactId`, moved with the Primary.\n ...(verdict.primaryChanged ? { contactName: primaryName || deleteField() } : {}),\n }\n setBusy(true)\n try {\n const written = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache },\n async () => {\n await updateDoc(doc(firestore, 'orgs', scope.orgId as string, CRM_COLLECTIONS.deals, deal.$id), {\n ...patch,\n ...crmClientListFields(\n 'deals',\n deal as unknown as Record<string, unknown>,\n patch,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n ),\n updatedAt: new Date(),\n })\n },\n )\n if (!written.ok) {\n enqueueSnackbar(written.message, { variant: 'warning', persist: false })\n return false\n }\n enqueueSnackbar(done, { variant: 'success', persist: false })\n return true\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n return false\n } finally {\n setBusy(false)\n }\n },\n [scope.orgId, deal, roleList.picklist, nameOf, unreadable, fromCache, firestore, enqueueSnackbar],\n )\n\n return (\n <ContactRolesEditor\n noun=\"deal\"\n roles={roles}\n busy={busy}\n adding={adding}\n onAddingChange={setAdding}\n ready={Boolean(scope.orgId)}\n hostId={hostId}\n org={org}\n routes={routes}\n picklist={roleList.picklist}\n nameOf={nameOf}\n help={pluginDocsHelp('deals', { anchor: '#contact-roles' })}\n emptyDescription=\"Name the people on the deal and the part each plays — one of them Primary.\"\n save={save}\n />\n )\n}\nDealContactRolesCard.displayName = 'DealContactRolesCard'\n\nexport default DealContactRolesCard\n"],"names":["CRM_COLLECTIONS","dealContactRolesOf","pluginDocsHelp","useSnackbar","useFirestore","writeGuardedBySeed","deleteField","doc","updateDoc","useCallback","useMemo","useState","useCrmPicklist","useCrmRecordNames","useCrmScope","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFields","dealContactRolesSave","ContactRolesEditor","DealContactRolesCard","props","scope","deal","hostId","org","routes","fromCache","unreadable","firestore","enqueueSnackbar","groupId","consentGroup","roles","roleList","orgId","nameOf","records","map","row","kind","id","contactId","busy","setBusy","adding","setAdding","save","next","done","verdict","picklist","ok","error","variant","persist","primaryName","undefined","patch","contactRoles","primaryChanged","contactName","written","subject","deals","$id","updatedAt","Date","message","console","allowDuplicate","noun","onAddingChange","ready","Boolean","help","anchor","emptyDescription","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SACEA,eAAe,EAEfC,kBAAkB,EAClBC,cAAc,QACT,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,iCAAgC;AACjF,SAASC,WAAW,EAAEC,GAAG,EAAEC,SAAS,QAAQ,qBAAoB;AAChE,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,cAAc,QAAQ,+BAA2B;AAC1D,SAASC,iBAAiB,QAAQ,mCAA+B;AACjE,SAAyBC,WAAW,QAAQ,4BAAwB;AACpE,SAASC,iCAAiC,EAAEC,mBAAmB,QAAQ,6BAAyB;AAGhG,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SAASC,kBAAkB,QAAQ,4BAAwB;AAa3D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;;QAKnDC;IAJhB,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,GAAG,EAAEC,MAAM,EAAEC,SAAS,EAAEC,UAAU,EAAE,GAAGP;IAC7D,MAAMQ,YAAYxB;IAClB,MAAM,EAAEyB,eAAe,EAAE,GAAG1B;IAC5B,MAAMkB,QAAQP,YAAY;QAAES;QAAQC;IAAI;IACxC,MAAMM,mBAAUT,sBAAAA,MAAMU,YAAY,qBAAlBV,oBAAoBS,OAAO,mBAAI;IAC/C,MAAME,QAAQtB,Q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AW,IAAIC;;YAEnB;YAEF,IAAI,CAACL,QAAQV,EAAE,EAAE;gBACftB,gBAAgBgC,QAAQM,OAAO,EAAE;oBAAEd,SAAS;oBAAWC,SAAS;gBAAM;gBACtE,OAAO;YACT;YACAzB,gBAAgBmB,MAAM;gBAAEK,SAAS;gBAAWC,SAAS;YAAM;YAC3D,OAAO;QACT,EAAE,OAAOF,OAAO;YACdgB,QAAQhB,KAAK,CAACA;YACdvB,gBAAgB,yBAAyB;gBAAEwB,SAAS;gBAASgB,gBAAgB;YAAK;YAClF,OAAO;QACT,SAAU;YACR1B,QAAQ;QACV;IACF,GACA;QAACtB,MAAMa,KAAK;QAAEZ;QAAMW,SAASiB,QAAQ;QAAEf;QAAQR;QAAYD;QAAWE;QAAWC;KAAgB;IAGnG,qBACE,KAACX;QACCoD,MAAK;QACLtC,OAAOA;QACPU,MAAMA;QACNE,QAAQA;QACR2B,gBAAgB1B;QAChB2B,OAAOC,QAAQpD,MAAMa,KAAK;QAC1BX,QAAQA;QACRC,KAAKA;QACLC,QAAQA;QACRyB,UAAUjB,SAASiB,QAAQ;QAC3Bf,QAAQA;QACRuC,MAAMxE,eAAe,SAAS;YAAEyE,QAAQ;QAAiB;QACzDC,kBAAiB;QACjB9B,MAAMA;;AAGZ;AACA3B,qBAAqB0D,WAAW,GAAG;AAEnC,eAAe1D,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-contact-roles-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\n'use client'\n\nimport {\n CRM_COLLECTIONS,\n type CrmDealContactRole,\n dealContactRolesOf,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport { deleteField, doc, updateDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from '../model/crm-list-query'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport type { DealDoc } from '../model/deal-board-model'\nimport { dealContactRolesSave } from '../model/deal-contact-roles'\nimport { ContactRolesEditor } from './contact-roles-editor'\n\nexport interface DealContactRolesCardProps {\n deal: DealDoc\n /** The site the page is read under, or `null` at the organization level. */\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\n /** The listener's verdict on the deal, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n /** The deal's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n}\n\n/**\n * Salesforce's Opportunity Contact Roles on a deal's page (AGL-3521): the\n * people on the deal, the part each plays, and which one is Primary.\n *\n * Every edit is one client-direct write of the whole list beside the\n * `contactId` its Primary names — the field every reader that came before\n * roles still reads — and the list fields a contact's page finds the deal\n * by. A role is one of the org's `opportunityContactRole` values, kept on\n * the Deals tab of Fields; a contact keeps the role it holds even once that\n * value is deactivated. Adding opens a dialog rather than a row of fields\n * above the list.\n */\nexport function DealContactRolesCard(props: DealContactRolesCardProps) {\n const { deal, hostId, org, routes, fromCache, unreadable, listen } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const scope = useCrmScope({ hostId, org })\n const groupId = scope.consentGroup?.groupId ?? null\n const roles = useMemo(() => dealContactRolesOf(deal), [deal])\n const roleList = useCrmPicklist('opportunityContactRole', scope.orgId)\n const nameOf = useCrmRecordNames({\n orgId: scope.orgId,\n groupId,\n org: (org ?? null) as Record<string, unknown> | null,\n records: roles.map((row) => ({ kind: 'contact' as const, id: row.contactId })),\n })\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n\n /** The one write: the list, its Primary as `contactId`, and the list fields. */\n const save = useCallback(\n async (next: CrmDealContactRole[], done: string) => {\n if (!scope.orgId) return false\n const verdict = dealContactRolesSave(deal, next, roleList.picklist)\n if (verdict.ok === false) {\n enqueueSnackbar(verdict.error, { variant: 'warning', persist: false })\n return false\n }\n const primaryName = verdict.contactId ? nameOf('contact', verdict.contactId) : undefined\n const patch: Record<string, unknown> = {\n contactRoles: verdict.contactRoles,\n contactId: verdict.contactId ?? deleteField(),\n // The name the drawer copies beside `contactId`, moved with the Primary.\n ...(verdict.primaryChanged ? { contactName: primaryName || deleteField() } : {}),\n }\n setBusy(true)\n try {\n const written = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache, listen },\n async () => {\n await updateDoc(doc(firestore, 'orgs', scope.orgId as string, CRM_COLLECTIONS.deals, deal.$id), {\n ...patch,\n ...crmClientListFields(\n 'deals',\n deal as unknown as Record<string, unknown>,\n patch,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n ),\n updatedAt: new Date(),\n })\n },\n )\n if (!written.ok) {\n enqueueSnackbar(written.message, { variant: 'warning', persist: false })\n return false\n }\n enqueueSnackbar(done, { variant: 'success', persist: false })\n return true\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n return false\n } finally {\n setBusy(false)\n }\n },\n [scope.orgId, deal, roleList.picklist, nameOf, unreadable, fromCache, listen, firestore, enqueueSnackbar],\n )\n\n return (\n <ContactRolesEditor\n noun=\"deal\"\n roles={roles}\n busy={busy}\n adding={adding}\n onAddingChange={setAdding}\n ready={Boolean(scope.orgId)}\n hostId={hostId}\n org={org}\n routes={routes}\n picklist={roleList.picklist}\n nameOf={nameOf}\n help={pluginDocsHelp('deals', { anchor: '#contact-roles' })}\n emptyDescription=\"Name the people on the deal and the part each plays — one of them Primary.\"\n save={save}\n />\n )\n}\nDealContactRolesCard.displayName = 'DealContactRolesCard'\n\nexport default DealContactRolesCard\n"],"names":["CRM_COLLECTIONS","dealContactRolesOf","pluginDocsHelp","useSnackbar","useFirestore","writeGuardedBySeed","deleteField","doc","updateDoc","useCallback","useMemo","useState","useCrmPicklist","useCrmRecordNames","useCrmScope","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFields","dealContactRolesSave","ContactRolesEditor","DealContactRolesCard","props","scope","deal","hostId","org","routes","fromCache","unreadable","listen","firestore","enqueueSnackbar","groupId","consentGroup","roles","roleList","orgId","nameOf","records","map","row","kind","id","contactId","busy","setBusy","adding","setAdding","save","next","done","verdict","picklist","ok","error","variant","persist","primaryName","undefined","patch","contactRoles","primaryChanged","contactName","written","subject","deals","$id","updatedAt","Date","message","console","allowDuplicate","noun","onAddingChange","ready","Boolean","help","anchor","emptyDescription","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SACEA,eAAe,EAEfC,kBAAkB,EAClBC,cAAc,QACT,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QAEb,iCAAgC;AACvC,SAASC,WAAW,EAAEC,GAAG,EAAEC,SAAS,QAAQ,qBAAoB;AAChE,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,cAAc,QAAQ,+BAA2B;AAC1D,SAASC,iBAAiB,QAAQ,mCAA+B;AACjE,SAAyBC,WAAW,QAAQ,4BAAwB;AACpE,SAASC,iCAAiC,EAAEC,mBAAmB,QAAQ,6BAAyB;AAGhG,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SAASC,kBAAkB,QAA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AAW,GAAG;AAEnC,eAAe3D,qBAAoB"}
@@ -73,7 +73,7 @@ import { RecordTasksCard } from "./record-tasks-card.js";
73
73
  hostId,
74
74
  org
75
75
  });
76
- const { data: deal, status, fromCache } = useDeal(scope.orgId, id);
76
+ const { data: deal, status, fromCache, listen } = useDeal(scope.orgId, id);
77
77
  // The feed the act is logged in, decided by the level it was performed
78
78
  // at (AGL-2738): this site's under a site, the organization's at the org
79
79
  // hub, where a client-direct append to the deal's own site would face a
@@ -303,7 +303,8 @@ import { RecordTasksCard } from "./record-tasks-card.js";
303
303
  org: org,
304
304
  routes: routes,
305
305
  fromCache: fromCache,
306
- unreadable: status === 'error'
306
+ unreadable: status === 'error',
307
+ listen: listen
307
308
  }),
308
309
  scope.orgId ? /*#__PURE__*/ _jsx(DealProductsCard, {
309
310
  deal: deal,
@@ -311,7 +312,8 @@ import { RecordTasksCard } from "./record-tasks-card.js";
311
312
  hostId: (_ref6 = hostId != null ? hostId : deal.hostId) != null ? _ref6 : null,
312
313
  org: org,
313
314
  fromCache: fromCache,
314
- unreadable: status === 'error'
315
+ unreadable: status === 'error',
316
+ listen: listen
315
317
  }) : null,
316
318
  /*#__PURE__*/ _jsx(RecordFilesCard, {
317
319
  scope: scope.scope,
@@ -348,7 +350,8 @@ import { RecordTasksCard } from "./record-tasks-card.js";
348
350
  pipelines: pipelineState.activePipelines,
349
351
  defaultPipeline: pipeline != null ? pipeline : pipelineState.pipeline,
350
352
  unreadable: status === 'error',
351
- fromCache: fromCache
353
+ fromCache: fromCache,
354
+ listen: listen
352
355
  })
353
356
  ]
354
357
  }));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-detail-page.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CRM_COLLECTIONS, dealStageById, pluginDocsHelp } from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport { Button, Stack, Typography } from '@mui/material'\nimport { deleteDoc, doc } from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useDealStageApi } from '../hooks/use-deal-stage-api'\nimport { useDeal } from '../hooks/use-deals'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { usePipeline } from '../hooks/use-pipeline'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport { DEAL_STATUS_LABELS, formatMoney } from '../model/deal-board-model'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { RecordActivityCard } from './record-activity-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { DealContactRolesCard } from './deal-contact-roles-card'\nimport { DealEditDrawer } from './deal-edit-drawer'\nimport { DealProductsCard } from './deal-products-card'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { DealPropertiesCard } from './deal-properties-card'\nimport { DealStageCard } from './deal-stage-card'\nimport RecordFilesCard from './record-files-card'\nimport { RecordTasksCard } from './record-tasks-card'\n\n/**\n * `/crm/deals/{dealId}` — one deal (AGL-2598).\n *\n * The record behind a card: its stage and the controls that move it, what\n * it is worth and who it is with — every contact on it and the part each\n * plays (AGL-3521) — the products behind the amount (AGL-2620), and the\n * tasks and activity filed against it. One live\n * document read; the pipeline and the roster are the same bounded reads\n * the board makes. Editing opens the same drawer the board creates with,\n * and deleting is the one destructive act here — confirmed, then a\n * client-direct delete the rules allow the same people who could have\n * created it.\n */\nexport function DealDetailPage(props: CrmDetailPageProps) {\n const { id, basePath, hostId, org } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const scope = useCrmScope({ hostId, org })\n const { data: deal, status, fromCache } = useDeal(scope.orgId, id)\n // The feed the act is logged in, decided by the level it was performed\n // at (AGL-2738): this site's under a site, the organization's at the org\n // hub, where a client-direct append to the deal's own site would face a\n // gate the record write never had to pass.\n const logActivity = useCrmActivityLogger(hostId)\n const pipelineState = usePipeline(scope.orgId, {\n hostId,\n org: (org ?? null) as Record<string, unknown> | null,\n })\n const pipeline = pipelineState.pipelineById(deal?.pipelineId)\n const roster = useOrgMemberDirectory(scope.orgId)\n const api = useDealStageApi(hostId)\n const nowMs = useMemo(() => Date.now(), [])\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n // The org's deal fields (AGL-2661), for the properties card's rows.\n const dealFields = useContactFieldDefinitions(scope.orgId, 'deal')\n // The deal's campaign by name (AGL-3516), read only for a deal that names one.\n const campaigns = useCrmCampaigns(\n { hostId, orgId: scope.orgId },\n { enabled: Boolean(deal?.campaignId) },\n )\n\n const notFound = scope.ready && (!scope.orgId || (status !== 'loading' && !deal))\n\n const handleDelete = useCallback(async () => {\n if (!deal || !scope.orgId) return\n const agreed = await confirm({\n title: 'Delete this deal?',\n description:\n `\"${deal.title}\" is removed from the pipeline along with its notes. ` +\n 'The contact and the company it names are not touched.',\n confirmationText: 'Delete deal',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeleting(true)\n try {\n await deleteDoc(doc(firestore, 'orgs', scope.orgId, CRM_COLLECTIONS.deals, deal.$id))\n // Setup → Activity shows CRM work (AGL-2622): the deal is org data,\n // but the act happened in this site's console and belongs in its feed.\n logActivity('Deleted deal', { type: 'deal', id: deal.$id, name: deal.title })\n enqueueSnackbar('Deal deleted', { variant: 'success', persist: false })\n router.push(routes.section('deals'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n setDeleting(false)\n }\n }, [deal, scope.orgId, confirm, firestore, logActivity, enqueueSnackbar, router, routes])\n\n const stage = deal ? dealStageById(pipeline, deal.stageId) : undefined\n\n return (\n // A create opened from this page — a task, an activity — files under\n // the deal's own site unless the reader says otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={deal?.hostId ?? null}>\n <Stack spacing={2}>\n <CrmRecordHeader\n kind=\"Deal\"\n title={deal?.title}\n subtitle={\n deal\n ? [pipeline?.name, stage?.name ?? deal.stageId].filter(Boolean).join(' · ')\n : undefined\n }\n help={pluginDocsHelp('deals', { anchor: '#a-deals-page' })}\n backHref={routes.section('deals')}\n backLabel=\"Back to deals\"\n loading={!deal && !notFound}\n // The booking door (AGL-2660): the deal's own site's services.\n booking={\n deal\n ? { hostId: hostId ?? deal.hostId ?? null, org, kind: 'deal', recordId: deal.$id }\n : undefined\n }\n actions={\n deal ? (\n <>\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiPencilOutline.path} size={0.8} />}\n onClick={() => setEditing(true)}\n >\n {'Edit'}\n </Button>\n <CrmSendEmailButton\n hostId={hostId ?? deal.hostId ?? null}\n org={org}\n dealId={deal.$id}\n contactId={deal.contactId}\n name={deal.contactName}\n />\n </>\n ) : null\n }\n menuItems={\n deal\n ? [\n {\n key: 'delete',\n label: 'Delete deal',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: deleting,\n disabledReason: 'The deal is being deleted',\n onClick: () => void handleDelete(),\n },\n ]\n : undefined\n }\n chips={\n deal ? (\n <>\n <CrmRecordChip\n label=\"Status\"\n value={DEAL_STATUS_LABELS[deal.status] ?? deal.status}\n color={deal.status === 'won' ? 'success' : deal.status === 'lost' ? 'default' : 'primary'}\n />\n <CrmRecordChip\n label=\"Amount\"\n value={\n typeof deal.amountCents === 'number'\n ? formatMoney(deal.amountCents, deal.currency)\n : undefined\n }\n />\n <CrmRecordChip label=\"Owner\" value={roster.nameOf(deal.ownerUid) || undefined} />\n {/* Seen here only through a share (AGL-3336). */}\n <CrmShareChipView\n chip={crmShareChipFor(\n deal as unknown as Record<string, unknown>,\n scope.consentGroup?.hostIds ?? [],\n )}\n org={org}\n />\n </>\n ) : null\n }\n >\n {notFound ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This deal does not exist, or is not visible to this site.'}\n </Typography>\n ) : null}\n </CrmRecordHeader>\n {deal ? (\n <>\n {/* What an assistant proposes about the deal, its stage included (AGL-2917). */}\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"deal\"\n recordId={deal.$id}\n name={deal.title}\n taskLink={{ dealId: deal.$id }}\n deal={{ pipeline, ref: deal, stageId: deal.stageId, status: deal.status, api }}\n />\n <DealStageCard deal={deal} pipeline={pipeline} api={api} nowMs={nowMs} />\n <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ alignItems: 'stretch' }}>\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <DealPropertiesCard\n deal={deal}\n pipeline={pipeline}\n ownerLabel={roster.nameOf(deal.ownerUid)}\n routes={routes}\n customFields={dealFields.active}\n campaignName={\n deal.campaignId\n ? (campaigns.options.find((option) => option.value === deal.campaignId)?.label ??\n deal.campaignId)\n : undefined\n }\n />\n </Stack>\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} dealId={deal.$id} />\n </Stack>\n </Stack>\n {/* The people on the deal and the part each plays (AGL-3521). */}\n <DealContactRolesCard\n deal={deal}\n hostId={hostId}\n org={org}\n routes={routes}\n fromCache={fromCache}\n unreadable={status === 'error'}\n />\n {scope.orgId ? (\n <DealProductsCard\n deal={deal}\n orgId={scope.orgId}\n hostId={hostId ?? deal.hostId ?? null}\n org={org}\n fromCache={fromCache}\n unreadable={status === 'error'}\n />\n ) : null}\n <RecordFilesCard\n scope={scope.scope}\n collection={CRM_COLLECTIONS.deals}\n recordId={deal.$id}\n mediaIds={deal.mediaIds}\n topic=\"deals\"\n />\n {/* Where the deal is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"deals\"\n id={deal.$id}\n record={deal as unknown as Record<string, unknown>}\n hostId={hostId ?? null}\n orgId={scope.orgId}\n org={org}\n viewingHostIds={scope.consentGroup?.hostIds}\n />\n <RecordActivityCard hostId={hostId} org={org} dealId={deal.$id} deal={deal} />\n </>\n ) : null}\n </Stack>\n <DealEditDrawer\n open={editing}\n onClose={() => setEditing(false)}\n hostId={hostId}\n org={org}\n deal={deal ?? null}\n pipelines={pipelineState.activePipelines}\n defaultPipeline={pipeline ?? pipelineState.pipeline}\n unreadable={status === 'error'}\n fromCache={fromCache}\n />\n </CrmCreateSiteDefault>\n )\n}\nDealDetailPage.displayName = 'DealDetailPage'\n\nexport default DealDetailPage\n"],"names":["CRM_COLLECTIONS","dealStageById","pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","Button","Stack","Typography","deleteDoc","doc","useRouter","useCallback","useMemo","useState","useContactFieldDefinitions","useCrmActivityLogger","CrmCreateSiteDefault","useCrmScope","useDealStageApi","useDeal","useOrgMemberDirectory","usePipeline","crmRoutes","DEAL_STATUS_LABELS","formatMoney","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","RecordActivityCard","CrmShareChipView","RecordSharingCard","crmShareChipFor","CrmSendEmailButton","DealContactRolesCard","DealEditDrawer","DealProductsCard","useCrmCampaigns","DealPropertiesCard","DealStageCard","RecordFilesCard","RecordTasksCard","DealDetailPage","props","hostId","scope","campaigns","id","basePath","org","routes","router","firestore","enqueueSnackbar","confirm","data","deal","status","fromCache","orgId","logActivity","pipelineState","pipeline","pipelineById","pipelineId","roster","api","nowMs","Date","now","editing","setEditing","deleting","setDeleting","dealFields","enabled","Boolean","campaignId","notFound","ready","handleDelete","agreed","title","description","confirmationText","confirmationButtonProps","color","then","catch","deals","$id","type","name","variant","persist","push","section","error","console","allowDuplicate","stage","stageId","undefined","spacing","kind","subtitle","filter","join","help","anchor","backHref","backLabel","loading","booking","recordId","actions","size","startIcon","path","onClick","dealId","contactId","contactName","menuItems","key","label","icon","destructive","disabled","disabledReason","chips","value","amountCents","currency","nameOf","ownerUid","chip","consentGroup","hostIds","taskLink","ref","direction","xs","md","sx","alignItems","flex","minWidth","ownerLabel","customFields","active","campaignName","options","find","option","unreadable","collection","mediaIds","topic","object","record","viewingHostIds","open","onClose","pipelines","activePipelines","defaultPipeline","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,EAAEC,aAAa,EAAEC,cAAc,QAAQ,eAAc;AAC7E,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,yBAAwB;AAC3E,SAASC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AACtE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SAASC,MAAM,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACzD,SAASC,SAAS,EAAEC,GAAG,QAAQ,qBAAoB;AACnD,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAA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AWA;;;;AAInB;AACAhB,eAAe6H,WAAW,GAAG;AAE7B,eAAe7H,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-detail-page.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CRM_COLLECTIONS, dealStageById, pluginDocsHelp } from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPencilOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport { Button, Stack, Typography } from '@mui/material'\nimport { deleteDoc, doc } from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useDealStageApi } from '../hooks/use-deal-stage-api'\nimport { useDeal } from '../hooks/use-deals'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { usePipeline } from '../hooks/use-pipeline'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport { DEAL_STATUS_LABELS, formatMoney } from '../model/deal-board-model'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { RecordActivityCard } from './record-activity-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { DealContactRolesCard } from './deal-contact-roles-card'\nimport { DealEditDrawer } from './deal-edit-drawer'\nimport { DealProductsCard } from './deal-products-card'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { DealPropertiesCard } from './deal-properties-card'\nimport { DealStageCard } from './deal-stage-card'\nimport RecordFilesCard from './record-files-card'\nimport { RecordTasksCard } from './record-tasks-card'\n\n/**\n * `/crm/deals/{dealId}` — one deal (AGL-2598).\n *\n * The record behind a card: its stage and the controls that move it, what\n * it is worth and who it is with — every contact on it and the part each\n * plays (AGL-3521) — the products behind the amount (AGL-2620), and the\n * tasks and activity filed against it. One live\n * document read; the pipeline and the roster are the same bounded reads\n * the board makes. Editing opens the same drawer the board creates with,\n * and deleting is the one destructive act here — confirmed, then a\n * client-direct delete the rules allow the same people who could have\n * created it.\n */\nexport function DealDetailPage(props: CrmDetailPageProps) {\n const { id, basePath, hostId, org } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const scope = useCrmScope({ hostId, org })\n const { data: deal, status, fromCache, listen } = useDeal(scope.orgId, id)\n // The feed the act is logged in, decided by the level it was performed\n // at (AGL-2738): this site's under a site, the organization's at the org\n // hub, where a client-direct append to the deal's own site would face a\n // gate the record write never had to pass.\n const logActivity = useCrmActivityLogger(hostId)\n const pipelineState = usePipeline(scope.orgId, {\n hostId,\n org: (org ?? null) as Record<string, unknown> | null,\n })\n const pipeline = pipelineState.pipelineById(deal?.pipelineId)\n const roster = useOrgMemberDirectory(scope.orgId)\n const api = useDealStageApi(hostId)\n const nowMs = useMemo(() => Date.now(), [])\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n // The org's deal fields (AGL-2661), for the properties card's rows.\n const dealFields = useContactFieldDefinitions(scope.orgId, 'deal')\n // The deal's campaign by name (AGL-3516), read only for a deal that names one.\n const campaigns = useCrmCampaigns(\n { hostId, orgId: scope.orgId },\n { enabled: Boolean(deal?.campaignId) },\n )\n\n const notFound = scope.ready && (!scope.orgId || (status !== 'loading' && !deal))\n\n const handleDelete = useCallback(async () => {\n if (!deal || !scope.orgId) return\n const agreed = await confirm({\n title: 'Delete this deal?',\n description:\n `\"${deal.title}\" is removed from the pipeline along with its notes. ` +\n 'The contact and the company it names are not touched.',\n confirmationText: 'Delete deal',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeleting(true)\n try {\n await deleteDoc(doc(firestore, 'orgs', scope.orgId, CRM_COLLECTIONS.deals, deal.$id))\n // Setup → Activity shows CRM work (AGL-2622): the deal is org data,\n // but the act happened in this site's console and belongs in its feed.\n logActivity('Deleted deal', { type: 'deal', id: deal.$id, name: deal.title })\n enqueueSnackbar('Deal deleted', { variant: 'success', persist: false })\n router.push(routes.section('deals'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n setDeleting(false)\n }\n }, [deal, scope.orgId, confirm, firestore, logActivity, enqueueSnackbar, router, routes])\n\n const stage = deal ? dealStageById(pipeline, deal.stageId) : undefined\n\n return (\n // A create opened from this page — a task, an activity — files under\n // the deal's own site unless the reader says otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={deal?.hostId ?? null}>\n <Stack spacing={2}>\n <CrmRecordHeader\n kind=\"Deal\"\n title={deal?.title}\n subtitle={\n deal\n ? [pipeline?.name, stage?.name ?? deal.stageId].filter(Boolean).join(' · ')\n : undefined\n }\n help={pluginDocsHelp('deals', { anchor: '#a-deals-page' })}\n backHref={routes.section('deals')}\n backLabel=\"Back to deals\"\n loading={!deal && !notFound}\n // The booking door (AGL-2660): the deal's own site's services.\n booking={\n deal\n ? { hostId: hostId ?? deal.hostId ?? null, org, kind: 'deal', recordId: deal.$id }\n : undefined\n }\n actions={\n deal ? (\n <>\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiPencilOutline.path} size={0.8} />}\n onClick={() => setEditing(true)}\n >\n {'Edit'}\n </Button>\n <CrmSendEmailButton\n hostId={hostId ?? deal.hostId ?? null}\n org={org}\n dealId={deal.$id}\n contactId={deal.contactId}\n name={deal.contactName}\n />\n </>\n ) : null\n }\n menuItems={\n deal\n ? [\n {\n key: 'delete',\n label: 'Delete deal',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: deleting,\n disabledReason: 'The deal is being deleted',\n onClick: () => void handleDelete(),\n },\n ]\n : undefined\n }\n chips={\n deal ? (\n <>\n <CrmRecordChip\n label=\"Status\"\n value={DEAL_STATUS_LABELS[deal.status] ?? deal.status}\n color={deal.status === 'won' ? 'success' : deal.status === 'lost' ? 'default' : 'primary'}\n />\n <CrmRecordChip\n label=\"Amount\"\n value={\n typeof deal.amountCents === 'number'\n ? formatMoney(deal.amountCents, deal.currency)\n : undefined\n }\n />\n <CrmRecordChip label=\"Owner\" value={roster.nameOf(deal.ownerUid) || undefined} />\n {/* Seen here only through a share (AGL-3336). */}\n <CrmShareChipView\n chip={crmShareChipFor(\n deal as unknown as Record<string, unknown>,\n scope.consentGroup?.hostIds ?? [],\n )}\n org={org}\n />\n </>\n ) : null\n }\n >\n {notFound ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This deal does not exist, or is not visible to this site.'}\n </Typography>\n ) : null}\n </CrmRecordHeader>\n {deal ? (\n <>\n {/* What an assistant proposes about the deal, its stage included (AGL-2917). */}\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"deal\"\n recordId={deal.$id}\n name={deal.title}\n taskLink={{ dealId: deal.$id }}\n deal={{ pipeline, ref: deal, stageId: deal.stageId, status: deal.status, api }}\n />\n <DealStageCard deal={deal} pipeline={pipeline} api={api} nowMs={nowMs} />\n <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ alignItems: 'stretch' }}>\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <DealPropertiesCard\n deal={deal}\n pipeline={pipeline}\n ownerLabel={roster.nameOf(deal.ownerUid)}\n routes={routes}\n customFields={dealFields.active}\n campaignName={\n deal.campaignId\n ? (campaigns.options.find((option) => option.value === deal.campaignId)?.label ??\n deal.campaignId)\n : undefined\n }\n />\n </Stack>\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} dealId={deal.$id} />\n </Stack>\n </Stack>\n {/* The people on the deal and the part each plays (AGL-3521). */}\n <DealContactRolesCard\n deal={deal}\n hostId={hostId}\n org={org}\n routes={routes}\n fromCache={fromCache}\n unreadable={status === 'error'}\n listen={listen}\n />\n {scope.orgId ? (\n <DealProductsCard\n deal={deal}\n orgId={scope.orgId}\n hostId={hostId ?? deal.hostId ?? null}\n org={org}\n fromCache={fromCache}\n unreadable={status === 'error'}\n listen={listen}\n />\n ) : null}\n <RecordFilesCard\n scope={scope.scope}\n collection={CRM_COLLECTIONS.deals}\n recordId={deal.$id}\n mediaIds={deal.mediaIds}\n topic=\"deals\"\n />\n {/* Where the deal is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"deals\"\n id={deal.$id}\n record={deal as unknown as Record<string, unknown>}\n hostId={hostId ?? null}\n orgId={scope.orgId}\n org={org}\n viewingHostIds={scope.consentGroup?.hostIds}\n />\n <RecordActivityCard hostId={hostId} org={org} dealId={deal.$id} deal={deal} />\n </>\n ) : null}\n </Stack>\n <DealEditDrawer\n open={editing}\n onClose={() => setEditing(false)}\n hostId={hostId}\n org={org}\n deal={deal ?? null}\n pipelines={pipelineState.activePipelines}\n defaultPipeline={pipeline ?? pipelineState.pipeline}\n unreadable={status === 'error'}\n fromCache={fromCache}\n listen={listen}\n />\n </CrmCreateSiteDefault>\n )\n}\nDealDetailPage.displayName = 'DealDetailPage'\n\nexport default DealDetailPage\n"],"names":["CRM_COLLECTIONS","dealStageById","pluginDocsHelp","mdiDeleteOutline","mdiPencilOutline","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","Button","Stack","Typography","deleteDoc","doc","useRouter","useCallback","useMemo","useState","useContactFieldDefinitions","useCrmActivityLogger","CrmCreateSiteDefault","useCrmScope","useDealStageApi","useDeal","useOrgMemberDirectory","usePipeline","crmRoutes","DEAL_STATUS_LABELS","formatMoney","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","RecordActivityCard","CrmShareChipView","RecordSharingCard","crmShareChipFor","CrmSendEmailButton","DealContactRolesCard","DealEditDrawer","DealProductsCard","useCrmCampaigns","DealPropertiesCard","DealStageCard","RecordFilesCard","RecordTasksCard","DealDetailPage","props","hostId","scope","campaigns","id","basePath","org","routes","router","firestore","enqueueSnackbar","confirm","data","deal","status","fromCache","listen","orgId","logActivity","pipelineState","pipeline","pipelineById","pipelineId","roster","api","nowMs","Date","now","editing","setEditing","deleting","setDeleting","dealFields","enabled","Boolean","campaignId","notFound","ready","handleDelete","agreed","title","description","confirmationText","confirmationButtonProps","color","then","catch","deals","$id","type","name","variant","persist","push","section","error","console","allowDuplicate","stage","stageId","undefined","spacing","kind","subtitle","filter","join","help","anchor","backHref","backLabel","loading","booking","recordId","actions","size","startIcon","path","onClick","dealId","contactId","contactName","menuItems","key","label","icon","destructive","disabled","disabledReason","chips","value","amountCents","currency","nameOf","ownerUid","chip","consentGroup","hostIds","taskLink","ref","direction","xs","md","sx","alignItems","flex","minWidth","ownerLabel","customFields","active","campaignName","options","find","option","unreadable","collection","mediaIds","topic","object","record","viewingHostIds","open","onClose","pipelines","activePipelines","defaultPipeline","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,EAAEC,aAAa,EAAEC,cAAc,QAAQ,eAAc;AAC7E,SAASC,gBAAgB,EAAEC,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F,OAAO;;0CAE7C,KAAC9G;gCAAmBe,QAAQA;gCAAQK,KAAKA;gCAAKwE,QAAQjE,KAAKmC,GAAG;gCAAEnC,MAAMA;;;yBAEtE;;;0BAEN,KAACrB;gBACCgI,MAAM5F;gBACN6F,SAAS,IAAM5F,WAAW;gBAC1B5B,QAAQA;gBACRK,KAAKA;gBACLO,IAAI,EAAEA,eAAAA,OAAQ;gBACd6G,WAAWvG,cAAcwG,eAAe;gBACxCC,eAAe,EAAExG,mBAAAA,WAAYD,cAAcC,QAAQ;gBACnD6F,YAAYnG,WAAW;gBACvBC,WAAWA;gBACXC,QAAQA;;;;AAIhB;AACAjB,eAAe8H,WAAW,GAAG;AAE7B,eAAe9H,eAAc"}
@@ -1,3 +1,4 @@
1
+ import { type ListenHandle } from '@aglyn/tenant-feature-instance';
1
2
  import { type CrmOrgDoc } from '../hooks/use-crm-scope';
2
3
  import { type DealDoc, type PipelineDoc } from '../model/deal-board-model';
3
4
  import { type DealFormValues } from '../model/deal-form-model';
@@ -18,9 +19,14 @@ export interface DealEditDrawerProps {
18
19
  pipelines: PipelineDoc[];
19
20
  /** Where a new deal lands when nobody picks a pipeline. */
20
21
  defaultPipeline: PipelineDoc | null;
21
- /** The listener's verdict on the row being edited, for the stale-seed guard. */
22
+ /**
23
+ * The listener's verdict on the row being edited. An unconfirmed row holds
24
+ * back only an edit that is worked out from it (`dealEditNeedsConfirmedRead`).
25
+ */
22
26
  unreadable?: boolean;
23
27
  fromCache?: boolean;
28
+ /** The deal's listener, so a save waits on that read alone (AGL-4135). */
29
+ listen?: ListenHandle | null;
24
30
  /** After a save, with the id of the deal written. */
25
31
  onSaved?: (dealId: string, mode: 'create' | 'edit') => void;
26
32
  }
@@ -43,6 +49,11 @@ export interface DealEditDrawerProps {
43
49
  * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the
44
50
  * caller was looking at.
45
51
  *
52
+ * An edit writes only what the reader changed (AGL-4132), so one field
53
+ * changed in a drawer opened on an unconfirmed read saves at once and cannot
54
+ * touch anything else on the deal. The form follows the stored deal in the
55
+ * fields they have not touched, and keeps what they typed in those they have.
56
+ *
46
57
  * ## The pickers
47
58
  *
48
59
  * The owner is picked from the org's roster, the company by a server-side
@@ -25,11 +25,12 @@ import { useSnackbar } from "@aglyn/shared-ui-snackstack";
25
25
  import { useFirestore, useFirestoreCollection, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
26
26
  import { Alert, Autocomplete, Button, IconButton, MenuItem, Stack, TextField, Typography } from "@mui/material";
27
27
  import { addDoc, collection, deleteField, doc, endAt, getDocs, limit, orderBy, query, startAt, updateDoc } from "firebase/firestore";
28
- import { useCallback, useEffect, useMemo, useState } from "react";
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
29
  import { useContactFieldDefinitions } from "../hooks/use-contact-field-definitions.js";
30
30
  import { useCrmActivityLogger } from "../hooks/use-crm-activity-logger.js";
31
31
  import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
32
32
  import { useCrmPicklist } from "../hooks/use-crm-picklist.js";
33
+ import { useCrmRecordNames } from "../hooks/use-crm-record-names.js";
33
34
  import { useCrmRecordsQuota } from "../hooks/use-crm-records-quota.js";
34
35
  import { crmScopeListable, crmVisibleToClause, useCrmScope } from "../hooks/use-crm-scope.js";
35
36
  import { useOrgMemberDirectory } from "../hooks/use-org-member-directory.js";
@@ -38,9 +39,9 @@ import { crmCustomDraftDocument, crmCustomDraftMissingRequired, crmCustomDraftVa
38
39
  import { CrmCustomFieldControl } from "./crm-custom-field-control.js";
39
40
  import { CrmPicklistSelect } from "./picklist-select.js";
40
41
  import { CrmSitePicker } from "./crm-site-picker.js";
41
- import { CRM_CLIENT_SEARCH_FIELDS, CRM_CLIENT_SORT_FIELDS, CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from "../model/crm-list-query.js";
42
+ import { CRM_CLIENT_SEARCH_FIELDS, CRM_CLIENT_SORT_FIELDS, CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFieldChanges } from "../model/crm-list-query.js";
42
43
  import { DEAL_CURRENCIES, openStages } from "../model/deal-board-model.js";
43
- import { contactChoicesFor, DEAL_NOTES_MAX, DEAL_TITLE_MAX, dealDocumentFromForm, dealFormFromDoc, dealFormProblem, dealPatchFromForm, emptyDealForm, judgeDealFormPicklists } from "../model/deal-form-model.js";
44
+ import { contactChoicesFor, DEAL_NOTES_MAX, DEAL_TITLE_MAX, dealDocumentFromForm, dealEditFromForm, dealEditNeedsConfirmedRead, dealFormFromDoc, dealFormProblem, emptyDealForm, judgeDealFormPicklists, rebaseDealForm } from "../model/deal-form-model.js";
44
45
  import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
45
46
  /**
46
47
  * How many recent contacts the picker matches against. The window is the
@@ -58,6 +59,25 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
58
59
  // The arrays a deal's contact roles are found by (AGL-3521).
59
60
  ...CRM_DEAL_CONTACT_ROLE_LIST_FIELDS
60
61
  ];
62
+ /**
63
+ * How long a save holds the drawer on the server's acknowledgement (AGL-4132).
64
+ * A durable console tab writes through whichever tab holds the lease, and a
65
+ * hidden or overloaded one can take a minute to answer (AGL-3806); 25 s was
66
+ * measured here. Stopping the wait does not stop the write: it is in the
67
+ * IndexedDB queue, the page behind the drawer already shows it, and the lease
68
+ * holder sends it.
69
+ */ const SAVE_HOLD_MS = 4000;
70
+ /** What a save says when its write fails after the hold let the drawer close. */ const SAVE_FAILED_LATE_MESSAGE = 'Your last change to this deal could not be saved. Open it and try again.';
71
+ /** Settles with `write`, or resolves when the hold runs out. */ function withinSaveHold(write) {
72
+ let timer;
73
+ const hold = new Promise((resolve)=>{
74
+ timer = setTimeout(resolve, SAVE_HOLD_MS);
75
+ });
76
+ return Promise.race([
77
+ write,
78
+ hold
79
+ ]).finally(()=>clearTimeout(timer));
80
+ }
61
81
  /**
62
82
  * The one form a deal is created and edited through (AGL-2598).
63
83
  *
@@ -77,6 +97,11 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
77
97
  * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the
78
98
  * caller was looking at.
79
99
  *
100
+ * An edit writes only what the reader changed (AGL-4132), so one field
101
+ * changed in a drawer opened on an unconfirmed read saves at once and cannot
102
+ * touch anything else on the deal. The form follows the stored deal in the
103
+ * fields they have not touched, and keeps what they typed in those they have.
104
+ *
80
105
  * ## The pickers
81
106
  *
82
107
  * The owner is picked from the org's roster, the company by a server-side
@@ -97,8 +122,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
97
122
  * picker of a lead offers at this level.
98
123
  */ export function DealEditDrawer(props) {
99
124
  var _ref, _dealFormProblem, _ref1, _ref2;
100
- var _contactChoices_find;
101
- const { open, onClose, hostId, org, deal, defaults, pipelines, defaultPipeline, unreadable = false, fromCache = false, onSaved } = props;
125
+ const { open, onClose, hostId, org, deal, defaults, pipelines, defaultPipeline, unreadable = false, fromCache = false, listen, onSaved } = props;
102
126
  const mode = deal ? 'edit' : 'create';
103
127
  const firestore = useFirestore();
104
128
  const { enqueueSnackbar } = useSnackbar();
@@ -140,12 +164,33 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
140
164
  deal == null ? void 0 : deal.custom
141
165
  ]);
142
166
  const [custom, setCustom] = useState({});
143
- // Re-seeded on every open: an existing deal's stored values, or a blank
144
- // form aimed at the default pipeline with whatever the opener preselected.
167
+ /*
168
+ * What the form was built from: what a save compares against, and what
169
+ * tells a field the reader changed from one they left alone. Held in a ref
170
+ * because nothing renders from it.
171
+ */ const seed = useRef(null);
172
+ // Seeded on every open: an existing deal's stored values, or a blank form
173
+ // aimed at the default pipeline with whatever the opener preselected. After
174
+ // that a new snapshot only moves the fields the reader has not touched.
145
175
  useEffect(()=>{
146
- if (!open) return;
147
- setValues(deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults));
148
- setCustom({});
176
+ var _ref;
177
+ if (!open) {
178
+ seed.current = null;
179
+ return;
180
+ }
181
+ const dealId = (_ref = deal == null ? void 0 : deal.$id) != null ? _ref : null;
182
+ const stored = deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults);
183
+ const previous = seed.current;
184
+ seed.current = {
185
+ dealId,
186
+ values: stored
187
+ };
188
+ if ((previous == null ? void 0 : previous.dealId) === dealId) {
189
+ setValues((current)=>rebaseDealForm(current, previous.values, stored));
190
+ } else {
191
+ setValues(stored);
192
+ setCustom({});
193
+ }
149
194
  }, [
150
195
  open,
151
196
  deal,
@@ -215,11 +260,42 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
215
260
  consentGroup,
216
261
  org
217
262
  ]);
218
- const contactValue = values.contactId ? {
219
- id: values.contactId,
220
- name: values.contactName,
221
- email: (_ref = (_contactChoices_find = contactChoices.find((choice)=>choice.id === values.contactId)) == null ? void 0 : _contactChoices_find.email) != null ? _ref : ''
222
- } : null;
263
+ /*
264
+ * THE LINKS' NAMES. The deal carries a copy beside each id, but a server
265
+ * door that moves the Primary drops it (`dealContactRolesUpdate`), so a link
266
+ * can arrive with no name to show. It is never shown blank: a picker that
267
+ * looks empty while it holds a link is how the link gets erased unseen.
268
+ */ const linkedName = useCrmRecordNames({
269
+ orgId: open ? orgId : null,
270
+ groupId: (_ref = consentGroup == null ? void 0 : consentGroup.groupId) != null ? _ref : null,
271
+ org: org != null ? org : null,
272
+ records: [
273
+ ...values.contactId && !values.contactName ? [
274
+ {
275
+ kind: 'contact',
276
+ id: values.contactId
277
+ }
278
+ ] : [],
279
+ ...values.companyId && !values.companyName ? [
280
+ {
281
+ kind: 'company',
282
+ id: values.companyId
283
+ }
284
+ ] : []
285
+ ]
286
+ });
287
+ const contactName = values.contactName || linkedName('contact', values.contactId) || 'Linked contact';
288
+ const companyName = values.companyName || linkedName('company', values.companyId) || 'Linked company';
289
+ // One object between renders: a new object is a new value to the picker,
290
+ // and a new value puts its label over whatever the reader is typing.
291
+ const contactValue = useMemo(()=>values.contactId ? {
292
+ id: values.contactId,
293
+ name: contactName,
294
+ email: ''
295
+ } : null, [
296
+ values.contactId,
297
+ contactName
298
+ ]);
223
299
  /*
224
300
  * THE COMPANY SEARCH: a prefix on `nameLower` with the scope, which the
225
301
  * companies collection indexes. Debounced so a name typed at speed is one
@@ -258,10 +334,13 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
258
334
  visibleTo,
259
335
  companyQuery
260
336
  ]);
261
- const companyValue = values.companyId ? {
262
- id: values.companyId,
263
- name: values.companyName
264
- } : null;
337
+ const companyValue = useMemo(()=>values.companyId ? {
338
+ id: values.companyId,
339
+ name: companyName
340
+ } : null, [
341
+ values.companyId,
342
+ companyName
343
+ ]);
265
344
  const customMissing = crmCustomDraftMissingRequired(fields.active, storedCustom, custom, mode);
266
345
  const problem = (_dealFormProblem = dealFormProblem(values, mode)) != null ? _dealFormProblem : customMissing.length ? `${customMissing.join(', ')} is required.` : null;
267
346
  const amountDerived = Boolean(deal && dealHasLineItems(deal));
@@ -310,34 +389,53 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
310
389
  try {
311
390
  const nowMs = Date.now();
312
391
  if (deal) {
313
- const verdict = await writeGuardedBySeed({
314
- subject: 'deal',
315
- unreadable,
316
- fromCache
317
- }, async ()=>{
318
- const { set, clear } = dealPatchFromForm(saved, nowMs, {
319
- amountDerived,
320
- stage: currentStage,
321
- current: deal
322
- });
323
- await updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, set, Object.fromEntries(clear.map((key)=>[
324
- key,
325
- deleteField()
326
- ])), crmCustomDraftWrites(storedCustom, custom), crmClientListFields('deals', deal, _extends({}, set, Object.fromEntries(clear.map((key)=>[
327
- key,
328
- null
329
- ]))), DEAL_CLIENT_LIST_FIELDS)));
392
+ var _ref;
393
+ var _seed_current;
394
+ const edit = dealEditFromForm(saved, (_ref = (_seed_current = seed.current) == null ? void 0 : _seed_current.values) != null ? _ref : dealFormFromDoc(deal), nowMs, {
395
+ amountDerived,
396
+ stage: currentStage,
397
+ current: deal
330
398
  });
331
- if (!verdict.ok) {
332
- enqueueSnackbar(verdict.message, {
333
- variant: 'warning',
334
- persist: false
399
+ // The custom keys that changed, merged into the stored map.
400
+ const customWrites = crmCustomDraftWrites(storedCustom, custom);
401
+ if (Object.keys(edit.set).length || edit.clear.length || Object.keys(customWrites).length) {
402
+ const verdict = await writeGuardedBySeed({
403
+ subject: 'deal',
404
+ unreadable,
405
+ fromCache: fromCache && dealEditNeedsConfirmedRead(edit),
406
+ listen
407
+ }, async ()=>{
408
+ let held = true;
409
+ const written = updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, edit.set, Object.fromEntries(edit.clear.map((key)=>[
410
+ key,
411
+ deleteField()
412
+ ])), customWrites, crmClientListFieldChanges('deals', deal, _extends({}, edit.set, Object.fromEntries(edit.clear.map((key)=>[
413
+ key,
414
+ null
415
+ ]))), DEAL_CLIENT_LIST_FIELDS), {
416
+ updatedAt: new Date(nowMs)
417
+ })).then(// Once the write has landed: sharing rules read the deal as stored.
418
+ ()=>followUpSharing('deals', [
419
+ deal.$id
420
+ ]), (error)=>{
421
+ if (held) throw error;
422
+ console.error(error);
423
+ enqueueSnackbar(SAVE_FAILED_LATE_MESSAGE, {
424
+ variant: 'error',
425
+ allowDuplicate: true
426
+ });
427
+ });
428
+ await withinSaveHold(written);
429
+ held = false;
335
430
  });
336
- return;
431
+ if (!verdict.ok) {
432
+ enqueueSnackbar(verdict.message, {
433
+ variant: 'warning',
434
+ persist: false
435
+ });
436
+ return;
437
+ }
337
438
  }
338
- followUpSharing('deals', [
339
- deal.$id
340
- ]);
341
439
  enqueueSnackbar('Deal saved', {
342
440
  variant: 'success',
343
441
  persist: false
@@ -401,6 +499,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
401
499
  values,
402
500
  unreadable,
403
501
  fromCache,
502
+ listen,
404
503
  firestore,
405
504
  createTokens,
406
505
  createHostId,
@@ -412,7 +511,8 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
412
511
  custom,
413
512
  typeList.picklist,
414
513
  leadSourceList.picklist,
415
- currentStage
514
+ currentStage,
515
+ amountDerived
416
516
  ]);
417
517
  return /*#__PURE__*/ _jsx(NavigationDrawerComponent, {
418
518
  open: open,
@@ -719,10 +819,10 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
719
819
  /*#__PURE__*/ _jsx(Autocomplete, {
720
820
  options: contactChoices,
721
821
  value: contactValue,
722
- inputValue: contactQuery,
723
- onInputChange: (_event, next, reason)=>{
724
- if (reason !== 'reset') setContactQuery(next);
725
- },
822
+ // The input is the picker's own, which is how a linked contact
823
+ // shows. The query is only what was typed, so the name it shows
824
+ // is not searched for.
825
+ onInputChange: (_event, next, reason)=>setContactQuery(reason === 'input' ? next : ''),
726
826
  onChange: (_event, picked)=>{
727
827
  var _ref;
728
828
  return update({
@@ -763,10 +863,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
763
863
  /*#__PURE__*/ _jsx(Autocomplete, {
764
864
  options: companyChoices,
765
865
  value: companyValue,
766
- inputValue: companyQuery,
767
- onInputChange: (_event, next, reason)=>{
768
- if (reason !== 'reset') setCompanyQuery(next);
769
- },
866
+ onInputChange: (_event, next, reason)=>setCompanyQuery(reason === 'input' ? next : ''),
770
867
  onChange: (_event, picked)=>{
771
868
  var _ref, _ref1;
772
869
  return update({