@aglyn/plugins-crm 1.20.3 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +15 -15
  2. package/src/lib/components/company-contact-roles-card.js +6 -1
  3. package/src/lib/components/company-contact-roles-card.js.map +1 -1
  4. package/src/lib/components/company-edit-drawer.js +58 -19
  5. package/src/lib/components/company-edit-drawer.js.map +1 -1
  6. package/src/lib/components/contact-associations-card.js +28 -3
  7. package/src/lib/components/contact-associations-card.js.map +1 -1
  8. package/src/lib/components/contact-field-drawer.d.ts +11 -1
  9. package/src/lib/components/contact-field-drawer.js +61 -21
  10. package/src/lib/components/contact-field-drawer.js.map +1 -1
  11. package/src/lib/components/contact-properties-card.js +100 -66
  12. package/src/lib/components/contact-properties-card.js.map +1 -1
  13. package/src/lib/components/contact-roles-editor.d.ts +6 -0
  14. package/src/lib/components/contact-roles-editor.js +149 -108
  15. package/src/lib/components/contact-roles-editor.js.map +1 -1
  16. package/src/lib/components/crm-glance-card.js +1 -1
  17. package/src/lib/components/crm-glance-card.js.map +1 -1
  18. package/src/lib/components/deal-contact-roles-card.js +6 -1
  19. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  20. package/src/lib/components/deal-edit-drawer.js +37 -6
  21. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  22. package/src/lib/components/deal-products-card.js +165 -117
  23. package/src/lib/components/deal-products-card.js.map +1 -1
  24. package/src/lib/components/fields-section.js +24 -5
  25. package/src/lib/components/fields-section.js.map +1 -1
  26. package/src/lib/components/lead-campaigns-card.js +53 -27
  27. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  28. package/src/lib/components/lead-properties-card.js +45 -24
  29. package/src/lib/components/lead-properties-card.js.map +1 -1
  30. package/src/lib/components/picklist-values-card.js +42 -16
  31. package/src/lib/components/picklist-values-card.js.map +1 -1
  32. package/src/lib/components/pipeline-stages-dialog.js +31 -3
  33. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  34. package/src/lib/components/pipelines-dialog.js +51 -12
  35. package/src/lib/components/pipelines-dialog.js.map +1 -1
  36. package/src/lib/components/record-tasks-card.js +7 -1
  37. package/src/lib/components/record-tasks-card.js.map +1 -1
  38. package/src/lib/components/task-edit-drawer.js +43 -6
  39. package/src/lib/components/task-edit-drawer.js.map +1 -1
  40. package/src/lib/components/tasks-section.js +7 -2
  41. package/src/lib/components/tasks-section.js.map +1 -1
  42. package/src/lib/model/crm-reports.d.ts +2 -11
  43. package/src/lib/model/crm-reports.js +1 -14
  44. package/src/lib/model/crm-reports.js.map +1 -1
  45. package/src/lib/model/local-day-bounds.d.ts +31 -0
  46. package/src/lib/model/local-day-bounds.js +36 -0
  47. package/src/lib/model/local-day-bounds.js.map +1 -0
  48. package/src/lib/transfer/fields.d.ts +2 -8
  49. package/src/lib/transfer/fields.js +3 -9
  50. package/src/lib/transfer/fields.js.map +1 -1
  51. package/src/lib/transfer/resource-keys.d.ts +33 -0
  52. package/src/lib/transfer/resource-keys.js +33 -0
  53. package/src/lib/transfer/resource-keys.js.map +1 -0
  54. package/src/lib/transfer/ui.js +1 -1
  55. package/src/lib/transfer/ui.js.map +1 -1
@@ -23,6 +23,7 @@ import { Container, MdiIcon, SrOnly } from "@aglyn/shared-ui-jsx";
23
23
  import { NavigationDrawerComponent } from "@aglyn/shared-ui-jsx/components/navigation-drawer.component";
24
24
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
25
25
  import { useFirestore, useFirestoreCollection, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
26
+ import { isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
26
27
  import { Alert, Autocomplete, Button, IconButton, MenuItem, Stack, TextField, Typography } from "@mui/material";
27
28
  import { addDoc, collection, deleteField, doc, endAt, getDocs, limit, orderBy, query, startAt, updateDoc } from "firebase/firestore";
28
29
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -121,7 +122,8 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
121
122
  * stamps both afresh. The campaign is one of the campaigns the Campaigns
122
123
  * picker of a lead offers at this level.
123
124
  */ export function DealEditDrawer(props) {
124
- var _ref, _dealFormProblem, _ref1, _ref2;
125
+ var _ref, _dealFormProblem, _ref1, _ref2, _ref3;
126
+ var _seed_current;
125
127
  const { open, onClose, hostId, org, deal, defaults, pipelines, defaultPipeline, unreadable = false, fromCache = false, listen, onSaved } = props;
126
128
  const mode = deal ? 'edit' : 'create';
127
129
  const firestore = useFirestore();
@@ -345,6 +347,20 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
345
347
  const problem = (_dealFormProblem = dealFormProblem(values, mode)) != null ? _dealFormProblem : customMissing.length ? `${customMissing.join(', ')} is required.` : null;
346
348
  const amountDerived = Boolean(deal && dealHasLineItems(deal));
347
349
  /*
350
+ * Save is held, with the reason beside it, while the deal read is the
351
+ * cache's and the edit typed so far is one worked out from it (AGL-4047):
352
+ * pressed then, it waited on the server and could end refused. Every other
353
+ * edit saves at once, as before, and the form already follows the stored
354
+ * deal in the fields nobody touched.
355
+ */ const checkingText = deal && isSeedChecking({
356
+ fromCache,
357
+ unreadable
358
+ }) && dealEditNeedsConfirmedRead(dealEditFromForm(values, (_ref1 = (_seed_current = seed.current) == null ? void 0 : _seed_current.values) != null ? _ref1 : dealFormFromDoc(deal), Date.now(), {
359
+ amountDerived,
360
+ stage: currentStage,
361
+ current: deal
362
+ })) ? seedCheckingText('deal') : undefined;
363
+ /*
348
364
  * THE RECORDS BAND (AGL-2611), read only while a CREATE is open: a deal
349
365
  * is a record of the band the contacts list is banded by, and on an org
350
366
  * at a full hard band this drawer refuses the way `upsertHostContact`
@@ -514,6 +530,15 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
514
530
  currentStage,
515
531
  amountDerived
516
532
  ]);
533
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
534
+ const held = useHeldSave(handleSave, {
535
+ checking: Boolean(checkingText),
536
+ subject: 'deal',
537
+ onRefused: (message)=>enqueueSnackbar(message, {
538
+ variant: 'warning',
539
+ persist: false
540
+ })
541
+ });
517
542
  return /*#__PURE__*/ _jsx(NavigationDrawerComponent, {
518
543
  open: open,
519
544
  anchor: "right",
@@ -692,7 +717,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
692
717
  picklistId: "opportunityType",
693
718
  picklist: typeList.picklist,
694
719
  value: values.type,
695
- stored: (_ref1 = deal == null ? void 0 : deal.type) != null ? _ref1 : '',
720
+ stored: (_ref2 = deal == null ? void 0 : deal.type) != null ? _ref2 : '',
696
721
  onChange: (type)=>update({
697
722
  type
698
723
  }),
@@ -702,7 +727,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
702
727
  picklistId: "leadSource",
703
728
  picklist: leadSourceList.picklist,
704
729
  value: values.leadSource,
705
- stored: (_ref2 = deal == null ? void 0 : deal.leadSource) != null ? _ref2 : '',
730
+ stored: (_ref3 = deal == null ? void 0 : deal.leadSource) != null ? _ref3 : '',
706
731
  onChange: (leadSource)=>update({
707
732
  leadSource
708
733
  }),
@@ -947,13 +972,19 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
947
972
  severity: "warning",
948
973
  children: problem
949
974
  }) : null,
975
+ checkingText ? /*#__PURE__*/ _jsx(Typography, {
976
+ variant: "body2",
977
+ color: "text.secondary",
978
+ role: "status",
979
+ children: checkingText
980
+ }) : null,
950
981
  /*#__PURE__*/ _jsx(Button, {
951
982
  variant: "contained",
952
983
  disabled: busy || Boolean(problem) || !orgId || bandFull || // A new deal waits for its scope: a site, where the org keeps
953
984
  // its sites apart; nothing, where every site sees it.
954
- mode === 'create' && !createTokens.length,
955
- onClick: ()=>void handleSave(),
956
- children: deal ? 'Save deal' : 'Create deal'
985
+ mode === 'create' && !createTokens.length || held.saving,
986
+ onClick: held.press,
987
+ children: held.saving ? 'Saving…' : deal ? 'Save deal' : 'Create deal'
957
988
  })
958
989
  ]
959
990
  })
@@ -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 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,EAChB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;yBACzB;oBACHiM,WAAWvE,OAAOmH,KAAK,iBAAG,KAAC1N;wBAAMmS,UAAS;kCAAWrH;yBAAmB;kCACzE,KAAC5K;wBACCwL,SAAQ;wBACR6C,UACE3H,QACAsE,QAAQJ,YACR,CAAChF,SACDsF,YACA,8DAA8D;wBAC9D,sDAAsD;wBACrD3F,SAAS,YAAY,CAACS,aAAa6E,MAAM;wBAE5CkD,SAAS,IAAM,KAAKzC;kCAEnBvG,OAAO,cAAc;;;;;;AAMlC;AACAN,eAAeyN,WAAW,GAAG;AAE7B,eAAezN,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 isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 * Save is held, with the reason beside it, while the deal read is the\n * cache's and the edit typed so far is one worked out from it (AGL-4047):\n * pressed then, it waited on the server and could end refused. Every other\n * edit saves at once, as before, and the form already follows the stored\n * deal in the fields nobody touched.\n */\n const checkingText =\n deal &&\n isSeedChecking({ fromCache, unreadable }) &&\n dealEditNeedsConfirmedRead(\n dealEditFromForm(values, seed.current?.values ?? dealFormFromDoc(deal), Date.now(), {\n amountDerived,\n stage: currentStage,\n current: deal,\n }),\n )\n ? seedCheckingText('deal')\n : undefined\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 // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking: Boolean(checkingText),\n subject: 'deal',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : 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 held.saving\n }\n onClick={held.press}\n >\n {held.saving ? 'Saving…' : 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","isSeedChecking","seedCheckingText","useHeldSave","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","seed","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","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","checkingText","Date","now","stage","undefined","recordsScope","bandFull","ready","quota","allowed","handleSave","uid","variant","persist","judged","type","picklist","leadSource","created","ok","error","saved","nowMs","edit","customWrites","Object","keys","set","clear","verdict","subject","held","written","deals","fromEntries","updatedAt","console","allowDuplicate","message","customDocument","record","title","checking","onRefused","anchor","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","role","saving","press","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,S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