@aglyn/plugins-crm 1.0.0-beta.244 → 1.0.0-beta.247
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +14 -14
- package/src/lib/components/contact-custom-columns.d.ts +15 -6
- package/src/lib/components/contact-custom-columns.js +27 -7
- package/src/lib/components/contact-custom-columns.js.map +1 -1
- package/src/lib/components/contact-field-drawer.d.ts +2 -0
- package/src/lib/components/contact-field-drawer.js +29 -15
- package/src/lib/components/contact-field-drawer.js.map +1 -1
- package/src/lib/components/contacts-section.js +9 -3
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-custom-field-control.d.ts +4 -2
- package/src/lib/components/crm-custom-field-control.js +53 -1
- package/src/lib/components/crm-custom-field-control.js.map +1 -1
- package/src/lib/components/fields-section.js +4 -2
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/form-contact-fields-card.js +2 -0
- package/src/lib/components/form-contact-fields-card.js.map +1 -1
- package/src/lib/constants/contact-filters.d.ts +7 -0
- package/src/lib/constants/contact-filters.js +8 -1
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/declarations.console-server.d.ts +7 -0
- package/src/lib/declarations.console-server.js +39 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/crm-picklist-setup-content.d.ts +121 -0
- package/src/lib/model/crm-picklist-setup-content.js +262 -0
- package/src/lib/model/crm-picklist-setup-content.js.map +1 -0
- package/src/lib/model/crm-record-routes.js +18 -0
- package/src/lib/model/crm-record-routes.js.map +1 -1
- package/src/lib/model/crm-setup-content.d.ts +199 -0
- package/src/lib/model/crm-setup-content.js +427 -0
- package/src/lib/model/crm-setup-content.js.map +1 -0
- package/src/lib/server/crm-setup-ai-capabilities.d.ts +68 -0
- package/src/lib/server/crm-setup-ai-capabilities.js +290 -0
- package/src/lib/server/crm-setup-ai-capabilities.js.map +1 -0
- package/src/lib/server/crm-setup-writers.server.d.ts +120 -0
- package/src/lib/server/crm-setup-writers.server.js +492 -0
- package/src/lib/server/crm-setup-writers.server.js.map +1 -0
- package/src/lib/server/picklist-regroup.d.ts +30 -0
- package/src/lib/server/picklist-regroup.js +61 -0
- package/src/lib/server/picklist-regroup.js.map +1 -0
- package/src/lib/server/picklist-values.d.ts +2 -14
- package/src/lib/server/picklist-values.js +3 -40
- package/src/lib/server/picklist-values.js.map +1 -1
- package/src/lib/transfer/common.d.ts +4 -2
- package/src/lib/transfer/common.js +14 -3
- package/src/lib/transfer/common.js.map +1 -1
- package/src/lib/transfer/fields.js +10 -1
- package/src/lib/transfer/fields.js.map +1 -1
- package/src/lib/transfer/pipelines.js +4 -2
- package/src/lib/transfer/pipelines.js.map +1 -1
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ // Modules by their own paths, never the `@aglyn/aglyn` barrel: the CRM's
|
|
17
|
+
// setup writers (AGL-3756) reach this file as well as the picklist route.
|
|
18
|
+
import { crmPicklistKey, crmPicklistValueByLabel } from "@aglyn/aglyn/app-utils/crm";
|
|
19
|
+
import { FieldPath } from "firebase-admin/firestore";
|
|
20
|
+
/** Writes per batch — under Firestore's 500, with room to spare. */ const BATCH_SIZE = 400;
|
|
21
|
+
/** The group a label is filed under in `picklist` — `null` for none, or a label it does not hold. */ export function picklistGroupOf(picklist, label) {
|
|
22
|
+
var _ref;
|
|
23
|
+
var _crmPicklistValueByLabel;
|
|
24
|
+
return (_ref = label === null ? null : (_crmPicklistValueByLabel = crmPicklistValueByLabel(picklist, label)) == null ? void 0 : _crmPicklistValueByLabel.group) != null ? _ref : null;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Rewrite a target's GROUP field (AGL-3577) — a lead's
|
|
28
|
+
* `leadSourceDirection` — on every record holding `label` in any spelling
|
|
29
|
+
* (by its `keyField`) whose group is not `group` already. Answers how many
|
|
30
|
+
* were written. The field is derived, like the list keys a restamp writes,
|
|
31
|
+
* so `updatedAt` is left alone.
|
|
32
|
+
*
|
|
33
|
+
* Paged by document id rather than re-run: a record already holding the
|
|
34
|
+
* group stays in the query's answer.
|
|
35
|
+
*/ export async function regroupEverywhere(firestore, records, target, label, group) {
|
|
36
|
+
const key = crmPicklistKey(label);
|
|
37
|
+
if (!key || !target.keyField || !target.groupField) return 0;
|
|
38
|
+
const query = records.where(target.keyField, '==', key).orderBy(FieldPath.documentId()).limit(BATCH_SIZE);
|
|
39
|
+
let written = 0;
|
|
40
|
+
let after = null;
|
|
41
|
+
for(;;){
|
|
42
|
+
var _page_docs_;
|
|
43
|
+
const page = await (after ? query.startAfter(after) : query).get();
|
|
44
|
+
if (page.empty) return written;
|
|
45
|
+
const batch = firestore.batch();
|
|
46
|
+
let changed = 0;
|
|
47
|
+
for (const snapshot of page.docs){
|
|
48
|
+
if (snapshot.get(target.groupField) === group) continue;
|
|
49
|
+
batch.update(snapshot.ref, {
|
|
50
|
+
[target.groupField]: group
|
|
51
|
+
});
|
|
52
|
+
changed += 1;
|
|
53
|
+
}
|
|
54
|
+
if (changed) await batch.commit();
|
|
55
|
+
written += changed;
|
|
56
|
+
if (page.size < BATCH_SIZE) return written;
|
|
57
|
+
after = (_page_docs_ = page.docs[page.docs.length - 1]) != null ? _page_docs_ : null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=picklist-regroup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/picklist-regroup.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Modules by their own paths, never the `@aglyn/aglyn` barrel: the CRM's\n// setup writers (AGL-3756) reach this file as well as the picklist route.\nimport {\n type CrmPicklist,\n type CrmPicklistTarget,\n crmPicklistKey,\n crmPicklistValueByLabel,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { FieldPath } from 'firebase-admin/firestore'\n\n/** Writes per batch — under Firestore's 500, with room to spare. */\nconst BATCH_SIZE = 400\n\n/** The group a label is filed under in `picklist` — `null` for none, or a label it does not hold. */\nexport function picklistGroupOf(picklist: CrmPicklist, label: string | null): string | null {\n return (label === null ? null : crmPicklistValueByLabel(picklist, label)?.group) ?? null\n}\n\n/**\n * Rewrite a target's GROUP field (AGL-3577) — a lead's\n * `leadSourceDirection` — on every record holding `label` in any spelling\n * (by its `keyField`) whose group is not `group` already. Answers how many\n * were written. The field is derived, like the list keys a restamp writes,\n * so `updatedAt` is left alone.\n *\n * Paged by document id rather than re-run: a record already holding the\n * group stays in the query's answer.\n */\nexport async function regroupEverywhere(\n firestore: FirebaseFirestore.Firestore,\n records: FirebaseFirestore.CollectionReference,\n target: CrmPicklistTarget,\n label: string,\n group: string | null,\n): Promise<number> {\n const key = crmPicklistKey(label)\n if (!key || !target.keyField || !target.groupField) return 0\n const query = records\n .where(target.keyField, '==', key)\n .orderBy(FieldPath.documentId())\n .limit(BATCH_SIZE)\n let written = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n const page: FirebaseFirestore.QuerySnapshot = await (after ? query.startAfter(after) : query).get()\n if (page.empty) return written\n const batch = firestore.batch()\n let changed = 0\n for (const snapshot of page.docs) {\n if (snapshot.get(target.groupField) === group) continue\n batch.update(snapshot.ref, { [target.groupField]: group })\n changed += 1\n }\n if (changed) await batch.commit()\n written += changed\n if (page.size < BATCH_SIZE) return written\n after = page.docs[page.docs.length - 1] ?? null\n }\n}\n"],"names":["crmPicklistKey","crmPicklistValueByLabel","FieldPath","BATCH_SIZE","picklistGroupOf","picklist","label","group","regroupEverywhere","firestore","records","target","key","keyField","groupField","query","where","orderBy","documentId","limit","written","after","page","startAfter","get","empty","batch","changed","snapshot","docs","update","ref","commit","size","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,yEAAyE;AACzE,0EAA0E;AAC1E,SAGEA,cAAc,EACdC,uBAAuB,QAClB,6BAA4B;AACnC,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,kEAAkE,GAClE,MAAMC,aAAa;AAEnB,mGAAmG,GACnG,OAAO,SAASC,gBAAgBC,QAAqB,EAAEC,KAAoB;QACjEA;QAAwBL;IAAhC,QAAQK,OAAAA,UAAU,OAAO,QAAOL,2BAAAA,wBAAwBI,UAAUC,2BAAlCL,yBAA0CM,KAAK,YAAvED,OAA4E;AACtF;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeE,kBACpBC,SAAsC,EACtCC,OAA8C,EAC9CC,MAAyB,EACzBL,KAAa,EACbC,KAAoB;IAEpB,MAAMK,MAAMZ,eAAeM;IAC3B,IAAI,CAACM,OAAO,CAACD,OAAOE,QAAQ,IAAI,CAACF,OAAOG,UAAU,EAAE,OAAO;IAC3D,MAAMC,QAAQL,QACXM,KAAK,CAACL,OAAOE,QAAQ,EAAE,MAAMD,KAC7BK,OAAO,CAACf,UAAUgB,UAAU,IAC5BC,KAAK,CAAChB;IACT,IAAIiB,UAAU;IACd,IAAIC,QAAwD;IAC5D,OAAS;YAaCC;QAZR,MAAMA,OAAwC,MAAM,AAACD,CAAAA,QAAQN,MAAMQ,UAAU,CAACF,SAASN,KAAI,EAAGS,GAAG;QACjG,IAAIF,KAAKG,KAAK,EAAE,OAAOL;QACvB,MAAMM,QAAQjB,UAAUiB,KAAK;QAC7B,IAAIC,UAAU;QACd,KAAK,MAAMC,YAAYN,KAAKO,IAAI,CAAE;YAChC,IAAID,SAASJ,GAAG,CAACb,OAAOG,UAAU,MAAMP,OAAO;YAC/CmB,MAAMI,MAAM,CAACF,SAASG,GAAG,EAAE;gBAAE,CAACpB,OAAOG,UAAU,CAAC,EAAEP;YAAM;YACxDoB,WAAW;QACb;QACA,IAAIA,SAAS,MAAMD,MAAMM,MAAM;QAC/BZ,WAAWO;QACX,IAAIL,KAAKW,IAAI,GAAG9B,YAAY,OAAOiB;QACnCC,SAAQC,cAAAA,KAAKO,IAAI,CAACP,KAAKO,IAAI,CAACK,MAAM,GAAG,EAAE,YAA/BZ,cAAmC;IAC7C;AACF"}
|
|
@@ -14,20 +14,8 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type
|
|
18
|
-
|
|
19
|
-
export declare function picklistGroupOf(picklist: CrmPicklist, label: string | null): string | null;
|
|
20
|
-
/**
|
|
21
|
-
* Rewrite a target's GROUP field (AGL-3577) — a lead's
|
|
22
|
-
* `leadSourceDirection` — on every record holding `label` in any spelling
|
|
23
|
-
* (by its `keyField`) whose group is not `group` already. Answers how many
|
|
24
|
-
* were written. The field is derived, like the list keys a restamp writes,
|
|
25
|
-
* so `updatedAt` is left alone.
|
|
26
|
-
*
|
|
27
|
-
* Paged by document id rather than re-run: a record already holding the
|
|
28
|
-
* group stays in the query's answer.
|
|
29
|
-
*/
|
|
30
|
-
export declare function regroupEverywhere(firestore: FirebaseFirestore.Firestore, records: FirebaseFirestore.CollectionReference, target: CrmPicklistTarget, label: string, group: string | null): Promise<number>;
|
|
17
|
+
import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
|
+
export { picklistGroupOf, regroupEverywhere } from './picklist-regroup';
|
|
31
19
|
/** `POST crm/picklist-values` — any registered picklist, named by `picklistId`. */
|
|
32
20
|
export declare const crmPicklistValuesHandler: PluginApiHandler;
|
|
33
21
|
/** `POST crm/lead-source-values` — the same route with the picklist fixed to the lead source. */
|
|
@@ -14,12 +14,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import { consentGroupForHost, CONTACT_FACETS_FIELD, CRM_COLLECTIONS, CRM_CONTACT_FACET_KEYS_FIELD, CRM_LEAD_SOURCE_PICKLIST, crmContactFacetKeys, crmPicklistDefinition, crmPicklistKey,
|
|
17
|
+
*/ import { consentGroupForHost, CONTACT_FACETS_FIELD, CRM_COLLECTIONS, CRM_CONTACT_FACET_KEYS_FIELD, CRM_LEAD_SOURCE_PICKLIST, crmContactFacetKeys, crmPicklistDefinition, crmPicklistKey, effectiveCrmPicklist, newResourceScopeFields, normalizeCrmPicklist, ORG_SCOPE_TOKEN } from "@aglyn/aglyn/server";
|
|
18
18
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { FieldPath, FieldValue } from "firebase-admin/firestore";
|
|
20
20
|
import { addPicklistValue, deletePicklistValue, picklistKeepsGroups, renamePicklistValue, setPicklistValueGroup } from "../model/picklist-values.js";
|
|
21
21
|
import { orgHostIds, readCrmRouteScope } from "./org-caller.js";
|
|
22
|
+
import { picklistGroupOf, regroupEverywhere } from "./picklist-regroup.js";
|
|
22
23
|
import { authorizeCrmWriter } from "./task-routes.js";
|
|
24
|
+
export { picklistGroupOf, regroupEverywhere } from "./picklist-regroup.js";
|
|
23
25
|
/** What the suite gate names when a plan without the CRM asks. */ const suiteAct = (definition)=>`Editing the organization's ${definition.plural}`;
|
|
24
26
|
/** The org subcollection each target object's records live in. */ const TARGET_COLLECTIONS = {
|
|
25
27
|
contact: 'contacts',
|
|
@@ -110,45 +112,6 @@ import { authorizeCrmWriter } from "./task-routes.js";
|
|
|
110
112
|
after = (_page_docs_ = page.docs[page.docs.length - 1]) != null ? _page_docs_ : null;
|
|
111
113
|
}
|
|
112
114
|
}
|
|
113
|
-
/** The group a label is filed under in `picklist` — `null` for none, or a label it does not hold. */ export function picklistGroupOf(picklist, label) {
|
|
114
|
-
var _ref;
|
|
115
|
-
var _crmPicklistValueByLabel;
|
|
116
|
-
return (_ref = label === null ? null : (_crmPicklistValueByLabel = crmPicklistValueByLabel(picklist, label)) == null ? void 0 : _crmPicklistValueByLabel.group) != null ? _ref : null;
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Rewrite a target's GROUP field (AGL-3577) — a lead's
|
|
120
|
-
* `leadSourceDirection` — on every record holding `label` in any spelling
|
|
121
|
-
* (by its `keyField`) whose group is not `group` already. Answers how many
|
|
122
|
-
* were written. The field is derived, like the list keys a restamp writes,
|
|
123
|
-
* so `updatedAt` is left alone.
|
|
124
|
-
*
|
|
125
|
-
* Paged by document id rather than re-run: a record already holding the
|
|
126
|
-
* group stays in the query's answer.
|
|
127
|
-
*/ export async function regroupEverywhere(firestore, records, target, label, group) {
|
|
128
|
-
const key = crmPicklistKey(label);
|
|
129
|
-
if (!key || !target.keyField || !target.groupField) return 0;
|
|
130
|
-
const query = records.where(target.keyField, '==', key).orderBy(FieldPath.documentId()).limit(BATCH_SIZE);
|
|
131
|
-
let written = 0;
|
|
132
|
-
let after = null;
|
|
133
|
-
for(;;){
|
|
134
|
-
var _page_docs_;
|
|
135
|
-
const page = await (after ? query.startAfter(after) : query).get();
|
|
136
|
-
if (page.empty) return written;
|
|
137
|
-
const batch = firestore.batch();
|
|
138
|
-
let changed = 0;
|
|
139
|
-
for (const snapshot of page.docs){
|
|
140
|
-
if (snapshot.get(target.groupField) === group) continue;
|
|
141
|
-
batch.update(snapshot.ref, {
|
|
142
|
-
[target.groupField]: group
|
|
143
|
-
});
|
|
144
|
-
changed += 1;
|
|
145
|
-
}
|
|
146
|
-
if (changed) await batch.commit();
|
|
147
|
-
written += changed;
|
|
148
|
-
if (page.size < BATCH_SIZE) return written;
|
|
149
|
-
after = (_page_docs_ = page.docs[page.docs.length - 1]) != null ? _page_docs_ : null;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
115
|
/** A contact as it reads once one holder's facet field holds `to` (or nothing, for `null`). */ function withFacetValue(data, groupId, field, to) {
|
|
153
116
|
var _data_CONTACT_FACETS_FIELD, _facets_groupId;
|
|
154
117
|
const facets = _extends({}, (_data_CONTACT_FACETS_FIELD = data[CONTACT_FACETS_FIELD]) != null ? _data_CONTACT_FACETS_FIELD : {});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/picklist-values.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 consentGroupForHost,\n CONTACT_FACETS_FIELD,\n CRM_COLLECTIONS,\n CRM_CONTACT_FACET_KEYS_FIELD,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n type CrmPicklistDefinition,\n type CrmPicklistId,\n type CrmPicklistObject,\n type CrmPicklistTarget,\n crmContactFacetKeys,\n crmPicklistDefinition,\n crmPicklistKey,\n crmPicklistValueByLabel,\n effectiveCrmPicklist,\n newResourceScopeFields,\n normalizeCrmPicklist,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport {\n addPicklistValue,\n deletePicklistValue,\n picklistKeepsGroups,\n type PicklistMove,\n type PicklistValuesResponse,\n renamePicklistValue,\n setPicklistValueGroup,\n} from '../model/picklist-values'\nimport { orgHostIds, readCrmRouteScope } from './org-caller'\nimport { authorizeCrmWriter } from './task-routes'\n\n/** What the suite gate names when a plan without the CRM asks. */\nconst suiteAct = (definition: CrmPicklistDefinition) =>\n `Editing the organization's ${definition.plural}`\n\n/** The org subcollection each target object's records live in. */\nconst TARGET_COLLECTIONS: Record<CrmPicklistObject, string> = {\n contact: 'contacts',\n lead: 'leads',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n task: CRM_COLLECTIONS.tasks,\n}\n\n/** Writes per batch — under Firestore's 500, with room to spare. */\nconst BATCH_SIZE = 400\n\n/**\n * Set `field` to `to` (or remove it, for `null`) on every document `query`\n * finds holding `from`, a batch at a time, with `beside` written alongside.\n * Answers how many were written.\n *\n * The query is re-run after each batch rather than paged, because each\n * batch moves its documents OUT of the query's answer — the next run finds\n * only what is left, and a run that finds nothing is the end.\n */\nasync function replaceEverywhere(\n firestore: FirebaseFirestore.Firestore,\n query: FirebaseFirestore.Query,\n field: string | FirebaseFirestore.FieldPath,\n to: string | null,\n beside:\n | Record<string, unknown>\n | ((snapshot: FirebaseFirestore.QueryDocumentSnapshot) => Record<string, unknown>) = {},\n): Promise<number> {\n let written = 0\n for (;;) {\n const page = await query.limit(BATCH_SIZE).get()\n if (page.empty) return written\n const batch = firestore.batch()\n for (const snapshot of page.docs) {\n const alongside = typeof beside === 'function' ? beside(snapshot) : beside\n batch.update(\n snapshot.ref,\n field,\n to ?? FieldValue.delete(),\n 'updatedAt',\n FieldValue.serverTimestamp(),\n ...Object.entries(alongside).flat(),\n )\n }\n await batch.commit()\n written += page.size\n if (page.size < BATCH_SIZE) return written\n }\n}\n\n/**\n * Rewrite an ARRAY target (AGL-3521): every record whose `keyField` lists\n * the old label's key has each entry of `field` holding `from` at\n * `arrayKey` moved to `to` — or the entry's label removed, for `null` —\n * and its `keyField` restamped from the entries as moved. Answers how many\n * records were written.\n *\n * Paged by document id rather than re-run, because a rename that changes\n * only the label's case keeps its key, so a written record can stay in the\n * query's answer.\n */\nasync function replaceInArrayEverywhere(\n firestore: FirebaseFirestore.Firestore,\n records: FirebaseFirestore.CollectionReference,\n target: CrmPicklistTarget & { arrayKey: string; keyField: string },\n from: string,\n to: string | null,\n): Promise<number> {\n const fromKey = crmPicklistKey(from)\n if (!fromKey) return 0\n const query = records\n .where(target.keyField, 'array-contains', fromKey)\n .orderBy(FieldPath.documentId())\n .limit(BATCH_SIZE)\n let written = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n const page: FirebaseFirestore.QuerySnapshot = await (after ? query.startAfter(after) : query).get()\n if (page.empty) return written\n const batch = firestore.batch()\n let changed = 0\n for (const snapshot of page.docs) {\n const entries = snapshot.get(target.field)\n if (!Array.isArray(entries)) continue\n let moved = false\n const next = entries.map((entry: unknown) => {\n if (!entry || typeof entry !== 'object') return entry\n const row = entry as Record<string, unknown>\n if (row[target.arrayKey] !== from) return entry\n moved = true\n const rest = { ...row }\n delete rest[target.arrayKey]\n return to === null ? rest : { ...rest, [target.arrayKey]: to }\n })\n if (!moved) continue\n const keys = new Set<string>()\n for (const entry of next) {\n const key =\n entry && typeof entry === 'object'\n ? crmPicklistKey((entry as Record<string, unknown>)[target.arrayKey])\n : null\n if (key) keys.add(key)\n }\n batch.update(snapshot.ref, {\n [target.field]: next,\n [target.keyField]: [...keys],\n updatedAt: FieldValue.serverTimestamp(),\n })\n changed += 1\n }\n if (changed) await batch.commit()\n written += changed\n if (page.size < BATCH_SIZE) return written\n after = page.docs[page.docs.length - 1] ?? null\n }\n}\n\n/** The group a label is filed under in `picklist` — `null` for none, or a label it does not hold. */\nexport function picklistGroupOf(picklist: CrmPicklist, label: string | null): string | null {\n return (label === null ? null : crmPicklistValueByLabel(picklist, label)?.group) ?? null\n}\n\n/**\n * Rewrite a target's GROUP field (AGL-3577) — a lead's\n * `leadSourceDirection` — on every record holding `label` in any spelling\n * (by its `keyField`) whose group is not `group` already. Answers how many\n * were written. The field is derived, like the list keys a restamp writes,\n * so `updatedAt` is left alone.\n *\n * Paged by document id rather than re-run: a record already holding the\n * group stays in the query's answer.\n */\nexport async function regroupEverywhere(\n firestore: FirebaseFirestore.Firestore,\n records: FirebaseFirestore.CollectionReference,\n target: CrmPicklistTarget,\n label: string,\n group: string | null,\n): Promise<number> {\n const key = crmPicklistKey(label)\n if (!key || !target.keyField || !target.groupField) return 0\n const query = records\n .where(target.keyField, '==', key)\n .orderBy(FieldPath.documentId())\n .limit(BATCH_SIZE)\n let written = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n const page: FirebaseFirestore.QuerySnapshot = await (after ? query.startAfter(after) : query).get()\n if (page.empty) return written\n const batch = firestore.batch()\n let changed = 0\n for (const snapshot of page.docs) {\n if (snapshot.get(target.groupField) === group) continue\n batch.update(snapshot.ref, { [target.groupField]: group })\n changed += 1\n }\n if (changed) await batch.commit()\n written += changed\n if (page.size < BATCH_SIZE) return written\n after = page.docs[page.docs.length - 1] ?? null\n }\n}\n\n/** A contact as it reads once one holder's facet field holds `to` (or nothing, for `null`). */\nfunction withFacetValue(\n data: Record<string, unknown>,\n groupId: string,\n field: string,\n to: string | null,\n): Record<string, unknown> {\n const facets = { ...((data[CONTACT_FACETS_FIELD] as Record<string, unknown> | undefined) ?? {}) }\n const facet = { ...((facets[groupId] as Record<string, unknown> | undefined) ?? {}) }\n if (to === null) delete facet[field]\n else facet[field] = to\n facets[groupId] = facet\n return { ...data, [CONTACT_FACETS_FIELD]: facets }\n}\n\n/**\n * `POST crm/picklist-values` — rename a value of one of the CRM's standard\n * picklists, or delete an added one and move its records to another\n * (AGL-3298, AGL-3510). `crm/lead-source-values` is the same route with the\n * picklist fixed to the lead source.\n *\n * Body: `{ hostId | orgId, picklistId, action: 'rename', valueId, label }` or\n * `{ hostId | orgId, picklistId, action: 'delete', valueId, replaceWith: label | null }`,\n * and, on a list whose records keep the value's group (`picklistKeepsGroups`,\n * AGL-3577), `{ …, action: 'group', valueId, group: id | null }` or\n * `{ …, action: 'add', label, group?, meaning? }`.\n * `picklistId` is one of `CRM_PICKLIST_DEFINITIONS`; anything else is refused.\n *\n * ## A value's group on its records\n *\n * A lead keeps its lead source's group as `leadSourceDirection` — the field\n * the Leads list's direction filter asks. Any move can change the group a\n * label has: a regroup, an add of a value records already hold, a rename\n * onto such a label, a delete. So after the move, every target naming a\n * `groupField` has it rewritten on the records holding the old label and\n * the new one, from the list as it now stands.\n *\n * Records store the value's LABEL (see the picklist block in `crm.ts`), so\n * both moves change records as well as the list: every record the\n * definition's `targets` name that holds the old label is rewritten to the\n * new one — or, for a delete with no replacement, cleared. That is\n * Salesforce's Replace, done as part of the move, so a report grouped by\n * the field follows a rename instead of splitting into the old name and\n * the new. A standard value cannot be deleted, and on a definition with\n * meanings a delete's replacement must mean the same (see\n * `deletePicklistValue`).\n *\n * ## The list first, then the records\n *\n * The list is written in a transaction before any record: from that moment\n * no picker offers the old label and no import or API write accepts it, so\n * the sweep that follows cannot be outrun by a new record taking the name\n * it is removing. A sweep interrupted part-way leaves records holding a\n * label the list no longer has, which they show as \"(not in the list)\"; the\n * same request sent again finishes it, because the rename of a value to its\n * own current label is a no-op on the list and still sweeps.\n *\n * ## Who may\n *\n * Whoever may write the CRM — `authorizeCrmWriter`, the question every CRM\n * route asks — which is who the rules let edit the list itself. The sweep\n * reaches every record in the org whatever the caller's scope: it changes\n * one label to another that the same caller could already have picked, and\n * reveals nothing about the records but their count.\n */\nfunction picklistValuesHandler(fixed?: CrmPicklistId): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body = (req.body ?? {}) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const definition = crmPicklistDefinition(fixed ?? body['picklistId'])\n if (!definition) {\n res.status(400).json({ error: 'Name one of the CRM’s picklists.' })\n return\n }\n const picklistId = definition.id as CrmPicklistId\n const action = body['action']\n const valueId = String(body['valueId'] ?? '').trim().slice(0, 64)\n const regrouping = action === 'group' || action === 'add'\n if (regrouping && !picklistKeepsGroups(definition)) {\n res.status(400).json({ error: `The ${definition.plural} are added and grouped on the Fields page.` })\n return\n }\n if (\n !(action === 'rename' || action === 'delete' || regrouping) ||\n (action === 'add' ? !String(body['label'] ?? '').trim() : !valueId)\n ) {\n res.status(400).json({ error: 'Name a value, and whether to rename or delete it.' })\n return\n }\n const asGroup = (raw: unknown) => (typeof raw === 'string' && raw ? raw : null)\n const replaceWith =\n body['replaceWith'] === null || body['replaceWith'] === undefined\n ? null\n : String(body['replaceWith'])\n\n try {\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: suiteAct(definition) })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(writer.orgId)\n const listRef = orgRef.collection(CRM_COLLECTIONS.picklists).doc(picklistId)\n\n /*\n * THE LIST. Read and written in one transaction, so two admins editing\n * at once cannot each write a list missing the other's change.\n */\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(listRef)\n const before: CrmPicklist = effectiveCrmPicklist(picklistId, snapshot.data())\n const value =\n action === 'add' ? null : before.values.find((entry) => entry.id === valueId)\n if (action !== 'add' && !value) {\n return { ok: false as const, error: 'That value is no longer in the list.' }\n }\n const move: PicklistMove =\n action === 'add'\n ? addPicklistValue(definition, before, String(body['label'] ?? ''), {\n group: asGroup(body['group']),\n meaning: asGroup(body['meaning']),\n })\n : action === 'group'\n ? { ok: true, picklist: setPicklistValueGroup(definition, before, valueId, asGroup(body['group'])) }\n : action === 'rename'\n ? renamePicklistValue(before, valueId, String(body['label'] ?? ''))\n : deletePicklistValue(definition, before, valueId, replaceWith)\n if (move.ok === false) return move\n const created = normalizeCrmPicklist(snapshot.data()) === null\n transaction.set(\n listRef,\n {\n values: move.picklist.values,\n defaultValueId: move.picklist.defaultValueId,\n updatedAt: FieldValue.serverTimestamp(),\n // The stamp every org-wide CRM document carries (see the Fields\n // page), written when this move is what creates the document.\n ...(created\n ? {\n hostId: scope.hostId || null,\n createdAt: FieldValue.serverTimestamp(),\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n }\n : {}),\n },\n { merge: true },\n )\n // A regroup and an add move no label: `from` and `to` are the value's own.\n const own =\n action === 'add'\n ? (move.picklist.values[move.picklist.values.length - 1]?.label ?? '')\n : (value?.label ?? '')\n const to =\n action === 'rename'\n ? (move.picklist.values.find((entry) => entry.id === valueId)?.label ?? null)\n : regrouping\n ? own\n : replaceWith === null\n ? null\n : (move.picklist.values.find(\n (entry) => entry.label.toLowerCase() === replaceWith.trim().toLowerCase(),\n )?.label ?? null)\n return { ok: true as const, from: regrouping ? own : (value?.label ?? ''), to, after: move.picklist }\n })\n if (moved.ok === false) {\n res.status(400).json({ error: moved.error })\n return\n }\n\n /*\n * THE RECORDS, target by target: a record's own field, with its query\n * key moved beside it; for an array target, each entry of a record's\n * list (a deal's contact roles); or, for a facet target, each holder's\n * facet on a contact — one query per consent group the org's sites\n * belong to.\n * A rename to the same label moves nothing, and says so.\n */\n const updated: PicklistValuesResponse['updated'] = {}\n let groupIds: string[] | null = null\n for (const target of definition.targets) {\n updated[target.object] ??= 0\n if (target.groupField && !target.facet && !target.arrayKey) {\n // The group each label now has, on every record holding either (AGL-3577).\n const labels = new Map<string, string>()\n for (const label of [moved.from, moved.to]) {\n const key = label === null ? null : crmPicklistKey(label)\n if (key && label !== null) labels.set(key, label)\n }\n const regroup = async () => {\n for (const label of labels.values()) {\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await regroupEverywhere(\n firestore,\n orgRef.collection(TARGET_COLLECTIONS[target.object]),\n target,\n label,\n picklistGroupOf(moved.after, label),\n ))\n }\n }\n if (moved.from === moved.to) {\n await regroup()\n continue\n }\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n orgRef.collection(TARGET_COLLECTIONS[target.object]).where(target.field, '==', moved.from),\n target.field,\n moved.to,\n {\n ...(target.keyField ? { [target.keyField]: crmPicklistKey(moved.to) } : {}),\n [target.groupField]: picklistGroupOf(moved.after, moved.to),\n },\n ))\n await regroup()\n continue\n }\n if (moved.from === moved.to) continue\n const records = orgRef.collection(TARGET_COLLECTIONS[target.object])\n if (target.arrayKey && target.keyField) {\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceInArrayEverywhere(\n firestore,\n records,\n { ...target, arrayKey: target.arrayKey, keyField: target.keyField },\n moved.from,\n moved.to,\n ))\n continue\n }\n if (target.facet) {\n if (!groupIds) {\n const hostIds = await orgHostIds(firestore, writer.orgId)\n groupIds = [\n ...new Set(hostIds.map((hostId) => consentGroupForHost(writer.org, hostId).groupId)),\n ].filter(Boolean)\n }\n for (const groupId of groupIds) {\n const path = new FieldPath(CONTACT_FACETS_FIELD, groupId, target.field)\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n records.where(path, '==', moved.from),\n path,\n moved.to,\n // A facet value a contact list filters by is keyed in\n // `facetKeys` (AGL-3511), restamped from the record as moved.\n (snapshot) => ({\n [CRM_CONTACT_FACET_KEYS_FIELD]: crmContactFacetKeys(\n withFacetValue(snapshot.data(), groupId, target.field, moved.to),\n ),\n }),\n ))\n }\n continue\n }\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n records.where(target.field, '==', moved.from),\n target.field,\n moved.to,\n target.keyField ? { [target.keyField]: crmPicklistKey(moved.to) } : {},\n ))\n }\n const answer: PicklistValuesResponse = { ok: true, updated }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] picklist-values failed', error)\n res.status(500).json({ error: `The ${definition.plural} could not be saved.` })\n }\n }\n}\n\n/** `POST crm/picklist-values` — any registered picklist, named by `picklistId`. */\nexport const crmPicklistValuesHandler: PluginApiHandler = picklistValuesHandler()\n\n/** `POST crm/lead-source-values` — the same route with the picklist fixed to the lead source. */\nexport const crmLeadSourceValuesHandler: PluginApiHandler =\n picklistValuesHandler(CRM_LEAD_SOURCE_PICKLIST)\n"],"names":["consentGroupForHost","CONTACT_FACETS_FIELD","CRM_COLLECTIONS","CRM_CONTACT_FACET_KEYS_FIELD","CRM_LEAD_SOURCE_PICKLIST","crmContactFacetKeys","crmPicklistDefinition","crmPicklistKey","crmPicklistValueByLabel","effectiveCrmPicklist","newResourceScopeFields","normalizeCrmPicklist","ORG_SCOPE_TOKEN","firebaseAdmin","FieldPath","FieldValue","addPicklistValue","deletePicklistValue","picklistKeepsGroups","renamePicklistValue","setPicklistValueGroup","orgHostIds","readCrmRouteScope","authorizeCrmWriter","suiteAct","definition","plural","TARGET_COLLECTIONS","contact","lead","company","companies","deal","deals","task","tasks","BATCH_SIZE","replaceEverywhere","firestore","query","field","to","beside","written","page","limit","get","empty","batch","snapshot","docs","alongside","update","ref","delete","serverTimestamp","Object","entries","flat","commit","size","replaceInArrayEverywhere","records","target","from","fromKey","where","keyField","orderBy","documentId","after","startAfter","changed","Array","isArray","moved","next","map","entry","row","arrayKey","rest","keys","Set","key","add","updatedAt","length","picklistGroupOf","picklist","label","group","regroupEverywhere","groupField","withFacetValue","data","groupId","facets","facet","picklistValuesHandler","fixed","req","res","body","method","setHeader","status","json","error","scope","picklistId","id","action","valueId","String","trim","slice","regrouping","asGroup","raw","replaceWith","undefined","writer","ok","app","orgRef","collection","doc","orgId","listRef","picklists","runTransaction","transaction","move","before","value","values","find","meaning","created","set","defaultValueId","hostId","createdAt","merge","own","toLowerCase","updated","groupIds","targets","object","labels","Map","regroup","hostIds","org","filter","Boolean","path","answer","console","crmPicklistValuesHandler","crmLeadSourceValuesHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,EACfC,4BAA4B,EAC5BC,wBAAwB,EAMxBC,mBAAmB,EACnBC,qBAAqB,EACrBC,cAAc,EACdC,uBAAuB,EACvBC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,eAAe,QAEV,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SACEC,gBAAgB,EAChBC,mBAAmB,EACnBC,mBAAmB,EAGnBC,mBAAmB,EACnBC,qBAAqB,QAChB,8BAA0B;AACjC,SAASC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;AAC5D,SAASC,kBAAkB,QAAQ,mBAAe;AAElD,gEAAgE,GAChE,MAAMC,WAAW,CAACC,aAChB,CAAC,2BAA2B,EAAEA,WAAWC,MAAM,EAAE;AAEnD,gEAAgE,GAChE,MAAMC,qBAAwD;IAC5DC,SAAS;IACTC,MAAM;IACNC,SAAS5B,gBAAgB6B,SAAS;IAClCC,MAAM9B,gBAAgB+B,KAAK;IAC3BC,MAAMhC,gBAAgBiC,KAAK;AAC7B;AAEA,kEAAkE,GAClE,MAAMC,aAAa;AAEnB;;;;;;;;CAQC,GACD,eAAeC,kBACbC,SAAsC,EACtCC,KAA8B,EAC9BC,KAA2C,EAC3CC,EAAiB,EACjBC,SAEuF,CAAC,CAAC;IAEzF,IAAIC,UAAU;IACd,OAAS;QACP,MAAMC,OAAO,MAAML,MAAMM,KAAK,CAACT,YAAYU,GAAG;QAC9C,IAAIF,KAAKG,KAAK,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,MAAMmC,MAAMX,IAAI,GAC5CD,OAAOvB,KAAK,EACZmC,MAAMlC,EAAE,EACRsB,OAAOI,QAAQ,GAAG;oBAAE,CAACJ,OAAOI,QAAQ,CAAC,EAAE5D,eAAeoE,MAAMlC,EAAE;gBAAE,IAAI,CAAC;YAE3E;YACA,MAAMsH,SAAiC;gBAAEpC,IAAI;gBAAMwB;YAAQ;YAC3D7C,IAAII,MAAM,CAAC,KAAKC,IAAI,CAACoD;QACvB,EAAE,OAAOnD,OAAO;YACdoD,QAAQpD,KAAK,CAAC,gCAAgCA;YAC9CN,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO,CAAC,IAAI,EAAEnF,WAAWC,MAAM,CAAC,oBAAoB,CAAC;YAAC;QAC/E;IACF;AACF;AAEA,iFAAiF,GACjF,OAAO,MAAMuI,2BAA6C9D,wBAAuB;AAEjF,+FAA+F,GAC/F,OAAO,MAAM+D,6BACX/D,sBAAsB/F,0BAAyB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/picklist-values.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 consentGroupForHost,\n CONTACT_FACETS_FIELD,\n CRM_COLLECTIONS,\n CRM_CONTACT_FACET_KEYS_FIELD,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n type CrmPicklistDefinition,\n type CrmPicklistId,\n type CrmPicklistObject,\n type CrmPicklistTarget,\n crmContactFacetKeys,\n crmPicklistDefinition,\n crmPicklistKey,\n effectiveCrmPicklist,\n newResourceScopeFields,\n normalizeCrmPicklist,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport {\n addPicklistValue,\n deletePicklistValue,\n picklistKeepsGroups,\n type PicklistMove,\n type PicklistValuesResponse,\n renamePicklistValue,\n setPicklistValueGroup,\n} from '../model/picklist-values'\nimport { orgHostIds, readCrmRouteScope } from './org-caller'\nimport { picklistGroupOf, regroupEverywhere } from './picklist-regroup'\nimport { authorizeCrmWriter } from './task-routes'\n\nexport { picklistGroupOf, regroupEverywhere } from './picklist-regroup'\n\n/** What the suite gate names when a plan without the CRM asks. */\nconst suiteAct = (definition: CrmPicklistDefinition) =>\n `Editing the organization's ${definition.plural}`\n\n/** The org subcollection each target object's records live in. */\nconst TARGET_COLLECTIONS: Record<CrmPicklistObject, string> = {\n contact: 'contacts',\n lead: 'leads',\n company: CRM_COLLECTIONS.companies,\n deal: CRM_COLLECTIONS.deals,\n task: CRM_COLLECTIONS.tasks,\n}\n\n/** Writes per batch — under Firestore's 500, with room to spare. */\nconst BATCH_SIZE = 400\n\n/**\n * Set `field` to `to` (or remove it, for `null`) on every document `query`\n * finds holding `from`, a batch at a time, with `beside` written alongside.\n * Answers how many were written.\n *\n * The query is re-run after each batch rather than paged, because each\n * batch moves its documents OUT of the query's answer — the next run finds\n * only what is left, and a run that finds nothing is the end.\n */\nasync function replaceEverywhere(\n firestore: FirebaseFirestore.Firestore,\n query: FirebaseFirestore.Query,\n field: string | FirebaseFirestore.FieldPath,\n to: string | null,\n beside:\n | Record<string, unknown>\n | ((snapshot: FirebaseFirestore.QueryDocumentSnapshot) => Record<string, unknown>) = {},\n): Promise<number> {\n let written = 0\n for (;;) {\n const page = await query.limit(BATCH_SIZE).get()\n if (page.empty) return written\n const batch = firestore.batch()\n for (const snapshot of page.docs) {\n const alongside = typeof beside === 'function' ? beside(snapshot) : beside\n batch.update(\n snapshot.ref,\n field,\n to ?? FieldValue.delete(),\n 'updatedAt',\n FieldValue.serverTimestamp(),\n ...Object.entries(alongside).flat(),\n )\n }\n await batch.commit()\n written += page.size\n if (page.size < BATCH_SIZE) return written\n }\n}\n\n/**\n * Rewrite an ARRAY target (AGL-3521): every record whose `keyField` lists\n * the old label's key has each entry of `field` holding `from` at\n * `arrayKey` moved to `to` — or the entry's label removed, for `null` —\n * and its `keyField` restamped from the entries as moved. Answers how many\n * records were written.\n *\n * Paged by document id rather than re-run, because a rename that changes\n * only the label's case keeps its key, so a written record can stay in the\n * query's answer.\n */\nasync function replaceInArrayEverywhere(\n firestore: FirebaseFirestore.Firestore,\n records: FirebaseFirestore.CollectionReference,\n target: CrmPicklistTarget & { arrayKey: string; keyField: string },\n from: string,\n to: string | null,\n): Promise<number> {\n const fromKey = crmPicklistKey(from)\n if (!fromKey) return 0\n const query = records\n .where(target.keyField, 'array-contains', fromKey)\n .orderBy(FieldPath.documentId())\n .limit(BATCH_SIZE)\n let written = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n const page: FirebaseFirestore.QuerySnapshot = await (after ? query.startAfter(after) : query).get()\n if (page.empty) return written\n const batch = firestore.batch()\n let changed = 0\n for (const snapshot of page.docs) {\n const entries = snapshot.get(target.field)\n if (!Array.isArray(entries)) continue\n let moved = false\n const next = entries.map((entry: unknown) => {\n if (!entry || typeof entry !== 'object') return entry\n const row = entry as Record<string, unknown>\n if (row[target.arrayKey] !== from) return entry\n moved = true\n const rest = { ...row }\n delete rest[target.arrayKey]\n return to === null ? rest : { ...rest, [target.arrayKey]: to }\n })\n if (!moved) continue\n const keys = new Set<string>()\n for (const entry of next) {\n const key =\n entry && typeof entry === 'object'\n ? crmPicklistKey((entry as Record<string, unknown>)[target.arrayKey])\n : null\n if (key) keys.add(key)\n }\n batch.update(snapshot.ref, {\n [target.field]: next,\n [target.keyField]: [...keys],\n updatedAt: FieldValue.serverTimestamp(),\n })\n changed += 1\n }\n if (changed) await batch.commit()\n written += changed\n if (page.size < BATCH_SIZE) return written\n after = page.docs[page.docs.length - 1] ?? null\n }\n}\n\n/** A contact as it reads once one holder's facet field holds `to` (or nothing, for `null`). */\nfunction withFacetValue(\n data: Record<string, unknown>,\n groupId: string,\n field: string,\n to: string | null,\n): Record<string, unknown> {\n const facets = { ...((data[CONTACT_FACETS_FIELD] as Record<string, unknown> | undefined) ?? {}) }\n const facet = { ...((facets[groupId] as Record<string, unknown> | undefined) ?? {}) }\n if (to === null) delete facet[field]\n else facet[field] = to\n facets[groupId] = facet\n return { ...data, [CONTACT_FACETS_FIELD]: facets }\n}\n\n/**\n * `POST crm/picklist-values` — rename a value of one of the CRM's standard\n * picklists, or delete an added one and move its records to another\n * (AGL-3298, AGL-3510). `crm/lead-source-values` is the same route with the\n * picklist fixed to the lead source.\n *\n * Body: `{ hostId | orgId, picklistId, action: 'rename', valueId, label }` or\n * `{ hostId | orgId, picklistId, action: 'delete', valueId, replaceWith: label | null }`,\n * and, on a list whose records keep the value's group (`picklistKeepsGroups`,\n * AGL-3577), `{ …, action: 'group', valueId, group: id | null }` or\n * `{ …, action: 'add', label, group?, meaning? }`.\n * `picklistId` is one of `CRM_PICKLIST_DEFINITIONS`; anything else is refused.\n *\n * ## A value's group on its records\n *\n * A lead keeps its lead source's group as `leadSourceDirection` — the field\n * the Leads list's direction filter asks. Any move can change the group a\n * label has: a regroup, an add of a value records already hold, a rename\n * onto such a label, a delete. So after the move, every target naming a\n * `groupField` has it rewritten on the records holding the old label and\n * the new one, from the list as it now stands.\n *\n * Records store the value's LABEL (see the picklist block in `crm.ts`), so\n * both moves change records as well as the list: every record the\n * definition's `targets` name that holds the old label is rewritten to the\n * new one — or, for a delete with no replacement, cleared. That is\n * Salesforce's Replace, done as part of the move, so a report grouped by\n * the field follows a rename instead of splitting into the old name and\n * the new. A standard value cannot be deleted, and on a definition with\n * meanings a delete's replacement must mean the same (see\n * `deletePicklistValue`).\n *\n * ## The list first, then the records\n *\n * The list is written in a transaction before any record: from that moment\n * no picker offers the old label and no import or API write accepts it, so\n * the sweep that follows cannot be outrun by a new record taking the name\n * it is removing. A sweep interrupted part-way leaves records holding a\n * label the list no longer has, which they show as \"(not in the list)\"; the\n * same request sent again finishes it, because the rename of a value to its\n * own current label is a no-op on the list and still sweeps.\n *\n * ## Who may\n *\n * Whoever may write the CRM — `authorizeCrmWriter`, the question every CRM\n * route asks — which is who the rules let edit the list itself. The sweep\n * reaches every record in the org whatever the caller's scope: it changes\n * one label to another that the same caller could already have picked, and\n * reveals nothing about the records but their count.\n */\nfunction picklistValuesHandler(fixed?: CrmPicklistId): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const body = (req.body ?? {}) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const definition = crmPicklistDefinition(fixed ?? body['picklistId'])\n if (!definition) {\n res.status(400).json({ error: 'Name one of the CRM’s picklists.' })\n return\n }\n const picklistId = definition.id as CrmPicklistId\n const action = body['action']\n const valueId = String(body['valueId'] ?? '').trim().slice(0, 64)\n const regrouping = action === 'group' || action === 'add'\n if (regrouping && !picklistKeepsGroups(definition)) {\n res.status(400).json({ error: `The ${definition.plural} are added and grouped on the Fields page.` })\n return\n }\n if (\n !(action === 'rename' || action === 'delete' || regrouping) ||\n (action === 'add' ? !String(body['label'] ?? '').trim() : !valueId)\n ) {\n res.status(400).json({ error: 'Name a value, and whether to rename or delete it.' })\n return\n }\n const asGroup = (raw: unknown) => (typeof raw === 'string' && raw ? raw : null)\n const replaceWith =\n body['replaceWith'] === null || body['replaceWith'] === undefined\n ? null\n : String(body['replaceWith'])\n\n try {\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: suiteAct(definition) })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(writer.orgId)\n const listRef = orgRef.collection(CRM_COLLECTIONS.picklists).doc(picklistId)\n\n /*\n * THE LIST. Read and written in one transaction, so two admins editing\n * at once cannot each write a list missing the other's change.\n */\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(listRef)\n const before: CrmPicklist = effectiveCrmPicklist(picklistId, snapshot.data())\n const value =\n action === 'add' ? null : before.values.find((entry) => entry.id === valueId)\n if (action !== 'add' && !value) {\n return { ok: false as const, error: 'That value is no longer in the list.' }\n }\n const move: PicklistMove =\n action === 'add'\n ? addPicklistValue(definition, before, String(body['label'] ?? ''), {\n group: asGroup(body['group']),\n meaning: asGroup(body['meaning']),\n })\n : action === 'group'\n ? { ok: true, picklist: setPicklistValueGroup(definition, before, valueId, asGroup(body['group'])) }\n : action === 'rename'\n ? renamePicklistValue(before, valueId, String(body['label'] ?? ''))\n : deletePicklistValue(definition, before, valueId, replaceWith)\n if (move.ok === false) return move\n const created = normalizeCrmPicklist(snapshot.data()) === null\n transaction.set(\n listRef,\n {\n values: move.picklist.values,\n defaultValueId: move.picklist.defaultValueId,\n updatedAt: FieldValue.serverTimestamp(),\n // The stamp every org-wide CRM document carries (see the Fields\n // page), written when this move is what creates the document.\n ...(created\n ? {\n hostId: scope.hostId || null,\n createdAt: FieldValue.serverTimestamp(),\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n }\n : {}),\n },\n { merge: true },\n )\n // A regroup and an add move no label: `from` and `to` are the value's own.\n const own =\n action === 'add'\n ? (move.picklist.values[move.picklist.values.length - 1]?.label ?? '')\n : (value?.label ?? '')\n const to =\n action === 'rename'\n ? (move.picklist.values.find((entry) => entry.id === valueId)?.label ?? null)\n : regrouping\n ? own\n : replaceWith === null\n ? null\n : (move.picklist.values.find(\n (entry) => entry.label.toLowerCase() === replaceWith.trim().toLowerCase(),\n )?.label ?? null)\n return { ok: true as const, from: regrouping ? own : (value?.label ?? ''), to, after: move.picklist }\n })\n if (moved.ok === false) {\n res.status(400).json({ error: moved.error })\n return\n }\n\n /*\n * THE RECORDS, target by target: a record's own field, with its query\n * key moved beside it; for an array target, each entry of a record's\n * list (a deal's contact roles); or, for a facet target, each holder's\n * facet on a contact — one query per consent group the org's sites\n * belong to.\n * A rename to the same label moves nothing, and says so.\n */\n const updated: PicklistValuesResponse['updated'] = {}\n let groupIds: string[] | null = null\n for (const target of definition.targets) {\n updated[target.object] ??= 0\n if (target.groupField && !target.facet && !target.arrayKey) {\n // The group each label now has, on every record holding either (AGL-3577).\n const labels = new Map<string, string>()\n for (const label of [moved.from, moved.to]) {\n const key = label === null ? null : crmPicklistKey(label)\n if (key && label !== null) labels.set(key, label)\n }\n const regroup = async () => {\n for (const label of labels.values()) {\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await regroupEverywhere(\n firestore,\n orgRef.collection(TARGET_COLLECTIONS[target.object]),\n target,\n label,\n picklistGroupOf(moved.after, label),\n ))\n }\n }\n if (moved.from === moved.to) {\n await regroup()\n continue\n }\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n orgRef.collection(TARGET_COLLECTIONS[target.object]).where(target.field, '==', moved.from),\n target.field,\n moved.to,\n {\n ...(target.keyField ? { [target.keyField]: crmPicklistKey(moved.to) } : {}),\n [target.groupField]: picklistGroupOf(moved.after, moved.to),\n },\n ))\n await regroup()\n continue\n }\n if (moved.from === moved.to) continue\n const records = orgRef.collection(TARGET_COLLECTIONS[target.object])\n if (target.arrayKey && target.keyField) {\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceInArrayEverywhere(\n firestore,\n records,\n { ...target, arrayKey: target.arrayKey, keyField: target.keyField },\n moved.from,\n moved.to,\n ))\n continue\n }\n if (target.facet) {\n if (!groupIds) {\n const hostIds = await orgHostIds(firestore, writer.orgId)\n groupIds = [\n ...new Set(hostIds.map((hostId) => consentGroupForHost(writer.org, hostId).groupId)),\n ].filter(Boolean)\n }\n for (const groupId of groupIds) {\n const path = new FieldPath(CONTACT_FACETS_FIELD, groupId, target.field)\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n records.where(path, '==', moved.from),\n path,\n moved.to,\n // A facet value a contact list filters by is keyed in\n // `facetKeys` (AGL-3511), restamped from the record as moved.\n (snapshot) => ({\n [CRM_CONTACT_FACET_KEYS_FIELD]: crmContactFacetKeys(\n withFacetValue(snapshot.data(), groupId, target.field, moved.to),\n ),\n }),\n ))\n }\n continue\n }\n updated[target.object] =\n (updated[target.object] ?? 0) +\n (await replaceEverywhere(\n firestore,\n records.where(target.field, '==', moved.from),\n target.field,\n moved.to,\n target.keyField ? { [target.keyField]: crmPicklistKey(moved.to) } : {},\n ))\n }\n const answer: PicklistValuesResponse = { ok: true, updated }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] picklist-values failed', error)\n res.status(500).json({ error: `The ${definition.plural} could not be saved.` })\n }\n }\n}\n\n/** `POST crm/picklist-values` — any registered picklist, named by `picklistId`. */\nexport const crmPicklistValuesHandler: PluginApiHandler = picklistValuesHandler()\n\n/** `POST crm/lead-source-values` — the same route with the picklist fixed to the lead source. */\nexport const crmLeadSourceValuesHandler: PluginApiHandler =\n picklistValuesHandler(CRM_LEAD_SOURCE_PICKLIST)\n"],"names":["consentGroupForHost","CONTACT_FACETS_FIELD","CRM_COLLECTIONS","CRM_CONTACT_FACET_KEYS_FIELD","CRM_LEAD_SOURCE_PICKLIST","crmContactFacetKeys","crmPicklistDefinition","crmPicklistKey","effectiveCrmPicklist","newResourceScopeFields","normalizeCrmPicklist","ORG_SCOPE_TOKEN","firebaseAdmin","FieldPath","FieldValue","addPicklistValue","deletePicklistValue","picklistKeepsGroups","renamePicklistValue","setPicklistValueGroup","orgHostIds","readCrmRouteScope","picklistGroupOf","regroupEverywhere","authorizeCrmWriter","suiteAct","definition","plural","TARGET_COLLECTIONS","contact","lead","company","companies","deal","deals","task","tasks","BATCH_SIZE","replaceEverywhere","firestore","query","field","to","beside","written","page","limit","get","empty","batch","snapshot","docs","alongside","update","ref","delete","serverTimestamp","Object","entries","flat","commit","size","replaceInArrayEverywhere","records","target","from","fromKey","where","keyField","orderBy","documentId","after","startAfter","changed","Array","isArray","moved","next","map","entry","row","arrayKey","rest","keys","Set","key","add","updatedAt","length","withFacetValue","data","groupId","facets","facet","picklistValuesHandler","fixed","req","res","body","method","setHeader","status","json","error","scope","picklistId","id","action","valueId","String","trim","slice","regrouping","asGroup","raw","replaceWith","undefined","writer","ok","app","orgRef","collection","doc","orgId","listRef","picklists","runTransaction","transaction","move","before","value","values","find","group","meaning","picklist","created","set","defaultValueId","hostId","createdAt","merge","own","label","toLowerCase","updated","groupIds","targets","object","groupField","labels","Map","regroup","hostIds","org","filter","Boolean","path","answer","console","crmPicklistValuesHandler","crmLeadSourceValuesHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,EACfC,4BAA4B,EAC5BC,wBAAwB,EAMxBC,mBAAmB,EACnBC,qBAAqB,EACrBC,cAAc,EACdC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,eAAe,QAEV,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SACEC,gBAAgB,EAChBC,mBAAmB,EACnBC,mBAAmB,EAGnBC,mBAAmB,EACnBC,qBAAqB,QAChB,8BAA0B;AACjC,SAASC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;AAC5D,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,wBAAoB;AACvE,SAASC,kBAAkB,QAAQ,mBAAe;AAElD,SAASF,eAAe,EAAEC,iBAAiB,QAAQ,wBAAoB;AAEvE,gEAAgE,GAChE,MAAME,WAAW,CAACC,aAChB,CAAC,2BAA2B,EAAEA,WAAWC,MAAM,EAAE;AAE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AAE,EACR,sDAAsD;wBACtD,8DAA8D;wBAC9D,CAACQ,WAAc,CAAA;gCACb,CAAC/C,6BAA6B,EAAEE,oBAC9BoF,eAAevC,SAASwC,IAAI,IAAIC,SAAS3B,OAAOvB,KAAK,EAAEmC,MAAMlC,EAAE;4BAEnE,CAAA;oBAEN;oBACA;gBACF;gBACAuG,OAAO,CAACjF,OAAOoF,MAAM,CAAC,GACpB,EAACH,yBAAAA,OAAO,CAACjF,OAAOoF,MAAM,CAAC,YAAtBH,yBAA0B,KAC1B,MAAM3G,kBACLC,WACAwB,QAAQI,KAAK,CAACH,OAAOvB,KAAK,EAAE,MAAMmC,MAAMX,IAAI,GAC5CD,OAAOvB,KAAK,EACZmC,MAAMlC,EAAE,EACRsB,OAAOI,QAAQ,GAAG;oBAAE,CAACJ,OAAOI,QAAQ,CAAC,EAAE7D,eAAeqE,MAAMlC,EAAE;gBAAE,IAAI,CAAC;YAE3E;YACA,MAAMoH,SAAiC;gBAAExC,IAAI;gBAAM2B;YAAQ;YAC3DhD,IAAII,MAAM,CAAC,KAAKC,IAAI,CAACwD;QACvB,EAAE,OAAOvD,OAAO;YACdwD,QAAQxD,KAAK,CAAC,gCAAgCA;YAC9CN,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO,CAAC,IAAI,EAAE7E,WAAWC,MAAM,CAAC,oBAAoB,CAAC;YAAC;QAC/E;IACF;AACF;AAEA,iFAAiF,GACjF,OAAO,MAAMqI,2BAA6ClE,wBAAuB;AAEjF,+FAA+F,GAC/F,OAAO,MAAMmE,6BACXnE,sBAAsB1F,0BAAyB"}
|
|
@@ -181,9 +181,11 @@ export declare function nameKey(value: string): string;
|
|
|
181
181
|
export declare function customKeyOf(fieldId: string): string | null;
|
|
182
182
|
/**
|
|
183
183
|
* A stored custom value as the file reads it: a date (stored as epoch
|
|
184
|
-
* milliseconds) as its day, `YYYY-MM-DD`;
|
|
184
|
+
* milliseconds) as its day, `YYYY-MM-DD`; an amount (stored as minor units)
|
|
185
|
+
* as major units in the field's currency, `1250.5` (AGL-3756); anything
|
|
186
|
+
* else as stored.
|
|
185
187
|
*/
|
|
186
|
-
export declare function customTransferValue(definition: Pick<ContactFieldDefinition, 'type'> | undefined, value: unknown): unknown;
|
|
188
|
+
export declare function customTransferValue(definition: Pick<ContactFieldDefinition, 'type' | 'currency'> | undefined, value: unknown): unknown;
|
|
187
189
|
/** Every custom field a record holds, as `custom:<key>` values. */
|
|
188
190
|
export declare function customTransferValues(definitions: readonly ContactFieldDefinition[], stored: unknown): Record<string, unknown>;
|
|
189
191
|
/**
|
|
@@ -35,7 +35,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
35
35
|
* (`TransferPlanRefusedError` carrying `suite-gate.ts`'s answer, else
|
|
36
36
|
* `TransferEngineError`), so the wizard shows the sentence a CRM route
|
|
37
37
|
* would have answered.
|
|
38
|
-
*=========================================*/ import { checkCrmRecordsQuota, consentGroupForHost, CRM_COLLECTIONS, crmPicklistDefinition, crmReadTokens, crmScopeTokens, effectiveCrmPicklist, fieldDefinitionsForObject, isCrmPicklistId, newResourceScopeFields, normalizeCrmPicklist, ORG_SCOPE_TOKEN, readCrmCustomInput, visibleToTokens } from "@aglyn/aglyn/server";
|
|
38
|
+
*=========================================*/ import { checkCrmRecordsQuota, consentGroupForHost, CRM_COLLECTIONS, crmPicklistDefinition, crmReadTokens, crmScopeTokens, effectiveCrmPicklist, fieldDefinitionsForObject, isCrmPicklistId, newResourceScopeFields, normalizeCrmPicklist, ORG_SCOPE_TOKEN, readCrmCustomInput, customFieldCurrency, currencyMinorToMajor, visibleToTokens } from "@aglyn/aglyn/server";
|
|
39
39
|
import { CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_LIFECYCLE_STAGES, CRM_FORECAST_CATEGORIES, CRM_FORECAST_CATEGORY_LABELS } from "@aglyn/aglyn/app-utils/crm";
|
|
40
40
|
import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
41
41
|
import { listOrgContainers } from "@aglyn/tenant-data-admin/server/org-containers";
|
|
@@ -646,9 +646,14 @@ const FILTER_OPS = new Set([
|
|
|
646
646
|
}
|
|
647
647
|
/**
|
|
648
648
|
* A stored custom value as the file reads it: a date (stored as epoch
|
|
649
|
-
* milliseconds) as its day, `YYYY-MM-DD`;
|
|
649
|
+
* milliseconds) as its day, `YYYY-MM-DD`; an amount (stored as minor units)
|
|
650
|
+
* as major units in the field's currency, `1250.5` (AGL-3756); anything
|
|
651
|
+
* else as stored.
|
|
650
652
|
*/ export function customTransferValue(definition, value) {
|
|
651
653
|
if (value === null || value === undefined) return null;
|
|
654
|
+
if ((definition == null ? void 0 : definition.type) === 'currency') {
|
|
655
|
+
return typeof value === 'number' && Number.isFinite(value) ? currencyMinorToMajor(value, customFieldCurrency(definition)) : null;
|
|
656
|
+
}
|
|
652
657
|
if ((definition == null ? void 0 : definition.type) === 'date') {
|
|
653
658
|
const ms = storedMs(value);
|
|
654
659
|
return ms === null ? null : new Date(ms).toISOString().slice(0, 10);
|
|
@@ -670,8 +675,14 @@ const FILTER_OPS = new Set([
|
|
|
670
675
|
var _Object_values_;
|
|
671
676
|
const raw = {};
|
|
672
677
|
for (const [fieldId, value] of Object.entries(values)){
|
|
678
|
+
var _definitions_find;
|
|
673
679
|
const key = customKeyOf(fieldId);
|
|
674
|
-
if (key)
|
|
680
|
+
if (!key) continue;
|
|
681
|
+
const blank = value === undefined || value === '';
|
|
682
|
+
// A file's amount is major units, which the reader takes as text; a
|
|
683
|
+
// number it is handed would be read as the minor units it stores.
|
|
684
|
+
const currency = ((_definitions_find = definitions.find((one)=>one.key === key)) == null ? void 0 : _definitions_find.type) === 'currency';
|
|
685
|
+
raw[key] = blank ? null : currency && typeof value === 'number' ? String(value) : value;
|
|
675
686
|
}
|
|
676
687
|
if (!Object.keys(raw).length) return {
|
|
677
688
|
values: {}
|