@aglyn/plugins-crm 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +14 -14
- package/src/lib/components/add-to-list-dialog.js +7 -3
- package/src/lib/components/add-to-list-dialog.js.map +1 -1
- package/src/lib/components/company-contact-roles-card.d.ts +3 -0
- package/src/lib/components/company-contact-roles-card.js +4 -2
- package/src/lib/components/company-contact-roles-card.js.map +1 -1
- package/src/lib/components/company-detail-page.js +5 -3
- package/src/lib/components/company-detail-page.js.map +1 -1
- package/src/lib/components/company-edit-drawer.d.ts +3 -0
- package/src/lib/components/company-edit-drawer.js +2 -1
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-properties-card.d.ts +3 -0
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-associations-card.d.ts +3 -0
- package/src/lib/components/contact-associations-card.js +3 -1
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.js +5 -3
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +3 -0
- package/src/lib/components/contact-properties-card.js +3 -1
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/deal-contact-roles-card.d.ts +3 -0
- package/src/lib/components/deal-contact-roles-card.js +4 -2
- package/src/lib/components/deal-contact-roles-card.js.map +1 -1
- package/src/lib/components/deal-detail-page.js +7 -4
- package/src/lib/components/deal-detail-page.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.d.ts +3 -0
- package/src/lib/components/deal-edit-drawer.js +4 -2
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.d.ts +3 -0
- package/src/lib/components/deal-products-card.js +4 -2
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/deals-section.js +1 -0
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.js +7 -3
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.d.ts +3 -1
- package/src/lib/components/lead-campaigns-card.js +3 -2
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-detail-page.js +3 -1
- package/src/lib/components/lead-detail-page.js.map +1 -1
- package/src/lib/components/lead-properties-card.d.ts +3 -1
- package/src/lib/components/lead-properties-card.js +3 -2
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +4 -2
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.d.ts +3 -0
- package/src/lib/components/pipeline-stages-dialog.js +43 -14
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.d.ts +3 -0
- package/src/lib/components/pipelines-dialog.js +5 -2
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/record-tasks-card.js +3 -2
- package/src/lib/components/record-tasks-card.js.map +1 -1
- package/src/lib/components/task-edit-drawer.d.ts +2 -0
- package/src/lib/components/task-edit-drawer.js +2 -1
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/components/tasks-section.js +3 -2
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/hooks/use-contact-field-definitions.d.ts +3 -0
- package/src/lib/hooks/use-contact-field-definitions.js +3 -2
- package/src/lib/hooks/use-contact-field-definitions.js.map +1 -1
- package/src/lib/hooks/use-crm-picklist.d.ts +3 -0
- package/src/lib/hooks/use-crm-picklist.js +5 -3
- package/src/lib/hooks/use-crm-picklist.js.map +1 -1
- package/src/lib/hooks/use-crm-tasks.d.ts +3 -0
- package/src/lib/hooks/use-crm-tasks.js +3 -1
- package/src/lib/hooks/use-crm-tasks.js.map +1 -1
- package/src/lib/hooks/use-lead-source-picklist.js +5 -3
- package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
- package/src/lib/hooks/use-lead-status-picklist.js +5 -3
- package/src/lib/hooks/use-lead-status-picklist.js.map +1 -1
- package/src/lib/hooks/use-pipeline.d.ts +3 -0
- package/src/lib/hooks/use-pipeline.js +3 -1
- package/src/lib/hooks/use-pipeline.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 {
|
|
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,QAAQ,4BAAwB;AAe3D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;;QAKnDC;IAJhB,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,GAAG,EAAEC,MAAM,EAAEC,SAAS,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, 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,E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G,WAAWvG,cAAcwG,eAAe;gBACxCC,eAAe,EAAExG,mBAAAA,WAAYD,cAAcC,QAAQ;gBACnD6F,YAAYlG,WAAW;gBACvBC,WAAWA;;;;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":"AA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AA,SAAU;gCAClBgB,OAAOf,MAAMe,KAAK;gCAClBX,KAAKA;gCACLiH,cAAc,GAAErH,uBAAAA,MAAM6F,YAAY,qBAAlB7F,qBAAoB8F,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';
|
|
@@ -24,6 +25,8 @@ export interface DealEditDrawerProps {
|
|
|
24
25
|
*/
|
|
25
26
|
unreadable?: boolean;
|
|
26
27
|
fromCache?: boolean;
|
|
28
|
+
/** The deal's listener, so a save waits on that read alone (AGL-4135). */
|
|
29
|
+
listen?: ListenHandle | null;
|
|
27
30
|
/** After a save, with the id of the deal written. */
|
|
28
31
|
onSaved?: (dealId: string, mode: 'create' | 'edit') => void;
|
|
29
32
|
}
|
|
@@ -122,7 +122,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
|
|
|
122
122
|
* picker of a lead offers at this level.
|
|
123
123
|
*/ export function DealEditDrawer(props) {
|
|
124
124
|
var _ref, _dealFormProblem, _ref1, _ref2;
|
|
125
|
-
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;
|
|
126
126
|
const mode = deal ? 'edit' : 'create';
|
|
127
127
|
const firestore = useFirestore();
|
|
128
128
|
const { enqueueSnackbar } = useSnackbar();
|
|
@@ -402,7 +402,8 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
|
|
|
402
402
|
const verdict = await writeGuardedBySeed({
|
|
403
403
|
subject: 'deal',
|
|
404
404
|
unreadable,
|
|
405
|
-
fromCache: fromCache && dealEditNeedsConfirmedRead(edit)
|
|
405
|
+
fromCache: fromCache && dealEditNeedsConfirmedRead(edit),
|
|
406
|
+
listen
|
|
406
407
|
}, async ()=>{
|
|
407
408
|
let held = true;
|
|
408
409
|
const written = updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, edit.set, Object.fromEntries(edit.clear.map((key)=>[
|
|
@@ -498,6 +499,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
|
|
|
498
499
|
values,
|
|
499
500
|
unreadable,
|
|
500
501
|
fromCache,
|
|
502
|
+
listen,
|
|
501
503
|
firestore,
|
|
502
504
|
createTokens,
|
|
503
505
|
createHostId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-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 CRM_COLLECTIONS,\n CRM_FORECAST_CATEGORIES,\n CRM_FORECAST_CATEGORY_LABELS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n type CrmForecastCategory,\n crmNewRecordListFields,\n DEAL_NEXT_STEP_MAX,\n dealHasLineItems,\n dealStageById,\n dealStageForecastCategory,\n findOrgMember,\n nameSearchKey,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, 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 useFirestoreCollection,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Autocomplete,\n Button,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n deleteField,\n doc,\n endAt,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport {\n type CrmOrgDoc,\n crmScopeListable,\n crmVisibleToClause,\n useCrmScope,\n} from '../hooks/use-crm-scope'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { contactPrimaryGroup } from '../model/contact-record'\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 { CrmPicklistSelect } from './picklist-select'\nimport { CrmSitePicker } from './crm-site-picker'\nimport {\n CRM_CLIENT_SEARCH_FIELDS,\n CRM_CLIENT_SORT_FIELDS,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n crmClientListFieldChanges,\n} from '../model/crm-list-query'\nimport {\n DEAL_CURRENCIES,\n type DealDoc,\n openStages,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport {\n type ContactChoice,\n contactChoicesFor,\n DEAL_NOTES_MAX,\n DEAL_TITLE_MAX,\n dealDocumentFromForm,\n dealEditFromForm,\n dealEditNeedsConfirmedRead,\n dealFormFromDoc,\n dealFormProblem,\n type DealFormValues,\n emptyDealForm,\n judgeDealFormPicklists,\n rebaseDealForm,\n} from '../model/deal-form-model'\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\n/**\n * How many recent contacts the picker matches against. The window is the\n * ask — it is read when the drawer opens, not when the section does — and\n * a person outside it is still linkable by pasting their address, which\n * the match tests as a prefix of the email.\n */\nconst CONTACT_WINDOW = 300\n\n/** Companies offered per keystroke; a longer list is a scroll, not a pick. */\nconst COMPANY_MATCHES = 8\n\n/** The list fields an edit restamps: the title's search words, the two picklist keys. */\nconst DEAL_CLIENT_LIST_FIELDS = [\n ...CRM_CLIENT_SEARCH_FIELDS,\n // The Deal, Amount and Expected close headers' sort keys (AGL-3680).\n ...CRM_CLIENT_SORT_FIELDS,\n 'typeKey',\n 'leadSourceKey',\n // The arrays a deal's contact roles are found by (AGL-3521).\n ...CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n] as const\n\n/** A company as the picker offers it. */\ninterface CompanyChoice {\n id: string\n name: string\n}\n\n/**\n * How long a save holds the drawer on the server's acknowledgement (AGL-4132).\n * A durable console tab writes through whichever tab holds the lease, and a\n * hidden or overloaded one can take a minute to answer (AGL-3806); 25 s was\n * measured here. Stopping the wait does not stop the write: it is in the\n * IndexedDB queue, the page behind the drawer already shows it, and the lease\n * holder sends it.\n */\nconst SAVE_HOLD_MS = 4_000\n\n/** What a save says when its write fails after the hold let the drawer close. */\nconst SAVE_FAILED_LATE_MESSAGE =\n 'Your last change to this deal could not be saved. Open it and try again.'\n\n/** Settles with `write`, or resolves when the hold runs out. */\nfunction withinSaveHold(write: Promise<void>): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const hold = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, SAVE_HOLD_MS)\n })\n return Promise.race([write, hold]).finally(() => clearTimeout(timer))\n}\n\nexport interface DealEditDrawerProps {\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 deal asks which site captures it and an\n * edit keeps the deal's own.\n */\n hostId: string | null\n org: CrmOrgDoc\n /** The deal being edited; absent for a new one. */\n deal?: DealDoc | null\n /** Links and values a new deal opens with — a contact's page passes itself. */\n defaults?: Partial<DealFormValues>\n pipelines: PipelineDoc[]\n /** Where a new deal lands when nobody picks a pipeline. */\n defaultPipeline: PipelineDoc | null\n /**\n * The listener's verdict on the row being edited. An unconfirmed row holds\n * back only an edit that is worked out from it (`dealEditNeedsConfirmedRead`).\n */\n unreadable?: boolean\n fromCache?: boolean\n /** After a save, with the id of the deal written. */\n onSaved?: (dealId: string, mode: 'create' | 'edit') => void\n}\n\n/**\n * The one form a deal is created and edited through (AGL-2598).\n *\n * ## What it writes, and what it does not\n *\n * Client-direct against the rules, like a contact's notes: the title, the\n * amount and its currency, the expected close, the owner, the linked\n * contact and company, and the notes. The stage and the status are shown on\n * a new deal — it has to start somewhere — and never on an existing one,\n * because a stage change is the moment an automation listens for and only\n * the server route can emit that event. A drawer that wrote `stageId`\n * directly would move a deal without anybody hearing it.\n *\n * Nor the amount of a deal that has line items (AGL-2620): it is their\n * sum, the products card on the deal's page owns it, and the field here\n * is read-only with a caption saying so. The pipeline picker on a new\n * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the\n * caller was looking at.\n *\n * An edit writes only what the reader changed (AGL-4132), so one field\n * changed in a drawer opened on an unconfirmed read saves at once and cannot\n * touch anything else on the deal. The form follows the stored deal in the\n * fields they have not touched, and keeps what they typed in those they have.\n *\n * ## The pickers\n *\n * The owner is picked from the org's roster, the company by a server-side\n * prefix on `nameLower` (indexed with the scope), and the contact from a\n * bounded window of the newest contacts matched in memory — see\n * `contactChoicesFor` for why the contact search cannot be a query. Both\n * pickers copy the chosen NAME onto the deal beside the id, so a board of\n * cards can caption itself without a read per card.\n *\n * ## Salesforce's Opportunity fields (AGL-3516)\n *\n * Type and Lead source are the org's picklists, judged on save as every\n * server door judges them (`judgeDealFormPicklists`) — a new deal with no\n * Type takes the list's default. The probability is this deal's own\n * override, blank for its stage's; the forecast category is one of the\n * fixed set, \"From the stage\" storing the stage's. A stage move later\n * stamps both afresh. The campaign is one of the campaigns the Campaigns\n * picker of a lead offers at this level.\n */\nexport function DealEditDrawer(props: DealEditDrawerProps) {\n const {\n open,\n onClose,\n hostId,\n org,\n deal,\n defaults,\n pipelines,\n defaultPipeline,\n unreadable = false,\n fromCache = false,\n onSaved,\n } = props\n const mode: 'create' | 'edit' = deal ? 'edit' : 'create'\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n const { orgId, consentGroup, visibleTo, createHostId, createTokens, createNeedsSite } =\n useCrmScope({ hostId, org })\n // A client-direct write owes the org's sharing rules a re-evaluation (AGL-3336).\n const followUpSharing = useCrmSharingFollowUp(hostId, orgId)\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 deal is STAMPED, which at the hub is a\n // 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 const roster = useOrgMemberDirectory(open ? orgId : null)\n\n const [values, setValues] = useState<DealFormValues>(() =>\n emptyDealForm(defaultPipeline, defaults),\n )\n const owner = findOrgMember(roster.members, values.ownerUid)\n const [busy, setBusy] = useState(false)\n /*\n * THE CUSTOM FIELDS (AGL-2661): the org's deal definitions, and the keys\n * the reader has touched over what the deal stores — saved as the\n * difference (`crm-custom-draft`) in the same write as the fixed fields.\n */\n const fields = useContactFieldDefinitions(open ? orgId : null, 'deal')\n // The org's lists for the two picklist fields, and its campaigns (AGL-3516).\n const typeList = useCrmPicklist('opportunityType', open ? orgId : null)\n const leadSourceList = useCrmPicklist('leadSource', open ? orgId : null)\n const campaigns = useCrmCampaigns({ hostId, orgId }, { enabled: open })\n const storedCustom = useMemo(() => deal?.custom ?? {}, [deal?.custom])\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n\n /*\n * What the form was built from: what a save compares against, and what\n * tells a field the reader changed from one they left alone. Held in a ref\n * because nothing renders from it.\n */\n const seed = useRef<{ dealId: string | null; values: DealFormValues } | null>(null)\n\n // Seeded on every open: an existing deal's stored values, or a blank form\n // aimed at the default pipeline with whatever the opener preselected. After\n // that a new snapshot only moves the fields the reader has not touched.\n useEffect(() => {\n if (!open) {\n seed.current = null\n return\n }\n const dealId = deal?.$id ?? null\n const stored = deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults)\n const previous = seed.current\n seed.current = { dealId, values: stored }\n if (previous?.dealId === dealId) {\n setValues((current) => rebaseDealForm(current, previous.values, stored))\n } else {\n setValues(stored)\n setCustom({})\n }\n }, [open, deal, defaultPipeline, defaults])\n\n const update = useCallback(\n (patch: Partial<DealFormValues>) =>\n setValues((current) => ({ ...current, ...patch })),\n [],\n )\n\n const pipeline = useMemo(\n () =>\n pipelines.find((entry) => entry.$id === values.pipelineId) ??\n defaultPipeline,\n [pipelines, values.pipelineId, defaultPipeline],\n )\n const stages = useMemo(() => openStages(pipeline), [pipeline])\n /*\n * The stage the deal is in — the one picked on a new deal, the stored one\n * on an edit, looked up in the deal's OWN pipeline and never the default's\n * — whose probability and forecast category the blank fields stand for.\n */\n const currentStage = useMemo(\n () =>\n dealStageById(\n pipelines.find((entry) => entry.$id === values.pipelineId),\n values.stageId,\n ),\n [pipelines, values.pipelineId, values.stageId],\n )\n const campaignOptions = useMemo(() => {\n const options = campaigns.options.map((option) => ({ value: option.value, label: option.label }))\n // A campaign the deal names but the picker no longer offers stays itself.\n return values.campaignId && !options.some((option) => option.value === values.campaignId)\n ? [...options, { value: values.campaignId, label: values.campaignId }]\n : options\n }, [campaigns.options, values.campaignId])\n\n /*\n * THE CONTACT WINDOW: the newest contacts this viewer may see, read only\n * while the drawer is open. Scoped and ordered like the contacts list —\n * the same `(visibleTo, updatedAt DESC)` index — and bounded, because the\n * picker's job is to find one person, not to list the audience.\n */\n const { data: contactRows } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n open && orgId && crmScopeListable(visibleTo)\n ? query(\n collection(firestore, 'orgs', orgId, 'contacts'),\n ...crmVisibleToClause(visibleTo),\n orderBy('updatedAt', 'desc'),\n limit(CONTACT_WINDOW),\n )\n : null,\n [firestore, open, orgId, visibleTo],\n { idField: '$id' },\n )\n const [contactQuery, setContactQuery] = useState('')\n // Named through the viewing group under a site; at the organization level\n // through each person's own primary holder.\n const contactChoices = useMemo(\n () =>\n contactChoicesFor(\n contactQuery,\n contactRows ?? [],\n consentGroup?.groupId ??\n ((row) => contactPrimaryGroup(row, org as Record<string, unknown>).groupId),\n ),\n [contactQuery, contactRows, consentGroup, org],\n )\n /*\n * THE LINKS' NAMES. The deal carries a copy beside each id, but a server\n * door that moves the Primary drops it (`dealContactRolesUpdate`), so a link\n * can arrive with no name to show. It is never shown blank: a picker that\n * looks empty while it holds a link is how the link gets erased unseen.\n */\n const linkedName = useCrmRecordNames({\n orgId: open ? orgId : null,\n groupId: consentGroup?.groupId ?? null,\n org: (org ?? null) as Record<string, unknown> | null,\n records: [\n ...(values.contactId && !values.contactName\n ? [{ kind: 'contact' as const, id: values.contactId }]\n : []),\n ...(values.companyId && !values.companyName\n ? [{ kind: 'company' as const, id: values.companyId }]\n : []),\n ],\n })\n const contactName =\n values.contactName || linkedName('contact', values.contactId) || 'Linked contact'\n const companyName =\n values.companyName || linkedName('company', values.companyId) || 'Linked company'\n // One object between renders: a new object is a new value to the picker,\n // and a new value puts its label over whatever the reader is typing.\n const contactValue = useMemo<ContactChoice | null>(\n () => (values.contactId ? { id: values.contactId, name: contactName, email: '' } : null),\n [values.contactId, contactName],\n )\n\n /*\n * THE COMPANY SEARCH: a prefix on `nameLower` with the scope, which the\n * companies collection indexes. Debounced so a name typed at speed is one\n * query rather than one per letter.\n */\n const [companyQuery, setCompanyQuery] = useState('')\n const [companyChoices, setCompanyChoices] = useState<CompanyChoice[]>([])\n useEffect(() => {\n if (!open || !orgId || !crmScopeListable(visibleTo)) return\n const key = nameSearchKey(companyQuery)\n let active = true\n const timer = setTimeout(() => {\n void getDocs(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.companies),\n ...crmVisibleToClause(visibleTo),\n orderBy('nameLower'),\n ...(key ? [startAt(key), endAt(`${key}\\uf8ff`)] : []),\n limit(COMPANY_MATCHES),\n ),\n )\n .then((snapshot) => {\n if (!active) return\n setCompanyChoices(\n snapshot.docs.map((entry) => ({\n id: entry.id,\n name: String(entry.get('name') ?? ''),\n })),\n )\n })\n .catch(() => {\n if (active) setCompanyChoices([])\n })\n }, 200)\n return () => {\n active = false\n clearTimeout(timer)\n }\n }, [firestore, open, orgId, visibleTo, companyQuery])\n const companyValue = useMemo<CompanyChoice | null>(\n () => (values.companyId ? { id: values.companyId, name: companyName } : null),\n [values.companyId, companyName],\n )\n\n const customMissing = crmCustomDraftMissingRequired(fields.active, storedCustom, custom, mode)\n const problem =\n dealFormProblem(values, mode) ??\n (customMissing.length ? `${customMissing.join(', ')} is required.` : null)\n const amountDerived = Boolean(deal && dealHasLineItems(deal))\n\n /*\n * THE RECORDS BAND (AGL-2611), read only while a CREATE is open: a deal\n * is a record of the band the contacts list is banded by, and on an org\n * at a full hard band this drawer refuses the way `upsertHostContact`\n * refuses a capture — same number, same sentence. Memoized, because the\n * tuple is an effect dependency and a fresh one per render would re-read\n * the three aggregates on every keystroke.\n */\n const recordsScope = useMemo(\n () => (open && mode === 'create' && orgId ? (['orgs', orgId] as const) : null),\n [open, mode, orgId],\n )\n const records = useCrmRecordsQuota(recordsScope, org)\n const bandFull = mode === 'create' && records.ready && !records.quota.allowed\n\n const handleSave = useCallback(async () => {\n if (problem || !orgId || !user?.uid) return\n if (bandFull) {\n enqueueSnackbar(CRM_RECORDS_BAND_FULL_MESSAGE, { variant: 'warning', persist: false })\n return\n }\n const judged = judgeDealFormPicklists(\n values,\n { type: typeList.picklist, leadSource: leadSourceList.picklist },\n { current: deal ?? null, created: !deal },\n )\n if (judged.ok === false) {\n enqueueSnackbar(judged.error, { variant: 'warning', persist: false })\n return\n }\n const saved = judged.values\n setBusy(true)\n try {\n const nowMs = Date.now()\n if (deal) {\n const edit = dealEditFromForm(saved, seed.current?.values ?? dealFormFromDoc(deal), nowMs, {\n amountDerived,\n stage: currentStage,\n current: deal,\n })\n // The custom keys that changed, merged into the stored map.\n const customWrites = crmCustomDraftWrites(storedCustom, custom)\n if (\n Object.keys(edit.set).length ||\n edit.clear.length ||\n Object.keys(customWrites).length\n ) {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'deal',\n unreadable,\n fromCache: fromCache && dealEditNeedsConfirmedRead(edit),\n },\n async () => {\n let held = true\n const written = updateDoc(\n doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id),\n {\n ...edit.set,\n ...Object.fromEntries(edit.clear.map((key) => [key, deleteField()])),\n ...customWrites,\n // The title is what the Deals table searches (AGL-3321), and\n // the Type and Lead source what it filters by (AGL-3516),\n // from the listener's row with the edit over it.\n ...crmClientListFieldChanges(\n 'deals',\n deal as unknown as Record<string, unknown>,\n { ...edit.set, ...Object.fromEntries(edit.clear.map((key) => [key, null])) },\n DEAL_CLIENT_LIST_FIELDS,\n ),\n updatedAt: new Date(nowMs),\n },\n ).then(\n // Once the write has landed: sharing rules read the deal as stored.\n () => followUpSharing('deals', [deal.$id]),\n (error) => {\n if (held) throw error\n console.error(error)\n enqueueSnackbar(SAVE_FAILED_LATE_MESSAGE, {\n variant: 'error',\n allowDuplicate: true,\n })\n },\n )\n await withinSaveHold(written)\n held = false\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return\n }\n }\n enqueueSnackbar('Deal saved', { variant: 'success', persist: false })\n onSaved?.(deal.$id, 'edit')\n } else {\n // Held by the button until it knows who may see the deal — the whole\n // org, or (in an org that keeps its sites apart) a picked site's\n // group; checked again here because a callback can outlive the\n // render that held it.\n if (!createTokens.length) return\n const customDocument = crmCustomDraftDocument(custom)\n const record: Record<string, unknown> = {\n ...dealDocumentFromForm(saved, {\n visibleTo: [...createTokens],\n hostId: createHostId,\n uid: user.uid,\n nowMs,\n stage: currentStage,\n }),\n ...(customDocument ? { custom: customDocument } : {}),\n }\n const created = await addDoc(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n // What the Deals table searches and filters by (AGL-3321), and\n // nothing scheduled against a deal that did not exist.\n { ...record, ...crmNewRecordListFields('deals', record) },\n )\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\n // feed. Creation only — an edit is a save the card reports.\n followUpSharing('deals', [created.id])\n logActivity('Added deal', { type: 'deal', id: created.id, name: values.title })\n enqueueSnackbar('Deal created', { variant: 'success', persist: false })\n onSaved?.(created.id, 'create')\n }\n onClose()\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [\n problem,\n bandFull,\n orgId,\n followUpSharing,\n user,\n deal,\n values,\n unreadable,\n fromCache,\n firestore,\n createTokens,\n createHostId,\n logActivity,\n enqueueSnackbar,\n onSaved,\n onClose,\n storedCustom,\n custom,\n typeList.picklist,\n leadSourceList.picklist,\n currentStage,\n amountDerived,\n ])\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={busy ? undefined : onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton color=\"inherit\" edge=\"start\" onClick={onClose} sx={{ mr: 2 }}>\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>close drawer</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {deal ? 'Edit deal' : 'New deal'}\n </Typography>\n </>\n }\n appBarRight={\n <Button variant=\"outlined\" color=\"inherit\" onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2} sx={{ width: { xs: '100%', sm: 420 } }}>\n {/*\n First, because the scope of everything below follows from it: at\n the organization level a new deal names the site it came from —\n required where the org keeps its sites apart, optional where every\n site sees it. Nothing under a site, and nothing on an edit — a deal\n keeps the site it was made on (AGL-2630).\n */}\n {mode === 'create' ? (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n optional={!createNeedsSite}\n helperText={\n createNeedsSite\n ? 'The site this deal belongs to — it decides which of your sites may see it.'\n : undefined\n }\n />\n ) : null}\n <TextField\n label=\"Title\"\n value={values.title}\n onChange={(event) => update({ title: event.target.value })}\n autoFocus\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_TITLE_MAX } }}\n />\n {mode === 'create' ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n select\n label=\"Pipeline\"\n value={pipelines.some((entry) => entry.$id === values.pipelineId) ? values.pipelineId : ''}\n onChange={(event) => {\n const next = pipelines.find(\n (entry) => entry.$id === event.target.value,\n )\n update({\n pipelineId: event.target.value,\n stageId: openStages(next)[0]?.id ?? '',\n })\n }}\n sx={{ flex: 1 }}\n >\n {pipelines.map((entry) => (\n <MenuItem key={entry.$id} value={entry.$id}>\n {entry.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n select\n label=\"Stage\"\n value={stages.some((stage) => stage.id === values.stageId) ? values.stageId : ''}\n onChange={(event) => update({ stageId: event.target.value })}\n sx={{ flex: 1 }}\n >\n {stages.map((stage) => (\n <MenuItem key={stage.id} value={stage.id}>\n {stage.name}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Amount\"\n value={values.amount}\n onChange={(event) => update({ amount: event.target.value })}\n placeholder=\"0.00\"\n sx={{ flex: 1 }}\n helperText={\n amountDerived\n ? \"The sum of the deal's line items — edit them on the Products card.\"\n : undefined\n }\n slotProps={{\n htmlInput: { inputMode: 'decimal', readOnly: amountDerived },\n }}\n />\n <TextField\n select\n label=\"Currency\"\n value={values.currency}\n onChange={(event) => update({ currency: event.target.value })}\n disabled={amountDerived}\n sx={{ width: 120 }}\n >\n {DEAL_CURRENCIES.map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n <TextField\n type=\"date\"\n label=\"Expected close\"\n value={values.expectedClose}\n onChange={(event) => update({ expectedClose: event.target.value })}\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <CrmPicklistSelect\n picklistId=\"opportunityType\"\n picklist={typeList.picklist}\n value={values.type}\n stored={deal?.type ?? ''}\n onChange={(type) => update({ type })}\n disabled={busy}\n />\n <CrmPicklistSelect\n picklistId=\"leadSource\"\n picklist={leadSourceList.picklist}\n value={values.leadSource}\n stored={deal?.leadSource ?? ''}\n onChange={(leadSource) => update({ leadSource })}\n disabled={busy}\n />\n </Stack>\n <TextField\n label=\"Next step\"\n value={values.nextStep}\n onChange={(event) => update({ nextStep: event.target.value })}\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_NEXT_STEP_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Probability\"\n value={values.probability}\n onChange={(event) => update({ probability: event.target.value })}\n placeholder={currentStage ? String(currentStage.probability) : ''}\n helperText={\n currentStage\n ? `From stage: ${currentStage.probability}%`\n : 'Blank uses the stage’s'\n }\n sx={{ flex: 1 }}\n slotProps={{\n htmlInput: { inputMode: 'numeric', 'aria-label': 'Probability' },\n input: { endAdornment: '%' },\n inputLabel: { shrink: true },\n }}\n />\n <TextField\n select\n label=\"Forecast category\"\n value={values.forecastCategory}\n onChange={(event) =>\n update({ forecastCategory: event.target.value as '' | CrmForecastCategory })\n }\n helperText=\"A stage move sets it from the new stage.\"\n sx={{ flex: 1 }}\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">\n {currentStage\n ? `From the stage (${CRM_FORECAST_CATEGORY_LABELS[dealStageForecastCategory(currentStage)]})`\n : 'From the stage'}\n </MenuItem>\n {CRM_FORECAST_CATEGORIES.map((category) => (\n <MenuItem key={category} value={category}>\n {CRM_FORECAST_CATEGORY_LABELS[category]}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n <TextField\n select\n label=\"Owner\"\n // The stored owner resolved to a member — by uid, or by an\n // address the roster has — so the picker highlights the person\n // and a save writes their uid.\n value={owner ? owner.uid : values.ownerUid ? '__keep' : ''}\n onChange={(event) =>\n update({\n ownerUid: event.target.value === '__keep' ? values.ownerUid : event.target.value,\n })\n }\n fullWidth\n helperText={\n !roster.loading && !roster.members.length\n ? 'The roster could not be read; the owner stays as stored.'\n : undefined\n }\n >\n <MenuItem value=\"\">{'Nobody yet'}</MenuItem>\n {values.ownerUid && !owner ? (\n // The stored owner is not on the roster the route returned —\n // a member who left, or a roster that failed to load. Shown by\n // uid so the field is never blank while the deal has an owner.\n <MenuItem value=\"__keep\">{values.ownerUid}</MenuItem>\n ) : null}\n {roster.members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n <Autocomplete<ContactChoice, false, false, false>\n options={contactChoices}\n value={contactValue}\n // The input is the picker's own, which is how a linked contact\n // shows. The query is only what was typed, so the name it shows\n // is not searched for.\n onInputChange={(_event, next, reason) =>\n setContactQuery(reason === 'input' ? next : '')\n }\n onChange={(_event, picked) =>\n update({\n contactId: picked?.id ?? '',\n contactName: picked ? picked.name || picked.email : '',\n })\n }\n getOptionLabel={(choice) => choice.name || choice.email}\n isOptionEqualToValue={(option, value) => option.id === value.id}\n // Matching is `contactChoicesFor`'s — the list's grammar over the\n // window — and never MUI's own substring filter over labels.\n filterOptions={(options) => options}\n renderOption={(optionProps, choice) => (\n <li {...optionProps} key={choice.id}>\n <Stack sx={{ lineHeight: 1.25 }}>\n <Typography variant=\"body2\">{choice.name || choice.email}</Typography>\n {choice.name ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {choice.email}\n </Typography>\n ) : null}\n </Stack>\n </li>\n )}\n noOptionsText=\"No recent contact matches\"\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Contact\"\n placeholder=\"Name or email\"\n helperText=\"Searches your most recent contacts by name or email.\"\n />\n )}\n />\n <Autocomplete<CompanyChoice, false, false, false>\n options={companyChoices}\n value={companyValue}\n onInputChange={(_event, next, reason) =>\n setCompanyQuery(reason === 'input' ? next : '')\n }\n onChange={(_event, picked) =>\n update({\n companyId: picked?.id ?? '',\n companyName: picked?.name ?? '',\n })\n }\n getOptionLabel={(choice) => choice.name}\n isOptionEqualToValue={(option, value) => option.id === value.id}\n filterOptions={(options) => options}\n noOptionsText=\"No company matches\"\n renderInput={(params) => (\n <TextField {...params} label=\"Company\" placeholder=\"Company name\" />\n )}\n />\n <TextField\n select\n label=\"Campaign\"\n value={values.campaignId}\n onChange={(event) => update({ campaignId: event.target.value })}\n fullWidth\n helperText={\n campaigns.ready && !campaignOptions.length\n ? 'There are no campaigns yet. Create one from Marketing.'\n : 'The campaign this deal is attributed to.'\n }\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {campaignOptions.map((option) => (\n <MenuItem key={option.value} value={option.value}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Notes\"\n value={values.notes}\n onChange={(event) => update({ notes: event.target.value })}\n multiline\n minRows={3}\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_NOTES_MAX } }}\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 {bandFull ? (\n <Alert severity=\"warning\">{CRM_RECORDS_BAND_FULL_MESSAGE}</Alert>\n ) : null}\n {problem && values.title ? <Alert severity=\"warning\">{problem}</Alert> : null}\n <Button\n variant=\"contained\"\n disabled={\n busy ||\n Boolean(problem) ||\n !orgId ||\n bandFull ||\n // A new deal waits for its scope: a site, where the org keeps\n // its sites apart; nothing, where every site sees it.\n (mode === 'create' && !createTokens.length)\n }\n onClick={() => void handleSave()}\n >\n {deal ? 'Save deal' : 'Create deal'}\n </Button>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nDealEditDrawer.displayName = 'DealEditDrawer'\n\nexport default DealEditDrawer\n"],"names":["CRM_COLLECTIONS","CRM_FORECAST_CATEGORIES","CRM_FORECAST_CATEGORY_LABELS","CRM_RECORDS_BAND_FULL_MESSAGE","crmNewRecordListFields","DEAL_NEXT_STEP_MAX","dealHasLineItems","dealStageById","dealStageForecastCategory","findOrgMember","nameSearchKey","crmMemberPickerLabel","ICON_VARIANT_CLOSE","Container","MdiIcon","SrOnly","NavigationDrawerComponent","useSnackbar","useFirestore","useFirestoreCollection","useUser","writeGuardedBySeed","Alert","Autocomplete","Button","IconButton","MenuItem","Stack","TextField","Typography","addDoc","collection","deleteField","doc","endAt","getDocs","limit","orderBy","query","startAt","updateDoc","useCallback","useEffect","useMemo","useRef","useState","useContactFieldDefinitions","useCrmActivityLogger","useCrmCampaigns","useCrmPicklist","useCrmRecordNames","useCrmRecordsQuota","crmScopeListable","crmVisibleToClause","useCrmScope","useOrgMemberDirectory","contactPrimaryGroup","crmCustomDraftDocument","crmCustomDraftMissingRequired","crmCustomDraftValue","crmCustomDraftWrites","CrmCustomFieldControl","CrmPicklistSelect","CrmSitePicker","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFieldChanges","DEAL_CURRENCIES","openStages","contactChoicesFor","DEAL_NOTES_MAX","DEAL_TITLE_MAX","dealDocumentFromForm","dealEditFromForm","dealEditNeedsConfirmedRead","dealFormFromDoc","dealFormProblem","emptyDealForm","judgeDealFormPicklists","rebaseDealForm","useCrmSharingFollowUp","CONTACT_WINDOW","COMPANY_MATCHES","DEAL_CLIENT_LIST_FIELDS","SAVE_HOLD_MS","SAVE_FAILED_LATE_MESSAGE","withinSaveHold","write","timer","hold","Promise","resolve","setTimeout","race","finally","clearTimeout","DealEditDrawer","props","open","onClose","hostId","org","deal","defaults","pipelines","defaultPipeline","unreadable","fromCache","onSaved","mode","firestore","enqueueSnackbar","data","user","orgId","consentGroup","visibleTo","createHostId","createTokens","createNeedsSite","followUpSharing","logActivity","roster","values","setValues","owner","members","ownerUid","busy","setBusy","fields","typeList","leadSourceList","campaigns","enabled","storedCustom","custom","setCustom","seed","current","dealId","$id","stored","previous","update","patch","pipeline","find","entry","pipelineId","stages","currentStage","stageId","campaignOptions","options","map","option","value","label","campaignId","some","contactRows","idField","contactQuery","setContactQuery","contactChoices","groupId","row","linkedName","records","contactId","contactName","kind","id","companyId","companyName","contactValue","name","email","companyQuery","setCompanyQuery","companyChoices","setCompanyChoices","key","active","companies","then","snapshot","docs","String","get","catch","companyValue","customMissing","problem","length","join","amountDerived","Boolean","recordsScope","bandFull","ready","quota","allowed","handleSave","uid","variant","persist","judged","type","picklist","leadSource","created","ok","error","saved","nowMs","Date","now","edit","stage","customWrites","Object","keys","set","clear","verdict","subject","held","written","deals","fromEntries","updatedAt","console","allowDuplicate","message","customDocument","record","title","anchor","undefined","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","appBarRight","disabled","gutterY","spacing","width","xs","sm","optional","helperText","onChange","event","target","autoFocus","fullWidth","slotProps","htmlInput","maxLength","direction","select","next","flex","alignItems","amount","placeholder","inputMode","readOnly","currency","code","toUpperCase","expectedClose","inputLabel","shrink","picklistId","nextStep","probability","input","endAdornment","forecastCategory","displayEmpty","category","loading","member","onInputChange","_event","reason","picked","getOptionLabel","choice","isOptionEqualToValue","filterOptions","renderOption","optionProps","li","lineHeight","noOptionsText","renderInput","params","notes","multiline","minRows","definition","severity","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SACEA,eAAe,EACfC,uBAAuB,EACvBC,4BAA4B,EAC5BC,6BAA6B,EAE7BC,sBAAsB,EACtBC,kBAAkB,EAClBC,gBAAgB,EAChBC,aAAa,EACbC,yBAAyB,EACzBC,aAAa,EACbC,aAAa,EACbC,oBAAoB,QACf,eAAc;AACrB,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,QAAQ,uBAAsB;AACjE,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AACvC,SACEC,KAAK,EACLC,YAAY,EACZC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,MAAM,EACNC,UAAU,EACVC,WAAW,EACXC,GAAG,EACHC,KAAK,E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AF,OAAOC,KAAK;;;kCAK/B,KAAClI;wBACCmI,OAAM;wBACND,OAAOlC,OAAOwL,KAAK;wBACnBhD,UAAU,CAACC,QAAUpH,OAAO;gCAAEmK,OAAO/C,MAAMC,MAAM,CAACxG,KAAK;4BAAC;wBACxDuJ,SAAS;wBACTC,SAAS;wBACT9C,SAAS;wBACTC,WAAW;4BAAEC,WAAW;gCAAEC,WAAWpM;4BAAe;wBAAE;;oBAEvD4D,OAAOsD,MAAM,CAACW,MAAM,iBACnB;;0CACE,KAACvK;gCAAWkL,SAAQ;0CAAa;;4BAChC5E,OAAOsD,MAAM,CAAC7B,GAAG,CAAC,CAAC2J,2BAClB,KAAC1P;oCAEC0P,YAAYA;oCACZzJ,OAAOnG,oBAAoB6E,cAAcC,QAAQ8K,WAAW/H,GAAG;oCAC/D4E,UAAU,CAACtG,QACTpB,UAAU,CAACE,UAAa,aAAKA;gDAAS,CAAC2K,WAAW/H,GAAG,CAAC,EAAE1B;;oCAE1D8F,UAAU3H;mCANLsL,WAAWzK,GAAG;;yBAUvB;oBACH2D,yBACC,KAACnL;wBAAMkS,UAAS;kCAAWrT;yBACzB;oBACHgM,WAAWvE,OAAOmH,KAAK,iBAAG,KAACzN;wBAAMkS,UAAS;kCAAWrH;yBAAmB;kCACzE,KAAC3K;wBACCuL,SAAQ;wBACR6C,UACE3H,QACAsE,QAAQJ,YACR,CAAChF,SACDsF,YACA,8DAA8D;wBAC9D,sDAAsD;wBACrD3F,SAAS,YAAY,CAACS,aAAa6E,MAAM;wBAE5CkD,SAAS,IAAM,KAAKzC;kCAEnBtG,OAAO,cAAc;;;;;;AAMlC;AACAN,eAAewN,WAAW,GAAG;AAE7B,eAAexN,eAAc"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-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 CRM_COLLECTIONS,\n CRM_FORECAST_CATEGORIES,\n CRM_FORECAST_CATEGORY_LABELS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n type CrmForecastCategory,\n crmNewRecordListFields,\n DEAL_NEXT_STEP_MAX,\n dealHasLineItems,\n dealStageById,\n dealStageForecastCategory,\n findOrgMember,\n nameSearchKey,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { Container, 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 useFirestoreCollection,\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Autocomplete,\n Button,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n deleteField,\n doc,\n endAt,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport {\n type CrmOrgDoc,\n crmScopeListable,\n crmVisibleToClause,\n useCrmScope,\n} from '../hooks/use-crm-scope'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { contactPrimaryGroup } from '../model/contact-record'\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 { CrmPicklistSelect } from './picklist-select'\nimport { CrmSitePicker } from './crm-site-picker'\nimport {\n CRM_CLIENT_SEARCH_FIELDS,\n CRM_CLIENT_SORT_FIELDS,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n crmClientListFieldChanges,\n} from '../model/crm-list-query'\nimport {\n DEAL_CURRENCIES,\n type DealDoc,\n openStages,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport {\n type ContactChoice,\n contactChoicesFor,\n DEAL_NOTES_MAX,\n DEAL_TITLE_MAX,\n dealDocumentFromForm,\n dealEditFromForm,\n dealEditNeedsConfirmedRead,\n dealFormFromDoc,\n dealFormProblem,\n type DealFormValues,\n emptyDealForm,\n judgeDealFormPicklists,\n rebaseDealForm,\n} from '../model/deal-form-model'\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\n/**\n * How many recent contacts the picker matches against. The window is the\n * ask — it is read when the drawer opens, not when the section does — and\n * a person outside it is still linkable by pasting their address, which\n * the match tests as a prefix of the email.\n */\nconst CONTACT_WINDOW = 300\n\n/** Companies offered per keystroke; a longer list is a scroll, not a pick. */\nconst COMPANY_MATCHES = 8\n\n/** The list fields an edit restamps: the title's search words, the two picklist keys. */\nconst DEAL_CLIENT_LIST_FIELDS = [\n ...CRM_CLIENT_SEARCH_FIELDS,\n // The Deal, Amount and Expected close headers' sort keys (AGL-3680).\n ...CRM_CLIENT_SORT_FIELDS,\n 'typeKey',\n 'leadSourceKey',\n // The arrays a deal's contact roles are found by (AGL-3521).\n ...CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n] as const\n\n/** A company as the picker offers it. */\ninterface CompanyChoice {\n id: string\n name: string\n}\n\n/**\n * How long a save holds the drawer on the server's acknowledgement (AGL-4132).\n * A durable console tab writes through whichever tab holds the lease, and a\n * hidden or overloaded one can take a minute to answer (AGL-3806); 25 s was\n * measured here. Stopping the wait does not stop the write: it is in the\n * IndexedDB queue, the page behind the drawer already shows it, and the lease\n * holder sends it.\n */\nconst SAVE_HOLD_MS = 4_000\n\n/** What a save says when its write fails after the hold let the drawer close. */\nconst SAVE_FAILED_LATE_MESSAGE =\n 'Your last change to this deal could not be saved. Open it and try again.'\n\n/** Settles with `write`, or resolves when the hold runs out. */\nfunction withinSaveHold(write: Promise<void>): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const hold = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, SAVE_HOLD_MS)\n })\n return Promise.race([write, hold]).finally(() => clearTimeout(timer))\n}\n\nexport interface DealEditDrawerProps {\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 deal asks which site captures it and an\n * edit keeps the deal's own.\n */\n hostId: string | null\n org: CrmOrgDoc\n /** The deal being edited; absent for a new one. */\n deal?: DealDoc | null\n /** Links and values a new deal opens with — a contact's page passes itself. */\n defaults?: Partial<DealFormValues>\n pipelines: PipelineDoc[]\n /** Where a new deal lands when nobody picks a pipeline. */\n defaultPipeline: PipelineDoc | null\n /**\n * The listener's verdict on the row being edited. An unconfirmed row holds\n * back only an edit that is worked out from it (`dealEditNeedsConfirmedRead`).\n */\n unreadable?: boolean\n fromCache?: boolean\n /** The deal's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n /** After a save, with the id of the deal written. */\n onSaved?: (dealId: string, mode: 'create' | 'edit') => void\n}\n\n/**\n * The one form a deal is created and edited through (AGL-2598).\n *\n * ## What it writes, and what it does not\n *\n * Client-direct against the rules, like a contact's notes: the title, the\n * amount and its currency, the expected close, the owner, the linked\n * contact and company, and the notes. The stage and the status are shown on\n * a new deal — it has to start somewhere — and never on an existing one,\n * because a stage change is the moment an automation listens for and only\n * the server route can emit that event. A drawer that wrote `stageId`\n * directly would move a deal without anybody hearing it.\n *\n * Nor the amount of a deal that has line items (AGL-2620): it is their\n * sum, the products card on the deal's page owns it, and the field here\n * is read-only with a caption saying so. The pipeline picker on a new\n * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the\n * caller was looking at.\n *\n * An edit writes only what the reader changed (AGL-4132), so one field\n * changed in a drawer opened on an unconfirmed read saves at once and cannot\n * touch anything else on the deal. The form follows the stored deal in the\n * fields they have not touched, and keeps what they typed in those they have.\n *\n * ## The pickers\n *\n * The owner is picked from the org's roster, the company by a server-side\n * prefix on `nameLower` (indexed with the scope), and the contact from a\n * bounded window of the newest contacts matched in memory — see\n * `contactChoicesFor` for why the contact search cannot be a query. Both\n * pickers copy the chosen NAME onto the deal beside the id, so a board of\n * cards can caption itself without a read per card.\n *\n * ## Salesforce's Opportunity fields (AGL-3516)\n *\n * Type and Lead source are the org's picklists, judged on save as every\n * server door judges them (`judgeDealFormPicklists`) — a new deal with no\n * Type takes the list's default. The probability is this deal's own\n * override, blank for its stage's; the forecast category is one of the\n * fixed set, \"From the stage\" storing the stage's. A stage move later\n * stamps both afresh. The campaign is one of the campaigns the Campaigns\n * picker of a lead offers at this level.\n */\nexport function DealEditDrawer(props: DealEditDrawerProps) {\n const {\n open,\n onClose,\n hostId,\n org,\n deal,\n defaults,\n pipelines,\n defaultPipeline,\n unreadable = false,\n fromCache = false,\n listen,\n onSaved,\n } = props\n const mode: 'create' | 'edit' = deal ? 'edit' : 'create'\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n const { orgId, consentGroup, visibleTo, createHostId, createTokens, createNeedsSite } =\n useCrmScope({ hostId, org })\n // A client-direct write owes the org's sharing rules a re-evaluation (AGL-3336).\n const followUpSharing = useCrmSharingFollowUp(hostId, orgId)\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 deal is STAMPED, which at the hub is a\n // 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 const roster = useOrgMemberDirectory(open ? orgId : null)\n\n const [values, setValues] = useState<DealFormValues>(() =>\n emptyDealForm(defaultPipeline, defaults),\n )\n const owner = findOrgMember(roster.members, values.ownerUid)\n const [busy, setBusy] = useState(false)\n /*\n * THE CUSTOM FIELDS (AGL-2661): the org's deal definitions, and the keys\n * the reader has touched over what the deal stores — saved as the\n * difference (`crm-custom-draft`) in the same write as the fixed fields.\n */\n const fields = useContactFieldDefinitions(open ? orgId : null, 'deal')\n // The org's lists for the two picklist fields, and its campaigns (AGL-3516).\n const typeList = useCrmPicklist('opportunityType', open ? orgId : null)\n const leadSourceList = useCrmPicklist('leadSource', open ? orgId : null)\n const campaigns = useCrmCampaigns({ hostId, orgId }, { enabled: open })\n const storedCustom = useMemo(() => deal?.custom ?? {}, [deal?.custom])\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n\n /*\n * What the form was built from: what a save compares against, and what\n * tells a field the reader changed from one they left alone. Held in a ref\n * because nothing renders from it.\n */\n const seed = useRef<{ dealId: string | null; values: DealFormValues } | null>(null)\n\n // Seeded on every open: an existing deal's stored values, or a blank form\n // aimed at the default pipeline with whatever the opener preselected. After\n // that a new snapshot only moves the fields the reader has not touched.\n useEffect(() => {\n if (!open) {\n seed.current = null\n return\n }\n const dealId = deal?.$id ?? null\n const stored = deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults)\n const previous = seed.current\n seed.current = { dealId, values: stored }\n if (previous?.dealId === dealId) {\n setValues((current) => rebaseDealForm(current, previous.values, stored))\n } else {\n setValues(stored)\n setCustom({})\n }\n }, [open, deal, defaultPipeline, defaults])\n\n const update = useCallback(\n (patch: Partial<DealFormValues>) =>\n setValues((current) => ({ ...current, ...patch })),\n [],\n )\n\n const pipeline = useMemo(\n () =>\n pipelines.find((entry) => entry.$id === values.pipelineId) ??\n defaultPipeline,\n [pipelines, values.pipelineId, defaultPipeline],\n )\n const stages = useMemo(() => openStages(pipeline), [pipeline])\n /*\n * The stage the deal is in — the one picked on a new deal, the stored one\n * on an edit, looked up in the deal's OWN pipeline and never the default's\n * — whose probability and forecast category the blank fields stand for.\n */\n const currentStage = useMemo(\n () =>\n dealStageById(\n pipelines.find((entry) => entry.$id === values.pipelineId),\n values.stageId,\n ),\n [pipelines, values.pipelineId, values.stageId],\n )\n const campaignOptions = useMemo(() => {\n const options = campaigns.options.map((option) => ({ value: option.value, label: option.label }))\n // A campaign the deal names but the picker no longer offers stays itself.\n return values.campaignId && !options.some((option) => option.value === values.campaignId)\n ? [...options, { value: values.campaignId, label: values.campaignId }]\n : options\n }, [campaigns.options, values.campaignId])\n\n /*\n * THE CONTACT WINDOW: the newest contacts this viewer may see, read only\n * while the drawer is open. Scoped and ordered like the contacts list —\n * the same `(visibleTo, updatedAt DESC)` index — and bounded, because the\n * picker's job is to find one person, not to list the audience.\n */\n const { data: contactRows } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n open && orgId && crmScopeListable(visibleTo)\n ? query(\n collection(firestore, 'orgs', orgId, 'contacts'),\n ...crmVisibleToClause(visibleTo),\n orderBy('updatedAt', 'desc'),\n limit(CONTACT_WINDOW),\n )\n : null,\n [firestore, open, orgId, visibleTo],\n { idField: '$id' },\n )\n const [contactQuery, setContactQuery] = useState('')\n // Named through the viewing group under a site; at the organization level\n // through each person's own primary holder.\n const contactChoices = useMemo(\n () =>\n contactChoicesFor(\n contactQuery,\n contactRows ?? [],\n consentGroup?.groupId ??\n ((row) => contactPrimaryGroup(row, org as Record<string, unknown>).groupId),\n ),\n [contactQuery, contactRows, consentGroup, org],\n )\n /*\n * THE LINKS' NAMES. The deal carries a copy beside each id, but a server\n * door that moves the Primary drops it (`dealContactRolesUpdate`), so a link\n * can arrive with no name to show. It is never shown blank: a picker that\n * looks empty while it holds a link is how the link gets erased unseen.\n */\n const linkedName = useCrmRecordNames({\n orgId: open ? orgId : null,\n groupId: consentGroup?.groupId ?? null,\n org: (org ?? null) as Record<string, unknown> | null,\n records: [\n ...(values.contactId && !values.contactName\n ? [{ kind: 'contact' as const, id: values.contactId }]\n : []),\n ...(values.companyId && !values.companyName\n ? [{ kind: 'company' as const, id: values.companyId }]\n : []),\n ],\n })\n const contactName =\n values.contactName || linkedName('contact', values.contactId) || 'Linked contact'\n const companyName =\n values.companyName || linkedName('company', values.companyId) || 'Linked company'\n // One object between renders: a new object is a new value to the picker,\n // and a new value puts its label over whatever the reader is typing.\n const contactValue = useMemo<ContactChoice | null>(\n () => (values.contactId ? { id: values.contactId, name: contactName, email: '' } : null),\n [values.contactId, contactName],\n )\n\n /*\n * THE COMPANY SEARCH: a prefix on `nameLower` with the scope, which the\n * companies collection indexes. Debounced so a name typed at speed is one\n * query rather than one per letter.\n */\n const [companyQuery, setCompanyQuery] = useState('')\n const [companyChoices, setCompanyChoices] = useState<CompanyChoice[]>([])\n useEffect(() => {\n if (!open || !orgId || !crmScopeListable(visibleTo)) return\n const key = nameSearchKey(companyQuery)\n let active = true\n const timer = setTimeout(() => {\n void getDocs(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.companies),\n ...crmVisibleToClause(visibleTo),\n orderBy('nameLower'),\n ...(key ? [startAt(key), endAt(`${key}\\uf8ff`)] : []),\n limit(COMPANY_MATCHES),\n ),\n )\n .then((snapshot) => {\n if (!active) return\n setCompanyChoices(\n snapshot.docs.map((entry) => ({\n id: entry.id,\n name: String(entry.get('name') ?? ''),\n })),\n )\n })\n .catch(() => {\n if (active) setCompanyChoices([])\n })\n }, 200)\n return () => {\n active = false\n clearTimeout(timer)\n }\n }, [firestore, open, orgId, visibleTo, companyQuery])\n const companyValue = useMemo<CompanyChoice | null>(\n () => (values.companyId ? { id: values.companyId, name: companyName } : null),\n [values.companyId, companyName],\n )\n\n const customMissing = crmCustomDraftMissingRequired(fields.active, storedCustom, custom, mode)\n const problem =\n dealFormProblem(values, mode) ??\n (customMissing.length ? `${customMissing.join(', ')} is required.` : null)\n const amountDerived = Boolean(deal && dealHasLineItems(deal))\n\n /*\n * THE RECORDS BAND (AGL-2611), read only while a CREATE is open: a deal\n * is a record of the band the contacts list is banded by, and on an org\n * at a full hard band this drawer refuses the way `upsertHostContact`\n * refuses a capture — same number, same sentence. Memoized, because the\n * tuple is an effect dependency and a fresh one per render would re-read\n * the three aggregates on every keystroke.\n */\n const recordsScope = useMemo(\n () => (open && mode === 'create' && orgId ? (['orgs', orgId] as const) : null),\n [open, mode, orgId],\n )\n const records = useCrmRecordsQuota(recordsScope, org)\n const bandFull = mode === 'create' && records.ready && !records.quota.allowed\n\n const handleSave = useCallback(async () => {\n if (problem || !orgId || !user?.uid) return\n if (bandFull) {\n enqueueSnackbar(CRM_RECORDS_BAND_FULL_MESSAGE, { variant: 'warning', persist: false })\n return\n }\n const judged = judgeDealFormPicklists(\n values,\n { type: typeList.picklist, leadSource: leadSourceList.picklist },\n { current: deal ?? null, created: !deal },\n )\n if (judged.ok === false) {\n enqueueSnackbar(judged.error, { variant: 'warning', persist: false })\n return\n }\n const saved = judged.values\n setBusy(true)\n try {\n const nowMs = Date.now()\n if (deal) {\n const edit = dealEditFromForm(saved, seed.current?.values ?? dealFormFromDoc(deal), nowMs, {\n amountDerived,\n stage: currentStage,\n current: deal,\n })\n // The custom keys that changed, merged into the stored map.\n const customWrites = crmCustomDraftWrites(storedCustom, custom)\n if (\n Object.keys(edit.set).length ||\n edit.clear.length ||\n Object.keys(customWrites).length\n ) {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'deal',\n unreadable,\n fromCache: fromCache && dealEditNeedsConfirmedRead(edit),\n listen,\n },\n async () => {\n let held = true\n const written = updateDoc(\n doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id),\n {\n ...edit.set,\n ...Object.fromEntries(edit.clear.map((key) => [key, deleteField()])),\n ...customWrites,\n // The title is what the Deals table searches (AGL-3321), and\n // the Type and Lead source what it filters by (AGL-3516),\n // from the listener's row with the edit over it.\n ...crmClientListFieldChanges(\n 'deals',\n deal as unknown as Record<string, unknown>,\n { ...edit.set, ...Object.fromEntries(edit.clear.map((key) => [key, null])) },\n DEAL_CLIENT_LIST_FIELDS,\n ),\n updatedAt: new Date(nowMs),\n },\n ).then(\n // Once the write has landed: sharing rules read the deal as stored.\n () => followUpSharing('deals', [deal.$id]),\n (error) => {\n if (held) throw error\n console.error(error)\n enqueueSnackbar(SAVE_FAILED_LATE_MESSAGE, {\n variant: 'error',\n allowDuplicate: true,\n })\n },\n )\n await withinSaveHold(written)\n held = false\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return\n }\n }\n enqueueSnackbar('Deal saved', { variant: 'success', persist: false })\n onSaved?.(deal.$id, 'edit')\n } else {\n // Held by the button until it knows who may see the deal — the whole\n // org, or (in an org that keeps its sites apart) a picked site's\n // group; checked again here because a callback can outlive the\n // render that held it.\n if (!createTokens.length) return\n const customDocument = crmCustomDraftDocument(custom)\n const record: Record<string, unknown> = {\n ...dealDocumentFromForm(saved, {\n visibleTo: [...createTokens],\n hostId: createHostId,\n uid: user.uid,\n nowMs,\n stage: currentStage,\n }),\n ...(customDocument ? { custom: customDocument } : {}),\n }\n const created = await addDoc(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n // What the Deals table searches and filters by (AGL-3321), and\n // nothing scheduled against a deal that did not exist.\n { ...record, ...crmNewRecordListFields('deals', record) },\n )\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\n // feed. Creation only — an edit is a save the card reports.\n followUpSharing('deals', [created.id])\n logActivity('Added deal', { type: 'deal', id: created.id, name: values.title })\n enqueueSnackbar('Deal created', { variant: 'success', persist: false })\n onSaved?.(created.id, 'create')\n }\n onClose()\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [\n problem,\n bandFull,\n orgId,\n followUpSharing,\n user,\n deal,\n values,\n unreadable,\n fromCache,\n listen,\n firestore,\n createTokens,\n createHostId,\n logActivity,\n enqueueSnackbar,\n onSaved,\n onClose,\n storedCustom,\n custom,\n typeList.picklist,\n leadSourceList.picklist,\n currentStage,\n amountDerived,\n ])\n\n return (\n <NavigationDrawerComponent\n open={open}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={busy ? undefined : onClose}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton color=\"inherit\" edge=\"start\" onClick={onClose} sx={{ mr: 2 }}>\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>close drawer</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {deal ? 'Edit deal' : 'New deal'}\n </Typography>\n </>\n }\n appBarRight={\n <Button variant=\"outlined\" color=\"inherit\" onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2} sx={{ width: { xs: '100%', sm: 420 } }}>\n {/*\n First, because the scope of everything below follows from it: at\n the organization level a new deal names the site it came from —\n required where the org keeps its sites apart, optional where every\n site sees it. Nothing under a site, and nothing on an edit — a deal\n keeps the site it was made on (AGL-2630).\n */}\n {mode === 'create' ? (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n optional={!createNeedsSite}\n helperText={\n createNeedsSite\n ? 'The site this deal belongs to — it decides which of your sites may see it.'\n : undefined\n }\n />\n ) : null}\n <TextField\n label=\"Title\"\n value={values.title}\n onChange={(event) => update({ title: event.target.value })}\n autoFocus\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_TITLE_MAX } }}\n />\n {mode === 'create' ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n select\n label=\"Pipeline\"\n value={pipelines.some((entry) => entry.$id === values.pipelineId) ? values.pipelineId : ''}\n onChange={(event) => {\n const next = pipelines.find(\n (entry) => entry.$id === event.target.value,\n )\n update({\n pipelineId: event.target.value,\n stageId: openStages(next)[0]?.id ?? '',\n })\n }}\n sx={{ flex: 1 }}\n >\n {pipelines.map((entry) => (\n <MenuItem key={entry.$id} value={entry.$id}>\n {entry.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n select\n label=\"Stage\"\n value={stages.some((stage) => stage.id === values.stageId) ? values.stageId : ''}\n onChange={(event) => update({ stageId: event.target.value })}\n sx={{ flex: 1 }}\n >\n {stages.map((stage) => (\n <MenuItem key={stage.id} value={stage.id}>\n {stage.name}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Amount\"\n value={values.amount}\n onChange={(event) => update({ amount: event.target.value })}\n placeholder=\"0.00\"\n sx={{ flex: 1 }}\n helperText={\n amountDerived\n ? \"The sum of the deal's line items — edit them on the Products card.\"\n : undefined\n }\n slotProps={{\n htmlInput: { inputMode: 'decimal', readOnly: amountDerived },\n }}\n />\n <TextField\n select\n label=\"Currency\"\n value={values.currency}\n onChange={(event) => update({ currency: event.target.value })}\n disabled={amountDerived}\n sx={{ width: 120 }}\n >\n {DEAL_CURRENCIES.map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n <TextField\n type=\"date\"\n label=\"Expected close\"\n value={values.expectedClose}\n onChange={(event) => update({ expectedClose: event.target.value })}\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <Stack direction=\"row\" spacing={1}>\n <CrmPicklistSelect\n picklistId=\"opportunityType\"\n picklist={typeList.picklist}\n value={values.type}\n stored={deal?.type ?? ''}\n onChange={(type) => update({ type })}\n disabled={busy}\n />\n <CrmPicklistSelect\n picklistId=\"leadSource\"\n picklist={leadSourceList.picklist}\n value={values.leadSource}\n stored={deal?.leadSource ?? ''}\n onChange={(leadSource) => update({ leadSource })}\n disabled={busy}\n />\n </Stack>\n <TextField\n label=\"Next step\"\n value={values.nextStep}\n onChange={(event) => update({ nextStep: event.target.value })}\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_NEXT_STEP_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Probability\"\n value={values.probability}\n onChange={(event) => update({ probability: event.target.value })}\n placeholder={currentStage ? String(currentStage.probability) : ''}\n helperText={\n currentStage\n ? `From stage: ${currentStage.probability}%`\n : 'Blank uses the stage’s'\n }\n sx={{ flex: 1 }}\n slotProps={{\n htmlInput: { inputMode: 'numeric', 'aria-label': 'Probability' },\n input: { endAdornment: '%' },\n inputLabel: { shrink: true },\n }}\n />\n <TextField\n select\n label=\"Forecast category\"\n value={values.forecastCategory}\n onChange={(event) =>\n update({ forecastCategory: event.target.value as '' | CrmForecastCategory })\n }\n helperText=\"A stage move sets it from the new stage.\"\n sx={{ flex: 1 }}\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">\n {currentStage\n ? `From the stage (${CRM_FORECAST_CATEGORY_LABELS[dealStageForecastCategory(currentStage)]})`\n : 'From the stage'}\n </MenuItem>\n {CRM_FORECAST_CATEGORIES.map((category) => (\n <MenuItem key={category} value={category}>\n {CRM_FORECAST_CATEGORY_LABELS[category]}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n <TextField\n select\n label=\"Owner\"\n // The stored owner resolved to a member — by uid, or by an\n // address the roster has — so the picker highlights the person\n // and a save writes their uid.\n value={owner ? owner.uid : values.ownerUid ? '__keep' : ''}\n onChange={(event) =>\n update({\n ownerUid: event.target.value === '__keep' ? values.ownerUid : event.target.value,\n })\n }\n fullWidth\n helperText={\n !roster.loading && !roster.members.length\n ? 'The roster could not be read; the owner stays as stored.'\n : undefined\n }\n >\n <MenuItem value=\"\">{'Nobody yet'}</MenuItem>\n {values.ownerUid && !owner ? (\n // The stored owner is not on the roster the route returned —\n // a member who left, or a roster that failed to load. Shown by\n // uid so the field is never blank while the deal has an owner.\n <MenuItem value=\"__keep\">{values.ownerUid}</MenuItem>\n ) : null}\n {roster.members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n <Autocomplete<ContactChoice, false, false, false>\n options={contactChoices}\n value={contactValue}\n // The input is the picker's own, which is how a linked contact\n // shows. The query is only what was typed, so the name it shows\n // is not searched for.\n onInputChange={(_event, next, reason) =>\n setContactQuery(reason === 'input' ? next : '')\n }\n onChange={(_event, picked) =>\n update({\n contactId: picked?.id ?? '',\n contactName: picked ? picked.name || picked.email : '',\n })\n }\n getOptionLabel={(choice) => choice.name || choice.email}\n isOptionEqualToValue={(option, value) => option.id === value.id}\n // Matching is `contactChoicesFor`'s — the list's grammar over the\n // window — and never MUI's own substring filter over labels.\n filterOptions={(options) => options}\n renderOption={(optionProps, choice) => (\n <li {...optionProps} key={choice.id}>\n <Stack sx={{ lineHeight: 1.25 }}>\n <Typography variant=\"body2\">{choice.name || choice.email}</Typography>\n {choice.name ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {choice.email}\n </Typography>\n ) : null}\n </Stack>\n </li>\n )}\n noOptionsText=\"No recent contact matches\"\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Contact\"\n placeholder=\"Name or email\"\n helperText=\"Searches your most recent contacts by name or email.\"\n />\n )}\n />\n <Autocomplete<CompanyChoice, false, false, false>\n options={companyChoices}\n value={companyValue}\n onInputChange={(_event, next, reason) =>\n setCompanyQuery(reason === 'input' ? next : '')\n }\n onChange={(_event, picked) =>\n update({\n companyId: picked?.id ?? '',\n companyName: picked?.name ?? '',\n })\n }\n getOptionLabel={(choice) => choice.name}\n isOptionEqualToValue={(option, value) => option.id === value.id}\n filterOptions={(options) => options}\n noOptionsText=\"No company matches\"\n renderInput={(params) => (\n <TextField {...params} label=\"Company\" placeholder=\"Company name\" />\n )}\n />\n <TextField\n select\n label=\"Campaign\"\n value={values.campaignId}\n onChange={(event) => update({ campaignId: event.target.value })}\n fullWidth\n helperText={\n campaigns.ready && !campaignOptions.length\n ? 'There are no campaigns yet. Create one from Marketing.'\n : 'The campaign this deal is attributed to.'\n }\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {campaignOptions.map((option) => (\n <MenuItem key={option.value} value={option.value}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Notes\"\n value={values.notes}\n onChange={(event) => update({ notes: event.target.value })}\n multiline\n minRows={3}\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_NOTES_MAX } }}\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 {bandFull ? (\n <Alert severity=\"warning\">{CRM_RECORDS_BAND_FULL_MESSAGE}</Alert>\n ) : null}\n {problem && values.title ? <Alert severity=\"warning\">{problem}</Alert> : null}\n <Button\n variant=\"contained\"\n disabled={\n busy ||\n Boolean(problem) ||\n !orgId ||\n bandFull ||\n // A new deal waits for its scope: a site, where the org keeps\n // its sites apart; nothing, where every site sees it.\n (mode === 'create' && !createTokens.length)\n }\n onClick={() => void handleSave()}\n >\n {deal ? 'Save deal' : 'Create deal'}\n </Button>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n )\n}\nDealEditDrawer.displayName = 'DealEditDrawer'\n\nexport default DealEditDrawer\n"],"names":["CRM_COLLECTIONS","CRM_FORECAST_CATEGORIES","CRM_FORECAST_CATEGORY_LABELS","CRM_RECORDS_BAND_FULL_MESSAGE","crmNewRecordListFields","DEAL_NEXT_STEP_MAX","dealHasLineItems","dealStageById","dealStageForecastCategory","findOrgMember","nameSearchKey","crmMemberPickerLabel","ICON_VARIANT_CLOSE","Container","MdiIcon","SrOnly","NavigationDrawerComponent","useSnackbar","useFirestore","useFirestoreCollection","useUser","writeGuardedBySeed","Alert","Autocomplete","Button","IconButton","MenuItem","Stack","TextField","Typography","addDoc","collection","deleteField","doc","endAt","getDocs","limit","orderBy","query","startAt","updateDoc","useCallback","useEffect","useMemo","useRef","useState","useContactFieldDefinitions","useCrmActivityLogger","useCrmCampaigns","useCrmPicklist","useCrmRecordNames","useCrmRecordsQuota","crmScopeListable","crmVisibleToClause","useCrmScope","useOrgMemberDirectory","contactPrimaryGroup","crmCustomDraftDocument","crmCustomDraftMissingRequired","crmCustomDraftValue","crmCustomDraftWrites","CrmCustomFieldControl","CrmPicklistSelect","CrmSitePicker","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFieldChanges","DEAL_CURRENCIES","openStages","contactChoicesFor","DEAL_NOTES_MAX","DEAL_TITLE_MAX","dealDocumentFromForm","dealEditFromForm","dealEditNeedsConfirmedRead","dealFormFromDoc","dealFormProblem","emptyDealForm","judgeDealFormPicklists","rebaseDealForm","useCrmSharingFollowUp","CONTACT_WINDOW","COMPANY_MATCHES","DEAL_CLIENT_LIST_FIELDS","SAVE_HOLD_MS","SAVE_FAILED_LATE_MESSAGE","withinSaveHold","write","timer","hold","Promise","resolve","setTimeout","race","finally","clearTimeout","DealEditDrawer","props","open","onClose","hostId","org","deal","defaults","pipelines","defaultPipeline","unreadable","fromCache","listen","onSaved","mode","firestore","enqueueSnackbar","data","user","orgId","consentGroup","visibleTo","createHostId","createTokens","createNeedsSite","followUpSharing","logActivity","roster","values","setValues","owner","members","ownerUid","busy","setBusy","fields","typeList","leadSourceList","campaigns","enabled","storedCustom","custom","setCustom","seed","current","dealId","$id","stored","previous","update","patch","pipeline","find","entry","pipelineId","stages","currentStage","stageId","campaignOptions","options","map","option","value","label","campaignId","some","contactRows","idField","contactQuery","setContactQuery","contactChoices","groupId","row","linkedName","records","contactId","contactName","kind","id","companyId","companyName","contactValue","name","email","companyQuery","setCompanyQuery","companyChoices","setCompanyChoices","key","active","companies","then","snapshot","docs","String","get","catch","companyValue","customMissing","problem","length","join","amountDerived","Boolean","recordsScope","bandFull","ready","quota","allowed","handleSave","uid","variant","persist","judged","type","picklist","leadSource","created","ok","error","saved","nowMs","Date","now","edit","stage","customWrites","Object","keys","set","clear","verdict","subject","held","written","deals","fromEntries","updatedAt","console","allowDuplicate","message","customDocument","record","title","anchor","undefined","AppBarProps","color","appBarLeft","edge","onClick","sx","mr","path","component","appBarRight","disabled","gutterY","spacing","width","xs","sm","optional","helperText","onChange","event","target","autoFocus","fullWidth","slotProps","htmlInput","maxLength","direction","select","next","flex","alignItems","amount","placeholder","inputMode","readOnly","currency","code","toUpperCase","expectedClose","inputLabel","shrink","picklistId","nextStep","probability","input","endAdornment","forecastCategory","displayEmpty","category","loading","member","onInputChange","_event","reason","picked","getOptionLabel","choice","isOptionEqualToValue","filterOptions","renderOption","optionProps","li","lineHeight","noOptionsText","renderInput","params","notes","multiline","minRows","definition","severity","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SACEA,eAAe,EACfC,uBAAuB,EACvBC,4BAA4B,EAC5BC,6BAA6B,EAE7BC,sBAAsB,EACtBC,kBAAkB,EAClBC,gBAAgB,EAChBC,aAAa,EACbC,yBAAyB,EACzBC,aAAa,EACbC,aAAa,EACbC,oBAAoB,QACf,eAAc;AACrB,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,QAAQ,uBAAsB;AACjE,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SAASC,WAAW,QAAQ,8BAA6B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AM;wBAE5CkD,SAAS,IAAM,KAAKzC;kCAEnBvG,OAAO,cAAc;;;;;;AAMlC;AACAN,eAAeyN,WAAW,GAAG;AAE7B,eAAezN,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 } from '../model/deal-board-model';
|
|
3
4
|
export interface DealProductsCardProps {
|
|
@@ -13,6 +14,8 @@ export interface DealProductsCardProps {
|
|
|
13
14
|
/** The listener's verdict on the deal, for the stale-seed guard. */
|
|
14
15
|
fromCache: boolean;
|
|
15
16
|
unreadable: boolean;
|
|
17
|
+
/** The deal's listener, so a save waits on that read alone (AGL-4135). */
|
|
18
|
+
listen?: ListenHandle | null;
|
|
16
19
|
}
|
|
17
20
|
/**
|
|
18
21
|
* The products behind a deal's amount (AGL-2620).
|