@aglyn/plugins-crm 1.4.0 → 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-crm",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,19 +25,19 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.4.0",
29
- "@aglyn/shared-data-enums": "1.4.0",
30
- "@aglyn/shared-data-mdi": "1.4.0",
31
- "@aglyn/shared-ui-jsx": "1.4.0",
32
- "@aglyn/shared-ui-next": "1.4.0",
33
- "@aglyn/shared-ui-snackstack": "1.4.0",
34
- "@aglyn/shared-util-email": "1.4.0",
35
- "@aglyn/shared-util-http": "1.4.0",
36
- "@aglyn/shared-util-timestamp": "1.4.0",
37
- "@aglyn/shared-util-tools": "1.4.0",
38
- "@aglyn/tenant-data-admin": "1.4.0",
39
- "@aglyn/tenant-feature-instance": "1.4.0",
40
- "@aglyn/tenant-runtime": "1.4.0",
28
+ "@aglyn/aglyn": "1.5.0",
29
+ "@aglyn/shared-data-enums": "1.5.0",
30
+ "@aglyn/shared-data-mdi": "1.5.0",
31
+ "@aglyn/shared-ui-jsx": "1.5.0",
32
+ "@aglyn/shared-ui-next": "1.5.0",
33
+ "@aglyn/shared-ui-snackstack": "1.5.0",
34
+ "@aglyn/shared-util-email": "1.5.0",
35
+ "@aglyn/shared-util-http": "1.5.0",
36
+ "@aglyn/shared-util-timestamp": "1.5.0",
37
+ "@aglyn/shared-util-tools": "1.5.0",
38
+ "@aglyn/tenant-data-admin": "1.5.0",
39
+ "@aglyn/tenant-feature-instance": "1.5.0",
40
+ "@aglyn/tenant-runtime": "1.5.0",
41
41
  "@dnd-kit/core": "^6.3.1",
42
42
  "@dnd-kit/utilities": "^3.2.2",
43
43
  "@swc/helpers": "0.5.23",
@@ -18,7 +18,10 @@ export interface DealEditDrawerProps {
18
18
  pipelines: PipelineDoc[];
19
19
  /** Where a new deal lands when nobody picks a pipeline. */
20
20
  defaultPipeline: PipelineDoc | null;
21
- /** The listener's verdict on the row being edited, for the stale-seed guard. */
21
+ /**
22
+ * The listener's verdict on the row being edited. An unconfirmed row holds
23
+ * back only an edit that is worked out from it (`dealEditNeedsConfirmedRead`).
24
+ */
22
25
  unreadable?: boolean;
23
26
  fromCache?: boolean;
24
27
  /** After a save, with the id of the deal written. */
@@ -43,6 +46,11 @@ export interface DealEditDrawerProps {
43
46
  * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the
44
47
  * caller was looking at.
45
48
  *
49
+ * An edit writes only what the reader changed (AGL-4132), so one field
50
+ * changed in a drawer opened on an unconfirmed read saves at once and cannot
51
+ * touch anything else on the deal. The form follows the stored deal in the
52
+ * fields they have not touched, and keeps what they typed in those they have.
53
+ *
46
54
  * ## The pickers
47
55
  *
48
56
  * The owner is picked from the org's roster, the company by a server-side
@@ -25,11 +25,12 @@ import { useSnackbar } from "@aglyn/shared-ui-snackstack";
25
25
  import { useFirestore, useFirestoreCollection, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
26
26
  import { Alert, Autocomplete, Button, IconButton, MenuItem, Stack, TextField, Typography } from "@mui/material";
27
27
  import { addDoc, collection, deleteField, doc, endAt, getDocs, limit, orderBy, query, startAt, updateDoc } from "firebase/firestore";
28
- import { useCallback, useEffect, useMemo, useState } from "react";
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
29
  import { useContactFieldDefinitions } from "../hooks/use-contact-field-definitions.js";
30
30
  import { useCrmActivityLogger } from "../hooks/use-crm-activity-logger.js";
31
31
  import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
32
32
  import { useCrmPicklist } from "../hooks/use-crm-picklist.js";
33
+ import { useCrmRecordNames } from "../hooks/use-crm-record-names.js";
33
34
  import { useCrmRecordsQuota } from "../hooks/use-crm-records-quota.js";
34
35
  import { crmScopeListable, crmVisibleToClause, useCrmScope } from "../hooks/use-crm-scope.js";
35
36
  import { useOrgMemberDirectory } from "../hooks/use-org-member-directory.js";
@@ -38,9 +39,9 @@ import { crmCustomDraftDocument, crmCustomDraftMissingRequired, crmCustomDraftVa
38
39
  import { CrmCustomFieldControl } from "./crm-custom-field-control.js";
39
40
  import { CrmPicklistSelect } from "./picklist-select.js";
40
41
  import { CrmSitePicker } from "./crm-site-picker.js";
41
- import { CRM_CLIENT_SEARCH_FIELDS, CRM_CLIENT_SORT_FIELDS, CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from "../model/crm-list-query.js";
42
+ import { CRM_CLIENT_SEARCH_FIELDS, CRM_CLIENT_SORT_FIELDS, CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFieldChanges } from "../model/crm-list-query.js";
42
43
  import { DEAL_CURRENCIES, openStages } from "../model/deal-board-model.js";
43
- import { contactChoicesFor, DEAL_NOTES_MAX, DEAL_TITLE_MAX, dealDocumentFromForm, dealFormFromDoc, dealFormProblem, dealPatchFromForm, emptyDealForm, judgeDealFormPicklists } from "../model/deal-form-model.js";
44
+ import { contactChoicesFor, DEAL_NOTES_MAX, DEAL_TITLE_MAX, dealDocumentFromForm, dealEditFromForm, dealEditNeedsConfirmedRead, dealFormFromDoc, dealFormProblem, emptyDealForm, judgeDealFormPicklists, rebaseDealForm } from "../model/deal-form-model.js";
44
45
  import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
45
46
  /**
46
47
  * How many recent contacts the picker matches against. The window is the
@@ -58,6 +59,25 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
58
59
  // The arrays a deal's contact roles are found by (AGL-3521).
59
60
  ...CRM_DEAL_CONTACT_ROLE_LIST_FIELDS
60
61
  ];
62
+ /**
63
+ * How long a save holds the drawer on the server's acknowledgement (AGL-4132).
64
+ * A durable console tab writes through whichever tab holds the lease, and a
65
+ * hidden or overloaded one can take a minute to answer (AGL-3806); 25 s was
66
+ * measured here. Stopping the wait does not stop the write: it is in the
67
+ * IndexedDB queue, the page behind the drawer already shows it, and the lease
68
+ * holder sends it.
69
+ */ const SAVE_HOLD_MS = 4000;
70
+ /** What a save says when its write fails after the hold let the drawer close. */ const SAVE_FAILED_LATE_MESSAGE = 'Your last change to this deal could not be saved. Open it and try again.';
71
+ /** Settles with `write`, or resolves when the hold runs out. */ function withinSaveHold(write) {
72
+ let timer;
73
+ const hold = new Promise((resolve)=>{
74
+ timer = setTimeout(resolve, SAVE_HOLD_MS);
75
+ });
76
+ return Promise.race([
77
+ write,
78
+ hold
79
+ ]).finally(()=>clearTimeout(timer));
80
+ }
61
81
  /**
62
82
  * The one form a deal is created and edited through (AGL-2598).
63
83
  *
@@ -77,6 +97,11 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
77
97
  * deal lists every ACTIVE pipeline (`pipelines`) and opens on the one the
78
98
  * caller was looking at.
79
99
  *
100
+ * An edit writes only what the reader changed (AGL-4132), so one field
101
+ * changed in a drawer opened on an unconfirmed read saves at once and cannot
102
+ * touch anything else on the deal. The form follows the stored deal in the
103
+ * fields they have not touched, and keeps what they typed in those they have.
104
+ *
80
105
  * ## The pickers
81
106
  *
82
107
  * The owner is picked from the org's roster, the company by a server-side
@@ -97,7 +122,6 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
97
122
  * picker of a lead offers at this level.
98
123
  */ export function DealEditDrawer(props) {
99
124
  var _ref, _dealFormProblem, _ref1, _ref2;
100
- var _contactChoices_find;
101
125
  const { open, onClose, hostId, org, deal, defaults, pipelines, defaultPipeline, unreadable = false, fromCache = false, onSaved } = props;
102
126
  const mode = deal ? 'edit' : 'create';
103
127
  const firestore = useFirestore();
@@ -140,12 +164,33 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
140
164
  deal == null ? void 0 : deal.custom
141
165
  ]);
142
166
  const [custom, setCustom] = useState({});
143
- // Re-seeded on every open: an existing deal's stored values, or a blank
144
- // form aimed at the default pipeline with whatever the opener preselected.
167
+ /*
168
+ * What the form was built from: what a save compares against, and what
169
+ * tells a field the reader changed from one they left alone. Held in a ref
170
+ * because nothing renders from it.
171
+ */ const seed = useRef(null);
172
+ // Seeded on every open: an existing deal's stored values, or a blank form
173
+ // aimed at the default pipeline with whatever the opener preselected. After
174
+ // that a new snapshot only moves the fields the reader has not touched.
145
175
  useEffect(()=>{
146
- if (!open) return;
147
- setValues(deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults));
148
- setCustom({});
176
+ var _ref;
177
+ if (!open) {
178
+ seed.current = null;
179
+ return;
180
+ }
181
+ const dealId = (_ref = deal == null ? void 0 : deal.$id) != null ? _ref : null;
182
+ const stored = deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults);
183
+ const previous = seed.current;
184
+ seed.current = {
185
+ dealId,
186
+ values: stored
187
+ };
188
+ if ((previous == null ? void 0 : previous.dealId) === dealId) {
189
+ setValues((current)=>rebaseDealForm(current, previous.values, stored));
190
+ } else {
191
+ setValues(stored);
192
+ setCustom({});
193
+ }
149
194
  }, [
150
195
  open,
151
196
  deal,
@@ -215,11 +260,42 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
215
260
  consentGroup,
216
261
  org
217
262
  ]);
218
- const contactValue = values.contactId ? {
219
- id: values.contactId,
220
- name: values.contactName,
221
- email: (_ref = (_contactChoices_find = contactChoices.find((choice)=>choice.id === values.contactId)) == null ? void 0 : _contactChoices_find.email) != null ? _ref : ''
222
- } : null;
263
+ /*
264
+ * THE LINKS' NAMES. The deal carries a copy beside each id, but a server
265
+ * door that moves the Primary drops it (`dealContactRolesUpdate`), so a link
266
+ * can arrive with no name to show. It is never shown blank: a picker that
267
+ * looks empty while it holds a link is how the link gets erased unseen.
268
+ */ const linkedName = useCrmRecordNames({
269
+ orgId: open ? orgId : null,
270
+ groupId: (_ref = consentGroup == null ? void 0 : consentGroup.groupId) != null ? _ref : null,
271
+ org: org != null ? org : null,
272
+ records: [
273
+ ...values.contactId && !values.contactName ? [
274
+ {
275
+ kind: 'contact',
276
+ id: values.contactId
277
+ }
278
+ ] : [],
279
+ ...values.companyId && !values.companyName ? [
280
+ {
281
+ kind: 'company',
282
+ id: values.companyId
283
+ }
284
+ ] : []
285
+ ]
286
+ });
287
+ const contactName = values.contactName || linkedName('contact', values.contactId) || 'Linked contact';
288
+ const companyName = values.companyName || linkedName('company', values.companyId) || 'Linked company';
289
+ // One object between renders: a new object is a new value to the picker,
290
+ // and a new value puts its label over whatever the reader is typing.
291
+ const contactValue = useMemo(()=>values.contactId ? {
292
+ id: values.contactId,
293
+ name: contactName,
294
+ email: ''
295
+ } : null, [
296
+ values.contactId,
297
+ contactName
298
+ ]);
223
299
  /*
224
300
  * THE COMPANY SEARCH: a prefix on `nameLower` with the scope, which the
225
301
  * companies collection indexes. Debounced so a name typed at speed is one
@@ -258,10 +334,13 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
258
334
  visibleTo,
259
335
  companyQuery
260
336
  ]);
261
- const companyValue = values.companyId ? {
262
- id: values.companyId,
263
- name: values.companyName
264
- } : null;
337
+ const companyValue = useMemo(()=>values.companyId ? {
338
+ id: values.companyId,
339
+ name: companyName
340
+ } : null, [
341
+ values.companyId,
342
+ companyName
343
+ ]);
265
344
  const customMissing = crmCustomDraftMissingRequired(fields.active, storedCustom, custom, mode);
266
345
  const problem = (_dealFormProblem = dealFormProblem(values, mode)) != null ? _dealFormProblem : customMissing.length ? `${customMissing.join(', ')} is required.` : null;
267
346
  const amountDerived = Boolean(deal && dealHasLineItems(deal));
@@ -310,34 +389,52 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
310
389
  try {
311
390
  const nowMs = Date.now();
312
391
  if (deal) {
313
- const verdict = await writeGuardedBySeed({
314
- subject: 'deal',
315
- unreadable,
316
- fromCache
317
- }, async ()=>{
318
- const { set, clear } = dealPatchFromForm(saved, nowMs, {
319
- amountDerived,
320
- stage: currentStage,
321
- current: deal
322
- });
323
- await updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, set, Object.fromEntries(clear.map((key)=>[
324
- key,
325
- deleteField()
326
- ])), crmCustomDraftWrites(storedCustom, custom), crmClientListFields('deals', deal, _extends({}, set, Object.fromEntries(clear.map((key)=>[
327
- key,
328
- null
329
- ]))), DEAL_CLIENT_LIST_FIELDS)));
392
+ var _ref;
393
+ var _seed_current;
394
+ const edit = dealEditFromForm(saved, (_ref = (_seed_current = seed.current) == null ? void 0 : _seed_current.values) != null ? _ref : dealFormFromDoc(deal), nowMs, {
395
+ amountDerived,
396
+ stage: currentStage,
397
+ current: deal
330
398
  });
331
- if (!verdict.ok) {
332
- enqueueSnackbar(verdict.message, {
333
- variant: 'warning',
334
- persist: false
399
+ // The custom keys that changed, merged into the stored map.
400
+ const customWrites = crmCustomDraftWrites(storedCustom, custom);
401
+ if (Object.keys(edit.set).length || edit.clear.length || Object.keys(customWrites).length) {
402
+ const verdict = await writeGuardedBySeed({
403
+ subject: 'deal',
404
+ unreadable,
405
+ fromCache: fromCache && dealEditNeedsConfirmedRead(edit)
406
+ }, async ()=>{
407
+ let held = true;
408
+ const written = updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), _extends({}, edit.set, Object.fromEntries(edit.clear.map((key)=>[
409
+ key,
410
+ deleteField()
411
+ ])), customWrites, crmClientListFieldChanges('deals', deal, _extends({}, edit.set, Object.fromEntries(edit.clear.map((key)=>[
412
+ key,
413
+ null
414
+ ]))), DEAL_CLIENT_LIST_FIELDS), {
415
+ updatedAt: new Date(nowMs)
416
+ })).then(// Once the write has landed: sharing rules read the deal as stored.
417
+ ()=>followUpSharing('deals', [
418
+ deal.$id
419
+ ]), (error)=>{
420
+ if (held) throw error;
421
+ console.error(error);
422
+ enqueueSnackbar(SAVE_FAILED_LATE_MESSAGE, {
423
+ variant: 'error',
424
+ allowDuplicate: true
425
+ });
426
+ });
427
+ await withinSaveHold(written);
428
+ held = false;
335
429
  });
336
- return;
430
+ if (!verdict.ok) {
431
+ enqueueSnackbar(verdict.message, {
432
+ variant: 'warning',
433
+ persist: false
434
+ });
435
+ return;
436
+ }
337
437
  }
338
- followUpSharing('deals', [
339
- deal.$id
340
- ]);
341
438
  enqueueSnackbar('Deal saved', {
342
439
  variant: 'success',
343
440
  persist: false
@@ -412,7 +509,8 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
412
509
  custom,
413
510
  typeList.picklist,
414
511
  leadSourceList.picklist,
415
- currentStage
512
+ currentStage,
513
+ amountDerived
416
514
  ]);
417
515
  return /*#__PURE__*/ _jsx(NavigationDrawerComponent, {
418
516
  open: open,
@@ -719,10 +817,10 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
719
817
  /*#__PURE__*/ _jsx(Autocomplete, {
720
818
  options: contactChoices,
721
819
  value: contactValue,
722
- inputValue: contactQuery,
723
- onInputChange: (_event, next, reason)=>{
724
- if (reason !== 'reset') setContactQuery(next);
725
- },
820
+ // The input is the picker's own, which is how a linked contact
821
+ // shows. The query is only what was typed, so the name it shows
822
+ // is not searched for.
823
+ onInputChange: (_event, next, reason)=>setContactQuery(reason === 'input' ? next : ''),
726
824
  onChange: (_event, picked)=>{
727
825
  var _ref;
728
826
  return update({
@@ -763,10 +861,7 @@ import { useCrmSharingFollowUp } from "../hooks/use-crm-sharing.js";
763
861
  /*#__PURE__*/ _jsx(Autocomplete, {
764
862
  options: companyChoices,
765
863
  value: companyValue,
766
- inputValue: companyQuery,
767
- onInputChange: (_event, next, reason)=>{
768
- if (reason !== 'reset') setCompanyQuery(next);
769
- },
864
+ onInputChange: (_event, next, reason)=>setCompanyQuery(reason === 'input' ? next : ''),
770
865
  onChange: (_event, picked)=>{
771
866
  var _ref, _ref1;
772
867
  return update({
@@ -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, 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 { 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 crmClientListFields,\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 dealFormFromDoc,\n dealFormProblem,\n type DealFormValues,\n dealPatchFromForm,\n emptyDealForm,\n judgeDealFormPicklists,\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\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 /** The listener's verdict on the row being edited, for the stale-seed guard. */\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 * ## 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 // Re-seeded on every open: an existing deal's stored values, or a blank\n // form aimed at the default pipeline with whatever the opener preselected.\n useEffect(() => {\n if (!open) return\n setValues(deal ? dealFormFromDoc(deal) : emptyDealForm(defaultPipeline, defaults))\n setCustom({})\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 const contactValue: ContactChoice | null = values.contactId\n ? {\n id: values.contactId,\n name: values.contactName,\n email:\n contactChoices.find((choice) => choice.id === values.contactId)?.email ?? '',\n }\n : null\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: CompanyChoice | null = values.companyId\n ? { id: values.companyId, name: values.companyName }\n : null\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 verdict = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache },\n async () => {\n const { set, clear } = dealPatchFromForm(saved, nowMs, {\n amountDerived,\n stage: currentStage,\n current: deal,\n })\n await updateDoc(\n doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id),\n {\n ...set,\n ...Object.fromEntries(clear.map((key) => [key, deleteField()])),\n // The custom keys that changed, merged into the stored map.\n ...crmCustomDraftWrites(storedCustom, custom),\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 ...crmClientListFields(\n 'deals',\n deal as unknown as Record<string, unknown>,\n { ...set, ...Object.fromEntries(clear.map((key) => [key, null])) },\n DEAL_CLIENT_LIST_FIELDS,\n ),\n },\n )\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return\n }\n followUpSharing('deals', [deal.$id])\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 ])\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 inputValue={contactQuery}\n onInputChange={(_event, next, reason) => {\n if (reason !== 'reset') setContactQuery(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 inputValue={companyQuery}\n onInputChange={(_event, next, reason) => {\n if (reason !== 'reset') setCompanyQuery(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","useState","useContactFieldDefinitions","useCrmActivityLogger","useCrmCampaigns","useCrmPicklist","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","crmClientListFields","DEAL_CURRENCIES","openStages","contactChoicesFor","DEAL_NOTES_MAX","DEAL_TITLE_MAX","dealDocumentFromForm","dealFormFromDoc","dealFormProblem","dealPatchFromForm","emptyDealForm","judgeDealFormPicklists","useCrmSharingFollowUp","CONTACT_WINDOW","COMPANY_MATCHES","DEAL_CLIENT_LIST_FIELDS","DealEditDrawer","props","contactChoices","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","update","patch","current","pipeline","find","entry","$id","pipelineId","stages","currentStage","stageId","campaignOptions","options","map","option","value","label","campaignId","some","contactRows","idField","contactQuery","setContactQuery","groupId","row","contactValue","contactId","id","name","contactName","email","choice","companyQuery","setCompanyQuery","companyChoices","setCompanyChoices","key","active","timer","setTimeout","companies","then","snapshot","docs","String","get","catch","clearTimeout","companyValue","companyId","companyName","customMissing","problem","length","join","amountDerived","Boolean","recordsScope","records","bandFull","ready","quota","allowed","handleSave","uid","variant","persist","judged","type","picklist","leadSource","created","ok","error","saved","nowMs","Date","now","verdict","subject","set","clear","stage","deals","Object","fromEntries","message","customDocument","record","title","console","allowDuplicate","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","stored","nextStep","probability","input","endAdornment","forecastCategory","displayEmpty","category","loading","member","inputValue","onInputChange","_event","reason","picked","getOptionLabel","isOptionEqualToValue","filterOptions","renderOption","optionProps","li","lineHeight","noOptionsText","renderInput","params","notes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CAACC,QAAUjH,OAAO;gCAAEiK,OAAOhD,MAAMC,MAAM,CAACnG,KAAK;4BAAC;wBACxDmJ,SAAS;wBACTC,SAAS;wBACT/C,SAAS;wBACTC,WAAW;4BAAEC,WAAW;gCAAEC,WAAW9K;4BAAe;wBAAE;;oBAEvD+C,OAAO6C,MAAM,CAACgB,MAAM,iBACnB;;0CACE,KAACpJ;gCAAWgK,SAAQ;0CAAa;;4BAChCzE,OAAO6C,MAAM,CAACxB,GAAG,CAAC,CAACuJ,2BAClB,KAACrO;oCAECqO,YAAYA;oCACZrJ,OAAOlF,oBAAoBgE,cAAcC,QAAQsK,WAAWhI,GAAG;oCAC/D4E,UAAU,CAACjG,QACThB,UAAU,CAACG,UAAa,aAAKA;gDAAS,CAACkK,WAAWhI,GAAG,CAAC,EAAErB;;oCAE1DyF,UAAUlH;mCANL8K,WAAW9J,GAAG;;yBAUvB;oBACHqD,yBACC,KAACjK;wBAAM2Q,UAAS;kCAAW9R;yBACzB;oBACH6K,WAAWnE,OAAOwG,KAAK,iBAAG,KAAC/L;wBAAM2Q,UAAS;kCAAWjH;yBAAmB;kCACzE,KAACxJ;wBACCqK,SAAQ;wBACRuC,UACElH,QACAkE,QAAQJ,YACR,CAAC5E,SACDmF,YACA,8DAA8D;wBAC9D,sDAAsD;wBACrDxF,SAAS,YAAY,CAACS,aAAayE,MAAM;wBAE5C6C,SAAS,IAAM,KAAKnC;kCAEnBnG,OAAO,cAAc;;;;;;AAMlC;AACAP,eAAeiN,WAAW,GAAG;AAE7B,eAAejN,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} 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;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B,KAACnI;oCAA4BoI,OAAOD,OAAOC,KAAK;8CAC7CD,OAAOE,KAAK;mCADAF,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"}
@@ -88,6 +88,13 @@ export declare function crmSelectField(column: string, path?: string): ListFilte
88
88
  * lead source list, which the caller passes in `context` once it has it.
89
89
  */
90
90
  export declare function crmClientListFields(collection: CrmListCollection, record: Readonly<Record<string, unknown>>, patch: Readonly<Record<string, unknown>>, fields: readonly string[], context?: CrmListFieldsContext): Record<string, unknown>;
91
+ /**
92
+ * {@link crmClientListFields}, less the fields the patch does not move
93
+ * (AGL-4132). For an edit that writes only what the reader changed, which may
94
+ * stand on a read the server has not confirmed: every field left out is one
95
+ * that read does not get to restamp.
96
+ */
97
+ export declare function crmClientListFieldChanges(collection: CrmListCollection, record: Readonly<Record<string, unknown>>, patch: Readonly<Record<string, unknown>>, fields: readonly string[], context?: CrmListFieldsContext): Record<string, unknown>;
91
98
  /** The search fields every CRM record carries — what a client edit of searched text rewrites. */
92
99
  export declare const CRM_CLIENT_SEARCH_FIELDS: readonly ["searchTokens", "scopedSearchTokens"];
93
100
  /**
@@ -174,6 +174,16 @@ const sameClause = (a, b)=>a.field === b.field && a.op === b.op && a.value === b
174
174
  computed[field]
175
175
  ]));
176
176
  }
177
+ /**
178
+ * {@link crmClientListFields}, less the fields the patch does not move
179
+ * (AGL-4132). For an edit that writes only what the reader changed, which may
180
+ * stand on a read the server has not confirmed: every field left out is one
181
+ * that read does not get to restamp.
182
+ */ export function crmClientListFieldChanges(collection, record, patch, fields, context = {}) {
183
+ const before = crmClientListFields(collection, record, {}, fields, context);
184
+ const after = crmClientListFields(collection, record, patch, fields, context);
185
+ return Object.fromEntries(Object.entries(after).filter(([field, value])=>JSON.stringify(value) !== JSON.stringify(before[field])));
186
+ }
177
187
  /** A web-SDK `FieldValue` — `deleteField()`, the one a client edit of these fields sends. */ const isSentinel = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value.isEqual === 'function';
178
188
  /** The search fields every CRM record carries — what a client edit of searched text rewrites. */ export const CRM_CLIENT_SEARCH_FIELDS = [
179
189
  'searchTokens',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-list-query.ts"],"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\nimport {\n CRM_SCOPED_SEARCH_TOKENS_FIELD,\n CRM_SEARCH_TOKENS_FIELD,\n type CrmListCollection,\n type CrmListFieldsContext,\n crmListFields,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { scopedSearch } from '@aglyn/aglyn/app-utils/name-search'\nimport type { ListFilterField, ListFilterRequest } from '@aglyn/shared-util-tools/list-query/list-filter'\nimport type { ListFilterOption } from '@aglyn/shared-util-tools/list-query/list-filter-codecs'\nimport { listQueryRefusals } from '@aglyn/shared-util-tools/list-query/list-query-refusals'\nimport type {\n ListQueryDeclaration,\n ListQueryFilter,\n ListQueryPlan,\n} from '@aglyn/shared-util-tools/list-query/list-query-plan'\n\n/*\n * THE CRM LISTS ON THEIR QUERIES (AGL-3321).\n *\n * Every CRM list — Leads, Contacts, Companies, Deals, Tasks — declares its\n * filterable fields, its one order and its search as a\n * `ListQueryDeclaration`, and `planListQuery` puts every clause and the\n * search word on ONE Firestore query paged by `useListQuery`. What a query\n * cannot hold is refused by name (`ListQueryNotices`), never matched over\n * the rows a page happened to load.\n *\n * This module is what the five share: the search every CRM record carries\n * (`searchTokens`, and `scopedSearchTokens` under a site — see\n * `crmListFields` in `@aglyn/aglyn`), the scope clause as the plan's base,\n * a stored clause translated to the one its query asks, and the refusals\n * read back through the clause the reader set.\n */\n\n/** Every CRM list's quick search: the tokens every writer stamps. */\nexport const CRM_LIST_SEARCH: NonNullable<ListQueryDeclaration['search']> = {\n tokensPath: CRM_SEARCH_TOKENS_FIELD,\n scoped: scopedSearch(CRM_SCOPED_SEARCH_TOKENS_FIELD),\n}\n\n/**\n * The scope clause as the plan's base: `visibleTo array-contains-any` over\n * the reader's tokens under a site, nothing at the organization level\n * (`null` tokens), where an org-wide member's listeners carry none.\n */\nexport function crmListBase(visibleTo: readonly string[] | null): ListQueryFilter[] {\n return visibleTo ? [{ path: 'visibleTo', op: 'array-contains-any', value: [...visibleTo] }] : []\n}\n\n/** The base's shape, for `listQueryIndexes`: the scope clause is an array clause. */\nexport const CRM_LIST_BASE_INDEX = [{ path: 'visibleTo', array: true }] as const\n\n/**\n * The declaration a reader may run.\n *\n * Under a site the search folds into the scope clause (`search.scoped`),\n * and a query without `visibleTo` is one the rules can prove only for an\n * ORG-WIDE member — `canReadScoped()` short-circuits on it, and for anybody\n * else inspects `visibleTo`, which the folded query no longer constrains.\n * A member whose reach is some sites keeps the scope clause, and the plan\n * refuses their search by name rather than sending a query the rules deny.\n */\nexport function crmListDeclarationFor(\n declaration: ListQueryDeclaration,\n foldsScope: boolean,\n): ListQueryDeclaration {\n if (foldsScope || !declaration.search?.scoped) return declaration\n return { ...declaration, search: { tokensPath: declaration.search.tokensPath } }\n}\n\n/*------------------------------------------\n * WHAT A LIST STORES, AND WHAT IT ASKS.\n *\n * A saved view stores clauses in the grid's grammar — \"Status is Open\",\n * \"Owner is Dana\", \"Lead source is none\" — and some of them name no stored\n * field one query can ask as it is: Open is two statuses, an owner under a\n * site is that holder's facet key, a lead source is compared by its key. A\n * list translates each stored clause into the clause its query asks, plans\n * those, and reads the plan's refusals back through the stored clause, so\n * the notice names what the reader set (\"Status is Open is not applied\")\n * and never the field it was translated to.\n *-----------------------------------------*/\n\n/** How one stored clause is asked: a query clause, or why it cannot be. */\nexport type CrmClauseAsked = ListFilterRequest | { refused: string }\n\nexport interface CrmAskedClauses {\n /** What the plan is asked, in the order the reader set them. */\n clauses: ListFilterRequest[]\n /** The stored clause each asked one stands for, index for index. */\n origins: ListFilterRequest[]\n /** Stored clauses refused before the plan saw them, with why. */\n refused: Array<{ clause: ListFilterRequest; reason: string }>\n}\n\n/** Every stored clause through `ask`, keeping where each came from. */\nexport function crmAskClauses(\n stored: readonly ListFilterRequest[],\n ask: (clause: ListFilterRequest) => CrmClauseAsked,\n): CrmAskedClauses {\n const clauses: ListFilterRequest[] = []\n const origins: ListFilterRequest[] = []\n const refused: CrmAskedClauses['refused'] = []\n for (const clause of stored) {\n const asked = ask(clause)\n if ('refused' in asked) {\n refused.push({ clause, reason: asked.refused })\n } else {\n clauses.push(asked)\n origins.push(clause)\n }\n }\n return { clauses, origins, refused }\n}\n\nconst sameClause = (a: ListFilterRequest, b: ListFilterRequest): boolean =>\n a.field === b.field && a.op === b.op && a.value === b.value\n\n/**\n * The plan's refusals and the translation's, each named by the clause the\n * reader SET, as `ListQueryNotices` takes them — through the platform's one\n * wording (`listQueryRefusals`), so a notice and its chip read alike.\n */\nexport function crmQueryRefusals(\n plan: Pick<ListQueryPlan, 'refused'>,\n asked: CrmAskedClauses,\n context: {\n fields: readonly ListFilterField[]\n headers?: Readonly<Record<string, string>>\n options?: Readonly<Record<string, readonly ListFilterOption[]>>\n },\n): Array<{ label: string; reason: string }> {\n const planned = plan.refused.map((entry) => {\n if (entry.clause === 'search') return entry\n const clause = entry.clause\n const at = asked.clauses.findIndex((candidate) => sameClause(candidate, clause))\n return { clause: at >= 0 ? asked.origins[at] : clause, reason: entry.reason }\n })\n return listQueryRefusals([...asked.refused, ...planned], context)\n}\n\n/** The comma-separated values of an `isAnyOf`, or the one value of anything else. */\nexport function crmClauseValues(clause: Pick<ListFilterRequest, 'op' | 'value'>): string[] {\n const raw = clause.op === 'isAnyOf' ? clause.value.split(',') : [clause.value]\n return [...new Set(raw.map((value) => value.trim()).filter(Boolean))]\n}\n\n/** One value as `equals`, several as `isAnyOf` — the shape the plan takes a list in. */\nexport function crmAnyOf(field: string, values: readonly string[]): CrmClauseAsked {\n const unique = [...new Set(values)]\n if (!unique.length) return { refused: 'no value yet' }\n return unique.length === 1\n ? { field, op: 'equals', value: unique[0] }\n : { field, op: 'isAnyOf', value: unique.join(',') }\n}\n\n/** A `select` field: equality and \"any of\" over stored values, nothing else. */\nexport function crmSelectField(column: string, path: string = column): ListFilterField {\n return { column, kind: 'exact', path, operators: ['equals', 'isAnyOf'] }\n}\n\n/**\n * The list fields a CLIENT edit writes beside its patch (AGL-3321): the\n * record as the listener holds it with the patch laid over — a `null` or a\n * sentinel in the patch reads as the field removed — through\n * `crmListFields`, narrowed to `fields`. A client never writes a field the\n * rules keep for the server (a lead's `emailStatus`), which is why the\n * caller names the ones it may. A lead's direction is read off the org's\n * lead source list, which the caller passes in `context` once it has it.\n */\nexport function crmClientListFields(\n collection: CrmListCollection,\n record: Readonly<Record<string, unknown>>,\n patch: Readonly<Record<string, unknown>>,\n fields: readonly string[],\n context: CrmListFieldsContext = {},\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...record }\n for (const [key, value] of Object.entries(patch)) {\n // A dotted path is a map entry (`custom.tier`), never a searched field.\n if (key.includes('.')) continue\n merged[key] = value === null || isSentinel(value) ? undefined : value\n }\n const computed = crmListFields(collection, merged, context)\n return Object.fromEntries(fields.filter((field) => field in computed).map((field) => [field, computed[field]]))\n}\n\n/** A web-SDK `FieldValue` — `deleteField()`, the one a client edit of these fields sends. */\nconst isSentinel = (value: unknown): boolean =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n typeof (value as { isEqual?: unknown }).isEqual === 'function'\n\n/** The search fields every CRM record carries — what a client edit of searched text rewrites. */\nexport const CRM_CLIENT_SEARCH_FIELDS = ['searchTokens', 'scopedSearchTokens'] as const\n\n/**\n * The header sort keys a client edit of their inputs rewrites (AGL-3680) —\n * see `crmSortKey` in `@aglyn/aglyn`. `crmClientListFields` writes only the\n * ones the collection computes, so one list serves every edit.\n */\nexport const CRM_CLIENT_SORT_FIELDS = [\n 'nameSortKey',\n 'companyLower',\n 'jobTitleLower',\n 'titleLower',\n 'amountSortCents',\n 'expectedCloseSortAtMs',\n 'priorityRank',\n] as const\n\n\n/**\n * The list fields a deal's contact roles are found by (AGL-3521) — what a\n * client write of `contactRoles` or `contactId` rewrites beside them.\n */\nexport const CRM_DEAL_CONTACT_ROLE_LIST_FIELDS = [\n 'contactRoleContactIds',\n 'scopedContactRoleContactIds',\n 'contactRoleKeys',\n] as const\n"],"names":["CRM_SCOPED_SEARCH_TOKENS_FIELD","CRM_SEARCH_TOKENS_FIELD","crmListFields","scopedSearch","listQueryRefusals","CRM_LIST_SEARCH","tokensPath","scoped","crmListBase","visibleTo","path","op","value","CRM_LIST_BASE_INDEX","array","crmListDeclarationFor","declaration","foldsScope","search","crmAskClauses","stored","ask","clauses","origins","refused","clause","asked","push","reason","sameClause","a","b","field","crmQueryRefusals","plan","context","planned","map","entry","at","findIndex","candidate","crmClauseValues","raw","split","Set","trim","filter","Boolean","crmAnyOf","values","unique","length","join","crmSelectField","column","kind","operators","crmClientListFields","collection","record","patch","fields","merged","key","Object","entries","includes","isSentinel","undefined","computed","fromEntries","Array","isArray","Date","isEqual","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,uBAAuB,EAGvBC,aAAa,QACR,6BAA4B;AACnC,SAASC,YAAY,QAAQ,qCAAoC;AAGjE,SAASC,iBAAiB,QAAQ,0DAAyD;AAO3F;;;;;;;;;;;;;;;CAeC,GAED,mEAAmE,GACnE,OAAO,MAAMC,kBAA+D;IAC1EC,YAAYL;IACZM,QAAQJ,aAAaH;AACvB,EAAC;AAED;;;;CAIC,GACD,OAAO,SAASQ,YAAYC,SAAmC;IAC7D,OAAOA,YAAY;QAAC;YAAEC,MAAM;YAAaC,IAAI;YAAsBC,OAAO;mBAAIH;aAAU;QAAC;KAAE,GAAG,EAAE;AAClG;AAEA,mFAAmF,GACnF,OAAO,MAAMI,sBAAsB;IAAC;QAAEH,MAAM;Q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xD,SAASyD,YAAYzD;IAClE;IACA,MAAM0D,WAAWpE,cAAcyD,YAAYI,QAAQ5B;IACnD,OAAO8B,OAAOM,WAAW,CAACT,OAAOf,MAAM,CAAC,CAACf,QAAUA,SAASsC,UAAUjC,GAAG,CAAC,CAACL,QAAU;YAACA;YAAOsC,QAAQ,CAACtC,MAAM;SAAC;AAC/G;AAEA,2FAA2F,GAC3F,MAAMoC,aAAa,CAACxD,QAClB,OAAOA,UAAU,YACjBA,UAAU,QACV,CAAC4D,MAAMC,OAAO,CAAC7D,UACf,CAAEA,CAAAA,iBAAiB8D,IAAG,KACtB,OAAO,AAAC9D,MAAgC+D,OAAO,KAAK;AAEtD,+FAA+F,GAC/F,OAAO,MAAMC,2BAA2B;IAAC;IAAgB;CAAqB,CAAS;AAEvF;;;;CAIC,GACD,OAAO,MAAMC,yBAAyB;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAGV;;;CAGC,GACD,OAAO,MAAMC,oCAAoC;IAC/C;IACA;IACA;CACD,CAAS"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-list-query.ts"],"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\nimport {\n CRM_SCOPED_SEARCH_TOKENS_FIELD,\n CRM_SEARCH_TOKENS_FIELD,\n type CrmListCollection,\n type CrmListFieldsContext,\n crmListFields,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { scopedSearch } from '@aglyn/aglyn/app-utils/name-search'\nimport type { ListFilterField, ListFilterRequest } from '@aglyn/shared-util-tools/list-query/list-filter'\nimport type { ListFilterOption } from '@aglyn/shared-util-tools/list-query/list-filter-codecs'\nimport { listQueryRefusals } from '@aglyn/shared-util-tools/list-query/list-query-refusals'\nimport type {\n ListQueryDeclaration,\n ListQueryFilter,\n ListQueryPlan,\n} from '@aglyn/shared-util-tools/list-query/list-query-plan'\n\n/*\n * THE CRM LISTS ON THEIR QUERIES (AGL-3321).\n *\n * Every CRM list — Leads, Contacts, Companies, Deals, Tasks — declares its\n * filterable fields, its one order and its search as a\n * `ListQueryDeclaration`, and `planListQuery` puts every clause and the\n * search word on ONE Firestore query paged by `useListQuery`. What a query\n * cannot hold is refused by name (`ListQueryNotices`), never matched over\n * the rows a page happened to load.\n *\n * This module is what the five share: the search every CRM record carries\n * (`searchTokens`, and `scopedSearchTokens` under a site — see\n * `crmListFields` in `@aglyn/aglyn`), the scope clause as the plan's base,\n * a stored clause translated to the one its query asks, and the refusals\n * read back through the clause the reader set.\n */\n\n/** Every CRM list's quick search: the tokens every writer stamps. */\nexport const CRM_LIST_SEARCH: NonNullable<ListQueryDeclaration['search']> = {\n tokensPath: CRM_SEARCH_TOKENS_FIELD,\n scoped: scopedSearch(CRM_SCOPED_SEARCH_TOKENS_FIELD),\n}\n\n/**\n * The scope clause as the plan's base: `visibleTo array-contains-any` over\n * the reader's tokens under a site, nothing at the organization level\n * (`null` tokens), where an org-wide member's listeners carry none.\n */\nexport function crmListBase(visibleTo: readonly string[] | null): ListQueryFilter[] {\n return visibleTo ? [{ path: 'visibleTo', op: 'array-contains-any', value: [...visibleTo] }] : []\n}\n\n/** The base's shape, for `listQueryIndexes`: the scope clause is an array clause. */\nexport const CRM_LIST_BASE_INDEX = [{ path: 'visibleTo', array: true }] as const\n\n/**\n * The declaration a reader may run.\n *\n * Under a site the search folds into the scope clause (`search.scoped`),\n * and a query without `visibleTo` is one the rules can prove only for an\n * ORG-WIDE member — `canReadScoped()` short-circuits on it, and for anybody\n * else inspects `visibleTo`, which the folded query no longer constrains.\n * A member whose reach is some sites keeps the scope clause, and the plan\n * refuses their search by name rather than sending a query the rules deny.\n */\nexport function crmListDeclarationFor(\n declaration: ListQueryDeclaration,\n foldsScope: boolean,\n): ListQueryDeclaration {\n if (foldsScope || !declaration.search?.scoped) return declaration\n return { ...declaration, search: { tokensPath: declaration.search.tokensPath } }\n}\n\n/*------------------------------------------\n * WHAT A LIST STORES, AND WHAT IT ASKS.\n *\n * A saved view stores clauses in the grid's grammar — \"Status is Open\",\n * \"Owner is Dana\", \"Lead source is none\" — and some of them name no stored\n * field one query can ask as it is: Open is two statuses, an owner under a\n * site is that holder's facet key, a lead source is compared by its key. A\n * list translates each stored clause into the clause its query asks, plans\n * those, and reads the plan's refusals back through the stored clause, so\n * the notice names what the reader set (\"Status is Open is not applied\")\n * and never the field it was translated to.\n *-----------------------------------------*/\n\n/** How one stored clause is asked: a query clause, or why it cannot be. */\nexport type CrmClauseAsked = ListFilterRequest | { refused: string }\n\nexport interface CrmAskedClauses {\n /** What the plan is asked, in the order the reader set them. */\n clauses: ListFilterRequest[]\n /** The stored clause each asked one stands for, index for index. */\n origins: ListFilterRequest[]\n /** Stored clauses refused before the plan saw them, with why. */\n refused: Array<{ clause: ListFilterRequest; reason: string }>\n}\n\n/** Every stored clause through `ask`, keeping where each came from. */\nexport function crmAskClauses(\n stored: readonly ListFilterRequest[],\n ask: (clause: ListFilterRequest) => CrmClauseAsked,\n): CrmAskedClauses {\n const clauses: ListFilterRequest[] = []\n const origins: ListFilterRequest[] = []\n const refused: CrmAskedClauses['refused'] = []\n for (const clause of stored) {\n const asked = ask(clause)\n if ('refused' in asked) {\n refused.push({ clause, reason: asked.refused })\n } else {\n clauses.push(asked)\n origins.push(clause)\n }\n }\n return { clauses, origins, refused }\n}\n\nconst sameClause = (a: ListFilterRequest, b: ListFilterRequest): boolean =>\n a.field === b.field && a.op === b.op && a.value === b.value\n\n/**\n * The plan's refusals and the translation's, each named by the clause the\n * reader SET, as `ListQueryNotices` takes them — through the platform's one\n * wording (`listQueryRefusals`), so a notice and its chip read alike.\n */\nexport function crmQueryRefusals(\n plan: Pick<ListQueryPlan, 'refused'>,\n asked: CrmAskedClauses,\n context: {\n fields: readonly ListFilterField[]\n headers?: Readonly<Record<string, string>>\n options?: Readonly<Record<string, readonly ListFilterOption[]>>\n },\n): Array<{ label: string; reason: string }> {\n const planned = plan.refused.map((entry) => {\n if (entry.clause === 'search') return entry\n const clause = entry.clause\n const at = asked.clauses.findIndex((candidate) => sameClause(candidate, clause))\n return { clause: at >= 0 ? asked.origins[at] : clause, reason: entry.reason }\n })\n return listQueryRefusals([...asked.refused, ...planned], context)\n}\n\n/** The comma-separated values of an `isAnyOf`, or the one value of anything else. */\nexport function crmClauseValues(clause: Pick<ListFilterRequest, 'op' | 'value'>): string[] {\n const raw = clause.op === 'isAnyOf' ? clause.value.split(',') : [clause.value]\n return [...new Set(raw.map((value) => value.trim()).filter(Boolean))]\n}\n\n/** One value as `equals`, several as `isAnyOf` — the shape the plan takes a list in. */\nexport function crmAnyOf(field: string, values: readonly string[]): CrmClauseAsked {\n const unique = [...new Set(values)]\n if (!unique.length) return { refused: 'no value yet' }\n return unique.length === 1\n ? { field, op: 'equals', value: unique[0] }\n : { field, op: 'isAnyOf', value: unique.join(',') }\n}\n\n/** A `select` field: equality and \"any of\" over stored values, nothing else. */\nexport function crmSelectField(column: string, path: string = column): ListFilterField {\n return { column, kind: 'exact', path, operators: ['equals', 'isAnyOf'] }\n}\n\n/**\n * The list fields a CLIENT edit writes beside its patch (AGL-3321): the\n * record as the listener holds it with the patch laid over — a `null` or a\n * sentinel in the patch reads as the field removed — through\n * `crmListFields`, narrowed to `fields`. A client never writes a field the\n * rules keep for the server (a lead's `emailStatus`), which is why the\n * caller names the ones it may. A lead's direction is read off the org's\n * lead source list, which the caller passes in `context` once it has it.\n */\nexport function crmClientListFields(\n collection: CrmListCollection,\n record: Readonly<Record<string, unknown>>,\n patch: Readonly<Record<string, unknown>>,\n fields: readonly string[],\n context: CrmListFieldsContext = {},\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...record }\n for (const [key, value] of Object.entries(patch)) {\n // A dotted path is a map entry (`custom.tier`), never a searched field.\n if (key.includes('.')) continue\n merged[key] = value === null || isSentinel(value) ? undefined : value\n }\n const computed = crmListFields(collection, merged, context)\n return Object.fromEntries(fields.filter((field) => field in computed).map((field) => [field, computed[field]]))\n}\n\n/**\n * {@link crmClientListFields}, less the fields the patch does not move\n * (AGL-4132). For an edit that writes only what the reader changed, which may\n * stand on a read the server has not confirmed: every field left out is one\n * that read does not get to restamp.\n */\nexport function crmClientListFieldChanges(\n collection: CrmListCollection,\n record: Readonly<Record<string, unknown>>,\n patch: Readonly<Record<string, unknown>>,\n fields: readonly string[],\n context: CrmListFieldsContext = {},\n): Record<string, unknown> {\n const before = crmClientListFields(collection, record, {}, fields, context)\n const after = crmClientListFields(collection, record, patch, fields, context)\n return Object.fromEntries(\n Object.entries(after).filter(\n ([field, value]) => JSON.stringify(value) !== JSON.stringify(before[field]),\n ),\n )\n}\n\n/** A web-SDK `FieldValue` — `deleteField()`, the one a client edit of these fields sends. */\nconst isSentinel = (value: unknown): boolean =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n typeof (value as { isEqual?: unknown }).isEqual === 'function'\n\n/** The search fields every CRM record carries — what a client edit of searched text rewrites. */\nexport const CRM_CLIENT_SEARCH_FIELDS = ['searchTokens', 'scopedSearchTokens'] as const\n\n/**\n * The header sort keys a client edit of their inputs rewrites (AGL-3680) —\n * see `crmSortKey` in `@aglyn/aglyn`. `crmClientListFields` writes only the\n * ones the collection computes, so one list serves every edit.\n */\nexport const CRM_CLIENT_SORT_FIELDS = [\n 'nameSortKey',\n 'companyLower',\n 'jobTitleLower',\n 'titleLower',\n 'amountSortCents',\n 'expectedCloseSortAtMs',\n 'priorityRank',\n] as const\n\n\n/**\n * The list fields a deal's contact roles are found by (AGL-3521) — what a\n * client write of `contactRoles` or `contactId` rewrites beside them.\n */\nexport const CRM_DEAL_CONTACT_ROLE_LIST_FIELDS = [\n 'contactRoleContactIds',\n 'scopedContactRoleContactIds',\n 'contactRoleKeys',\n] as const\n"],"names":["CRM_SCOPED_SEARCH_TOKENS_FIELD","CRM_SEARCH_TOKENS_FIELD","crmListFields","scopedSearch","listQueryRefusals","CRM_LIST_SEARCH","tokensPath","scoped","crmListBase","visibleTo","path","op","value","CRM_LIST_BASE_INDEX","array","crmListDeclarationFor","declaration","foldsScope","search","crmAskClauses","stored","ask","clauses","origins","refused","clause","asked","push","reason","sameClause","a","b","field","crmQueryRefusals","plan","context","planned","map","entry","at","findIndex","candidate","crmClauseValues","raw","split","Set","trim","filter","Boolean","crmAnyOf","values","unique","length","join","crmSelectField","column","kind","operators","crmClientListFields","collection","record","patch","fields","merged","key","Object","entries","includes","isSentinel","undefined","computed","fromEntries","crmClientListFieldChanges","before","after","JSON","stringify","Array","isArray","Date","isEqual","CRM_CLIENT_SEARCH_FIELDS","CRM_CLIENT_SORT_FIELDS","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,uBAAuB,EAGvBC,aAAa,QACR,6BAA4B;AACnC,SAASC,YAAY,QAAQ,qCAAoC;AAGjE,SAASC,iBAAiB,QAAQ,0DAAyD;AAO3F;;;;;;;;;;;;;;;CAeC,GAED,mEAAmE,GACnE,OAAO,MAAMC,kBAA+D;IAC1EC,YAAYL;IACZM,QAAQJ,aAAaH;AACvB,EAAC;AAED;;;;CAIC,GACD,OAAO,SAASQ,YAAYC,SAAmC;IAC7D,OAAOA,YAAY;QAAC;YAAEC,MAAM;YAAaC,IAAI;YAAsBC,OAAO;mBAAIH;aAAU;QAAC;KAAE,GAAG,EAAE;AAClG;AAEA,mFAAmF,GACnF,OAAO,MAAMI,sBAAsB;IAAC;QAAEH,MAAM;QAAaI,OAAO;IAAK;CAAE,CAAS;AAEhF;;;;;;;;;CASC,GACD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YAAYI,QAAQ5B;IACnD,OAAO8B,OAAOM,WAAW,CAACT,OAAOf,MAAM,CAAC,CAACf,QAAUA,SAASsC,UAAUjC,GAAG,CAAC,CAACL,QAAU;YAACA;YAAOsC,QAAQ,CAACtC,MAAM;SAAC;AAC/G;AAEA;;;;;CAKC,GACD,OAAO,SAASwC,0BACdb,UAA6B,EAC7BC,MAAyC,EACzCC,KAAwC,EACxCC,MAAyB,EACzB3B,UAAgC,CAAC,CAAC;IAElC,MAAMsC,SAASf,oBAAoBC,YAAYC,QAAQ,CAAC,GAAGE,QAAQ3B;IACnE,MAAMuC,QAAQhB,oBAAoBC,YAAYC,QAAQC,OAAOC,QAAQ3B;IACrE,OAAO8B,OAAOM,WAAW,CACvBN,OAAOC,OAAO,CAACQ,OAAO3B,MAAM,CAC1B,CAAC,CAACf,OAAOpB,MAAM,GAAK+D,KAAKC,SAAS,CAAChE,WAAW+D,KAAKC,SAAS,CAACH,MAAM,CAACzC,MAAM;AAGhF;AAEA,2FAA2F,GAC3F,MAAMoC,aAAa,CAACxD,QAClB,OAAOA,UAAU,YACjBA,UAAU,QACV,CAACiE,MAAMC,OAAO,CAAClE,UACf,CAAEA,CAAAA,iBAAiBmE,IAAG,KACtB,OAAO,AAACnE,MAAgCoE,OAAO,KAAK;AAEtD,+FAA+F,GAC/F,OAAO,MAAMC,2BAA2B;IAAC;IAAgB;CAAqB,CAAS;AAEvF;;;;CAIC,GACD,OAAO,MAAMC,yBAAyB;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAGV;;;CAGC,GACD,OAAO,MAAMC,oCAAoC;IAC/C;IACA;IACA;CACD,CAAS"}
@@ -141,6 +141,41 @@ export declare function dealPatchFromForm(values: DealFormValues, nowMs: number,
141
141
  set: Record<string, unknown>;
142
142
  clear: string[];
143
143
  };
144
+ /** What {@link dealEditFromForm} found the reader changed. */
145
+ export interface DealEdit {
146
+ set: Record<string, unknown>;
147
+ clear: string[];
148
+ }
149
+ /**
150
+ * The stored deal moved while the form was open (AGL-4132): the fields the
151
+ * reader has not touched follow it, and the ones they have stay as typed.
152
+ *
153
+ * A listener hands over a new object for every snapshot, a confirmation of
154
+ * unchanged data included, so a form rebuilt from each one loses whatever was
155
+ * typed the moment the server answers.
156
+ */
157
+ export declare function rebaseDealForm(current: DealFormValues, seed: DealFormValues, stored: DealFormValues): DealFormValues;
158
+ /**
159
+ * The write a save makes on an existing deal: {@link dealPatchFromForm},
160
+ * narrowed to the fields the reader changed from `seed`, with no `updatedAt`
161
+ * so a caller can tell an edit from nothing at all (AGL-4132).
162
+ *
163
+ * The narrowing is what protects the deal. A patch of every field sent from a
164
+ * read the server has not confirmed writes that read back over the document,
165
+ * and one that held no `contactId` deletes the link. This one cannot touch a
166
+ * field the reader left alone, however old the read behind the form.
167
+ */
168
+ export declare function dealEditFromForm(values: DealFormValues, seed: DealFormValues, nowMs: number, options?: Parameters<typeof dealPatchFromForm>[2]): DealEdit;
169
+ /**
170
+ * Whether an edit can only be trusted on a read the server has confirmed
171
+ * (AGL-4132).
172
+ *
173
+ * The contact roles are the stored list with the Primary moved, so writing
174
+ * them from an old read takes out a role added since. The amount and the
175
+ * currency are the form's only while the deal has no line items, which the
176
+ * read is what says. Everything else in an edit is a value the reader typed.
177
+ */
178
+ export declare function dealEditNeedsConfirmedRead(edit: DealEdit): boolean;
144
179
  /** A contact as the picker offers it. */
145
180
  export interface ContactChoice {
146
181
  id: string;
@@ -248,6 +248,109 @@ export const DEAL_NOTES_MAX = 4000;
248
248
  clear
249
249
  };
250
250
  }
251
+ /** The document fields each form field writes. A blank list writes nothing on an edit. */ const DEAL_FORM_FIELD_WRITES = {
252
+ title: [
253
+ 'title',
254
+ 'titleLower'
255
+ ],
256
+ pipelineId: [],
257
+ stageId: [],
258
+ amount: [
259
+ 'amountCents'
260
+ ],
261
+ currency: [
262
+ 'currency'
263
+ ],
264
+ expectedClose: [
265
+ 'expectedCloseAtMs'
266
+ ],
267
+ ownerUid: [
268
+ 'ownerUid'
269
+ ],
270
+ contactId: [
271
+ 'contactId',
272
+ 'contactName',
273
+ 'contactRoles'
274
+ ],
275
+ contactName: [
276
+ 'contactName'
277
+ ],
278
+ companyId: [
279
+ 'companyId',
280
+ 'companyName'
281
+ ],
282
+ companyName: [
283
+ 'companyName'
284
+ ],
285
+ notes: [
286
+ 'notes'
287
+ ],
288
+ type: [
289
+ 'type'
290
+ ],
291
+ leadSource: [
292
+ 'leadSource'
293
+ ],
294
+ nextStep: [
295
+ 'nextStep'
296
+ ],
297
+ probability: [
298
+ 'probability'
299
+ ],
300
+ forecastCategory: [
301
+ 'forecastCategory'
302
+ ],
303
+ campaignId: [
304
+ 'campaignId'
305
+ ]
306
+ };
307
+ const DEAL_FORM_FIELDS = Object.keys(DEAL_FORM_FIELD_WRITES);
308
+ /**
309
+ * The stored deal moved while the form was open (AGL-4132): the fields the
310
+ * reader has not touched follow it, and the ones they have stay as typed.
311
+ *
312
+ * A listener hands over a new object for every snapshot, a confirmation of
313
+ * unchanged data included, so a form rebuilt from each one loses whatever was
314
+ * typed the moment the server answers.
315
+ */ export function rebaseDealForm(current, seed, stored) {
316
+ return Object.fromEntries(DEAL_FORM_FIELDS.map((field)=>[
317
+ field,
318
+ current[field] === seed[field] ? stored[field] : current[field]
319
+ ]));
320
+ }
321
+ /**
322
+ * The write a save makes on an existing deal: {@link dealPatchFromForm},
323
+ * narrowed to the fields the reader changed from `seed`, with no `updatedAt`
324
+ * so a caller can tell an edit from nothing at all (AGL-4132).
325
+ *
326
+ * The narrowing is what protects the deal. A patch of every field sent from a
327
+ * read the server has not confirmed writes that read back over the document,
328
+ * and one that held no `contactId` deletes the link. This one cannot touch a
329
+ * field the reader left alone, however old the read behind the form.
330
+ */ export function dealEditFromForm(values, seed, nowMs, options = {}) {
331
+ const { set, clear } = dealPatchFromForm(values, nowMs, options);
332
+ const changed = new Set(DEAL_FORM_FIELDS.filter((field)=>values[field] !== seed[field]).flatMap((field)=>DEAL_FORM_FIELD_WRITES[field]));
333
+ return {
334
+ set: Object.fromEntries(Object.entries(set).filter(([key])=>changed.has(key))),
335
+ clear: clear.filter((key)=>changed.has(key))
336
+ };
337
+ }
338
+ /** The fields an edit works out from the stored deal rather than takes as typed. */ const DEAL_EDIT_FIELDS_FROM_THE_READ = [
339
+ 'contactRoles',
340
+ 'amountCents',
341
+ 'currency'
342
+ ];
343
+ /**
344
+ * Whether an edit can only be trusted on a read the server has confirmed
345
+ * (AGL-4132).
346
+ *
347
+ * The contact roles are the stored list with the Primary moved, so writing
348
+ * them from an old read takes out a role added since. The amount and the
349
+ * currency are the form's only while the deal has no line items, which the
350
+ * read is what says. Everything else in an edit is a value the reader typed.
351
+ */ export function dealEditNeedsConfirmedRead(edit) {
352
+ return DEAL_EDIT_FIELDS_FROM_THE_READ.some((field)=>field in edit.set || edit.clear.includes(field));
353
+ }
251
354
  /**
252
355
  * The contacts a typed query matches, from a window of recent contact rows,
253
356
  * in the list's own grammar.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deal-form-model.ts"],"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/**\n * The deal drawer's values and the documents they become (AGL-2598), as pure\n * functions — the drawer holds strings the way inputs do, and this module is\n * the one place those strings turn into the typed fields a `CrmDeal` stores.\n * Kept out of the component so the translation can be tested without a\n * Firestore or a DOM, and so the contact card and the company card, which\n * open the same drawer with a link preselected, build a deal the same way.\n */\n\nimport {\n contactDisplayName,\n type CrmDeal,\n type CrmDealStage,\n type CrmForecastCategory,\n type CrmPicklist,\n crmPicklistDefaultLabel,\n DEAL_NEXT_STEP_MAX,\n dealContactRolesOf,\n dealContactRolesWithPrimary,\n dealStageForecastCategory,\n isCrmForecastCategory,\n judgeCrmPicklistValue,\n nameSearchKey,\n nameSearchToken,\n readDealProbability,\n} from '@aglyn/aglyn'\nimport {\n amountInputValue,\n dateInputMs,\n dateInputValue,\n DEFAULT_DEAL_CURRENCY,\n type DealDoc,\n openStages,\n parseAmountInput,\n type PipelineDoc,\n} from './deal-board-model'\n\n/** What the drawer edits — strings as the inputs hold them. */\nexport interface DealFormValues {\n title: string\n pipelineId: string\n stageId: string\n /** As typed: `1,250.00`; parsed at save. */\n amount: string\n currency: string\n /** `YYYY-MM-DD` from a date input, or empty. */\n expectedClose: string\n ownerUid: string\n contactId: string\n contactName: string\n companyId: string\n companyName: string\n notes: string\n /*\n * Salesforce's Opportunity fields (AGL-3516).\n */\n /** The `opportunityType` label, or empty. */\n type: string\n /** The `leadSource` label, or empty. */\n leadSource: string\n nextStep: string\n /** The override as typed, `35`; empty means the stage's. */\n probability: string\n /** Empty means the stage's — what a save stamps when nobody picked one. */\n forecastCategory: '' | CrmForecastCategory\n /** One of the org's campaigns, or empty. */\n campaignId: string\n}\n\nexport const DEAL_TITLE_MAX = 120\nexport const DEAL_NOTES_MAX = 4000\n\n/**\n * A blank form aimed at a pipeline's first open stage.\n *\n * `defaults` is how a contact's page or a company's page starts a deal\n * already linked to itself: the caller passes the ids and names it knows and\n * the drawer opens with those fields filled. Anything it does not pass stays\n * blank rather than being guessed.\n */\nexport function emptyDealForm(\n pipeline: Pick<PipelineDoc, '$id' | 'stages'> | null | undefined,\n defaults: Partial<DealFormValues> = {},\n): DealFormValues {\n const firstOpen = openStages(pipeline)[0]\n return {\n title: '',\n pipelineId: pipeline?.$id ?? '',\n stageId: firstOpen?.id ?? '',\n amount: '',\n currency: DEFAULT_DEAL_CURRENCY,\n expectedClose: '',\n ownerUid: '',\n contactId: '',\n contactName: '',\n companyId: '',\n companyName: '',\n notes: '',\n type: '',\n leadSource: '',\n nextStep: '',\n probability: '',\n forecastCategory: '',\n campaignId: '',\n ...defaults,\n }\n}\n\n/** The form an existing deal opens as. */\nexport function dealFormFromDoc(deal: DealDoc): DealFormValues {\n return {\n title: String(deal.title ?? ''),\n pipelineId: String(deal.pipelineId ?? ''),\n stageId: String(deal.stageId ?? ''),\n amount: amountInputValue(deal.amountCents),\n currency: String(deal.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n expectedClose: dateInputValue(deal.expectedCloseAtMs),\n ownerUid: String(deal.ownerUid ?? ''),\n contactId: String(deal.contactId ?? ''),\n contactName: String(deal.contactName ?? ''),\n companyId: String(deal.companyId ?? ''),\n companyName: String(deal.companyName ?? ''),\n notes: String(deal.notes ?? ''),\n type: String(deal.type ?? ''),\n leadSource: String(deal.leadSource ?? ''),\n nextStep: String(deal.nextStep ?? ''),\n probability: typeof deal.probability === 'number' ? String(deal.probability) : '',\n forecastCategory: isCrmForecastCategory(deal.forecastCategory) ? deal.forecastCategory : '',\n campaignId: String(deal.campaignId ?? ''),\n }\n}\n\n/**\n * Why the form cannot be saved, or `null` when it can.\n *\n * A title is the one thing a deal needs — a card with no title is a card\n * nobody can find on the board. The amount is optional but, if typed, has to\n * parse: a deal saved with an amount the merchant typed and the model dropped\n * would forecast at zero without saying so. The stage is only checked on a\n * new deal, because an existing deal's stage is moved by the stage route and\n * is not this form's to write.\n */\nexport function dealFormProblem(\n values: DealFormValues,\n mode: 'create' | 'edit',\n): string | null {\n if (!values.title.trim()) return 'A deal needs a title.'\n if (values.amount.trim() && parseAmountInput(values.amount) === null) {\n return 'The amount has to be a number of zero or more.'\n }\n if (values.expectedClose.trim() && dateInputMs(values.expectedClose) === null) {\n return 'The expected close has to be a date.'\n }\n if (readDealProbability(values.probability) === undefined) {\n return 'The probability has to be a whole number from 0 to 100.'\n }\n if (mode === 'create' && (!values.pipelineId || !values.stageId)) {\n return 'Pick the stage the deal starts in.'\n }\n return null\n}\n\n/** What every deal write stamps besides the fields the form edits. */\nexport interface DealWriteContext {\n visibleTo: string[]\n hostId: string\n uid: string\n nowMs: number\n /**\n * The stage the deal is in, whose forecast category a form left on\n * \"from the stage\" stamps (AGL-3516). Absent, the field is left unset and\n * every reader derives it from the stage.\n */\n stage?: Pick<CrmDealStage, 'kind' | 'forecastCategory'> | null\n}\n\n/**\n * The form's two picklist fields judged against the org's lists (AGL-3516),\n * the way every server door judges them: an active value is stored as the\n * list spells it, a blank clears, the deal's own current value is kept, and\n * anything else is refused naming what the list allows. A NEW deal with no\n * Type takes the list's default, as Salesforce's does; the lead source is\n * never defaulted — it records where a deal came from.\n */\nexport function judgeDealFormPicklists(\n values: DealFormValues,\n lists: { type: CrmPicklist; leadSource: CrmPicklist },\n options: { current?: Partial<Pick<CrmDeal, 'type' | 'leadSource'>> | null; created: boolean },\n): { ok: true; values: DealFormValues } | { ok: false; error: string } {\n const typed = values.type.trim() || (options.created ? (crmPicklistDefaultLabel(lists.type) ?? '') : '')\n const type = judgeCrmPicklistValue('opportunityType', lists.type, typed, options.current?.type)\n if (type.ok === false) return type\n const leadSource = judgeCrmPicklistValue(\n 'leadSource',\n lists.leadSource,\n values.leadSource,\n options.current?.leadSource,\n )\n if (leadSource.ok === false) return leadSource\n return {\n ok: true,\n values: { ...values, type: type.value ?? '', leadSource: leadSource.value ?? '' },\n }\n}\n\n/** The forecast category a save stamps: the form's, else the stage's, else none. */\nfunction forecastCategoryFor(\n values: Pick<DealFormValues, 'forecastCategory'>,\n stage: DealWriteContext['stage'],\n): CrmForecastCategory | null {\n if (isCrmForecastCategory(values.forecastCategory)) return values.forecastCategory\n return stage ? dealStageForecastCategory(stage) : null\n}\n\n/**\n * The optional fields, as the values to SET and the keys to CLEAR.\n *\n * Split rather than written as `null` because a deal's optional ids are\n * typed as absent-or-string, and the indexes on `contactId` and `companyId`\n * are what the contact and company pages query — a `null` there would be a\n * row those pages cannot see and a filter on \"no contact\" could not find\n * either. On a create the cleared keys are simply not written; on an edit\n * the component turns them into field deletes.\n */\nfunction optionalFields(values: DealFormValues): {\n set: Record<string, string | number>\n clear: string[]\n} {\n const set: Record<string, string | number> = {}\n const clear: string[] = []\n const put = (key: string, value: string | number | null) => {\n if (value === null || value === '') clear.push(key)\n else set[key] = value\n }\n put('amountCents', parseAmountInput(values.amount))\n put('expectedCloseAtMs', dateInputMs(values.expectedClose))\n put('ownerUid', values.ownerUid.trim())\n put('contactId', values.contactId.trim())\n put('contactName', values.contactId.trim() ? values.contactName.trim() : '')\n put('companyId', values.companyId.trim())\n put('companyName', values.companyId.trim() ? values.companyName.trim() : '')\n put('notes', values.notes.trim().slice(0, DEAL_NOTES_MAX))\n put('type', values.type.trim())\n put('leadSource', values.leadSource.trim())\n put('nextStep', values.nextStep.trim().replace(/\\s+/g, ' ').slice(0, DEAL_NEXT_STEP_MAX))\n put('probability', readDealProbability(values.probability) ?? null)\n put('campaignId', values.campaignId.trim())\n return { set, clear }\n}\n\n/**\n * The document a new deal is created as. Open, in the chosen stage, with\n * the stage clock started now so \"days in stage\" counts from creation.\n */\nexport function dealDocumentFromForm(\n values: DealFormValues,\n context: DealWriteContext,\n): Record<string, unknown> {\n const title = values.title.trim().slice(0, DEAL_TITLE_MAX)\n const { set } = optionalFields(values)\n const forecastCategory = forecastCategoryFor(values, context.stage)\n const contactId = values.contactId.trim()\n return {\n title,\n titleLower: nameSearchKey(title),\n pipelineId: values.pipelineId,\n stageId: values.stageId,\n status: 'open' satisfies CrmDeal['status'],\n // The contact picked is the deal's Primary contact role (AGL-3521).\n ...(contactId ? { contactRoles: [{ contactId, primary: true }] } : {}),\n currency: String(values.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n stageChangedAtMs: context.nowMs,\n ...(forecastCategory ? { forecastCategory } : {}),\n ...set,\n visibleTo: context.visibleTo,\n hostId: context.hostId,\n createdByUid: context.uid,\n createdAt: new Date(context.nowMs),\n updatedAt: new Date(context.nowMs),\n }\n}\n\n/**\n * The patch an edit writes. Never the stage, the status or the scope: the\n * stage goes through the server route so the automations hear it, and the\n * scope is changed only by an org-wide member on purpose.\n *\n * Nor the amount or the currency of a deal whose amount is DERIVED\n * (`amountDerived`, AGL-2620): with line items on the deal the amount is\n * their sum and the currency is theirs, both owned by the products card. The\n * form shows them read-only, and a patch that re-wrote the number it was\n * seeded with would overwrite a line added from another tab meanwhile.\n */\nexport function dealPatchFromForm(\n values: DealFormValues,\n nowMs: number,\n options: {\n amountDerived?: boolean\n stage?: DealWriteContext['stage']\n /**\n * The deal as stored, whose contact roles a changed contact moves\n * (AGL-3521): the contact picked becomes the Primary — added with no\n * role when the deal did not name them — and a cleared contact leaves\n * the deal with no Primary. An unchanged contact writes no roles, so a\n * role edited on the deal's page meanwhile is not overwritten.\n */\n current?: Pick<CrmDeal, 'contactId' | 'contactRoles'> | null\n } = {},\n): { set: Record<string, unknown>; clear: string[] } {\n const title = values.title.trim().slice(0, DEAL_TITLE_MAX)\n const optional = optionalFields(values)\n const set: Record<string, unknown> = optional.set\n const { clear } = optional\n const contactId = values.contactId.trim()\n if (options.current && contactId !== (options.current.contactId ?? '')) {\n set['contactRoles'] = dealContactRolesWithPrimary(dealContactRolesOf(options.current), contactId || null)\n }\n // The category picked, else the stage's again; with neither, the field\n // goes and every reader derives it from the stage.\n const forecastCategory = forecastCategoryFor(values, options.stage)\n if (forecastCategory) set['forecastCategory'] = forecastCategory\n else clear.push('forecastCategory')\n if (options.amountDerived) {\n delete set['amountCents']\n return {\n set: { title, titleLower: nameSearchKey(title), ...set, updatedAt: new Date(nowMs) },\n clear: clear.filter((key) => key !== 'amountCents'),\n }\n }\n return {\n set: {\n title,\n titleLower: nameSearchKey(title),\n currency: String(values.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n ...set,\n updatedAt: new Date(nowMs),\n },\n clear,\n }\n}\n\n/** A contact as the picker offers it. */\nexport interface ContactChoice {\n id: string\n name: string\n email: string\n}\n\n/**\n * The contacts a typed query matches, from a window of recent contact rows,\n * in the list's own grammar.\n *\n * In memory rather than by query because the contacts collection has no\n * composite index over `visibleTo` with `nameLower` or `email`, and a\n * scoped list can carry only one array clause — so the picker reads the\n * newest rows the viewer may see (bounded, ordered) and matches here. The\n * match is what the list's search does: the normalized query as a prefix of\n * the email, or as a prefix of any word of the name (`nameTokens` holds\n * every word prefix a write produced; `nameLower` covers rows written before\n * the tokens existed). The holder's own name for the person wins over the\n * canonical one, as everywhere else.\n */\nexport function contactChoicesFor(\n queryText: string,\n rows: readonly Record<string, unknown>[],\n /**\n * The holder each row is named through: one group for every row under a\n * site, or a resolver per row at the organization level (AGL-2630), where\n * each contact reads through its own primary holder.\n */\n groupId: string | ((row: Record<string, unknown>) => string),\n max = 8,\n): ContactChoice[] {\n const key = nameSearchKey(queryText)\n const token = nameSearchToken(queryText)\n const choices: ContactChoice[] = []\n for (const row of rows) {\n const email = String(row['email'] ?? '').toLowerCase()\n const name = contactDisplayName(\n row,\n typeof groupId === 'function' ? groupId(row) : groupId,\n )\n const nameLower = nameSearchKey(name)\n const tokens = Array.isArray(row['nameTokens'])\n ? (row['nameTokens'] as unknown[]).map(String)\n : []\n const matches =\n !key ||\n email.startsWith(key) ||\n nameLower.startsWith(key) ||\n nameLower.includes(` ${key}`) ||\n (token ? tokens.includes(token) : false)\n if (!matches) continue\n choices.push({ id: String(row['$id'] ?? ''), name, email })\n if (choices.length >= max) break\n }\n return choices\n}\n"],"names":["contactDisplayName","crmPicklistDefaultLabel","DEAL_NEXT_STEP_MAX","dealContactRolesOf","dealContactRolesWithPrimary","dealStageForecastCategory","isCrmForecastCategory","judgeCrmPicklistValue","nameSearchKey","nameSearchToken","readDealProbability","amountInputValue","dateInputMs","dateInputValue","DEFAULT_DEAL_CURRENCY","openStages","parseAmountInput","DEAL_TITLE_MAX","DEAL_NOTES_MAX","emptyDealForm","pipeline","defaults","firstOpen","title","pipelineId","$id","stageId","id","amount","currency","expectedClose","ownerUid","contactId","contactName","companyId","companyName","notes","type","leadSource","nextStep","probability","forecastCategory","campaignId","dealFormFromDoc","deal","String","amountCents","toLowerCase","expectedCloseAtMs","dealFormProblem","values","mode","trim","undefined","judgeDealFormPicklists","lists","options","typed","created","current","ok","value","forecastCategoryFor","stage","optionalFields","set","clear","put","key","push","slice","replace","dealDocumentFromForm","context","titleLower","status","contactRoles","primary","stageChangedAtMs","nowMs","visibleTo","hostId","createdByUid","uid","createdAt","Date","updatedAt","dealPatchFromForm","optional","amountDerived","filter","contactChoicesFor","queryText","rows","groupId","max","token","choices","row","email","name","nameLower","tokens","Array","isArray","map","matches","startsWith","includes","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC,GAED,SACEA,kBAAkB,EAKlBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBAAqB,EACrBC,aAAa,EACbC,eAAe,EACfC,mBAAmB,QACd,eAAc;AACrB,SACEC,gBAAgB,EAChBC,WAAW,EACXC,cAAc,EACdC,qBAAqB,EAErBC,UAAU,EACVC,gBAAgB,QAEX,wBAAoB;AAkC3B,OAAO,MAAMC,iBAAiB,IAAG;AACjC,OAAO,MAAMC,iBAAiB,KAAI;AAElC;;;;;;;CAOC,GACD,OAAO,SAASC,cACdC,QAAgE,EAChEC,WAAoC,CAAC,CAAC;;IAEtC,MAAMC,YAAYP,WAAWK,SAAS,CAAC,EAAE;IACzC,OAAO;QACLG,OAAO;QACPC,UAAU,UAAEJ,4BAAAA,SAAUK,GAAG,mBAAI;QAC7BC,OAAO,WAAEJ,6BAAAA,UAAWK,EAAE,oBAAI;QAC1BC,QAAQ;QACRC,UAAUf;QACVgB,eAAe;QACfC,UAAU;QACVC,WAAW;QACXC,aAAa;QACbC,WAAW;QACXC,aAAa;QACbC,OAAO;QACPC,MAAM;QACNC,YAAY;QACZC,UAAU;QACVC,aAAa;QACbC,kBAAkB;QAClBC,YAAY;OACTrB;AAEP;AAEA,wCAAwC,GACxC,OAAO,S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;QAEjD,MAAMO,YAAY7F,cAAc4F;QAChC,MAAME,SAASC,MAAMC,OAAO,CAACN,GAAG,CAAC,aAAa,IAC1C,AAACA,GAAG,CAAC,aAAa,CAAeO,GAAG,CAAC5D,UACrC,EAAE;QACN,MAAM6D,UACJ,CAACtC,OACD+B,MAAMQ,UAAU,CAACvC,QACjBiC,UAAUM,UAAU,CAACvC,QACrBiC,UAAUO,QAAQ,CAAC,CAAC,CAAC,EAAExC,KAAK,KAC3B4B,CAAAA,QAAQM,OAAOM,QAAQ,CAACZ,SAAS,KAAI;QACxC,IAAI,CAACU,SAAS;QACdT,QAAQ5B,IAAI,CAAC;YAAE1C,IAAIkB,QAAOqD,WAAAA,GAAG,CAAC,MAAM,YAAVA,WAAc;YAAKE;YAAMD;QAAM;QACzD,IAAIF,QAAQY,MAAM,IAAId,KAAK;IAC7B;IACA,OAAOE;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deal-form-model.ts"],"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/**\n * The deal drawer's values and the documents they become (AGL-2598), as pure\n * functions — the drawer holds strings the way inputs do, and this module is\n * the one place those strings turn into the typed fields a `CrmDeal` stores.\n * Kept out of the component so the translation can be tested without a\n * Firestore or a DOM, and so the contact card and the company card, which\n * open the same drawer with a link preselected, build a deal the same way.\n */\n\nimport {\n contactDisplayName,\n type CrmDeal,\n type CrmDealStage,\n type CrmForecastCategory,\n type CrmPicklist,\n crmPicklistDefaultLabel,\n DEAL_NEXT_STEP_MAX,\n dealContactRolesOf,\n dealContactRolesWithPrimary,\n dealStageForecastCategory,\n isCrmForecastCategory,\n judgeCrmPicklistValue,\n nameSearchKey,\n nameSearchToken,\n readDealProbability,\n} from '@aglyn/aglyn'\nimport {\n amountInputValue,\n dateInputMs,\n dateInputValue,\n DEFAULT_DEAL_CURRENCY,\n type DealDoc,\n openStages,\n parseAmountInput,\n type PipelineDoc,\n} from './deal-board-model'\n\n/** What the drawer edits — strings as the inputs hold them. */\nexport interface DealFormValues {\n title: string\n pipelineId: string\n stageId: string\n /** As typed: `1,250.00`; parsed at save. */\n amount: string\n currency: string\n /** `YYYY-MM-DD` from a date input, or empty. */\n expectedClose: string\n ownerUid: string\n contactId: string\n contactName: string\n companyId: string\n companyName: string\n notes: string\n /*\n * Salesforce's Opportunity fields (AGL-3516).\n */\n /** The `opportunityType` label, or empty. */\n type: string\n /** The `leadSource` label, or empty. */\n leadSource: string\n nextStep: string\n /** The override as typed, `35`; empty means the stage's. */\n probability: string\n /** Empty means the stage's — what a save stamps when nobody picked one. */\n forecastCategory: '' | CrmForecastCategory\n /** One of the org's campaigns, or empty. */\n campaignId: string\n}\n\nexport const DEAL_TITLE_MAX = 120\nexport const DEAL_NOTES_MAX = 4000\n\n/**\n * A blank form aimed at a pipeline's first open stage.\n *\n * `defaults` is how a contact's page or a company's page starts a deal\n * already linked to itself: the caller passes the ids and names it knows and\n * the drawer opens with those fields filled. Anything it does not pass stays\n * blank rather than being guessed.\n */\nexport function emptyDealForm(\n pipeline: Pick<PipelineDoc, '$id' | 'stages'> | null | undefined,\n defaults: Partial<DealFormValues> = {},\n): DealFormValues {\n const firstOpen = openStages(pipeline)[0]\n return {\n title: '',\n pipelineId: pipeline?.$id ?? '',\n stageId: firstOpen?.id ?? '',\n amount: '',\n currency: DEFAULT_DEAL_CURRENCY,\n expectedClose: '',\n ownerUid: '',\n contactId: '',\n contactName: '',\n companyId: '',\n companyName: '',\n notes: '',\n type: '',\n leadSource: '',\n nextStep: '',\n probability: '',\n forecastCategory: '',\n campaignId: '',\n ...defaults,\n }\n}\n\n/** The form an existing deal opens as. */\nexport function dealFormFromDoc(deal: DealDoc): DealFormValues {\n return {\n title: String(deal.title ?? ''),\n pipelineId: String(deal.pipelineId ?? ''),\n stageId: String(deal.stageId ?? ''),\n amount: amountInputValue(deal.amountCents),\n currency: String(deal.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n expectedClose: dateInputValue(deal.expectedCloseAtMs),\n ownerUid: String(deal.ownerUid ?? ''),\n contactId: String(deal.contactId ?? ''),\n contactName: String(deal.contactName ?? ''),\n companyId: String(deal.companyId ?? ''),\n companyName: String(deal.companyName ?? ''),\n notes: String(deal.notes ?? ''),\n type: String(deal.type ?? ''),\n leadSource: String(deal.leadSource ?? ''),\n nextStep: String(deal.nextStep ?? ''),\n probability: typeof deal.probability === 'number' ? String(deal.probability) : '',\n forecastCategory: isCrmForecastCategory(deal.forecastCategory) ? deal.forecastCategory : '',\n campaignId: String(deal.campaignId ?? ''),\n }\n}\n\n/**\n * Why the form cannot be saved, or `null` when it can.\n *\n * A title is the one thing a deal needs — a card with no title is a card\n * nobody can find on the board. The amount is optional but, if typed, has to\n * parse: a deal saved with an amount the merchant typed and the model dropped\n * would forecast at zero without saying so. The stage is only checked on a\n * new deal, because an existing deal's stage is moved by the stage route and\n * is not this form's to write.\n */\nexport function dealFormProblem(\n values: DealFormValues,\n mode: 'create' | 'edit',\n): string | null {\n if (!values.title.trim()) return 'A deal needs a title.'\n if (values.amount.trim() && parseAmountInput(values.amount) === null) {\n return 'The amount has to be a number of zero or more.'\n }\n if (values.expectedClose.trim() && dateInputMs(values.expectedClose) === null) {\n return 'The expected close has to be a date.'\n }\n if (readDealProbability(values.probability) === undefined) {\n return 'The probability has to be a whole number from 0 to 100.'\n }\n if (mode === 'create' && (!values.pipelineId || !values.stageId)) {\n return 'Pick the stage the deal starts in.'\n }\n return null\n}\n\n/** What every deal write stamps besides the fields the form edits. */\nexport interface DealWriteContext {\n visibleTo: string[]\n hostId: string\n uid: string\n nowMs: number\n /**\n * The stage the deal is in, whose forecast category a form left on\n * \"from the stage\" stamps (AGL-3516). Absent, the field is left unset and\n * every reader derives it from the stage.\n */\n stage?: Pick<CrmDealStage, 'kind' | 'forecastCategory'> | null\n}\n\n/**\n * The form's two picklist fields judged against the org's lists (AGL-3516),\n * the way every server door judges them: an active value is stored as the\n * list spells it, a blank clears, the deal's own current value is kept, and\n * anything else is refused naming what the list allows. A NEW deal with no\n * Type takes the list's default, as Salesforce's does; the lead source is\n * never defaulted — it records where a deal came from.\n */\nexport function judgeDealFormPicklists(\n values: DealFormValues,\n lists: { type: CrmPicklist; leadSource: CrmPicklist },\n options: { current?: Partial<Pick<CrmDeal, 'type' | 'leadSource'>> | null; created: boolean },\n): { ok: true; values: DealFormValues } | { ok: false; error: string } {\n const typed = values.type.trim() || (options.created ? (crmPicklistDefaultLabel(lists.type) ?? '') : '')\n const type = judgeCrmPicklistValue('opportunityType', lists.type, typed, options.current?.type)\n if (type.ok === false) return type\n const leadSource = judgeCrmPicklistValue(\n 'leadSource',\n lists.leadSource,\n values.leadSource,\n options.current?.leadSource,\n )\n if (leadSource.ok === false) return leadSource\n return {\n ok: true,\n values: { ...values, type: type.value ?? '', leadSource: leadSource.value ?? '' },\n }\n}\n\n/** The forecast category a save stamps: the form's, else the stage's, else none. */\nfunction forecastCategoryFor(\n values: Pick<DealFormValues, 'forecastCategory'>,\n stage: DealWriteContext['stage'],\n): CrmForecastCategory | null {\n if (isCrmForecastCategory(values.forecastCategory)) return values.forecastCategory\n return stage ? dealStageForecastCategory(stage) : null\n}\n\n/**\n * The optional fields, as the values to SET and the keys to CLEAR.\n *\n * Split rather than written as `null` because a deal's optional ids are\n * typed as absent-or-string, and the indexes on `contactId` and `companyId`\n * are what the contact and company pages query — a `null` there would be a\n * row those pages cannot see and a filter on \"no contact\" could not find\n * either. On a create the cleared keys are simply not written; on an edit\n * the component turns them into field deletes.\n */\nfunction optionalFields(values: DealFormValues): {\n set: Record<string, string | number>\n clear: string[]\n} {\n const set: Record<string, string | number> = {}\n const clear: string[] = []\n const put = (key: string, value: string | number | null) => {\n if (value === null || value === '') clear.push(key)\n else set[key] = value\n }\n put('amountCents', parseAmountInput(values.amount))\n put('expectedCloseAtMs', dateInputMs(values.expectedClose))\n put('ownerUid', values.ownerUid.trim())\n put('contactId', values.contactId.trim())\n put('contactName', values.contactId.trim() ? values.contactName.trim() : '')\n put('companyId', values.companyId.trim())\n put('companyName', values.companyId.trim() ? values.companyName.trim() : '')\n put('notes', values.notes.trim().slice(0, DEAL_NOTES_MAX))\n put('type', values.type.trim())\n put('leadSource', values.leadSource.trim())\n put('nextStep', values.nextStep.trim().replace(/\\s+/g, ' ').slice(0, DEAL_NEXT_STEP_MAX))\n put('probability', readDealProbability(values.probability) ?? null)\n put('campaignId', values.campaignId.trim())\n return { set, clear }\n}\n\n/**\n * The document a new deal is created as. Open, in the chosen stage, with\n * the stage clock started now so \"days in stage\" counts from creation.\n */\nexport function dealDocumentFromForm(\n values: DealFormValues,\n context: DealWriteContext,\n): Record<string, unknown> {\n const title = values.title.trim().slice(0, DEAL_TITLE_MAX)\n const { set } = optionalFields(values)\n const forecastCategory = forecastCategoryFor(values, context.stage)\n const contactId = values.contactId.trim()\n return {\n title,\n titleLower: nameSearchKey(title),\n pipelineId: values.pipelineId,\n stageId: values.stageId,\n status: 'open' satisfies CrmDeal['status'],\n // The contact picked is the deal's Primary contact role (AGL-3521).\n ...(contactId ? { contactRoles: [{ contactId, primary: true }] } : {}),\n currency: String(values.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n stageChangedAtMs: context.nowMs,\n ...(forecastCategory ? { forecastCategory } : {}),\n ...set,\n visibleTo: context.visibleTo,\n hostId: context.hostId,\n createdByUid: context.uid,\n createdAt: new Date(context.nowMs),\n updatedAt: new Date(context.nowMs),\n }\n}\n\n/**\n * The patch an edit writes. Never the stage, the status or the scope: the\n * stage goes through the server route so the automations hear it, and the\n * scope is changed only by an org-wide member on purpose.\n *\n * Nor the amount or the currency of a deal whose amount is DERIVED\n * (`amountDerived`, AGL-2620): with line items on the deal the amount is\n * their sum and the currency is theirs, both owned by the products card. The\n * form shows them read-only, and a patch that re-wrote the number it was\n * seeded with would overwrite a line added from another tab meanwhile.\n */\nexport function dealPatchFromForm(\n values: DealFormValues,\n nowMs: number,\n options: {\n amountDerived?: boolean\n stage?: DealWriteContext['stage']\n /**\n * The deal as stored, whose contact roles a changed contact moves\n * (AGL-3521): the contact picked becomes the Primary — added with no\n * role when the deal did not name them — and a cleared contact leaves\n * the deal with no Primary. An unchanged contact writes no roles, so a\n * role edited on the deal's page meanwhile is not overwritten.\n */\n current?: Pick<CrmDeal, 'contactId' | 'contactRoles'> | null\n } = {},\n): { set: Record<string, unknown>; clear: string[] } {\n const title = values.title.trim().slice(0, DEAL_TITLE_MAX)\n const optional = optionalFields(values)\n const set: Record<string, unknown> = optional.set\n const { clear } = optional\n const contactId = values.contactId.trim()\n if (options.current && contactId !== (options.current.contactId ?? '')) {\n set['contactRoles'] = dealContactRolesWithPrimary(dealContactRolesOf(options.current), contactId || null)\n }\n // The category picked, else the stage's again; with neither, the field\n // goes and every reader derives it from the stage.\n const forecastCategory = forecastCategoryFor(values, options.stage)\n if (forecastCategory) set['forecastCategory'] = forecastCategory\n else clear.push('forecastCategory')\n if (options.amountDerived) {\n delete set['amountCents']\n return {\n set: { title, titleLower: nameSearchKey(title), ...set, updatedAt: new Date(nowMs) },\n clear: clear.filter((key) => key !== 'amountCents'),\n }\n }\n return {\n set: {\n title,\n titleLower: nameSearchKey(title),\n currency: String(values.currency || DEFAULT_DEAL_CURRENCY).toLowerCase(),\n ...set,\n updatedAt: new Date(nowMs),\n },\n clear,\n }\n}\n\n/** The document fields each form field writes. A blank list writes nothing on an edit. */\nconst DEAL_FORM_FIELD_WRITES: Readonly<Record<keyof DealFormValues, readonly string[]>> = {\n title: ['title', 'titleLower'],\n pipelineId: [],\n stageId: [],\n amount: ['amountCents'],\n currency: ['currency'],\n expectedClose: ['expectedCloseAtMs'],\n ownerUid: ['ownerUid'],\n contactId: ['contactId', 'contactName', 'contactRoles'],\n contactName: ['contactName'],\n companyId: ['companyId', 'companyName'],\n companyName: ['companyName'],\n notes: ['notes'],\n type: ['type'],\n leadSource: ['leadSource'],\n nextStep: ['nextStep'],\n probability: ['probability'],\n forecastCategory: ['forecastCategory'],\n campaignId: ['campaignId'],\n}\n\nconst DEAL_FORM_FIELDS = Object.keys(DEAL_FORM_FIELD_WRITES) as (keyof DealFormValues)[]\n\n/** What {@link dealEditFromForm} found the reader changed. */\nexport interface DealEdit {\n set: Record<string, unknown>\n clear: string[]\n}\n\n/**\n * The stored deal moved while the form was open (AGL-4132): the fields the\n * reader has not touched follow it, and the ones they have stay as typed.\n *\n * A listener hands over a new object for every snapshot, a confirmation of\n * unchanged data included, so a form rebuilt from each one loses whatever was\n * typed the moment the server answers.\n */\nexport function rebaseDealForm(\n current: DealFormValues,\n seed: DealFormValues,\n stored: DealFormValues,\n): DealFormValues {\n return Object.fromEntries(\n DEAL_FORM_FIELDS.map((field) => [\n field,\n current[field] === seed[field] ? stored[field] : current[field],\n ]),\n ) as unknown as DealFormValues\n}\n\n/**\n * The write a save makes on an existing deal: {@link dealPatchFromForm},\n * narrowed to the fields the reader changed from `seed`, with no `updatedAt`\n * so a caller can tell an edit from nothing at all (AGL-4132).\n *\n * The narrowing is what protects the deal. A patch of every field sent from a\n * read the server has not confirmed writes that read back over the document,\n * and one that held no `contactId` deletes the link. This one cannot touch a\n * field the reader left alone, however old the read behind the form.\n */\nexport function dealEditFromForm(\n values: DealFormValues,\n seed: DealFormValues,\n nowMs: number,\n options: Parameters<typeof dealPatchFromForm>[2] = {},\n): DealEdit {\n const { set, clear } = dealPatchFromForm(values, nowMs, options)\n const changed = new Set(\n DEAL_FORM_FIELDS\n .filter((field) => values[field] !== seed[field])\n .flatMap((field) => DEAL_FORM_FIELD_WRITES[field]),\n )\n return {\n set: Object.fromEntries(Object.entries(set).filter(([key]) => changed.has(key))),\n clear: clear.filter((key) => changed.has(key)),\n }\n}\n\n/** The fields an edit works out from the stored deal rather than takes as typed. */\nconst DEAL_EDIT_FIELDS_FROM_THE_READ = ['contactRoles', 'amountCents', 'currency'] as const\n\n/**\n * Whether an edit can only be trusted on a read the server has confirmed\n * (AGL-4132).\n *\n * The contact roles are the stored list with the Primary moved, so writing\n * them from an old read takes out a role added since. The amount and the\n * currency are the form's only while the deal has no line items, which the\n * read is what says. Everything else in an edit is a value the reader typed.\n */\nexport function dealEditNeedsConfirmedRead(edit: DealEdit): boolean {\n return DEAL_EDIT_FIELDS_FROM_THE_READ.some(\n (field) => field in edit.set || edit.clear.includes(field),\n )\n}\n\n/** A contact as the picker offers it. */\nexport interface ContactChoice {\n id: string\n name: string\n email: string\n}\n\n/**\n * The contacts a typed query matches, from a window of recent contact rows,\n * in the list's own grammar.\n *\n * In memory rather than by query because the contacts collection has no\n * composite index over `visibleTo` with `nameLower` or `email`, and a\n * scoped list can carry only one array clause — so the picker reads the\n * newest rows the viewer may see (bounded, ordered) and matches here. The\n * match is what the list's search does: the normalized query as a prefix of\n * the email, or as a prefix of any word of the name (`nameTokens` holds\n * every word prefix a write produced; `nameLower` covers rows written before\n * the tokens existed). The holder's own name for the person wins over the\n * canonical one, as everywhere else.\n */\nexport function contactChoicesFor(\n queryText: string,\n rows: readonly Record<string, unknown>[],\n /**\n * The holder each row is named through: one group for every row under a\n * site, or a resolver per row at the organization level (AGL-2630), where\n * each contact reads through its own primary holder.\n */\n groupId: string | ((row: Record<string, unknown>) => string),\n max = 8,\n): ContactChoice[] {\n const key = nameSearchKey(queryText)\n const token = nameSearchToken(queryText)\n const choices: ContactChoice[] = []\n for (const row of rows) {\n const email = String(row['email'] ?? '').toLowerCase()\n const name = contactDisplayName(\n row,\n typeof groupId === 'function' ? groupId(row) : groupId,\n )\n const nameLower = nameSearchKey(name)\n const tokens = Array.isArray(row['nameTokens'])\n ? (row['nameTokens'] as unknown[]).map(String)\n : []\n const matches =\n !key ||\n email.startsWith(key) ||\n nameLower.startsWith(key) ||\n nameLower.includes(` ${key}`) ||\n (token ? tokens.includes(token) : false)\n if (!matches) continue\n choices.push({ id: String(row['$id'] ?? ''), name, email })\n if (choices.length >= max) break\n }\n return choices\n}\n"],"names":["contactDisplayName","crmPicklistDefaultLabel","DEAL_NEXT_STEP_MAX","dealContactRolesOf","dealContactRolesWithPrimary","dealStageForecastCategory","isCrmForecastCategory","judgeCrmPicklistValue","nameSearchKey","nameSearchToken","readDealProbability","amountInputValue","dateInputMs","dateInputValue","DEFAULT_DEAL_CURRENCY","openStages","parseAmountInput","DEAL_TITLE_MAX","DEAL_NOTES_MAX","emptyDealForm","pipeline","defaults","firstOpen","title","pipelineId","$id","stageId","id","amount","currency","expectedClose","ownerUid","contactId","contactName","companyId","companyName","notes","type","leadSource","nextStep","probability","forecastCategory","campaignId","dealFormFromDoc","deal","String","amountCents","toLowerCase","expectedCloseAtMs","dealFormProblem","values","mode","trim","undefined","judgeDealFormPicklists","lists","options","typed","created","current","ok","value","forecastCategoryFor","stage","optionalFields","set","clear","put","key","push","slice","replace","dealDocumentFromForm","context","titleLower","status","contactRoles","primary","stageChangedAtMs","nowMs","visibleTo","hostId","createdByUid","uid","createdAt","Date","updatedAt","dealPatchFromForm","optional","amountDerived","filter","DEAL_FORM_FIELD_WRITES","DEAL_FORM_FIELDS","Object","keys","rebaseDealForm","seed","stored","fromEntries","map","field","dealEditFromForm","changed","Set","flatMap","entries","has","DEAL_EDIT_FIELDS_FROM_THE_READ","dealEditNeedsConfirmedRead","edit","some","includes","contactChoicesFor","queryText","rows","groupId","max","token","choices","row","email","name","nameLower","tokens","Array","isArray","matches","startsWith","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC,GAED,SACEA,kBAAkB,EAKlBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBA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