@aglyn/plugins-crm 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/add-to-list-dialog.js +7 -3
- package/src/lib/components/add-to-list-dialog.js.map +1 -1
- package/src/lib/components/company-contact-roles-card.d.ts +3 -0
- package/src/lib/components/company-contact-roles-card.js +4 -2
- package/src/lib/components/company-contact-roles-card.js.map +1 -1
- package/src/lib/components/company-detail-page.js +5 -3
- package/src/lib/components/company-detail-page.js.map +1 -1
- package/src/lib/components/company-edit-drawer.d.ts +3 -0
- package/src/lib/components/company-edit-drawer.js +2 -1
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-properties-card.d.ts +3 -0
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-associations-card.d.ts +3 -0
- package/src/lib/components/contact-associations-card.js +3 -1
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.js +5 -3
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +3 -0
- package/src/lib/components/contact-properties-card.js +3 -1
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/deal-contact-roles-card.d.ts +3 -0
- package/src/lib/components/deal-contact-roles-card.js +4 -2
- package/src/lib/components/deal-contact-roles-card.js.map +1 -1
- package/src/lib/components/deal-detail-page.js +7 -4
- package/src/lib/components/deal-detail-page.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.d.ts +12 -1
- package/src/lib/components/deal-edit-drawer.js +150 -53
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.d.ts +3 -0
- package/src/lib/components/deal-products-card.js +4 -2
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/deals-section.js +1 -0
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.js +7 -3
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.d.ts +3 -1
- package/src/lib/components/lead-campaigns-card.js +3 -2
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-detail-page.js +3 -1
- package/src/lib/components/lead-detail-page.js.map +1 -1
- package/src/lib/components/lead-properties-card.d.ts +3 -1
- package/src/lib/components/lead-properties-card.js +3 -2
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +4 -2
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.d.ts +3 -0
- package/src/lib/components/pipeline-stages-dialog.js +43 -14
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.d.ts +3 -0
- package/src/lib/components/pipelines-dialog.js +5 -2
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/record-tasks-card.js +3 -2
- package/src/lib/components/record-tasks-card.js.map +1 -1
- package/src/lib/components/task-edit-drawer.d.ts +2 -0
- package/src/lib/components/task-edit-drawer.js +2 -1
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/components/tasks-section.js +3 -2
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/hooks/use-contact-field-definitions.d.ts +3 -0
- package/src/lib/hooks/use-contact-field-definitions.js +3 -2
- package/src/lib/hooks/use-contact-field-definitions.js.map +1 -1
- package/src/lib/hooks/use-crm-picklist.d.ts +3 -0
- package/src/lib/hooks/use-crm-picklist.js +5 -3
- package/src/lib/hooks/use-crm-picklist.js.map +1 -1
- package/src/lib/hooks/use-crm-tasks.d.ts +3 -0
- package/src/lib/hooks/use-crm-tasks.js +3 -1
- package/src/lib/hooks/use-crm-tasks.js.map +1 -1
- package/src/lib/hooks/use-lead-source-picklist.js +5 -3
- package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
- package/src/lib/hooks/use-lead-status-picklist.js +5 -3
- package/src/lib/hooks/use-lead-status-picklist.js.map +1 -1
- package/src/lib/hooks/use-pipeline.d.ts +3 -0
- package/src/lib/hooks/use-pipeline.js +3 -1
- package/src/lib/hooks/use-pipeline.js.map +1 -1
- package/src/lib/model/crm-list-query.d.ts +7 -0
- package/src/lib/model/crm-list-query.js +10 -0
- package/src/lib/model/crm-list-query.js.map +1 -1
- package/src/lib/model/deal-form-model.d.ts +35 -0
- package/src/lib/model/deal-form-model.js +103 -0
- package/src/lib/model/deal-form-model.js.map +1 -1
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type CrmTask } from '@aglyn/aglyn';
|
|
18
|
+
import { type ListenHandle } from '@aglyn/tenant-feature-instance';
|
|
18
19
|
import type { ListFilterRequest } from '@aglyn/shared-ui-jsx/const/list-filter';
|
|
19
20
|
import type { ListQueryPlan, ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan';
|
|
20
21
|
import { type CrmTaskView } from '../model/task-views';
|
|
@@ -36,6 +37,8 @@ export interface CrmTaskListResult {
|
|
|
36
37
|
status: 'loading' | 'success' | 'error';
|
|
37
38
|
/** The rows are unconfirmed by the server — what a guarded write reads. */
|
|
38
39
|
fromCache: boolean;
|
|
40
|
+
/** The rows' listener, so a save waits on that read alone (AGL-4135). */
|
|
41
|
+
listen: ListenHandle | null;
|
|
39
42
|
/** The window filled up; there are tasks this view is not showing. */
|
|
40
43
|
truncated: boolean;
|
|
41
44
|
scope: readonly [string, string] | null;
|
|
@@ -93,6 +93,7 @@ import { crmVisibleToClause, useCrmScope } from "./use-crm-scope.js";
|
|
|
93
93
|
tasks,
|
|
94
94
|
status: paged.status,
|
|
95
95
|
fromCache: paged.fromCache,
|
|
96
|
+
listen: paged.listen,
|
|
96
97
|
truncated: paged.hasMore,
|
|
97
98
|
scope,
|
|
98
99
|
orgId,
|
|
@@ -128,7 +129,7 @@ const NO_WORDS = [];
|
|
|
128
129
|
});
|
|
129
130
|
const field = record.contactId ? 'contactId' : record.companyId ? 'companyId' : record.dealId ? 'dealId' : null;
|
|
130
131
|
const id = field ? record[field] : undefined;
|
|
131
|
-
const { data, status, fromCache } = useFirestoreCollection(()=>{
|
|
132
|
+
const { data, status, fromCache, listen } = useFirestoreCollection(()=>{
|
|
132
133
|
if (!scope || !field || !id) return null;
|
|
133
134
|
return query(collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks), ...crmVisibleToClause(readTokens), where(field, '==', id), orderBy('dueAtMs', 'asc'), limit(CRM_RECORD_TASK_LIMIT));
|
|
134
135
|
}, [
|
|
@@ -147,6 +148,7 @@ const NO_WORDS = [];
|
|
|
147
148
|
tasks,
|
|
148
149
|
status,
|
|
149
150
|
fromCache,
|
|
151
|
+
listen,
|
|
150
152
|
truncated: ((_ref = data == null ? void 0 : data.length) != null ? _ref : 0) >= CRM_RECORD_TASK_LIMIT,
|
|
151
153
|
scope,
|
|
152
154
|
orgId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-tasks.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 { CRM_COLLECTIONS, type CrmTask } from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport {\n collection,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useState } from 'react'\nimport type { ListFilterRequest } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport type { ListQueryPlan, ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport {\n type CrmTaskView,\n crmTaskViewBase,\n crmTaskViewPlan,\n crmTaskViewSort,\n orderTaskRows,\n TASK_LIST_DECLARATION,\n} from '../model/task-views'\nimport { useCrmFoldsScope, useCrmListQuery } from './use-crm-list-query'\nimport { crmVisibleToClause, useCrmScope } from './use-crm-scope'\n\n/** A task as the console lists it: the document plus its id. */\nexport type CrmTaskRow = CrmTask & { $id: string }\n\n/**\n * The reader's clock, refreshed once a minute (AGL-2599).\n *\n * \"Overdue\" and \"today\" are computed at read time against this value, so a\n * tab left open across midnight repaints yesterday's work red without a\n * reload. A minute is coarse enough that the re-render is invisible and fine\n * enough that a task due at 9:00 does not read as upcoming at 9:05.\n */\nexport function useNowMs(): number {\n const [nowMs, setNowMs] = useState(() => Date.now())\n useEffect(() => {\n const timer = setInterval(() => setNowMs(Date.now()), 60_000)\n return () => clearInterval(timer)\n }, [])\n return nowMs\n}\n\nexport interface CrmTaskListResult {\n tasks: CrmTaskRow[]\n status: 'loading' | 'success' | 'error'\n /** The rows are unconfirmed by the server — what a guarded write reads. */\n fromCache: boolean\n /** The window filled up; there are tasks this view is not showing. */\n truncated: boolean\n scope: readonly [string, string] | null\n orgId: string | null | undefined\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n readTokens: readonly string[] | null\n}\n\n/** One page of the tasks list, and what its query held. */\nexport interface CrmTaskPageResult extends CrmTaskListResult {\n /** What the query holds, what it refused and why (AGL-3321). */\n plan: ListQueryPlan\n hasMore: boolean\n page: number\n setPage: (page: number) => void\n pageSize: number\n setPageSize: (pageSize: number) => void\n}\n\n/**\n * One view of the tasks section, PAGED BY ITS QUERY (AGL-3321).\n *\n * The plan comes from `crmTaskViewPlan`, so the hook holds no opinion about\n * what \"today\" means; the view's predicates are the query's base beside the\n * scope clause, and Kind, Priority, Assignee and the search word are planned\n * onto the same query — every page a page of matches, none narrowed in\n * memory. \"My tasks\" opens no listener until the reader's uid is known — a\n * query for `assigneeUid == ''` would be a real read that could only answer\n * nothing.\n */\nexport function useCrmTaskList(options: {\n /** The site the list is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Record<string, unknown> | null\n view: CrmTaskView\n uid: string | null | undefined\n nowMs: number\n /** The Filters panel's clauses, the view's own excluded. */\n clauses?: readonly ListFilterRequest[]\n search?: readonly string[]\n /**\n * A header's order (AGL-3680), one of `TASK_LIST_SORTS`; absent, the\n * view's own — Due soonest first, Done most recently due first.\n */\n sort?: ListQuerySort | null\n}): CrmTaskPageResult {\n const { hostId, org, view, uid, nowMs, clauses = NO_CLAUSES, search = NO_WORDS } = options\n // The org root and the reader's tokens from the one scope hook (AGL-2614)\n // — the same expression the contacts list runs, so a task listed beside a\n // contact is scoped by exactly the predicate that admitted the contact.\n const { scope, orgId, visibleTo: readTokens } = useCrmScope({ hostId, org })\n const plan = useMemo(\n () => crmTaskViewPlan(view, { nowMs, uid }),\n [view, nowMs, uid],\n )\n const base = useMemo(() => crmTaskViewBase(plan), [plan])\n const viewSort = useMemo(() => crmTaskViewSort(plan), [plan])\n const sort = options.sort ?? viewSort\n const foldsScope = useCrmFoldsScope(orgId, readTokens)\n const paged = useCrmListQuery<CrmTaskRow>({\n scope,\n collection: CRM_COLLECTIONS.tasks,\n visibleTo: readTokens,\n foldsScope,\n declaration: TASK_LIST_DECLARATION,\n clauses,\n search,\n sort,\n base,\n enabled: plan.assigneeUid === undefined || Boolean(plan.assigneeUid),\n })\n // Undated last only under the Due order; a header's order is the query's.\n const orderedByDue = paged.plan.orderBy.path === 'dueAtMs'\n const tasks = useMemo(\n () => (orderedByDue ? orderTaskRows(paged.rows) : paged.rows),\n [paged.rows, orderedByDue],\n )\n return {\n tasks,\n status: paged.status,\n fromCache: paged.fromCache,\n truncated: paged.hasMore,\n scope,\n orgId,\n readTokens,\n plan: paged.plan,\n hasMore: paged.hasMore,\n page: paged.page,\n setPage: paged.setPage,\n pageSize: paged.pageSize,\n setPageSize: paged.setPageSize,\n }\n}\n\nconst NO_CLAUSES: readonly ListFilterRequest[] = []\nconst NO_WORDS: readonly string[] = []\n\n/**\n * How many of one record's tasks a card reads. A person with more than fifty\n * open tasks about one contact has a different problem than a short list.\n */\nexport const CRM_RECORD_TASK_LIMIT = 50\n\n/** Which record a task list is FOR — exactly one of the three. */\nexport interface CrmRecordRef {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * The tasks that hang off one contact, company or deal, open and done\n * together, soonest due first.\n *\n * Rides the per-record indexes — `(visibleTo, contactId, dueAtMs)` and its\n * two siblings — with no status clause, because the card shows the open ones\n * and counts the rest, and two listeners for one short list is one too many.\n */\nexport function useCrmRecordTasks(options: {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Record<string, unknown> | null\n record: CrmRecordRef\n}): CrmTaskListResult {\n const { hostId, org, record } = options\n const firestore = useFirestore()\n const { scope, orgId, visibleTo: readTokens } = useCrmScope({ hostId, org })\n const field = record.contactId\n ? 'contactId'\n : record.companyId\n ? 'companyId'\n : record.dealId\n ? 'dealId'\n : null\n const id = field ? record[field] : undefined\n const { data, status, fromCache } = useFirestoreCollection<CrmTaskRow>(\n () => {\n if (!scope || !field || !id) return null\n return query(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks),\n ...crmVisibleToClause(readTokens),\n where(field, '==', id),\n orderBy('dueAtMs', 'asc'),\n limit(CRM_RECORD_TASK_LIMIT),\n )\n },\n [firestore, scope, readTokens, field, id],\n { idField: '$id' },\n )\n const tasks = useMemo(() => orderTaskRows(data ?? []), [data])\n return {\n tasks,\n status,\n fromCache,\n truncated: (data?.length ?? 0) >= CRM_RECORD_TASK_LIMIT,\n scope,\n orgId,\n readTokens,\n }\n}\n"],"names":["CRM_COLLECTIONS","useFirestore","useFirestoreCollection","collection","limit","orderBy","query","where","useEffect","useMemo","useState","crmTaskViewBase","crmTaskViewPlan","crmTaskViewSort","orderTaskRows","TASK_LIST_DECLARATION","useCrmFoldsScope","useCrmListQuery","crmVisibleToClause","useCrmScope","useNowMs","nowMs","setNowMs","Date","now","timer","setInterval","clearInterval","useCrmTaskList","options","hostId","org","view","uid","clauses","NO_CLAUSES","search","NO_WORDS","scope","orgId","visibleTo","readTokens","plan","base","viewSort","sort","foldsScope","paged","tasks","declaration","enabled","assigneeUid","undefined","Boolean","orderedByDue","path","rows","status","fromCache","truncated","hasMore","page","setPage","pageSize","setPageSize","CRM_RECORD_TASK_LIMIT","useCrmRecordTasks","record","firestore","field","contactId","companyId","dealId","id","data","idField","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAsB,eAAc;AAC5D,SACEC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SACEC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAGpD,SAEEC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,aAAa,EACbC,qBAAqB,QAChB,yBAAqB;AAC5B,SAASC,gBAAgB,EAAEC,eAAe,QAAQ,0BAAsB;AACxE,SAASC,kBAAkB,EAAEC,WAAW,QAAQ,qBAAiB;AAKjE;;;;;;;CAOC,GACD,OAAO,SAASC;IACd,MAAM,CAACC,OAAOC,SAAS,GAAGZ,SAAS,IAAMa,KAAKC,GAAG;IACjDhB,UAAU;QACR,MAAMiB,QAAQC,YAAY,IAAMJ,SAASC,KAAKC,GAAG,KAAK;QACtD,OAAO,IAAMG,cAAcF;IAC7B,GAAG,EAAE;IACL,OAAOJ;AACT;AA0BA;;;;;;;;;;CAUC,GACD,OAAO,SAASO,eAAeC,OAe9B;QAYcA;IAXb,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAEC,IAAI,EAAEC,GAAG,EAAEZ,KAAK,EAAEa,UAAUC,UAAU,EAAEC,SAASC,QAAQ,EAAE,GAAGR;IACnF,0EAA0E;IAC1E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GACD,OAAO,MAAM4B,wBAAwB,GAAE;AASvC;;;;;;;CAOC,GACD,OAAO,SAASC,kBAAkBrC,OAKjC;;IACC,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAEoC,MAAM,EAAE,GAAGtC;IAChC,MAAMuC,YAAYnE;IAClB,MAAM,EAAEqC,KAAK,EAAEC,KAAK,EAAEC,WAAWC,UAAU,EAAE,GAAGtB,YAAY;QAAEW;QAAQC;IAAI;IAC1E,MAAMsC,QAAQF,OAAOG,SAAS,GAC1B,cACAH,OAAOI,SAAS,GACd,cACAJ,OAAOK,MAAM,GACX,WACA;IACR,MAAMC,KAAKJ,QAAQF,MAAM,CAACE,MAAM,GAAGjB;IACnC,MAAM,EAAEsB,IAAI,EAAEjB,MAAM,EAAEC,SAAS,EAAE,GAAGxD,uBAClC;QACE,IAAI,CAACoC,SAAS,CAAC+B,SAAS,CAACI,IAAI,OAAO;QACpC,OAAOnE,MACLH,WAAWiE,WAAW9B,KAAK,CAAC,EAAE,EAAEA,KAAK,CAAC,EAAE,EAAEtC,gBAAgBgD,KAAK,MAC5D9B,mBAAmBuB,aACtBlC,MAAM8D,OAAO,MAAMI,KACnBpE,QAAQ,WAAW,QACnBD,MAAM6D;IAEV,GACA;QAACG;QAAW9B;QAAOG;QAAY4B;QAAOI;KAAG,EACzC;QAAEE,SAAS;IAAM;IAEnB,MAAM3B,QAAQvC,QAAQ,IAAMK,cAAc4D,eAAAA,OAAQ,EAAE,GAAG;QAACA;KAAK;IAC7D,OAAO;QACL1B;QACAS;QACAC;QACAC,WAAW,SAACe,wBAAAA,KAAME,MAAM,mBAAI,MAAMX;QAClC3B;QACAC;QACAE;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-tasks.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 { CRM_COLLECTIONS, type CrmTask } from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n collection,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useState } from 'react'\nimport type { ListFilterRequest } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport type { ListQueryPlan, ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport {\n type CrmTaskView,\n crmTaskViewBase,\n crmTaskViewPlan,\n crmTaskViewSort,\n orderTaskRows,\n TASK_LIST_DECLARATION,\n} from '../model/task-views'\nimport { useCrmFoldsScope, useCrmListQuery } from './use-crm-list-query'\nimport { crmVisibleToClause, useCrmScope } from './use-crm-scope'\n\n/** A task as the console lists it: the document plus its id. */\nexport type CrmTaskRow = CrmTask & { $id: string }\n\n/**\n * The reader's clock, refreshed once a minute (AGL-2599).\n *\n * \"Overdue\" and \"today\" are computed at read time against this value, so a\n * tab left open across midnight repaints yesterday's work red without a\n * reload. A minute is coarse enough that the re-render is invisible and fine\n * enough that a task due at 9:00 does not read as upcoming at 9:05.\n */\nexport function useNowMs(): number {\n const [nowMs, setNowMs] = useState(() => Date.now())\n useEffect(() => {\n const timer = setInterval(() => setNowMs(Date.now()), 60_000)\n return () => clearInterval(timer)\n }, [])\n return nowMs\n}\n\nexport interface CrmTaskListResult {\n tasks: CrmTaskRow[]\n status: 'loading' | 'success' | 'error'\n /** The rows are unconfirmed by the server — what a guarded write reads. */\n fromCache: boolean\n /** The rows' listener, so a save waits on that read alone (AGL-4135). */\n listen: ListenHandle | null\n /** The window filled up; there are tasks this view is not showing. */\n truncated: boolean\n scope: readonly [string, string] | null\n orgId: string | null | undefined\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n readTokens: readonly string[] | null\n}\n\n/** One page of the tasks list, and what its query held. */\nexport interface CrmTaskPageResult extends CrmTaskListResult {\n /** What the query holds, what it refused and why (AGL-3321). */\n plan: ListQueryPlan\n hasMore: boolean\n page: number\n setPage: (page: number) => void\n pageSize: number\n setPageSize: (pageSize: number) => void\n}\n\n/**\n * One view of the tasks section, PAGED BY ITS QUERY (AGL-3321).\n *\n * The plan comes from `crmTaskViewPlan`, so the hook holds no opinion about\n * what \"today\" means; the view's predicates are the query's base beside the\n * scope clause, and Kind, Priority, Assignee and the search word are planned\n * onto the same query — every page a page of matches, none narrowed in\n * memory. \"My tasks\" opens no listener until the reader's uid is known — a\n * query for `assigneeUid == ''` would be a real read that could only answer\n * nothing.\n */\nexport function useCrmTaskList(options: {\n /** The site the list is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Record<string, unknown> | null\n view: CrmTaskView\n uid: string | null | undefined\n nowMs: number\n /** The Filters panel's clauses, the view's own excluded. */\n clauses?: readonly ListFilterRequest[]\n search?: readonly string[]\n /**\n * A header's order (AGL-3680), one of `TASK_LIST_SORTS`; absent, the\n * view's own — Due soonest first, Done most recently due first.\n */\n sort?: ListQuerySort | null\n}): CrmTaskPageResult {\n const { hostId, org, view, uid, nowMs, clauses = NO_CLAUSES, search = NO_WORDS } = options\n // The org root and the reader's tokens from the one scope hook (AGL-2614)\n // — the same expression the contacts list runs, so a task listed beside a\n // contact is scoped by exactly the predicate that admitted the contact.\n const { scope, orgId, visibleTo: readTokens } = useCrmScope({ hostId, org })\n const plan = useMemo(\n () => crmTaskViewPlan(view, { nowMs, uid }),\n [view, nowMs, uid],\n )\n const base = useMemo(() => crmTaskViewBase(plan), [plan])\n const viewSort = useMemo(() => crmTaskViewSort(plan), [plan])\n const sort = options.sort ?? viewSort\n const foldsScope = useCrmFoldsScope(orgId, readTokens)\n const paged = useCrmListQuery<CrmTaskRow>({\n scope,\n collection: CRM_COLLECTIONS.tasks,\n visibleTo: readTokens,\n foldsScope,\n declaration: TASK_LIST_DECLARATION,\n clauses,\n search,\n sort,\n base,\n enabled: plan.assigneeUid === undefined || Boolean(plan.assigneeUid),\n })\n // Undated last only under the Due order; a header's order is the query's.\n const orderedByDue = paged.plan.orderBy.path === 'dueAtMs'\n const tasks = useMemo(\n () => (orderedByDue ? orderTaskRows(paged.rows) : paged.rows),\n [paged.rows, orderedByDue],\n )\n return {\n tasks,\n status: paged.status,\n fromCache: paged.fromCache,\n listen: paged.listen,\n truncated: paged.hasMore,\n scope,\n orgId,\n readTokens,\n plan: paged.plan,\n hasMore: paged.hasMore,\n page: paged.page,\n setPage: paged.setPage,\n pageSize: paged.pageSize,\n setPageSize: paged.setPageSize,\n }\n}\n\nconst NO_CLAUSES: readonly ListFilterRequest[] = []\nconst NO_WORDS: readonly string[] = []\n\n/**\n * How many of one record's tasks a card reads. A person with more than fifty\n * open tasks about one contact has a different problem than a short list.\n */\nexport const CRM_RECORD_TASK_LIMIT = 50\n\n/** Which record a task list is FOR — exactly one of the three. */\nexport interface CrmRecordRef {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * The tasks that hang off one contact, company or deal, open and done\n * together, soonest due first.\n *\n * Rides the per-record indexes — `(visibleTo, contactId, dueAtMs)` and its\n * two siblings — with no status clause, because the card shows the open ones\n * and counts the rest, and two listeners for one short list is one too many.\n */\nexport function useCrmRecordTasks(options: {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n org?: Record<string, unknown> | null\n record: CrmRecordRef\n}): CrmTaskListResult {\n const { hostId, org, record } = options\n const firestore = useFirestore()\n const { scope, orgId, visibleTo: readTokens } = useCrmScope({ hostId, org })\n const field = record.contactId\n ? 'contactId'\n : record.companyId\n ? 'companyId'\n : record.dealId\n ? 'dealId'\n : null\n const id = field ? record[field] : undefined\n const { data, status, fromCache, listen } = useFirestoreCollection<CrmTaskRow>(\n () => {\n if (!scope || !field || !id) return null\n return query(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks),\n ...crmVisibleToClause(readTokens),\n where(field, '==', id),\n orderBy('dueAtMs', 'asc'),\n limit(CRM_RECORD_TASK_LIMIT),\n )\n },\n [firestore, scope, readTokens, field, id],\n { idField: '$id' },\n )\n const tasks = useMemo(() => orderTaskRows(data ?? []), [data])\n return {\n tasks,\n status,\n fromCache,\n listen,\n truncated: (data?.length ?? 0) >= CRM_RECORD_TASK_LIMIT,\n scope,\n orgId,\n readTokens,\n }\n}\n"],"names":["CRM_COLLECTIONS","useFirestore","useFirestoreCollection","collection","limit","orderBy","query","where","useEffect","useMemo","useState","crmTaskViewBase","crmTaskViewPlan","crmTaskViewSort","orderTaskRows","TASK_LIST_DECLARATION","useCrmFoldsScope","useCrmListQuery","crmVisibleToClause","useCrmScope","useNowMs","nowMs","setNowMs","Date","now","timer","setInterval","clearInterval","useCrmTaskList","options","hostId","org","view","uid","clauses","NO_CLAUSES","search","NO_WORDS","scope","orgId","visibleTo","readTokens","plan","base","viewSort","sort","foldsScope","paged","tasks","declaration","enabled","assigneeUid","undefined","Boolean","orderedByDue","path","rows","status","fromCache","listen","truncated","hasMore","page","setPage","pageSize","setPageSize","CRM_RECORD_TASK_LIMIT","useCrmRecordTasks","record","firestore","field","contactId","companyId","dealId","id","data","idField","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAsB,eAAc;AAC5D,SACEC,YAAY,EACZC,sBAAsB,QAEjB,iCAAgC;AACvC,SACEC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAGpD,SAEEC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,aAAa,EACbC,qBAAqB,QAChB,yBAAqB;AAC5B,SAASC,gBAAgB,EAAEC,eAAe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K,MAC5D9B,mBAAmBuB,aACtBlC,MAAM+D,OAAO,MAAMI,KACnBrE,QAAQ,WAAW,QACnBD,MAAM8D;IAEV,GACA;QAACG;QAAW/B;QAAOG;QAAY6B;QAAOI;KAAG,EACzC;QAAEE,SAAS;IAAM;IAEnB,MAAM5B,QAAQvC,QAAQ,IAAMK,cAAc6D,eAAAA,OAAQ,EAAE,GAAG;QAACA;KAAK;IAC7D,OAAO;QACL3B;QACAS;QACAC;QACAC;QACAC,WAAW,SAACe,wBAAAA,KAAME,MAAM,mBAAI,MAAMX;QAClC5B;QACAC;QACAE;IACF;AACF"}
|
|
@@ -22,17 +22,19 @@ import { useCrmPicklist } from "./use-crm-picklist.js";
|
|
|
22
22
|
* lead source: the lead page's select, the New lead drawer, the contact's
|
|
23
23
|
* card, the leads list's filter and the import drawer.
|
|
24
24
|
*/ export function useLeadSourcePicklist(orgId) {
|
|
25
|
-
const { picklist, stored, ready, fromCache } = useCrmPicklist(CRM_LEAD_SOURCE_PICKLIST, orgId);
|
|
25
|
+
const { picklist, stored, ready, fromCache, listen } = useCrmPicklist(CRM_LEAD_SOURCE_PICKLIST, orgId);
|
|
26
26
|
return useMemo(()=>({
|
|
27
27
|
picklist,
|
|
28
28
|
stored,
|
|
29
29
|
ready,
|
|
30
|
-
fromCache
|
|
30
|
+
fromCache,
|
|
31
|
+
listen
|
|
31
32
|
}), [
|
|
32
33
|
picklist,
|
|
33
34
|
stored,
|
|
34
35
|
ready,
|
|
35
|
-
fromCache
|
|
36
|
+
fromCache,
|
|
37
|
+
listen
|
|
36
38
|
]);
|
|
37
39
|
}
|
|
38
40
|
export default useLeadSourcePicklist;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-lead-source-picklist.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'use client'\n\nimport { CRM_LEAD_SOURCE_PICKLIST } from '@aglyn/aglyn'\nimport { useMemo } from 'react'\nimport { type CrmPicklistResult, useCrmPicklist } from './use-crm-picklist'\n\nexport type LeadSourcePicklistResult = Omit<CrmPicklistResult, 'definition'>\n\n/**\n * The org's lead source values (AGL-3298) — {@link useCrmPicklist} for the\n * lead source: the lead page's select, the New lead drawer, the contact's\n * card, the leads list's filter and the import drawer.\n */\nexport function useLeadSourcePicklist(orgId: string | null | undefined): LeadSourcePicklistResult {\n const { picklist, stored, ready, fromCache } = useCrmPicklist(CRM_LEAD_SOURCE_PICKLIST, orgId)\n return useMemo(() => ({ picklist, stored, ready, fromCache })
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-lead-source-picklist.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'use client'\n\nimport { CRM_LEAD_SOURCE_PICKLIST } from '@aglyn/aglyn'\nimport { useMemo } from 'react'\nimport { type CrmPicklistResult, useCrmPicklist } from './use-crm-picklist'\n\nexport type LeadSourcePicklistResult = Omit<CrmPicklistResult, 'definition'>\n\n/**\n * The org's lead source values (AGL-3298) — {@link useCrmPicklist} for the\n * lead source: the lead page's select, the New lead drawer, the contact's\n * card, the leads list's filter and the import drawer.\n */\nexport function useLeadSourcePicklist(orgId: string | null | undefined): LeadSourcePicklistResult {\n const { picklist, stored, ready, fromCache, listen } = useCrmPicklist(CRM_LEAD_SOURCE_PICKLIST, orgId)\n return useMemo(\n () => ({ picklist, stored, ready, fromCache, listen }),\n [picklist, stored, ready, fromCache, listen],\n )\n}\n\nexport default useLeadSourcePicklist\n"],"names":["CRM_LEAD_SOURCE_PICKLIST","useMemo","useCrmPicklist","useLeadSourcePicklist","orgId","picklist","stored","ready","fromCache","listen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,wBAAwB,QAAQ,eAAc;AACvD,SAASC,OAAO,QAAQ,QAAO;AAC/B,SAAiCC,cAAc,QAAQ,wBAAoB;AAI3E;;;;CAIC,GACD,OAAO,SAASC,sBAAsBC,KAAgC;IACpE,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGP,eAAeF,0BAA0BI;IAChG,OAAOH,QACL,IAAO,CAAA;YAAEI;YAAUC;YAAQC;YAAOC;YAAWC;QAAO,CAAA,GACpD;QAACJ;QAAUC;QAAQC;QAAOC;QAAWC;KAAO;AAEhD;AAEA,eAAeN,sBAAqB"}
|
|
@@ -22,17 +22,19 @@ import { useCrmPicklist } from "./use-crm-picklist.js";
|
|
|
22
22
|
* lead status: every chip, select and filter that shows a lead's status by
|
|
23
23
|
* the label the org gave its meaning. One shared document listen.
|
|
24
24
|
*/ export function useLeadStatusPicklist(orgId) {
|
|
25
|
-
const { picklist, stored, ready, fromCache } = useCrmPicklist(CRM_LEAD_STATUS_PICKLIST, orgId);
|
|
25
|
+
const { picklist, stored, ready, fromCache, listen } = useCrmPicklist(CRM_LEAD_STATUS_PICKLIST, orgId);
|
|
26
26
|
return useMemo(()=>({
|
|
27
27
|
picklist,
|
|
28
28
|
stored,
|
|
29
29
|
ready,
|
|
30
|
-
fromCache
|
|
30
|
+
fromCache,
|
|
31
|
+
listen
|
|
31
32
|
}), [
|
|
32
33
|
picklist,
|
|
33
34
|
stored,
|
|
34
35
|
ready,
|
|
35
|
-
fromCache
|
|
36
|
+
fromCache,
|
|
37
|
+
listen
|
|
36
38
|
]);
|
|
37
39
|
}
|
|
38
40
|
export default useLeadStatusPicklist;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-lead-status-picklist.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'use client'\n\nimport { CRM_LEAD_STATUS_PICKLIST } from '@aglyn/aglyn'\nimport { useMemo } from 'react'\nimport { type CrmPicklistResult, useCrmPicklist } from './use-crm-picklist'\n\nexport type LeadStatusPicklistResult = Omit<CrmPicklistResult, 'definition'>\n\n/**\n * The org's lead status values (AGL-3512) — {@link useCrmPicklist} for the\n * lead status: every chip, select and filter that shows a lead's status by\n * the label the org gave its meaning. One shared document listen.\n */\nexport function useLeadStatusPicklist(orgId: string | null | undefined): LeadStatusPicklistResult {\n const { picklist, stored, ready, fromCache } = useCrmPicklist(CRM_LEAD_STATUS_PICKLIST, orgId)\n return useMemo(() => ({ picklist, stored, ready, fromCache })
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-lead-status-picklist.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'use client'\n\nimport { CRM_LEAD_STATUS_PICKLIST } from '@aglyn/aglyn'\nimport { useMemo } from 'react'\nimport { type CrmPicklistResult, useCrmPicklist } from './use-crm-picklist'\n\nexport type LeadStatusPicklistResult = Omit<CrmPicklistResult, 'definition'>\n\n/**\n * The org's lead status values (AGL-3512) — {@link useCrmPicklist} for the\n * lead status: every chip, select and filter that shows a lead's status by\n * the label the org gave its meaning. One shared document listen.\n */\nexport function useLeadStatusPicklist(orgId: string | null | undefined): LeadStatusPicklistResult {\n const { picklist, stored, ready, fromCache, listen } = useCrmPicklist(CRM_LEAD_STATUS_PICKLIST, orgId)\n return useMemo(\n () => ({ picklist, stored, ready, fromCache, listen }),\n [picklist, stored, ready, fromCache, listen],\n )\n}\n\nexport default useLeadStatusPicklist\n"],"names":["CRM_LEAD_STATUS_PICKLIST","useMemo","useCrmPicklist","useLeadStatusPicklist","orgId","picklist","stored","ready","fromCache","listen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,wBAAwB,QAAQ,eAAc;AACvD,SAASC,OAAO,QAAQ,QAAO;AAC/B,SAAiCC,cAAc,QAAQ,wBAAoB;AAI3E;;;;CAIC,GACD,OAAO,SAASC,sBAAsBC,KAAgC;IACpE,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGP,eAAeF,0BAA0BI;IAChG,OAAOH,QACL,IAAO,CAAA;YAAEI;YAAUC;YAAQC;YAAOC;YAAWC;QAAO,CAAA,GACpD;QAACJ;QAAUC;QAAQC;QAAOC;QAAWC;KAAO;AAEhD;AAEA,eAAeN,sBAAqB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ListenHandle } from '@aglyn/tenant-feature-instance';
|
|
1
2
|
import { type PipelineDoc } from '../model/deal-board-model';
|
|
2
3
|
/** The most pipelines one org is read with. */
|
|
3
4
|
export declare const PIPELINE_READ_LIMIT = 20;
|
|
@@ -19,6 +20,8 @@ export interface UsePipelineResult {
|
|
|
19
20
|
pipeline: PipelineDoc | null;
|
|
20
21
|
status: 'loading' | 'success' | 'error';
|
|
21
22
|
fromCache: boolean;
|
|
23
|
+
/** The rows' listener, so a save waits on that read alone (AGL-4135). */
|
|
24
|
+
listen: ListenHandle;
|
|
22
25
|
/** A seed write is in flight because the org had no pipeline. */
|
|
23
26
|
seeding: boolean;
|
|
24
27
|
/**
|
|
@@ -71,7 +71,7 @@ import { crmScopeListable, crmVisibleToClause, useCrmScope } from "./use-crm-sco
|
|
|
71
71
|
hostId,
|
|
72
72
|
org: org
|
|
73
73
|
});
|
|
74
|
-
const { data, status, fromCache } = useFirestoreCollection(()=>orgId && crmScopeListable(visibleToTokens) ? query(collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines), ...crmVisibleToClause(visibleToTokens), orderBy(documentId()), limit(PIPELINE_READ_LIMIT)) : null, [
|
|
74
|
+
const { data, status, fromCache, listen } = useFirestoreCollection(()=>orgId && crmScopeListable(visibleToTokens) ? query(collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines), ...crmVisibleToClause(visibleToTokens), orderBy(documentId()), limit(PIPELINE_READ_LIMIT)) : null, [
|
|
75
75
|
firestore,
|
|
76
76
|
orgId,
|
|
77
77
|
visibleToTokens
|
|
@@ -139,6 +139,7 @@ import { crmScopeListable, crmVisibleToClause, useCrmScope } from "./use-crm-sco
|
|
|
139
139
|
pipeline: defaultPipelineOf(pipelines),
|
|
140
140
|
status,
|
|
141
141
|
fromCache,
|
|
142
|
+
listen,
|
|
142
143
|
seeding,
|
|
143
144
|
visibleToTokens,
|
|
144
145
|
pipelineById: (id)=>{
|
|
@@ -150,6 +151,7 @@ import { crmScopeListable, crmVisibleToClause, useCrmScope } from "./use-crm-sco
|
|
|
150
151
|
data,
|
|
151
152
|
status,
|
|
152
153
|
fromCache,
|
|
154
|
+
listen,
|
|
153
155
|
seeding,
|
|
154
156
|
visibleToTokens
|
|
155
157
|
]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-pipeline.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'use client'\n\nimport {\n CRM_COLLECTIONS,\n DEFAULT_DEAL_STAGES,\n ORG_SCOPE_TOKEN,\n} from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n collection,\n doc,\n documentId,\n limit,\n orderBy,\n query,\n runTransaction,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport {\n activePipelines,\n DEFAULT_PIPELINE_ID,\n DEFAULT_PIPELINE_NAME,\n defaultPipelineOf,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport {\n crmScopeListable,\n crmVisibleToClause,\n useCrmScope,\n} from './use-crm-scope'\n\n/** The most pipelines one org is read with. */\nexport const PIPELINE_READ_LIMIT = 20\n\nexport interface UsePipelineOptions {\n /**\n * The site whose console is reading — provenance on the seeded pipeline —\n * or `null` at the organization level (AGL-2630).\n */\n hostId: string | null\n /** The org document the shell passed, for the scope the seed is stamped with. */\n org: Record<string, unknown> | null | undefined\n}\n\nexport interface UsePipelineResult {\n /** Every pipeline the viewer may read, archived ones included, in document-id order. */\n pipelines: PipelineDoc[]\n /** The pipelines a picker offers — see `activePipelines`. */\n activePipelines: PipelineDoc[]\n /** The default ACTIVE pipeline — `isDefault`, else the first — or null before one exists. */\n pipeline: PipelineDoc | null\n status: 'loading' | 'success' | 'error'\n fromCache: boolean\n /** A seed write is in flight because the org had no pipeline. */\n seeding: boolean\n /**\n * The scope tokens this viewer reads with — what a new deal is filtered\n * by — or `null` at the organization level, where nothing filters.\n */\n visibleToTokens: readonly string[] | null\n pipelineById: (id: string | undefined) => PipelineDoc | null\n}\n\n/**\n * The org's pipelines, and the default one seeded the first time nobody has\n * made any (AGL-2598).\n *\n * ## Bounded, scoped, ordered\n *\n * `orgs/{orgId}/pipelines` is read with the same `visibleTo` predicate every\n * CRM listener uses, ordered by document id and capped at twenty. A pipeline\n * is a handful of documents per org — the cap is there so the query has one,\n * not because anybody is expected to reach it. Archived pipelines are read\n * too (AGL-2620): a closed deal still names the pipeline it closed in, and\n * `pipelineById` has to resolve its stage on the deal's page and in the\n * reports. Only `activePipelines` and the default exclude them.\n *\n * ## The seed\n *\n * A merchant opening Deals for the first time should see a board, not a\n * setup step. When the SERVER has confirmed the org has no pipeline at all,\n * the hook writes one — `Sales`, with the default stages, `isDefault` — under\n * a fixed document id inside a transaction that first re-reads it. The\n * transaction is what makes two tabs opening the section together produce\n * one pipeline rather than two: whichever commits second sees the document\n * and writes nothing.\n *\n * A cached empty answer does not seed. The listener reports `fromCache`\n * while the local cache is serving it, and an empty cache is what a first\n * load looks like in every org that already has a pipeline — seeding on it\n * would race the real answer and, on an offline tab, write a second default\n * once the tab reconnected.\n *\n * The seed carries what every CRM creator stamps: the scope a contact\n * captured on this site would carry, the site as provenance, and the\n * creating account. At the ORGANIZATION level (AGL-2630) the seed is the\n * org's: stamped `['org']`, so every site's board opens on the same default\n * pipeline rather than each site seeding one of its own the others cannot\n * see — a pipeline's stages describe how the business sells, and at this\n * level the business is the org. Its provenance is the site the reader has\n * picked, when they have; a default made before any pick names none.\n */\nexport function usePipeline(\n orgId: string | null | undefined,\n options: UsePipelineOptions,\n): UsePipelineResult {\n const { hostId, org } = options\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid\n\n // The reader's tokens and the seed's stamp, from the one scope hook\n // (AGL-2614): under a site the group's tokens both ways; at the org level\n // no read clause, and a create stamp from the picked site.\n const {\n level,\n visibleTo: visibleToTokens,\n createHostId,\n createTokens,\n } = useCrmScope({ hostId, org: org as Record<string, unknown> | null })\n\n const { data, status, fromCache } = useFirestoreCollection<PipelineDoc>(\n () =>\n orgId && crmScopeListable(visibleToTokens)\n ? query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines),\n ...crmVisibleToClause(visibleToTokens),\n orderBy(documentId()),\n limit(PIPELINE_READ_LIMIT),\n )\n : null,\n [firestore, orgId, visibleToTokens],\n { idField: '$id' },\n )\n\n const [seeding, setSeeding] = useState(false)\n // One seed attempt per org per mount, whatever the listener does after.\n const seededFor = useRef<string | null>(null)\n useEffect(() => {\n if (!orgId || !uid) return\n // Under a site the seed needs the site's own stamp; without one it\n // would be a pipeline nobody may read.\n if (level === 'site' && !createTokens.length) return\n if (status !== 'success' || fromCache || data.length > 0) return\n if (seededFor.current === orgId) return\n seededFor.current = orgId\n let active = true\n setSeeding(true)\n const ref = doc(\n firestore,\n 'orgs',\n orgId,\n CRM_COLLECTIONS.pipelines,\n DEFAULT_PIPELINE_ID,\n )\n void runTransaction(firestore, async (transaction) => {\n const existing = await transaction.get(ref)\n if (existing.exists()) return\n transaction.set(ref, {\n name: DEFAULT_PIPELINE_NAME,\n stages: [...DEFAULT_DEAL_STAGES],\n isDefault: true,\n archivedAt: null,\n visibleTo: level === 'site' ? [...createTokens] : [ORG_SCOPE_TOKEN],\n hostId: createHostId,\n createdByUid: uid,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n })\n .catch((error) => {\n console.error(error)\n })\n .finally(() => {\n if (active) setSeeding(false)\n })\n return () => {\n active = false\n }\n }, [\n firestore,\n orgId,\n uid,\n level,\n createTokens,\n createHostId,\n status,\n fromCache,\n data,\n ])\n\n return useMemo(() => {\n const pipelines = data ?? []\n return {\n pipelines,\n activePipelines: activePipelines(pipelines),\n pipeline: defaultPipelineOf(pipelines),\n status,\n fromCache,\n seeding,\n visibleToTokens,\n pipelineById: (id) =>\n id ? (pipelines.find((entry) => entry.$id === id) ?? null) : null,\n }\n }, [data, status, fromCache, seeding, visibleToTokens])\n}\n\nexport default usePipeline\n"],"names":["CRM_COLLECTIONS","DEFAULT_DEAL_STAGES","ORG_SCOPE_TOKEN","useFirestore","useFirestoreCollection","useUser","collection","doc","documentId","limit","orderBy","query","runTransaction","useEffect","useMemo","useRef","useState","activePipelines","DEFAULT_PIPELINE_ID","DEFAULT_PIPELINE_NAME","defaultPipelineOf","crmScopeListable","crmVisibleToClause","useCrmScope","PIPELINE_READ_LIMIT","usePipeline","orgId","options","hostId","org","firestore","data","user","uid","level","visibleTo","visibleToTokens","createHostId","createTokens","status","fromCache","pipelines","idField","seeding","setSeeding","seededFor","length","current","active","ref","transaction","existing","get","exists","set","name","stages","isDefault","archivedAt","createdByUid","createdAt","Date","updatedAt","catch","error","console","finally","pipeline","pipelineById","id","find","entry","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SACEA,eAAe,EACfC,mBAAmB,EACnBC,eAAe,QACV,eAAc;AACrB,SACEC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,QACF,iCAAgC;AACvC,SACEC,UAAU,EACVC,GAAG,EACHC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,cAAc,QAET,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC5D,SACEC,eAAe,EACfC,mBAAmB,EACnBC,qBAAqB,EACrBC,iBAAiB,QAEZ,+BAA2B;AAClC,SACEC,gBAAgB,EAChBC,kBAAkB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ACzBvB;QAEF,KAAKN,eAAekB,WAAW,OAAOoB;YACpC,MAAMC,WAAW,MAAMD,YAAYE,GAAG,CAACH;YACvC,IAAIE,SAASE,MAAM,IAAI;YACvBH,YAAYI,GAAG,CAACL,KAAK;gBACnBM,MAAMpC;gBACNqC,QAAQ;uBAAIvD;iBAAoB;gBAChCwD,WAAW;gBACXC,YAAY;gBACZvB,WAAWD,UAAU,SAAS;uBAAII;iBAAa,GAAG;oBAACpC;iBAAgB;gBACnE0B,QAAQS;gBACRsB,cAAc1B;gBACd2B,WAAW,IAAIC;gBACfC,WAAW,IAAID;YACjB;QACF,GACGE,KAAK,CAAC,CAACC;YACNC,QAAQD,KAAK,CAACA;QAChB,GACCE,OAAO,CAAC;YACP,IAAIlB,QAAQJ,WAAW;QACzB;QACF,OAAO;YACLI,SAAS;QACX;IACF,GAAG;QACDlB;QACAJ;QACAO;QACAC;QACAI;QACAD;QACAE;QACAC;QACAT;KACD;IAED,OAAOjB,QAAQ;QACb,MAAM2B,YAAYV,eAAAA,OAAQ,EAAE;QAC5B,OAAO;YACLU;YACAxB,iBAAiBA,gBAAgBwB;YACjC0B,UAAU/C,kBAAkBqB;YAC5BF;YACAC;YACAG;YACAP;YACAgC,cAAc,CAACC;oBACP5B;uBAAN4B,MAAM5B,kBAAAA,UAAU6B,IAAI,CAAC,CAACC,QAAUA,MAAMC,GAAG,KAAKH,eAAxC5B,kBAA+C,OAAQ;;QACjE;IACF,GAAG;QAACV;QAAMQ;QAAQC;QAAWG;QAASP;KAAgB;AACxD;AAEA,eAAeX,YAAW"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-pipeline.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'use client'\n\nimport {\n CRM_COLLECTIONS,\n DEFAULT_DEAL_STAGES,\n ORG_SCOPE_TOKEN,\n} from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n collection,\n doc,\n documentId,\n limit,\n orderBy,\n query,\n runTransaction,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport {\n activePipelines,\n DEFAULT_PIPELINE_ID,\n DEFAULT_PIPELINE_NAME,\n defaultPipelineOf,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport {\n crmScopeListable,\n crmVisibleToClause,\n useCrmScope,\n} from './use-crm-scope'\n\n/** The most pipelines one org is read with. */\nexport const PIPELINE_READ_LIMIT = 20\n\nexport interface UsePipelineOptions {\n /**\n * The site whose console is reading — provenance on the seeded pipeline —\n * or `null` at the organization level (AGL-2630).\n */\n hostId: string | null\n /** The org document the shell passed, for the scope the seed is stamped with. */\n org: Record<string, unknown> | null | undefined\n}\n\nexport interface UsePipelineResult {\n /** Every pipeline the viewer may read, archived ones included, in document-id order. */\n pipelines: PipelineDoc[]\n /** The pipelines a picker offers — see `activePipelines`. */\n activePipelines: PipelineDoc[]\n /** The default ACTIVE pipeline — `isDefault`, else the first — or null before one exists. */\n pipeline: PipelineDoc | null\n status: 'loading' | 'success' | 'error'\n fromCache: boolean\n /** The rows' listener, so a save waits on that read alone (AGL-4135). */\n listen: ListenHandle\n /** A seed write is in flight because the org had no pipeline. */\n seeding: boolean\n /**\n * The scope tokens this viewer reads with — what a new deal is filtered\n * by — or `null` at the organization level, where nothing filters.\n */\n visibleToTokens: readonly string[] | null\n pipelineById: (id: string | undefined) => PipelineDoc | null\n}\n\n/**\n * The org's pipelines, and the default one seeded the first time nobody has\n * made any (AGL-2598).\n *\n * ## Bounded, scoped, ordered\n *\n * `orgs/{orgId}/pipelines` is read with the same `visibleTo` predicate every\n * CRM listener uses, ordered by document id and capped at twenty. A pipeline\n * is a handful of documents per org — the cap is there so the query has one,\n * not because anybody is expected to reach it. Archived pipelines are read\n * too (AGL-2620): a closed deal still names the pipeline it closed in, and\n * `pipelineById` has to resolve its stage on the deal's page and in the\n * reports. Only `activePipelines` and the default exclude them.\n *\n * ## The seed\n *\n * A merchant opening Deals for the first time should see a board, not a\n * setup step. When the SERVER has confirmed the org has no pipeline at all,\n * the hook writes one — `Sales`, with the default stages, `isDefault` — under\n * a fixed document id inside a transaction that first re-reads it. The\n * transaction is what makes two tabs opening the section together produce\n * one pipeline rather than two: whichever commits second sees the document\n * and writes nothing.\n *\n * A cached empty answer does not seed. The listener reports `fromCache`\n * while the local cache is serving it, and an empty cache is what a first\n * load looks like in every org that already has a pipeline — seeding on it\n * would race the real answer and, on an offline tab, write a second default\n * once the tab reconnected.\n *\n * The seed carries what every CRM creator stamps: the scope a contact\n * captured on this site would carry, the site as provenance, and the\n * creating account. At the ORGANIZATION level (AGL-2630) the seed is the\n * org's: stamped `['org']`, so every site's board opens on the same default\n * pipeline rather than each site seeding one of its own the others cannot\n * see — a pipeline's stages describe how the business sells, and at this\n * level the business is the org. Its provenance is the site the reader has\n * picked, when they have; a default made before any pick names none.\n */\nexport function usePipeline(\n orgId: string | null | undefined,\n options: UsePipelineOptions,\n): UsePipelineResult {\n const { hostId, org } = options\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid\n\n // The reader's tokens and the seed's stamp, from the one scope hook\n // (AGL-2614): under a site the group's tokens both ways; at the org level\n // no read clause, and a create stamp from the picked site.\n const {\n level,\n visibleTo: visibleToTokens,\n createHostId,\n createTokens,\n } = useCrmScope({ hostId, org: org as Record<string, unknown> | null })\n\n const { data, status, fromCache, listen } = useFirestoreCollection<PipelineDoc>(\n () =>\n orgId && crmScopeListable(visibleToTokens)\n ? query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines),\n ...crmVisibleToClause(visibleToTokens),\n orderBy(documentId()),\n limit(PIPELINE_READ_LIMIT),\n )\n : null,\n [firestore, orgId, visibleToTokens],\n { idField: '$id' },\n )\n\n const [seeding, setSeeding] = useState(false)\n // One seed attempt per org per mount, whatever the listener does after.\n const seededFor = useRef<string | null>(null)\n useEffect(() => {\n if (!orgId || !uid) return\n // Under a site the seed needs the site's own stamp; without one it\n // would be a pipeline nobody may read.\n if (level === 'site' && !createTokens.length) return\n if (status !== 'success' || fromCache || data.length > 0) return\n if (seededFor.current === orgId) return\n seededFor.current = orgId\n let active = true\n setSeeding(true)\n const ref = doc(\n firestore,\n 'orgs',\n orgId,\n CRM_COLLECTIONS.pipelines,\n DEFAULT_PIPELINE_ID,\n )\n void runTransaction(firestore, async (transaction) => {\n const existing = await transaction.get(ref)\n if (existing.exists()) return\n transaction.set(ref, {\n name: DEFAULT_PIPELINE_NAME,\n stages: [...DEFAULT_DEAL_STAGES],\n isDefault: true,\n archivedAt: null,\n visibleTo: level === 'site' ? [...createTokens] : [ORG_SCOPE_TOKEN],\n hostId: createHostId,\n createdByUid: uid,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n })\n .catch((error) => {\n console.error(error)\n })\n .finally(() => {\n if (active) setSeeding(false)\n })\n return () => {\n active = false\n }\n }, [\n firestore,\n orgId,\n uid,\n level,\n createTokens,\n createHostId,\n status,\n fromCache,\n data,\n ])\n\n return useMemo(() => {\n const pipelines = data ?? []\n return {\n pipelines,\n activePipelines: activePipelines(pipelines),\n pipeline: defaultPipelineOf(pipelines),\n status,\n fromCache,\n listen,\n seeding,\n visibleToTokens,\n pipelineById: (id) =>\n id ? (pipelines.find((entry) => entry.$id === id) ?? null) : null,\n }\n }, [data, status, fromCache, listen, seeding, visibleToTokens])\n}\n\nexport default usePipeline\n"],"names":["CRM_COLLECTIONS","DEFAULT_DEAL_STAGES","ORG_SCOPE_TOKEN","useFirestore","useFirestoreCollection","useUser","collection","doc","documentId","limit","orderBy","query","runTransaction","useEffect","useMemo","useRef","useState","activePipelines","DEFAULT_PIPELINE_ID","DEFAULT_PIPELINE_NAME","defaultPipelineOf","crmScopeListable","crmVisibleToClause","useCrmScope","PIPELINE_READ_LIMIT","usePipeline","orgId","options","hostId","org","firestore","data","user","uid","level","visibleTo","visibleToTokens","createHostId","createTokens","status","fromCache","listen","pipelines","idField","seeding","setSeeding","seededFor","length","current","active","ref","transaction","existing","get","exists","set","name","stages","isDefault","archivedAt","createdByUid","createdAt","Date","updatedAt","catch","error","console","finally","pipeline","pipelineById","id","find","entry","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SACEA,eAAe,EACfC,mBAAmB,EACnBC,eAAe,QACV,eAAc;AACrB,SACEC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,QAEF,iCAAgC;AACvC,SACEC,UAAU,EACVC,GAAG,EACHC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,cAAc,QAET,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC5D,SACEC,eAAe,EACfC,mBAAmB,EACnBC,qBAAqB,EACrBC,iBAAiB,QAEZ,+BAA2B;AAClC,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,WAAW,QACN,qBAAiB;AAExB,6CAA6C,GAC7C,OAAO,MAAMC,sBAAsB,GAAE;AAiCrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GACD,OAAO,SAASC,YACdC,KAAgC,EAChCC,OAA2B;IAE3B,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAE,GAAGF;IACxB,MAAMG,YAAY3B;IAClB,MAAM,EAAE4B,MAAMC,IAAI,EAAE,GAAG3B;IACvB,MAAM4B,MAAMD,wBAAAA,KAAMC,GAAG;IAErB,oEAAoE;IACpE,0EAA0E;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AAW,IAAID;YACjB;QACF,GACGE,KAAK,CAAC,CAACC;YACNC,QAAQD,KAAK,CAACA;QAChB,GACCE,OAAO,CAAC;YACP,IAAIlB,QAAQJ,WAAW;QACzB;QACF,OAAO;YACLI,SAAS;QACX;IACF,GAAG;QACDnB;QACAJ;QACAO;QACAC;QACAI;QACAD;QACAE;QACAC;QACAT;KACD;IAED,OAAOjB,QAAQ;QACb,MAAM4B,YAAYX,eAAAA,OAAQ,EAAE;QAC5B,OAAO;YACLW;YACAzB,iBAAiBA,gBAAgByB;YACjC0B,UAAUhD,kBAAkBsB;YAC5BH;YACAC;YACAC;YACAG;YACAR;YACAiC,cAAc,CAACC;oBACP5B;uBAAN4B,MAAM5B,kBAAAA,UAAU6B,IAAI,CAAC,CAACC,QAAUA,MAAMC,GAAG,KAAKH,eAAxC5B,kBAA+C,OAAQ;;QACjE;IACF,GAAG;QAACX;QAAMQ;QAAQC;QAAWC;QAAQG;QAASR;KAAgB;AAChE;AAEA,eAAeX,YAAW"}
|
|
@@ -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;QAAaI,OAAO;IAAK;CAAE,CAAS;AAEhF;;;;;;;;;CASC,GACD,OAAO,SAASC,sBACdC,WAAiC,EACjCC,UAAmB;QAEAD;IAAnB,IAAIC,cAAc,GAACD,sBAAAA,YAAYE,MAAM,qBAAlBF,oBAAoBT,MAAM,GAAE,OAAOS;IACtD,OAAO,aAAKA;QAAaE,QAAQ;YAAEZ,YAAYU,YAAYE,MAAM,CAACZ,UAAU;QAAC;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B,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,OAAO,SAASC,sBACdC,WAAiC,EACjCC,UAAmB;QAEAD;IAAnB,IAAIC,cAAc,GAACD,sBAAAA,YAAYE,MAAM,qBAAlBF,oBAAoBT,MAAM,GAAE,OAAOS;IACtD,OAAO,aAAKA;QAAaE,QAAQ;YAAEZ,YAAYU,YAAYE,MAAM,CAACZ,UAAU;QAAC;;AAC/E;AA2BA,qEAAqE,GACrE,OAAO,SAASa,cACdC,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ACzB3B,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.
|