@aglyn/plugins-crm 1.0.0-beta.178 → 1.0.0-beta.180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/contact-detail-page.js +1 -0
  3. package/src/lib/components/contact-detail-page.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.d.ts +6 -0
  5. package/src/lib/components/contact-properties-card.js +25 -2
  6. package/src/lib/components/contact-properties-card.js.map +1 -1
  7. package/src/lib/components/csv-import-drawer.d.ts +7 -0
  8. package/src/lib/components/csv-import-drawer.js +7 -0
  9. package/src/lib/components/csv-import-drawer.js.map +1 -1
  10. package/src/lib/components/fields-section.js +6 -0
  11. package/src/lib/components/fields-section.js.map +1 -1
  12. package/src/lib/components/lead-import-drawer.d.ts +3 -0
  13. package/src/lib/components/lead-import-drawer.js +29 -6
  14. package/src/lib/components/lead-import-drawer.js.map +1 -1
  15. package/src/lib/components/lead-properties-card.js +10 -12
  16. package/src/lib/components/lead-properties-card.js.map +1 -1
  17. package/src/lib/components/lead-source-select.d.ts +30 -0
  18. package/src/lib/components/lead-source-select.js +96 -0
  19. package/src/lib/components/lead-source-select.js.map +1 -0
  20. package/src/lib/components/lead-source-values-card.d.ts +27 -0
  21. package/src/lib/components/lead-source-values-card.js +606 -0
  22. package/src/lib/components/lead-source-values-card.js.map +1 -0
  23. package/src/lib/components/leads-section.js +100 -4
  24. package/src/lib/components/leads-section.js.map +1 -1
  25. package/src/lib/components/new-lead-drawer.js +27 -11
  26. package/src/lib/components/new-lead-drawer.js.map +1 -1
  27. package/src/lib/hooks/use-lead-source-picklist.d.ts +23 -0
  28. package/src/lib/hooks/use-lead-source-picklist.js +50 -0
  29. package/src/lib/hooks/use-lead-source-picklist.js.map +1 -0
  30. package/src/lib/model/contact-record.d.ts +2 -0
  31. package/src/lib/model/contact-record.js +2 -1
  32. package/src/lib/model/contact-record.js.map +1 -1
  33. package/src/lib/model/contact-update.d.ts +6 -0
  34. package/src/lib/model/contact-update.js +1 -0
  35. package/src/lib/model/contact-update.js.map +1 -1
  36. package/src/lib/model/crm-lead-import.d.ts +10 -2
  37. package/src/lib/model/crm-lead-import.js +19 -1
  38. package/src/lib/model/crm-lead-import.js.map +1 -1
  39. package/src/lib/model/crm-record-routes.js +4 -4
  40. package/src/lib/model/crm-record-routes.js.map +1 -1
  41. package/src/lib/model/lead-filters.d.ts +13 -0
  42. package/src/lib/model/lead-filters.js +17 -1
  43. package/src/lib/model/lead-filters.js.map +1 -1
  44. package/src/lib/model/lead-source-values.d.ts +82 -0
  45. package/src/lib/model/lead-source-values.js +149 -0
  46. package/src/lib/model/lead-source-values.js.map +1 -0
  47. package/src/lib/server/contact-update.js +25 -2
  48. package/src/lib/server/contact-update.js.map +1 -1
  49. package/src/lib/server/lead-create.js +19 -0
  50. package/src/lib/server/lead-create.js.map +1 -1
  51. package/src/lib/server/lead-source-picklist.d.ts +42 -0
  52. package/src/lib/server/lead-source-picklist.js +52 -0
  53. package/src/lib/server/lead-source-picklist.js.map +1 -0
  54. package/src/lib/server/lead-source-values.d.ts +50 -0
  55. package/src/lib/server/lead-source-values.js +187 -0
  56. package/src/lib/server/lead-source-values.js.map +1 -0
  57. package/src/lib/server/leads-import.js +31 -2
  58. package/src/lib/server/leads-import.js.map +1 -1
  59. package/src/lib/server.js +5 -0
  60. package/src/lib/server.js.map +1 -1
@@ -0,0 +1,82 @@
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
+ */
17
+ import { type CrmPicklist } from '@aglyn/aglyn/app-utils/crm';
18
+ /**
19
+ * THE LEAD SOURCE LIST'S EDITS (AGL-3298), as pure moves over a picklist.
20
+ *
21
+ * The Fields page applies the ones that touch only the list — add, reorder,
22
+ * sort, activate, deactivate, default — as one client write of the whole
23
+ * document. The two that change what RECORDS hold — a rename and a delete
24
+ * with its replacement — go to `crm/lead-source-values`, which rewrites the
25
+ * list and every lead and contact holding the old label in one request;
26
+ * this module is where both sides agree what each move does.
27
+ */
28
+ /** The route the two record-changing moves are posted to. */
29
+ export declare const CRM_LEAD_SOURCE_VALUES_ROUTE: "crm/lead-source-values";
30
+ export declare const crmLeadSourceValuesRouteUrl: () => string;
31
+ /** What the route is asked. `hostId` or `orgId` names the org, as every CRM route's scope does. */
32
+ export type LeadSourceValuesRequest = {
33
+ hostId?: string | null;
34
+ orgId?: string;
35
+ } & ({
36
+ action: 'rename';
37
+ valueId: string;
38
+ label: string;
39
+ } | {
40
+ action: 'delete';
41
+ valueId: string;
42
+ /** An active value's label the records move to, or `null` to clear them. */
43
+ replaceWith: string | null;
44
+ });
45
+ /** What the route answers. */
46
+ export interface LeadSourceValuesResponse {
47
+ ok: true;
48
+ /** How many leads now hold the new label (or none). */
49
+ leads: number;
50
+ /**
51
+ * How many contact FACETS were rewritten — one per holder that held the
52
+ * old label, so a person two sites both filed under it counts twice.
53
+ */
54
+ contacts: number;
55
+ }
56
+ /** Why a move is refused, in the sentence the page shows. */
57
+ export type PicklistMove = {
58
+ ok: true;
59
+ picklist: CrmPicklist;
60
+ } | {
61
+ ok: false;
62
+ error: string;
63
+ };
64
+ /** Append a value. */
65
+ export declare function addPicklistValue(picklist: CrmPicklist, rawLabel: string): PicklistMove;
66
+ /** Rename a value, keeping its id — the list half of the route's rename. */
67
+ export declare function renamePicklistValue(picklist: CrmPicklist, valueId: string, rawLabel: string): PicklistMove;
68
+ /**
69
+ * Remove a value — the list half of the route's delete. The replacement,
70
+ * when there is one, must be another ACTIVE value: records are not moved
71
+ * onto a value the pickers no longer offer. A default that named the
72
+ * deleted value is cleared.
73
+ */
74
+ export declare function deletePicklistValue(picklist: CrmPicklist, valueId: string, replaceWith: string | null): PicklistMove;
75
+ /** Turn a value on or off. Deactivating the default clears the default. */
76
+ export declare function setPicklistValueActive(picklist: CrmPicklist, valueId: string, active: boolean): CrmPicklist;
77
+ /** Make a value the default for new records, or clear the default with `null`. */
78
+ export declare function setPicklistDefault(picklist: CrmPicklist, valueId: string | null): CrmPicklist;
79
+ /** Move the value at `from` to `to`, the drag and the arrows alike. */
80
+ export declare function movePicklistValue(picklist: CrmPicklist, from: number, to: number): CrmPicklist;
81
+ /** Every value in A–Z order by label, as Salesforce's "Sort alphabetically" does. */
82
+ export declare function sortPicklistValues(picklist: CrmPicklist): CrmPicklist;
@@ -0,0 +1,149 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { crmPicklistValueByLabel, crmPicklistValueId, normalizeCrmPicklistLabel } from "@aglyn/aglyn/app-utils/crm";
18
+ /**
19
+ * THE LEAD SOURCE LIST'S EDITS (AGL-3298), as pure moves over a picklist.
20
+ *
21
+ * The Fields page applies the ones that touch only the list — add, reorder,
22
+ * sort, activate, deactivate, default — as one client write of the whole
23
+ * document. The two that change what RECORDS hold — a rename and a delete
24
+ * with its replacement — go to `crm/lead-source-values`, which rewrites the
25
+ * list and every lead and contact holding the old label in one request;
26
+ * this module is where both sides agree what each move does.
27
+ */ /** The route the two record-changing moves are posted to. */ export const CRM_LEAD_SOURCE_VALUES_ROUTE = 'crm/lead-source-values';
28
+ export const crmLeadSourceValuesRouteUrl = ()=>`/api/${CRM_LEAD_SOURCE_VALUES_ROUTE}`;
29
+ const DUPLICATE = (label)=>`“${label}” is already in the list.`;
30
+ /** Append a value. */ export function addPicklistValue(picklist, rawLabel) {
31
+ const label = normalizeCrmPicklistLabel(rawLabel);
32
+ if (!label) return {
33
+ ok: false,
34
+ error: 'Enter a name for the value.'
35
+ };
36
+ const existing = crmPicklistValueByLabel(picklist, label);
37
+ if (existing) {
38
+ return {
39
+ ok: false,
40
+ error: existing.active ? DUPLICATE(existing.label) : `“${existing.label}” is in the list, inactive — activate it instead.`
41
+ };
42
+ }
43
+ const value = {
44
+ id: crmPicklistValueId(label, picklist.values.map((entry)=>entry.id)),
45
+ label,
46
+ active: true
47
+ };
48
+ return {
49
+ ok: true,
50
+ picklist: _extends({}, picklist, {
51
+ values: [
52
+ ...picklist.values,
53
+ value
54
+ ]
55
+ })
56
+ };
57
+ }
58
+ /** Rename a value, keeping its id — the list half of the route's rename. */ export function renamePicklistValue(picklist, valueId, rawLabel) {
59
+ const label = normalizeCrmPicklistLabel(rawLabel);
60
+ if (!label) return {
61
+ ok: false,
62
+ error: 'Enter a name for the value.'
63
+ };
64
+ if (!picklist.values.some((value)=>value.id === valueId)) {
65
+ return {
66
+ ok: false,
67
+ error: 'That value is no longer in the list.'
68
+ };
69
+ }
70
+ const clash = crmPicklistValueByLabel(picklist, label);
71
+ if (clash && clash.id !== valueId) return {
72
+ ok: false,
73
+ error: DUPLICATE(clash.label)
74
+ };
75
+ return {
76
+ ok: true,
77
+ picklist: _extends({}, picklist, {
78
+ values: picklist.values.map((value)=>value.id === valueId ? _extends({}, value, {
79
+ label
80
+ }) : value)
81
+ })
82
+ };
83
+ }
84
+ /**
85
+ * Remove a value — the list half of the route's delete. The replacement,
86
+ * when there is one, must be another ACTIVE value: records are not moved
87
+ * onto a value the pickers no longer offer. A default that named the
88
+ * deleted value is cleared.
89
+ */ export function deletePicklistValue(picklist, valueId, replaceWith) {
90
+ if (!picklist.values.some((value)=>value.id === valueId)) {
91
+ return {
92
+ ok: false,
93
+ error: 'That value is no longer in the list.'
94
+ };
95
+ }
96
+ if (replaceWith !== null) {
97
+ const target = crmPicklistValueByLabel(picklist, replaceWith);
98
+ if (!target || target.id === valueId || !target.active) {
99
+ return {
100
+ ok: false,
101
+ error: 'Pick an active value to move its records to, or none.'
102
+ };
103
+ }
104
+ }
105
+ return {
106
+ ok: true,
107
+ picklist: {
108
+ values: picklist.values.filter((value)=>value.id !== valueId),
109
+ defaultValueId: picklist.defaultValueId === valueId ? null : picklist.defaultValueId
110
+ }
111
+ };
112
+ }
113
+ /** Turn a value on or off. Deactivating the default clears the default. */ export function setPicklistValueActive(picklist, valueId, active) {
114
+ return {
115
+ values: picklist.values.map((value)=>value.id === valueId ? _extends({}, value, {
116
+ active
117
+ }) : value),
118
+ defaultValueId: !active && picklist.defaultValueId === valueId ? null : picklist.defaultValueId
119
+ };
120
+ }
121
+ /** Make a value the default for new records, or clear the default with `null`. */ export function setPicklistDefault(picklist, valueId) {
122
+ const value = picklist.values.find((entry)=>entry.id === valueId);
123
+ return _extends({}, picklist, {
124
+ defaultValueId: (value == null ? void 0 : value.active) ? value.id : null
125
+ });
126
+ }
127
+ /** Move the value at `from` to `to`, the drag and the arrows alike. */ export function movePicklistValue(picklist, from, to) {
128
+ const size = picklist.values.length;
129
+ if (from === to || from < 0 || to < 0 || from >= size || to >= size) return picklist;
130
+ const values = [
131
+ ...picklist.values
132
+ ];
133
+ const [moved] = values.splice(from, 1);
134
+ values.splice(to, 0, moved);
135
+ return _extends({}, picklist, {
136
+ values
137
+ });
138
+ }
139
+ /** Every value in A–Z order by label, as Salesforce's "Sort alphabetically" does. */ export function sortPicklistValues(picklist) {
140
+ return _extends({}, picklist, {
141
+ values: [
142
+ ...picklist.values
143
+ ].sort((a, b)=>a.label.localeCompare(b.label, undefined, {
144
+ sensitivity: 'base'
145
+ }))
146
+ });
147
+ }
148
+
149
+ //# sourceMappingURL=lead-source-values.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/lead-source-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 type CrmPicklist,\n type CrmPicklistValue,\n crmPicklistValueByLabel,\n crmPicklistValueId,\n normalizeCrmPicklistLabel,\n} from '@aglyn/aglyn/app-utils/crm'\n\n/**\n * THE LEAD SOURCE LIST'S EDITS (AGL-3298), as pure moves over a picklist.\n *\n * The Fields page applies the ones that touch only the list — add, reorder,\n * sort, activate, deactivate, default — as one client write of the whole\n * document. The two that change what RECORDS hold — a rename and a delete\n * with its replacement — go to `crm/lead-source-values`, which rewrites the\n * list and every lead and contact holding the old label in one request;\n * this module is where both sides agree what each move does.\n */\n\n/** The route the two record-changing moves are posted to. */\nexport const CRM_LEAD_SOURCE_VALUES_ROUTE = 'crm/lead-source-values' as const\n\nexport const crmLeadSourceValuesRouteUrl = (): string => `/api/${CRM_LEAD_SOURCE_VALUES_ROUTE}`\n\n/** What the route is asked. `hostId` or `orgId` names the org, as every CRM route's scope does. */\nexport type LeadSourceValuesRequest = { hostId?: string | null; orgId?: string } & (\n | { action: 'rename'; valueId: string; label: string }\n | {\n action: 'delete'\n valueId: string\n /** An active value's label the records move to, or `null` to clear them. */\n replaceWith: string | null\n }\n)\n\n/** What the route answers. */\nexport interface LeadSourceValuesResponse {\n ok: true\n /** How many leads now hold the new label (or none). */\n leads: number\n /**\n * How many contact FACETS were rewritten — one per holder that held the\n * old label, so a person two sites both filed under it counts twice.\n */\n contacts: number\n}\n\n/** Why a move is refused, in the sentence the page shows. */\nexport type PicklistMove = { ok: true; picklist: CrmPicklist } | { ok: false; error: string }\n\nconst DUPLICATE = (label: string) => `“${label}” is already in the list.`\n\n/** Append a value. */\nexport function addPicklistValue(picklist: CrmPicklist, rawLabel: string): PicklistMove {\n const label = normalizeCrmPicklistLabel(rawLabel)\n if (!label) return { ok: false, error: 'Enter a name for the value.' }\n const existing = crmPicklistValueByLabel(picklist, label)\n if (existing) {\n return {\n ok: false,\n error: existing.active\n ? DUPLICATE(existing.label)\n : `“${existing.label}” is in the list, inactive — activate it instead.`,\n }\n }\n const value: CrmPicklistValue = {\n id: crmPicklistValueId(\n label,\n picklist.values.map((entry) => entry.id),\n ),\n label,\n active: true,\n }\n return { ok: true, picklist: { ...picklist, values: [...picklist.values, value] } }\n}\n\n/** Rename a value, keeping its id — the list half of the route's rename. */\nexport function renamePicklistValue(\n picklist: CrmPicklist,\n valueId: string,\n rawLabel: string,\n): PicklistMove {\n const label = normalizeCrmPicklistLabel(rawLabel)\n if (!label) return { ok: false, error: 'Enter a name for the value.' }\n if (!picklist.values.some((value) => value.id === valueId)) {\n return { ok: false, error: 'That value is no longer in the list.' }\n }\n const clash = crmPicklistValueByLabel(picklist, label)\n if (clash && clash.id !== valueId) return { ok: false, error: DUPLICATE(clash.label) }\n return {\n ok: true,\n picklist: {\n ...picklist,\n values: picklist.values.map((value) => (value.id === valueId ? { ...value, label } : value)),\n },\n }\n}\n\n/**\n * Remove a value — the list half of the route's delete. The replacement,\n * when there is one, must be another ACTIVE value: records are not moved\n * onto a value the pickers no longer offer. A default that named the\n * deleted value is cleared.\n */\nexport function deletePicklistValue(\n picklist: CrmPicklist,\n valueId: string,\n replaceWith: string | null,\n): PicklistMove {\n if (!picklist.values.some((value) => value.id === valueId)) {\n return { ok: false, error: 'That value is no longer in the list.' }\n }\n if (replaceWith !== null) {\n const target = crmPicklistValueByLabel(picklist, replaceWith)\n if (!target || target.id === valueId || !target.active) {\n return { ok: false, error: 'Pick an active value to move its records to, or none.' }\n }\n }\n return {\n ok: true,\n picklist: {\n values: picklist.values.filter((value) => value.id !== valueId),\n defaultValueId: picklist.defaultValueId === valueId ? null : picklist.defaultValueId,\n },\n }\n}\n\n/** Turn a value on or off. Deactivating the default clears the default. */\nexport function setPicklistValueActive(\n picklist: CrmPicklist,\n valueId: string,\n active: boolean,\n): CrmPicklist {\n return {\n values: picklist.values.map((value) => (value.id === valueId ? { ...value, active } : value)),\n defaultValueId:\n !active && picklist.defaultValueId === valueId ? null : picklist.defaultValueId,\n }\n}\n\n/** Make a value the default for new records, or clear the default with `null`. */\nexport function setPicklistDefault(picklist: CrmPicklist, valueId: string | null): CrmPicklist {\n const value = picklist.values.find((entry) => entry.id === valueId)\n return { ...picklist, defaultValueId: value?.active ? value.id : null }\n}\n\n/** Move the value at `from` to `to`, the drag and the arrows alike. */\nexport function movePicklistValue(picklist: CrmPicklist, from: number, to: number): CrmPicklist {\n const size = picklist.values.length\n if (from === to || from < 0 || to < 0 || from >= size || to >= size) return picklist\n const values = [...picklist.values]\n const [moved] = values.splice(from, 1)\n values.splice(to, 0, moved)\n return { ...picklist, values }\n}\n\n/** Every value in A–Z order by label, as Salesforce's \"Sort alphabetically\" does. */\nexport function sortPicklistValues(picklist: CrmPicklist): CrmPicklist {\n return {\n ...picklist,\n values: [...picklist.values].sort((a, b) =>\n a.label.localeCompare(b.label, undefined, { sensitivity: 'base' }),\n ),\n }\n}\n"],"names":["crmPicklistValueByLabel","crmPicklistValueId","normalizeCrmPicklistLabel","CRM_LEAD_SOURCE_VALUES_ROUTE","crmLeadSourceValuesRouteUrl","DUPLICATE","label","addPicklistValue","picklist","rawLabel","ok","error","existing","active","value","id","values","map","entry","renamePicklistValue","valueId","some","clash","deletePicklistValue","replaceWith","target","filter","defaultValueId","setPicklistValueActive","setPicklistDefault","find","movePicklistValue","from","to","size","length","moved","splice","sortPicklistValues","sort","a","b","localeCompare","undefined","sensitivity"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAGEA,uBAAuB,EACvBC,kBAAkB,EAClBC,yBAAyB,QACpB,6BAA4B;AAEnC;;;;;;;;;CASC,GAED,2DAA2D,GAC3D,OAAO,MAAMC,+BAA+B,yBAAiC;AAE7E,OAAO,MAAMC,8BAA8B,IAAc,CAAC,KAAK,EAAED,8BAA8B,CAAA;AA4B/F,MAAME,YAAY,CAACC,QAAkB,CAAC,CAAC,EAAEA,MAAM,yBAAyB,CAAC;AAEzE,oBAAoB,GACpB,OAAO,SAASC,iBAAiBC,QAAqB,EAAEC,QAAgB;IACtE,MAAMH,QAAQJ,0BAA0BO;IACxC,IAAI,CAACH,OAAO,OAAO;QAAEI,IAAI;QAAOC,OAAO;IAA8B;IACrE,MAAMC,WAAWZ,wBAAwBQ,UAAUF;IACnD,IAAIM,UAAU;QACZ,OAAO;YACLF,IAAI;YACJC,OAAOC,SAASC,MAAM,GAClBR,UAAUO,SAASN,KAAK,IACxB,CAAC,CAAC,EAAEM,SAASN,KAAK,CAAC,iDAAiD,CAAC;QAC3E;IACF;IACA,MAAMQ,QAA0B;QAC9BC,IAAId,mBACFK,OACAE,SAASQ,MAAM,CAACC,GAAG,CAAC,CAACC,QAAUA,MAAMH,EAAE;QAEzCT;QACAO,QAAQ;IACV;IACA,OAAO;QAAEH,IAAI;QAAMF,UAAU,aAAKA;YAAUQ,QAAQ;mBAAIR,SAASQ,MAAM;gBAAEF;aAAM;;IAAG;AACpF;AAEA,0EAA0E,GAC1E,OAAO,SAASK,oBACdX,QAAqB,EACrBY,OAAe,EACfX,QAAgB;IAEhB,MAAMH,QAAQJ,0BAA0BO;IACxC,IAAI,CAACH,OAAO,OAAO;QAAEI,IAAI;QAAOC,OAAO;IAA8B;IACrE,IAAI,CAACH,SAASQ,MAAM,CAACK,IAAI,CAAC,CAACP,QAAU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L,SAASmB,cAAc,KAAKP,UAAU,OAAOZ,SAASmB,cAAc;IACnF;AACF;AAEA,gFAAgF,GAChF,OAAO,SAASE,mBAAmBrB,QAAqB,EAAEY,OAAsB;IAC9E,MAAMN,QAAQN,SAASQ,MAAM,CAACc,IAAI,CAAC,CAACZ,QAAUA,MAAMH,EAAE,KAAKK;IAC3D,OAAO,aAAKZ;QAAUmB,gBAAgBb,CAAAA,yBAAAA,MAAOD,MAAM,IAAGC,MAAMC,EAAE,GAAG;;AACnE;AAEA,qEAAqE,GACrE,OAAO,SAASgB,kBAAkBvB,QAAqB,EAAEwB,IAAY,EAAEC,EAAU;IAC/E,MAAMC,OAAO1B,SAASQ,MAAM,CAACmB,MAAM;IACnC,IAAIH,SAASC,MAAMD,OAAO,KAAKC,KAAK,KAAKD,QAAQE,QAAQD,MAAMC,MAAM,OAAO1B;IAC5E,MAAMQ,SAAS;WAAIR,SAASQ,MAAM;KAAC;IACnC,MAAM,CAACoB,MAAM,GAAGpB,OAAOqB,MAAM,CAACL,MAAM;IACpChB,OAAOqB,MAAM,CAACJ,IAAI,GAAGG;IACrB,OAAO,aAAK5B;QAAUQ;;AACxB;AAEA,mFAAmF,GACnF,OAAO,SAASsB,mBAAmB9B,QAAqB;IACtD,OAAO,aACFA;QACHQ,QAAQ;eAAIR,SAASQ,MAAM;SAAC,CAACuB,IAAI,CAAC,CAACC,GAAGC,IACpCD,EAAElC,KAAK,CAACoC,aAAa,CAACD,EAAEnC,KAAK,EAAEqC,WAAW;gBAAEC,aAAa;YAAO;;AAGtE"}
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -67,7 +68,7 @@
67
68
  * link: summed per company and settled once the contacts are written, so a
68
69
  * company deleted in between cannot fail the save of the people at it — the
69
70
  * company page's live aggregate is what corrects a count that did not move.
70
- */ import { consentGroupForHost, CONTACT_FIELDS_MAX_PER_ORG, campaignMembershipValue, contactCampaignFieldPath, contactFacetPath, contactPrimaryGroup, CRM_COLLECTIONS, CRM_MEDIA_IDS_FIELD, crmReadTokens, isOrgWideMember, normalizeAddress, normalizeCrmMediaIds, normalizePhone, planContactCompanyLink, readContactCompanyLink, readContactFacet, readCrmCustomInput, visibleToTokens } from "@aglyn/aglyn/server";
71
+ */ import { consentGroupForHost, CONTACT_FIELDS_MAX_PER_ORG, campaignMembershipValue, contactCampaignFieldPath, contactFacetPath, contactPrimaryGroup, CRM_COLLECTIONS, CRM_LEAD_SOURCE_PICKLIST, CRM_MEDIA_IDS_FIELD, crmReadTokens, effectiveCrmLeadSourcePicklist, isOrgWideMember, judgeCrmLeadSource, normalizeAddress, normalizeCrmMediaIds, normalizeCrmPicklistLabel, normalizePhone, planContactCompanyLink, readContactCompanyLink, readContactFacet, readCrmCustomInput, visibleToTokens } from "@aglyn/aglyn/server";
71
72
  import { companyContactsCountFields, contactCompanyLinkFields, firebaseAdmin, resolveOrgMembership } from "@aglyn/tenant-data-admin";
72
73
  import { FieldValue } from "firebase-admin/firestore";
73
74
  import { CONTACT_UPDATE_FIELDS, CRM_CONTACT_UPDATE_MAX } from "../model/contact-update.js";
@@ -79,6 +80,7 @@ import { authorizeCrmWriter, canReach } from "./task-routes.js";
79
80
  name: "Editing a contact's profile",
80
81
  phone: "Editing a contact's profile",
81
82
  jobTitle: "Editing a contact's profile",
83
+ leadSource: "Editing a contact's profile",
82
84
  address: "Editing a contact's profile",
83
85
  notes: "Editing a contact's notes",
84
86
  tags: 'Tagging a contact',
@@ -132,6 +134,9 @@ import { authorizeCrmWriter, canReach } from "./task-routes.js";
132
134
  fields.phone = phone;
133
135
  }
134
136
  if ('jobTitle' in raw) fields.jobTitle = typed(raw['jobTitle'], 120);
137
+ // Held to the label's shape here; judged against the org's list by the
138
+ // handler, which alone can read it (AGL-3298).
139
+ if ('leadSource' in raw) fields.leadSource = normalizeCrmPicklistLabel(raw['leadSource']);
135
140
  if ('address' in raw) {
136
141
  const address = raw['address'];
137
142
  fields.address = address && typeof address === 'object' && !Array.isArray(address) ? normalizeAddress(address) : null;
@@ -257,6 +262,7 @@ const refused = (contactId, error)=>({
257
262
  update['phone'] = text(fields.phone);
258
263
  }
259
264
  if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle);
265
+ if (fields.leadSource !== undefined) update[path('leadSource')] = text(fields.leadSource);
260
266
  if (fields.address !== undefined) {
261
267
  var _fields_address;
262
268
  update[path('address')] = (_fields_address = fields.address) != null ? _fields_address : FieldValue.delete();
@@ -420,6 +426,11 @@ export const crmContactUpdateHandler = async (req, res)=>{
420
426
  }
421
427
  custom = judged.values;
422
428
  }
429
+ /*
430
+ * THE ORG'S LEAD SOURCES (AGL-3298), read only when the body names one.
431
+ * Judged per contact below, because a contact keeps the value it
432
+ * already holds even when the list has since deactivated it.
433
+ */ const leadSources = fields.leadSource ? effectiveCrmLeadSourcePicklist((await orgRef.collection(CRM_COLLECTIONS.picklists).doc(CRM_LEAD_SOURCE_PICKLIST).get()).data()) : null;
423
434
  if (fields.ownerUid) {
424
435
  const owner = await resolveOrgMembership(fields.ownerUid, writer.orgId).catch(()=>null);
425
436
  if (!(owner == null ? void 0 : owner.member)) {
@@ -470,7 +481,19 @@ export const crmContactUpdateHandler = async (req, res)=>{
470
481
  outcomes.set(contactId, refused(contactId, NO_HOLDER_REFUSAL));
471
482
  return;
472
483
  }
473
- const patch = contactPatch(data, group.groupId, fields, custom, linkedCompanyName);
484
+ let rowFields = fields;
485
+ if (leadSources && fields.leadSource) {
486
+ var _judged_value;
487
+ const judged = judgeCrmLeadSource(leadSources, fields.leadSource, readContactFacet(data, group.groupId).leadSource);
488
+ if (judged.ok === false) {
489
+ outcomes.set(contactId, refused(contactId, judged.error));
490
+ return;
491
+ }
492
+ rowFields = _extends({}, fields, {
493
+ leadSource: (_judged_value = judged.value) != null ? _judged_value : ''
494
+ });
495
+ }
496
+ const patch = contactPatch(data, group.groupId, rowFields, custom, linkedCompanyName);
474
497
  if ('refused' in patch) {
475
498
  outcomes.set(contactId, refused(contactId, patch.refused));
476
499
  return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/contact-update.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `POST /api/crm/contact-update` — one holder's profile fields on one or\n * more contacts (AGL-2804).\n *\n * Body: `{ hostId, contactIds, set }` under a site, or `{ orgId, hostId?,\n * contactIds, set }` at the organization level, where `set` is\n * `ContactUpdateFields`. Answers `{ ok, results }`: one outcome per contact,\n * in the order the ids were sent.\n *\n * ## Why every facet write comes here\n *\n * A contact's fields live in the facet of the holder that keeps them —\n * `facets.{groupId}.*` — and the Firestore rules cannot tell one field of a\n * facet from another: the holder is a map key a rule cannot address, and a\n * write's affected keys name only `facets`. So the rules let a client update\n * change nothing in a facet beyond letting a holder go, and the console's\n * edits arrive here, where the plan is asked about the fields the request\n * actually carries.\n *\n * ## Who may call it\n *\n * The CRM writer the task routes admit (`authorizeCrmWriter`): under a site,\n * a member whose role writes org data, who holds `data.manage` and whose\n * access reaches the site; at the organization level, an org-wide member\n * with the permission. Each contact must then be one the caller may read —\n * the rules' `canReadScoped()` — and, under a site, one the site's hub lists.\n *\n * ## The plan\n *\n * Every field is the CRM's (AGL-2790), and a plan without the CRM has none\n * of it (AGL-2851), so it edits no contact: not the owner, company, custom\n * values or files, and not the profile a capture writes (name, phone, job\n * title, address), the tags, the notes or the campaign filing either. A\n * request carrying any field is refused to such a plan once the caller is\n * known, and before a contact is read — staff included, because the plan is\n * a fact about the workspace. Erasing a person is another route, open on\n * every plan.\n *\n * ## One holder, by dotted path\n *\n * Under a site the facet is the site's consent group's; at the organization\n * level it is each contact's own primary holder, the facet the record page\n * shows there. Every field is one dotted path — a nested `facets` object\n * would replace every other holder's map — and a text field sent empty is\n * deleted rather than stored blank, so \"no phone\" has one shape.\n *\n * ## Many contacts, one commit\n *\n * The contacts are read together and written in one batch. A batch that\n * fails is retried contact by contact, so the one that could not be written\n * is named and the rest still land. A company's contacts count follows the\n * link: summed per company and settled once the contacts are written, so a\n * company deleted in between cannot fail the save of the people at it — the\n * company page's live aggregate is what corrects a count that did not move.\n */\n\nimport {\n type AglynPostalAddress,\n consentGroupForHost,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ContactCompanyLinkPlan,\n type ContactCustomValue,\n type ContactFieldDefinition,\n campaignMembershipValue,\n contactCampaignFieldPath,\n contactFacetPath,\n contactPrimaryGroup,\n CRM_COLLECTIONS,\n CRM_MEDIA_IDS_FIELD,\n crmReadTokens,\n isOrgWideMember,\n normalizeAddress,\n normalizeCrmMediaIds,\n normalizePhone,\n type PluginApiHandler,\n planContactCompanyLink,\n readContactCompanyLink,\n readContactFacet,\n readCrmCustomInput,\n visibleToTokens,\n} from '@aglyn/aglyn/server'\nimport {\n companyContactsCountFields,\n contactCompanyLinkFields,\n firebaseAdmin,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CONTACT_UPDATE_FIELDS,\n type ContactUpdateFields,\n type ContactUpdateOutcome,\n type ContactUpdateResponse,\n CRM_CONTACT_UPDATE_MAX,\n} from '../model/contact-update'\nimport {\n CONTACT_NOTES_MAX,\n CONTACT_PHONE_REFUSAL,\n CONTACT_TAGS_MAX,\n normalizeTags,\n readBulkTag,\n typed,\n} from './contact-profile'\nimport { readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\nimport { authorizeCrmWriter, canReach, type Writer } from './task-routes'\n\n/** What the suite gate names for each field a request can carry. */\nconst SUITE_ACTS: Record<keyof ContactUpdateFields, string> = {\n name: \"Editing a contact's profile\",\n phone: \"Editing a contact's profile\",\n jobTitle: \"Editing a contact's profile\",\n address: \"Editing a contact's profile\",\n notes: \"Editing a contact's notes\",\n tags: 'Tagging a contact',\n addTag: 'Tagging a contact',\n removeTag: 'Tagging a contact',\n campaignIds: 'Filing a contact under a campaign',\n ownerUid: \"Assigning a contact's owner\",\n companyId: 'Filing a contact under a company',\n companyName: 'Filing a contact under a company',\n custom: \"Editing a contact's custom fields\",\n mediaIds: 'Attaching files to a contact',\n}\n\n/** A contact read at the organization level that no site has captured. */\nconst NO_HOLDER_REFUSAL = 'No site holds this contact yet, so it has no profile to edit.'\n\n/**\n * The act a request is refused for on a plan without the CRM: the first\n * field it carries, in the order the route reads them. Every field is the\n * CRM's, so whichever field a request names is the act its refusal names.\n */\nexport function contactUpdateSuiteAct(fields: ContactUpdateFields): string {\n const field = CONTACT_UPDATE_FIELDS.find((key) => fields[key] !== undefined)\n return field ? SUITE_ACTS[field] : \"Editing a contact's profile\"\n}\n\n/**\n * A body's `set`, read into the fields it names, or the sentence refusing\n * it. A key the route does not save is refused rather than dropped: a save\n * that silently lost a field would read as a save that kept it.\n */\nexport function readContactUpdateFields(\n input: unknown,\n): { ok: true; fields: ContactUpdateFields } | { ok: false; error: string } {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n return { ok: false, error: 'Name the fields to save.' }\n }\n const raw = input as Record<string, unknown>\n const unknownKey = Object.keys(raw).find(\n (key) => !(CONTACT_UPDATE_FIELDS as readonly string[]).includes(key),\n )\n if (unknownKey) {\n return { ok: false, error: `\"${unknownKey}\" is not a field a contact's profile saves.` }\n }\n const fields: ContactUpdateFields = {}\n if ('name' in raw) fields.name = typed(raw['name'], 120)\n if ('phone' in raw) {\n const text = typed(raw['phone'], 40)\n const phone = text ? normalizePhone(text) : ''\n if (phone === null) return { ok: false, error: CONTACT_PHONE_REFUSAL }\n fields.phone = phone\n }\n if ('jobTitle' in raw) fields.jobTitle = typed(raw['jobTitle'], 120)\n if ('address' in raw) {\n const address = raw['address']\n fields.address =\n address && typeof address === 'object' && !Array.isArray(address)\n ? normalizeAddress(address as AglynPostalAddress)\n : null\n }\n if ('notes' in raw) fields.notes = String(raw['notes'] ?? '').slice(0, CONTACT_NOTES_MAX)\n // One write may carry one transform per field, so the tags are replaced,\n // added to or taken from — never two of those at once.\n if (['tags', 'addTag', 'removeTag'].filter((key) => key in raw).length > 1) {\n return { ok: false, error: 'Send the tags, a tag to add or a tag to remove — one of them.' }\n }\n if ('tags' in raw) {\n if (!Array.isArray(raw['tags'])) return { ok: false, error: 'Tags must be a list.' }\n fields.tags = normalizeTags(raw['tags'])\n }\n for (const key of ['addTag', 'removeTag'] as const) {\n if (!(key in raw)) continue\n const tag = readBulkTag(raw[key])\n if (!tag) return { ok: false, error: 'Name the tag.' }\n fields[key] = tag\n }\n if ('campaignIds' in raw) {\n const ids = raw['campaignIds']\n if (!Array.isArray(ids)) return { ok: false, error: 'Campaigns must be a list.' }\n fields.campaignIds = campaignMembershipValue(ids.map((id) => String(id ?? '')))\n }\n if ('ownerUid' in raw) fields.ownerUid = typed(raw['ownerUid'], 128)\n if ('companyId' in raw) {\n const companyId = raw['companyId'] === null ? null : typed(raw['companyId'], 128)\n if (companyId !== null && (!companyId || companyId.includes('/'))) {\n return { ok: false, error: 'The company could not be read.' }\n }\n fields.companyId = companyId\n }\n if ('companyName' in raw) fields.companyName = typed(raw['companyName'], 120)\n if ('custom' in raw) {\n const custom = raw['custom']\n if (!custom || typeof custom !== 'object' || Array.isArray(custom)) {\n return { ok: false, error: 'Custom fields must be values keyed by field key.' }\n }\n fields.custom = custom as Record<string, ContactCustomValue>\n }\n if ('mediaIds' in raw) {\n if (!Array.isArray(raw['mediaIds'])) {\n return { ok: false, error: 'Files must be a list of ids.' }\n }\n fields.mediaIds = normalizeCrmMediaIds(raw['mediaIds'])\n }\n if (!Object.keys(fields).length) return { ok: false, error: 'Name the fields to save.' }\n return { ok: true, fields }\n}\n\n/** The ids a body names, deduplicated — or `null` when any is unreadable or there are too many. */\nfunction readContactIds(value: unknown): string[] | null {\n if (!Array.isArray(value) || !value.length || value.length > CRM_CONTACT_UPDATE_MAX) {\n return null\n }\n const ids = value.map((id) => typed(id, 200))\n if (ids.some((id) => !id || id.includes('/'))) return null\n return [...new Set(ids)]\n}\n\n/**\n * Under a site, whether the caller's access reaches it. The rules could not\n * ask this of a facet write — they cannot see which holder a write is for —\n * and a collaborator on one site must not write another site's notes on a\n * person both of them hold.\n */\nfunction reachesSite(writer: Writer, hostId: string): boolean {\n return (\n writer.staff ||\n isOrgWideMember(writer.member) ||\n Boolean((writer.member?.hostAccess as Record<string, unknown> | undefined)?.[hostId])\n )\n}\n\nconst refused = (contactId: string, error: string): ContactUpdateOutcome => ({\n contactId,\n ok: false,\n error,\n})\n\ninterface ContactWrite {\n contactId: string\n ref: FirebaseFirestore.DocumentReference\n update: Record<string, unknown>\n counts: ContactCompanyLinkPlan['counts']\n}\n\n/**\n * One contact's update for one holder, or the sentence refusing the row.\n * `update` is `null` when the document already says everything asked — a tag\n * the row already carries, a link already made.\n */\nfunction contactPatch(\n contact: Record<string, unknown>,\n groupId: string,\n fields: ContactUpdateFields,\n custom: Record<string, ContactCustomValue> | undefined,\n linkedCompanyName: string,\n):\n | { update: Record<string, unknown> | null; counts: ContactCompanyLinkPlan['counts'] }\n | { refused: string } {\n const path = (field: string) => contactFacetPath(groupId, field)\n /** A text field as stored: the value, or the field's absence. */\n const text = (value: string) => value || FieldValue.delete()\n const update: Record<string, unknown> = {}\n let counts: ContactCompanyLinkPlan['counts'] = []\n\n if (fields.name !== undefined) update[path('name')] = text(fields.name)\n if (fields.phone !== undefined) {\n update[path('phone')] = text(fields.phone)\n // The search echo — see `HostContact.phone`.\n update['phone'] = text(fields.phone)\n }\n if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle)\n if (fields.address !== undefined) {\n update[path('address')] = fields.address ?? FieldValue.delete()\n }\n if (fields.notes !== undefined) update[path('notes')] = fields.notes\n if (fields.tags !== undefined) update[path('tags')] = fields.tags\n\n const held = (readContactFacet(contact, groupId).tags ?? []).map((tag) =>\n String(tag).toLowerCase(),\n )\n if (fields.addTag && !held.includes(fields.addTag)) {\n // The record page's cap, which a selection must not slip past.\n if (held.length >= CONTACT_TAGS_MAX) {\n return { refused: `already has ${CONTACT_TAGS_MAX} tags` }\n }\n update[path('tags')] = FieldValue.arrayUnion(fields.addTag)\n }\n if (fields.removeTag && held.includes(fields.removeTag)) {\n update[path('tags')] = FieldValue.arrayRemove(fields.removeTag)\n }\n if (fields.campaignIds !== undefined) {\n update[contactCampaignFieldPath(groupId)] = fields.campaignIds\n }\n if (fields.ownerUid !== undefined) update[path('ownerUid')] = text(fields.ownerUid)\n\n if (fields.companyId !== undefined) {\n const plan = planContactCompanyLink(\n readContactCompanyLink(contact, groupId),\n fields.companyId,\n )\n if (plan) {\n Object.assign(update, contactCompanyLinkFields(plan, groupId))\n counts = plan.counts\n if (fields.companyName === undefined) {\n // The label follows the link: the company's own name, or nothing.\n const label = plan.companyId ? linkedCompanyName : ''\n update[path('companyName')] = text(label)\n // The search echo — see `HostContact.companyName`.\n update['companyName'] = text(label)\n }\n }\n }\n if (fields.companyName !== undefined) {\n update[path('companyName')] = text(fields.companyName)\n update['companyName'] = text(fields.companyName)\n }\n for (const [key, value] of Object.entries(custom ?? {})) {\n update[path(`custom.${key}`)] = value\n }\n if (fields.mediaIds !== undefined) update[path(CRM_MEDIA_IDS_FIELD)] = fields.mediaIds\n\n if (!Object.keys(update).length) return { update: null, counts }\n update['updatedAt'] = FieldValue.serverTimestamp()\n return { update, counts }\n}\n\n/**\n * Every write in one batch, and — when the batch is refused — each on its\n * own, so the contact that could not be written is the only one reported.\n * Answers the ids that were not written.\n */\nasync function commitContactWrites(\n firestore: FirebaseFirestore.Firestore,\n writes: readonly ContactWrite[],\n): Promise<Set<string>> {\n const failed = new Set<string>()\n if (!writes.length) return failed\n const batch = firestore.batch()\n for (const write of writes) batch.update(write.ref, write.update)\n try {\n await batch.commit()\n return failed\n } catch {\n // A batch names no document; the pass below finds the one it was.\n }\n for (const write of writes) {\n try {\n await write.ref.update(write.update)\n } catch (error) {\n console.error('[crm] contact-update could not write a contact', write.contactId, error)\n failed.add(write.contactId)\n }\n }\n return failed\n}\n\n/** Each company's contacts count moved once, by the sum of what the written links moved. */\nasync function settleCompanyCounts(\n companies: FirebaseFirestore.CollectionReference,\n writes: readonly ContactWrite[],\n): Promise<void> {\n const deltas = new Map<string, number>()\n for (const write of writes) {\n for (const count of write.counts) {\n deltas.set(count.companyId, (deltas.get(count.companyId) ?? 0) + count.delta)\n }\n }\n await Promise.all(\n [...deltas]\n .filter(([, delta]) => delta !== 0)\n .map(([companyId, delta]) =>\n companies\n .doc(companyId)\n .update(companyContactsCountFields(delta))\n .catch((error: unknown) => {\n console.error('[crm] company contacts count could not move', companyId, delta, error)\n }),\n ),\n )\n}\n\nexport const crmContactUpdateHandler: PluginApiHandler = 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 contactIds = readContactIds(body['contactIds'])\n if (!contactIds) {\n res.status(400).json({ error: `Name between 1 and ${CRM_CONTACT_UPDATE_MAX} contacts.` })\n return\n }\n const read = readContactUpdateFields(body['set'])\n if (read.ok === false) {\n res.status(400).json({ error: read.error })\n return\n }\n const { fields } = read\n\n try {\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: null })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n if (scope.level === 'site' && !reachesSite(writer, scope.hostId)) {\n res.status(403).json({ error: 'Your access to this organization does not reach this site.' })\n return\n }\n // The plan after the person, and before any contact is read (AGL-2787).\n const suite = crmSuiteRefusal(writer.org, contactUpdateSuiteAct(fields))\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(writer.orgId)\n const siteGroup =\n scope.level === 'site' ? consentGroupForHost(writer.org, scope.hostId) : null\n const siteTokens = siteGroup ? crmReadTokens(siteGroup) : null\n\n let custom: Record<string, ContactCustomValue> | undefined\n if (fields.custom) {\n const definitions = await orgRef\n .collection(CRM_COLLECTIONS.contactFields)\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n const judged = readCrmCustomInput(\n fields.custom,\n definitions.docs.map((doc) => doc.data() as ContactFieldDefinition),\n 'contact',\n )\n if ('errors' in judged) {\n res.status(400).json({\n error: Object.values(judged.errors)[0] ?? 'A custom value could not be saved.',\n })\n return\n }\n custom = judged.values\n }\n\n if (fields.ownerUid) {\n const owner = await resolveOrgMembership(fields.ownerUid, writer.orgId).catch(() => null)\n if (!owner?.member) {\n res.status(400).json({ error: 'The owner is not a member of this organization.' })\n return\n }\n }\n\n // The company a link names has to exist and be visible to the caller and\n // the site, or a person could be filed under a record nobody here can open.\n let linkedCompanyName = ''\n if (fields.companyId) {\n const company = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(fields.companyId)\n .get()\n const tokens = company.exists ? (company.get('visibleTo') as string[] | undefined) : undefined\n const visible =\n company.exists &&\n canReach(writer, tokens) &&\n (!siteTokens || visibleToTokens(tokens, siteTokens))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n linkedCompanyName = typed(company.get('name'), 120)\n }\n\n const contacts = orgRef.collection('contacts')\n const snapshots = await firestore.getAll(...contactIds.map((id) => contacts.doc(id)))\n const outcomes = new Map<string, ContactUpdateOutcome>()\n const writes: ContactWrite[] = []\n snapshots.forEach((snapshot, index) => {\n const contactId = contactIds[index]\n if (!snapshot.exists) {\n outcomes.set(contactId, refused(contactId, 'That contact no longer exists.'))\n return\n }\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n const visibleTo = data['visibleTo'] as string[] | undefined\n if (!canReach(writer, visibleTo)) {\n outcomes.set(contactId, refused(contactId, 'That contact is not visible to you.'))\n return\n }\n if (siteTokens && !visibleToTokens(visibleTo, siteTokens)) {\n outcomes.set(contactId, refused(contactId, 'That contact is not visible to this site.'))\n return\n }\n const group = siteGroup ?? contactPrimaryGroup(data, writer.org)\n if (!group.groupId) {\n outcomes.set(contactId, refused(contactId, NO_HOLDER_REFUSAL))\n return\n }\n const patch = contactPatch(data, group.groupId, fields, custom, linkedCompanyName)\n if ('refused' in patch) {\n outcomes.set(contactId, refused(contactId, patch.refused))\n return\n }\n outcomes.set(contactId, { contactId, ok: true })\n if (patch.update) {\n writes.push({ contactId, ref: snapshot.ref, update: patch.update, counts: patch.counts })\n }\n })\n\n const failed = await commitContactWrites(firestore, writes)\n for (const contactId of failed) {\n outcomes.set(contactId, refused(contactId, 'The contact could not be saved.'))\n }\n await settleCompanyCounts(\n orgRef.collection(CRM_COLLECTIONS.companies),\n writes.filter((write) => !failed.has(write.contactId)),\n )\n\n const answer: ContactUpdateResponse = {\n ok: true,\n results: contactIds.map(\n (contactId) => outcomes.get(contactId) ?? refused(contactId, 'The contact could not be saved.'),\n ),\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] contact-update failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n"],"names":["consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","campaignMembershipValue","contactCampaignFieldPath","contactFacetPath","contactPrimaryGroup","CRM_COLLECTIONS","CRM_MEDIA_IDS_FIELD","crmReadTokens","isOrgWideMember","normalizeAddress","normalizeCrmMediaIds","normalizePhone","planContactCompanyLink","readContactCompanyLink","readContactFacet","readCrmCustomInput","visibleToTokens","companyContactsCountFields","contactCompanyLinkFields","firebaseAdmin","resolveOrgMembership","FieldValue","CONTACT_UPDATE_FIELDS","CRM_CONTACT_UPDATE_MAX","CONTACT_NOTES_MAX","CONTACT_PHONE_REFUSAL","CONTACT_TAGS_MAX","normalizeTags","readBulkTag","typed","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","canReach","SUITE_ACTS","name","phone","jobTitle","address","notes","tags","addTag","removeTag","campaignIds","ownerUid","companyId","companyName","custom","mediaIds","NO_HOLDER_REFUSAL","contactUpdateSuiteAct","fields","field","find","key","undefined","readContactUpdateFields","input","raw","Array","isArray","ok","error","unknownKey","Object","keys","includes","text","String","slice","filter","length","tag","ids","map","id","readContactIds","value","some","Set","reachesSite","writer","hostId","staff","member","Boolean","hostAccess","refused","contactId","contactPatch","contact","groupId","linkedCompanyName","path","delete","update","counts","held","toLowerCase","arrayUnion","arrayRemove","plan","assign","label","entries","serverTimestamp","commitContactWrites","firestore","writes","failed","batch","write","ref","commit","console","add","settleCompanyCounts","companies","deltas","Map","count","set","get","delta","Promise","all","doc","catch","crmContactUpdateHandler","req","res","method","setHeader","status","json","body","scope","contactIds","read","suiteAct","level","suite","org","app","orgRef","collection","orgId","siteGroup","siteTokens","definitions","contactFields","limit","judged","docs","data","values","errors","owner","company","tokens","exists","visible","contacts","snapshots","getAll","outcomes","forEach","snapshot","index","visibleTo","group","patch","push","has","answer","results"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsDC,GAED,SAEEA,mBAAmB,EACnBC,0BAA0B,EAI1BC,uBAAuB,EACvBC,wBAAwB,EACxBC,gBAAgB,EAChBC,mBAAmB,EACnBC,eAAe,EACfC,mBAAmB,EACnBC,aAAa,EACbC,eAAe,EACfC,gBAAgB,EAChBC,oBAAoB,EACpBC,cAAc,EAEdC,sBAAsB,EACtBC,sBAAsB,EACtBC,gBAAgB,EAChBC,kBAAkB,EAClBC,eAAe,QACV,sBAAqB;AAC5B,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,aAAa,EACbC,oBA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EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/contact-update.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `POST /api/crm/contact-update` — one holder's profile fields on one or\n * more contacts (AGL-2804).\n *\n * Body: `{ hostId, contactIds, set }` under a site, or `{ orgId, hostId?,\n * contactIds, set }` at the organization level, where `set` is\n * `ContactUpdateFields`. Answers `{ ok, results }`: one outcome per contact,\n * in the order the ids were sent.\n *\n * ## Why every facet write comes here\n *\n * A contact's fields live in the facet of the holder that keeps them —\n * `facets.{groupId}.*` — and the Firestore rules cannot tell one field of a\n * facet from another: the holder is a map key a rule cannot address, and a\n * write's affected keys name only `facets`. So the rules let a client update\n * change nothing in a facet beyond letting a holder go, and the console's\n * edits arrive here, where the plan is asked about the fields the request\n * actually carries.\n *\n * ## Who may call it\n *\n * The CRM writer the task routes admit (`authorizeCrmWriter`): under a site,\n * a member whose role writes org data, who holds `data.manage` and whose\n * access reaches the site; at the organization level, an org-wide member\n * with the permission. Each contact must then be one the caller may read —\n * the rules' `canReadScoped()` — and, under a site, one the site's hub lists.\n *\n * ## The plan\n *\n * Every field is the CRM's (AGL-2790), and a plan without the CRM has none\n * of it (AGL-2851), so it edits no contact: not the owner, company, custom\n * values or files, and not the profile a capture writes (name, phone, job\n * title, address), the tags, the notes or the campaign filing either. A\n * request carrying any field is refused to such a plan once the caller is\n * known, and before a contact is read — staff included, because the plan is\n * a fact about the workspace. Erasing a person is another route, open on\n * every plan.\n *\n * ## One holder, by dotted path\n *\n * Under a site the facet is the site's consent group's; at the organization\n * level it is each contact's own primary holder, the facet the record page\n * shows there. Every field is one dotted path — a nested `facets` object\n * would replace every other holder's map — and a text field sent empty is\n * deleted rather than stored blank, so \"no phone\" has one shape.\n *\n * ## Many contacts, one commit\n *\n * The contacts are read together and written in one batch. A batch that\n * fails is retried contact by contact, so the one that could not be written\n * is named and the rest still land. A company's contacts count follows the\n * link: summed per company and settled once the contacts are written, so a\n * company deleted in between cannot fail the save of the people at it — the\n * company page's live aggregate is what corrects a count that did not move.\n */\n\nimport {\n type AglynPostalAddress,\n consentGroupForHost,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ContactCompanyLinkPlan,\n type ContactCustomValue,\n type ContactFieldDefinition,\n campaignMembershipValue,\n contactCampaignFieldPath,\n contactFacetPath,\n contactPrimaryGroup,\n CRM_COLLECTIONS,\n CRM_LEAD_SOURCE_PICKLIST,\n CRM_MEDIA_IDS_FIELD,\n crmReadTokens,\n effectiveCrmLeadSourcePicklist,\n isOrgWideMember,\n judgeCrmLeadSource,\n normalizeAddress,\n normalizeCrmMediaIds,\n normalizeCrmPicklistLabel,\n normalizePhone,\n type PluginApiHandler,\n planContactCompanyLink,\n readContactCompanyLink,\n readContactFacet,\n readCrmCustomInput,\n visibleToTokens,\n} from '@aglyn/aglyn/server'\nimport {\n companyContactsCountFields,\n contactCompanyLinkFields,\n firebaseAdmin,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CONTACT_UPDATE_FIELDS,\n type ContactUpdateFields,\n type ContactUpdateOutcome,\n type ContactUpdateResponse,\n CRM_CONTACT_UPDATE_MAX,\n} from '../model/contact-update'\nimport {\n CONTACT_NOTES_MAX,\n CONTACT_PHONE_REFUSAL,\n CONTACT_TAGS_MAX,\n normalizeTags,\n readBulkTag,\n typed,\n} from './contact-profile'\nimport { readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\nimport { authorizeCrmWriter, canReach, type Writer } from './task-routes'\n\n/** What the suite gate names for each field a request can carry. */\nconst SUITE_ACTS: Record<keyof ContactUpdateFields, string> = {\n name: \"Editing a contact's profile\",\n phone: \"Editing a contact's profile\",\n jobTitle: \"Editing a contact's profile\",\n leadSource: \"Editing a contact's profile\",\n address: \"Editing a contact's profile\",\n notes: \"Editing a contact's notes\",\n tags: 'Tagging a contact',\n addTag: 'Tagging a contact',\n removeTag: 'Tagging a contact',\n campaignIds: 'Filing a contact under a campaign',\n ownerUid: \"Assigning a contact's owner\",\n companyId: 'Filing a contact under a company',\n companyName: 'Filing a contact under a company',\n custom: \"Editing a contact's custom fields\",\n mediaIds: 'Attaching files to a contact',\n}\n\n/** A contact read at the organization level that no site has captured. */\nconst NO_HOLDER_REFUSAL = 'No site holds this contact yet, so it has no profile to edit.'\n\n/**\n * The act a request is refused for on a plan without the CRM: the first\n * field it carries, in the order the route reads them. Every field is the\n * CRM's, so whichever field a request names is the act its refusal names.\n */\nexport function contactUpdateSuiteAct(fields: ContactUpdateFields): string {\n const field = CONTACT_UPDATE_FIELDS.find((key) => fields[key] !== undefined)\n return field ? SUITE_ACTS[field] : \"Editing a contact's profile\"\n}\n\n/**\n * A body's `set`, read into the fields it names, or the sentence refusing\n * it. A key the route does not save is refused rather than dropped: a save\n * that silently lost a field would read as a save that kept it.\n */\nexport function readContactUpdateFields(\n input: unknown,\n): { ok: true; fields: ContactUpdateFields } | { ok: false; error: string } {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n return { ok: false, error: 'Name the fields to save.' }\n }\n const raw = input as Record<string, unknown>\n const unknownKey = Object.keys(raw).find(\n (key) => !(CONTACT_UPDATE_FIELDS as readonly string[]).includes(key),\n )\n if (unknownKey) {\n return { ok: false, error: `\"${unknownKey}\" is not a field a contact's profile saves.` }\n }\n const fields: ContactUpdateFields = {}\n if ('name' in raw) fields.name = typed(raw['name'], 120)\n if ('phone' in raw) {\n const text = typed(raw['phone'], 40)\n const phone = text ? normalizePhone(text) : ''\n if (phone === null) return { ok: false, error: CONTACT_PHONE_REFUSAL }\n fields.phone = phone\n }\n if ('jobTitle' in raw) fields.jobTitle = typed(raw['jobTitle'], 120)\n // Held to the label's shape here; judged against the org's list by the\n // handler, which alone can read it (AGL-3298).\n if ('leadSource' in raw) fields.leadSource = normalizeCrmPicklistLabel(raw['leadSource'])\n if ('address' in raw) {\n const address = raw['address']\n fields.address =\n address && typeof address === 'object' && !Array.isArray(address)\n ? normalizeAddress(address as AglynPostalAddress)\n : null\n }\n if ('notes' in raw) fields.notes = String(raw['notes'] ?? '').slice(0, CONTACT_NOTES_MAX)\n // One write may carry one transform per field, so the tags are replaced,\n // added to or taken from — never two of those at once.\n if (['tags', 'addTag', 'removeTag'].filter((key) => key in raw).length > 1) {\n return { ok: false, error: 'Send the tags, a tag to add or a tag to remove — one of them.' }\n }\n if ('tags' in raw) {\n if (!Array.isArray(raw['tags'])) return { ok: false, error: 'Tags must be a list.' }\n fields.tags = normalizeTags(raw['tags'])\n }\n for (const key of ['addTag', 'removeTag'] as const) {\n if (!(key in raw)) continue\n const tag = readBulkTag(raw[key])\n if (!tag) return { ok: false, error: 'Name the tag.' }\n fields[key] = tag\n }\n if ('campaignIds' in raw) {\n const ids = raw['campaignIds']\n if (!Array.isArray(ids)) return { ok: false, error: 'Campaigns must be a list.' }\n fields.campaignIds = campaignMembershipValue(ids.map((id) => String(id ?? '')))\n }\n if ('ownerUid' in raw) fields.ownerUid = typed(raw['ownerUid'], 128)\n if ('companyId' in raw) {\n const companyId = raw['companyId'] === null ? null : typed(raw['companyId'], 128)\n if (companyId !== null && (!companyId || companyId.includes('/'))) {\n return { ok: false, error: 'The company could not be read.' }\n }\n fields.companyId = companyId\n }\n if ('companyName' in raw) fields.companyName = typed(raw['companyName'], 120)\n if ('custom' in raw) {\n const custom = raw['custom']\n if (!custom || typeof custom !== 'object' || Array.isArray(custom)) {\n return { ok: false, error: 'Custom fields must be values keyed by field key.' }\n }\n fields.custom = custom as Record<string, ContactCustomValue>\n }\n if ('mediaIds' in raw) {\n if (!Array.isArray(raw['mediaIds'])) {\n return { ok: false, error: 'Files must be a list of ids.' }\n }\n fields.mediaIds = normalizeCrmMediaIds(raw['mediaIds'])\n }\n if (!Object.keys(fields).length) return { ok: false, error: 'Name the fields to save.' }\n return { ok: true, fields }\n}\n\n/** The ids a body names, deduplicated — or `null` when any is unreadable or there are too many. */\nfunction readContactIds(value: unknown): string[] | null {\n if (!Array.isArray(value) || !value.length || value.length > CRM_CONTACT_UPDATE_MAX) {\n return null\n }\n const ids = value.map((id) => typed(id, 200))\n if (ids.some((id) => !id || id.includes('/'))) return null\n return [...new Set(ids)]\n}\n\n/**\n * Under a site, whether the caller's access reaches it. The rules could not\n * ask this of a facet write — they cannot see which holder a write is for —\n * and a collaborator on one site must not write another site's notes on a\n * person both of them hold.\n */\nfunction reachesSite(writer: Writer, hostId: string): boolean {\n return (\n writer.staff ||\n isOrgWideMember(writer.member) ||\n Boolean((writer.member?.hostAccess as Record<string, unknown> | undefined)?.[hostId])\n )\n}\n\nconst refused = (contactId: string, error: string): ContactUpdateOutcome => ({\n contactId,\n ok: false,\n error,\n})\n\ninterface ContactWrite {\n contactId: string\n ref: FirebaseFirestore.DocumentReference\n update: Record<string, unknown>\n counts: ContactCompanyLinkPlan['counts']\n}\n\n/**\n * One contact's update for one holder, or the sentence refusing the row.\n * `update` is `null` when the document already says everything asked — a tag\n * the row already carries, a link already made.\n */\nfunction contactPatch(\n contact: Record<string, unknown>,\n groupId: string,\n fields: ContactUpdateFields,\n custom: Record<string, ContactCustomValue> | undefined,\n linkedCompanyName: string,\n):\n | { update: Record<string, unknown> | null; counts: ContactCompanyLinkPlan['counts'] }\n | { refused: string } {\n const path = (field: string) => contactFacetPath(groupId, field)\n /** A text field as stored: the value, or the field's absence. */\n const text = (value: string) => value || FieldValue.delete()\n const update: Record<string, unknown> = {}\n let counts: ContactCompanyLinkPlan['counts'] = []\n\n if (fields.name !== undefined) update[path('name')] = text(fields.name)\n if (fields.phone !== undefined) {\n update[path('phone')] = text(fields.phone)\n // The search echo — see `HostContact.phone`.\n update['phone'] = text(fields.phone)\n }\n if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle)\n if (fields.leadSource !== undefined) update[path('leadSource')] = text(fields.leadSource)\n if (fields.address !== undefined) {\n update[path('address')] = fields.address ?? FieldValue.delete()\n }\n if (fields.notes !== undefined) update[path('notes')] = fields.notes\n if (fields.tags !== undefined) update[path('tags')] = fields.tags\n\n const held = (readContactFacet(contact, groupId).tags ?? []).map((tag) =>\n String(tag).toLowerCase(),\n )\n if (fields.addTag && !held.includes(fields.addTag)) {\n // The record page's cap, which a selection must not slip past.\n if (held.length >= CONTACT_TAGS_MAX) {\n return { refused: `already has ${CONTACT_TAGS_MAX} tags` }\n }\n update[path('tags')] = FieldValue.arrayUnion(fields.addTag)\n }\n if (fields.removeTag && held.includes(fields.removeTag)) {\n update[path('tags')] = FieldValue.arrayRemove(fields.removeTag)\n }\n if (fields.campaignIds !== undefined) {\n update[contactCampaignFieldPath(groupId)] = fields.campaignIds\n }\n if (fields.ownerUid !== undefined) update[path('ownerUid')] = text(fields.ownerUid)\n\n if (fields.companyId !== undefined) {\n const plan = planContactCompanyLink(\n readContactCompanyLink(contact, groupId),\n fields.companyId,\n )\n if (plan) {\n Object.assign(update, contactCompanyLinkFields(plan, groupId))\n counts = plan.counts\n if (fields.companyName === undefined) {\n // The label follows the link: the company's own name, or nothing.\n const label = plan.companyId ? linkedCompanyName : ''\n update[path('companyName')] = text(label)\n // The search echo — see `HostContact.companyName`.\n update['companyName'] = text(label)\n }\n }\n }\n if (fields.companyName !== undefined) {\n update[path('companyName')] = text(fields.companyName)\n update['companyName'] = text(fields.companyName)\n }\n for (const [key, value] of Object.entries(custom ?? {})) {\n update[path(`custom.${key}`)] = value\n }\n if (fields.mediaIds !== undefined) update[path(CRM_MEDIA_IDS_FIELD)] = fields.mediaIds\n\n if (!Object.keys(update).length) return { update: null, counts }\n update['updatedAt'] = FieldValue.serverTimestamp()\n return { update, counts }\n}\n\n/**\n * Every write in one batch, and — when the batch is refused — each on its\n * own, so the contact that could not be written is the only one reported.\n * Answers the ids that were not written.\n */\nasync function commitContactWrites(\n firestore: FirebaseFirestore.Firestore,\n writes: readonly ContactWrite[],\n): Promise<Set<string>> {\n const failed = new Set<string>()\n if (!writes.length) return failed\n const batch = firestore.batch()\n for (const write of writes) batch.update(write.ref, write.update)\n try {\n await batch.commit()\n return failed\n } catch {\n // A batch names no document; the pass below finds the one it was.\n }\n for (const write of writes) {\n try {\n await write.ref.update(write.update)\n } catch (error) {\n console.error('[crm] contact-update could not write a contact', write.contactId, error)\n failed.add(write.contactId)\n }\n }\n return failed\n}\n\n/** Each company's contacts count moved once, by the sum of what the written links moved. */\nasync function settleCompanyCounts(\n companies: FirebaseFirestore.CollectionReference,\n writes: readonly ContactWrite[],\n): Promise<void> {\n const deltas = new Map<string, number>()\n for (const write of writes) {\n for (const count of write.counts) {\n deltas.set(count.companyId, (deltas.get(count.companyId) ?? 0) + count.delta)\n }\n }\n await Promise.all(\n [...deltas]\n .filter(([, delta]) => delta !== 0)\n .map(([companyId, delta]) =>\n companies\n .doc(companyId)\n .update(companyContactsCountFields(delta))\n .catch((error: unknown) => {\n console.error('[crm] company contacts count could not move', companyId, delta, error)\n }),\n ),\n )\n}\n\nexport const crmContactUpdateHandler: PluginApiHandler = 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 contactIds = readContactIds(body['contactIds'])\n if (!contactIds) {\n res.status(400).json({ error: `Name between 1 and ${CRM_CONTACT_UPDATE_MAX} contacts.` })\n return\n }\n const read = readContactUpdateFields(body['set'])\n if (read.ok === false) {\n res.status(400).json({ error: read.error })\n return\n }\n const { fields } = read\n\n try {\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: null })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n if (scope.level === 'site' && !reachesSite(writer, scope.hostId)) {\n res.status(403).json({ error: 'Your access to this organization does not reach this site.' })\n return\n }\n // The plan after the person, and before any contact is read (AGL-2787).\n const suite = crmSuiteRefusal(writer.org, contactUpdateSuiteAct(fields))\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(writer.orgId)\n const siteGroup =\n scope.level === 'site' ? consentGroupForHost(writer.org, scope.hostId) : null\n const siteTokens = siteGroup ? crmReadTokens(siteGroup) : null\n\n let custom: Record<string, ContactCustomValue> | undefined\n if (fields.custom) {\n const definitions = await orgRef\n .collection(CRM_COLLECTIONS.contactFields)\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n const judged = readCrmCustomInput(\n fields.custom,\n definitions.docs.map((doc) => doc.data() as ContactFieldDefinition),\n 'contact',\n )\n if ('errors' in judged) {\n res.status(400).json({\n error: Object.values(judged.errors)[0] ?? 'A custom value could not be saved.',\n })\n return\n }\n custom = judged.values\n }\n\n /*\n * THE ORG'S LEAD SOURCES (AGL-3298), read only when the body names one.\n * Judged per contact below, because a contact keeps the value it\n * already holds even when the list has since deactivated it.\n */\n const leadSources = fields.leadSource\n ? effectiveCrmLeadSourcePicklist(\n (\n await orgRef.collection(CRM_COLLECTIONS.picklists).doc(CRM_LEAD_SOURCE_PICKLIST).get()\n ).data(),\n )\n : null\n\n if (fields.ownerUid) {\n const owner = await resolveOrgMembership(fields.ownerUid, writer.orgId).catch(() => null)\n if (!owner?.member) {\n res.status(400).json({ error: 'The owner is not a member of this organization.' })\n return\n }\n }\n\n // The company a link names has to exist and be visible to the caller and\n // the site, or a person could be filed under a record nobody here can open.\n let linkedCompanyName = ''\n if (fields.companyId) {\n const company = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(fields.companyId)\n .get()\n const tokens = company.exists ? (company.get('visibleTo') as string[] | undefined) : undefined\n const visible =\n company.exists &&\n canReach(writer, tokens) &&\n (!siteTokens || visibleToTokens(tokens, siteTokens))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n linkedCompanyName = typed(company.get('name'), 120)\n }\n\n const contacts = orgRef.collection('contacts')\n const snapshots = await firestore.getAll(...contactIds.map((id) => contacts.doc(id)))\n const outcomes = new Map<string, ContactUpdateOutcome>()\n const writes: ContactWrite[] = []\n snapshots.forEach((snapshot, index) => {\n const contactId = contactIds[index]\n if (!snapshot.exists) {\n outcomes.set(contactId, refused(contactId, 'That contact no longer exists.'))\n return\n }\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n const visibleTo = data['visibleTo'] as string[] | undefined\n if (!canReach(writer, visibleTo)) {\n outcomes.set(contactId, refused(contactId, 'That contact is not visible to you.'))\n return\n }\n if (siteTokens && !visibleToTokens(visibleTo, siteTokens)) {\n outcomes.set(contactId, refused(contactId, 'That contact is not visible to this site.'))\n return\n }\n const group = siteGroup ?? contactPrimaryGroup(data, writer.org)\n if (!group.groupId) {\n outcomes.set(contactId, refused(contactId, NO_HOLDER_REFUSAL))\n return\n }\n let rowFields = fields\n if (leadSources && fields.leadSource) {\n const judged = judgeCrmLeadSource(\n leadSources,\n fields.leadSource,\n readContactFacet(data, group.groupId).leadSource,\n )\n if (judged.ok === false) {\n outcomes.set(contactId, refused(contactId, judged.error))\n return\n }\n rowFields = { ...fields, leadSource: judged.value ?? '' }\n }\n const patch = contactPatch(data, group.groupId, rowFields, custom, linkedCompanyName)\n if ('refused' in patch) {\n outcomes.set(contactId, refused(contactId, patch.refused))\n return\n }\n outcomes.set(contactId, { contactId, ok: true })\n if (patch.update) {\n writes.push({ contactId, ref: snapshot.ref, update: patch.update, counts: patch.counts })\n }\n })\n\n const failed = await commitContactWrites(firestore, writes)\n for (const contactId of failed) {\n outcomes.set(contactId, refused(contactId, 'The contact could not be saved.'))\n }\n await settleCompanyCounts(\n orgRef.collection(CRM_COLLECTIONS.companies),\n writes.filter((write) => !failed.has(write.contactId)),\n )\n\n const answer: ContactUpdateResponse = {\n ok: true,\n results: contactIds.map(\n (contactId) => outcomes.get(contactId) ?? refused(contactId, 'The contact could not be saved.'),\n ),\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] contact-update failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n"],"names":["consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","campaignMembershipValue","contactCampaignFieldPath","contactFacetPath","contactPrimaryGroup","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","CRM_MEDIA_IDS_FIELD","crmReadTokens","effectiveCrmLeadSourcePicklist","isOrgWideMember","judgeCrmLeadSource","normalizeAddress","normalizeCrmMediaIds","normalizeCrmPicklistLabel","normalizePhone","planContactCompanyLink","readContactCompanyLink","readContactFacet","readCrmCustomInput","visibleToTokens","companyContactsCountFields","contactCompanyLinkFields","firebaseAdmin","resolveOrgMembership","FieldValue","CONTACT_UPDATE_FIELDS","CRM_CONTACT_UPDATE_MAX","CONTACT_NOTES_MAX","CONTACT_PHONE_REFUSAL","CONTACT_TAGS_MAX","normalizeTags","readBulkTag","typed","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","canReach","SUITE_ACTS","name","phone","jobTitle","leadSource","address","notes","tags","addTag","removeTag","campaignIds","ownerUid","companyId","companyName","custom","mediaIds","NO_HOLDER_REFUSAL","contactUpdateSuiteAct","fields","field","find","key","undefined","readContactUpdateFields","input","raw","Array","isArray","ok","error","unknownKey","Object","keys","includes","text","String","slice","filter","length","tag","ids","map","id","readContactIds","value","some","Set","reachesSite","writer","hostId","staff","member","Boolean","hostAccess","refused","contactId","contactPatch","contact","groupId","linkedCompanyName","path","delete","update","counts","held","toLowerCase","arrayUnion","arrayRemove","plan","assign","label","entries","serverTimestamp","commitContactWrites","firestore","writes","failed","batch","write","ref","commit","console","add","settleCompanyCounts","companies","deltas","Map","count","set","get","delta","Promise","all","doc","catch","crmContactUpdateHandler","req","res","method","setHeader","status","json","body","scope","contactIds","read","suiteAct","level","suite","org","app","orgRef","collection","orgId","siteGroup","siteTokens","definitions","contactFields","limit","judged","docs","data","values","errors","leadSources","picklists","owner","company","tokens","exists","visible","contacts","snapshots","getAll","outcomes","forEach","snapshot","index","visibleTo","group","rowFields","patch","push","has","answer","results"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsDC,GAED,SAEEA,mBAAmB,EACnBC,0BAA0B,EAI1BC,uBAAuB,EACvBC,wBAAwB,EACxBC,gBAAgB,EAChBC,mBAAmB,EACnBC,eAAe,EACfC,wBAAwB,EACxBC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,EAC9BC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,EAChBC,oBAAoB,EACpBC,yBAAyB,EACzBC,cAAc,EAEdC,sBAAsB,EACtBC,sBAAsB,EACtBC,gBAAgB,EAChBC,kBAAkB,EAClBC,eAAe,QACV,sBAAqB;AAC5B,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,aAAa,EACbC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,qBAAqB,EAIrBC,sBAAsB,QACjB,6BAAyB;AAChC,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,gBAAgB,EAChBC,aAAa,EACbC,WAAW,EACXC,KAAK,QACA,uBAAmB;AAC1B,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,eAAe,QAAQ,kBAAc;AAC9C,SAASC,kBAAkB,EAAEC,QAAQ,QAAqB,mBAAe;AAEzE,kEAAkE,GAClE,MAAMC,aAAwD;IAC5DC,MAAM;IACNC,OAAO;IACPC,UAAU;IACVC,YAAY;IACZC,SAAS;IACTC,OAAO;IACPC,MAA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AAMvB,SAAS;QAGtD,MAAMyF,SAAgC;YACpCpH,IAAI;YACJqH,SAASzC,WAAW/D,GAAG,CACrB,CAACc;oBAAc+E;wBAAAA,gBAAAA,SAAS7C,GAAG,CAAClC,sBAAb+E,gBAA2BhF,QAAQC,WAAW;;QAEjE;QACA0C,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC2C;IACvB,EAAE,OAAOnH,OAAO;QACdoD,QAAQpD,KAAK,CAAC,+BAA+BA;QAC7CoE,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAExE,OAAO;QAAkC;IAClE;AACF,EAAC"}
@@ -50,6 +50,7 @@ import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
50
50
  import { normalizeCampaignIds, readCampaignIds } from "@aglyn/aglyn/app-utils/campaign-membership";
51
51
  import { FieldValue } from "firebase-admin/firestore";
52
52
  import { fileCampaignFilingActivities } from "./campaign-filing-activity.js";
53
+ import { readLeadSourcePicklist, resolveLeadSourceWrite } from "./lead-source-picklist.js";
53
54
  import { holdsDataManage } from "./org-caller.js";
54
55
  import { crmSuiteRefusal } from "./suite-gate.js";
55
56
  /** The statuses a lead may be entered in — everything but the converted state. */ const CREATE_STATUSES = [
@@ -220,6 +221,24 @@ export const leadCreateHandler = async (req, res)=>{
220
221
  const before = await readLeadForHost(hostId, leadId);
221
222
  const created = !before;
222
223
  /*
224
+ * THE ORG'S LEAD SOURCES (AGL-3298), judged before any write: a value
225
+ * outside the list is refused under the field naming what the list
226
+ * allows, a lead the site already held keeps the value it has, and a
227
+ * new lead that named none starts from the list's default.
228
+ */ const leadSource = resolveLeadSourceWrite(await readLeadSourcePicklist(firestore, resolved.orgId), patch.leadSource, {
229
+ current: before == null ? void 0 : before.get('leadSource'),
230
+ created
231
+ });
232
+ if (leadSource.ok === false) {
233
+ res.status(400).json({
234
+ error: leadSource.error,
235
+ field: 'leadSource'
236
+ });
237
+ return;
238
+ }
239
+ if (leadSource.write === undefined) delete patch.leadSource;
240
+ else patch.leadSource = leadSource.write;
241
+ /*
223
242
  * The platform ceiling, judged here so the drawer can say WHY rather
224
243
  * than only that the lead could not be saved; the door re-judges it
225
244
  * inside its own transaction, so a race is still refused there.