@aglyn/plugins-crm 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/crm-related-to-picker.d.ts +1 -1
- package/src/lib/components/crm-related-to-picker.js +10 -39
- package/src/lib/components/crm-related-to-picker.js.map +1 -1
- package/src/lib/model/crm-activity-link.d.ts +33 -0
- package/src/lib/model/crm-activity-link.js +54 -0
- package/src/lib/model/crm-activity-link.js.map +1 -1
- package/src/lib/model/deal-contact-roles.d.ts +1 -1
- package/src/lib/model/deal-contact-roles.js +1 -1
- package/src/lib/model/deal-contact-roles.js.map +1 -1
- package/src/lib/server/contact-update.js +8 -5
- package/src/lib/server/contact-update.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-crm",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,19 +25,19 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.
|
|
30
|
-
"@aglyn/shared-data-mdi": "1.
|
|
31
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
32
|
-
"@aglyn/shared-ui-next": "1.
|
|
33
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
34
|
-
"@aglyn/shared-util-email": "1.
|
|
35
|
-
"@aglyn/shared-util-http": "1.
|
|
36
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
37
|
-
"@aglyn/shared-util-tools": "1.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.9.0",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.9.0",
|
|
30
|
+
"@aglyn/shared-data-mdi": "1.9.0",
|
|
31
|
+
"@aglyn/shared-ui-jsx": "1.9.0",
|
|
32
|
+
"@aglyn/shared-ui-next": "1.9.0",
|
|
33
|
+
"@aglyn/shared-ui-snackstack": "1.9.0",
|
|
34
|
+
"@aglyn/shared-util-email": "1.9.0",
|
|
35
|
+
"@aglyn/shared-util-http": "1.9.0",
|
|
36
|
+
"@aglyn/shared-util-timestamp": "1.9.0",
|
|
37
|
+
"@aglyn/shared-util-tools": "1.9.0",
|
|
38
|
+
"@aglyn/tenant-data-admin": "1.9.0",
|
|
39
|
+
"@aglyn/tenant-feature-instance": "1.9.0",
|
|
40
|
+
"@aglyn/tenant-runtime": "1.9.0",
|
|
41
41
|
"@dnd-kit/core": "^6.3.1",
|
|
42
42
|
"@dnd-kit/utilities": "^3.2.2",
|
|
43
43
|
"@swc/helpers": "0.5.23",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CrmActivityRelated } from '../model/crm-activity-link';
|
|
2
2
|
export interface CrmRelatedToPickerProps {
|
|
3
3
|
/** The org root, or `null` until it is known. */
|
|
4
4
|
scope: readonly [string, string] | null;
|
|
@@ -20,10 +20,9 @@ import { Autocomplete, TextField } from "@mui/material";
|
|
|
20
20
|
import { useMemo, useState } from "react";
|
|
21
21
|
import { useCrmFoldsScope } from "../hooks/use-crm-list-query.js";
|
|
22
22
|
import { useContactRoleDeals, useLinkedDeals } from "../hooks/use-deals.js";
|
|
23
|
+
import { crmRelatedToOptions } from "../model/crm-activity-link.js";
|
|
23
24
|
import { CRM_RECORD_PICKER_LIMIT, useCrmRecordWindow } from "./crm-record-picker.js";
|
|
24
|
-
const OPEN_DEALS_GROUP = 'Open deals';
|
|
25
25
|
const sameRecord = (a, b)=>a.kind === b.kind && a.id === b.id;
|
|
26
|
-
const byLabel = (a, b)=>a.label.localeCompare(b.label);
|
|
27
26
|
/**
|
|
28
27
|
* An activity's **Related To** (AGL-4123), Salesforce's What: one company or
|
|
29
28
|
* one deal.
|
|
@@ -51,43 +50,15 @@ const byLabel = (a, b)=>a.label.localeCompare(b.label);
|
|
|
51
50
|
});
|
|
52
51
|
const options = useMemo(()=>{
|
|
53
52
|
var _contactDeals_data, _roleDeals_data, _companyDeals_data, _deals_data, _companies_data;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
id: deal.$id,
|
|
64
|
-
label: deal.title || 'Untitled deal',
|
|
65
|
-
group: OPEN_DEALS_GROUP
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
const named = (row, field)=>{
|
|
69
|
-
var _row_field;
|
|
70
|
-
return String((_row_field = row[field]) != null ? _row_field : '') || row.$id;
|
|
71
|
-
};
|
|
72
|
-
const otherDeals = ((_deals_data = deals.data) != null ? _deals_data : []).filter((row)=>!open.has(row.$id)).map((row)=>({
|
|
73
|
-
kind: 'deal',
|
|
74
|
-
id: row.$id,
|
|
75
|
-
label: named(row, 'title'),
|
|
76
|
-
group: 'Deals'
|
|
77
|
-
}));
|
|
78
|
-
const listed = ((_companies_data = companies.data) != null ? _companies_data : []).map((row)=>({
|
|
79
|
-
kind: 'company',
|
|
80
|
-
id: row.$id,
|
|
81
|
-
label: named(row, 'name'),
|
|
82
|
-
group: 'Companies'
|
|
83
|
-
}));
|
|
84
|
-
return [
|
|
85
|
-
...[
|
|
86
|
-
...open.values()
|
|
87
|
-
].sort(byLabel),
|
|
88
|
-
...listed.sort(byLabel),
|
|
89
|
-
...otherDeals.sort(byLabel)
|
|
90
|
-
];
|
|
53
|
+
return crmRelatedToOptions({
|
|
54
|
+
linkedDeals: [
|
|
55
|
+
...(_contactDeals_data = contactDeals.data) != null ? _contactDeals_data : [],
|
|
56
|
+
...(_roleDeals_data = roleDeals.data) != null ? _roleDeals_data : [],
|
|
57
|
+
...(_companyDeals_data = companyDeals.data) != null ? _companyDeals_data : []
|
|
58
|
+
],
|
|
59
|
+
deals: (_deals_data = deals.data) != null ? _deals_data : [],
|
|
60
|
+
companies: (_companies_data = companies.data) != null ? _companies_data : []
|
|
61
|
+
});
|
|
91
62
|
}, [
|
|
92
63
|
contactDeals.data,
|
|
93
64
|
roleDeals.data,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-related-to-picker.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { Autocomplete, TextField } from '@mui/material'\nimport { useMemo, useState } from 'react'\nimport { useCrmFoldsScope } from '../hooks/use-crm-list-query'\nimport { useContactRoleDeals, useLinkedDeals } from '../hooks/use-deals'\nimport type { CrmActivityRelated } from '../model/crm-activity-link'\nimport { CRM_RECORD_PICKER_LIMIT, useCrmRecordWindow } from './crm-record-picker'\n\nexport interface CrmRelatedToPickerProps {\n /** The org root, or `null` until it is known. */\n scope: readonly [string, string] | null\n orgId: string | null\n /** The reader's tokens, or `null` at the organization level. */\n readTokens: readonly string[] | null\n /** The contact the entry is with, whose open deals lead the list. */\n contactId: string | null\n /** The company the entry is about, whose open deals lead the list. */\n companyId: string | null\n value: CrmActivityRelated | null\n /** The current value's name, shown while the lists do not hold the record. */\n valueLabel?: string\n onChange: (next: CrmActivityRelated | null) => void\n disabled?: boolean\n}\n\ninterface RelatedOption extends CrmActivityRelated {\n label: string\n group: string\n}\n\nconst OPEN_DEALS_GROUP = 'Open deals'\n\nconst sameRecord = (a: CrmActivityRelated, b: CrmActivityRelated) =>\n a.kind === b.kind && a.id === b.id\n\nconst byLabel = (a: RelatedOption, b: RelatedOption) => a.label.localeCompare(b.label)\n\n/**\n * An activity's **Related To** (AGL-4123), Salesforce's What: one company or\n * one deal.\n *\n * The open deals of the person and the company on the entry lead the list,\n * because logging a call with someone who has a deal in flight is the case\n * this field exists for: naming that deal puts the entry on it too. Below\n * them sit the windows every record picker offers, so an older record stays\n * one search away. Nothing listens until the menu is first opened, because\n * most entries are saved with the field as it opened.\n */\nexport function CrmRelatedToPicker(props: CrmRelatedToPickerProps) {\n const { scope, orgId, readTokens, contactId, companyId, value, valueLabel, onChange, disabled } =\n props\n const [opened, setOpened] = useState(false)\n const companies = useCrmRecordWindow('company', scope, readTokens, opened)\n const deals = useCrmRecordWindow('deal', scope, readTokens, opened)\n const foldsScope = useCrmFoldsScope(orgId, readTokens)\n const contactDeals = useLinkedDeals(orgId, readTokens, {\n contactId: opened ? (contactId ?? '') : '',\n })\n const roleDeals = useContactRoleDeals(\n orgId,\n readTokens,\n foldsScope,\n opened ? contactId : null,\n )\n const companyDeals = useLinkedDeals(orgId, readTokens, {\n companyId: opened ? (companyId ?? '') : '',\n })\n\n const options = useMemo<RelatedOption[]>(() => {\n const open = new Map<string, RelatedOption>()\n for (const deal of [\n ...(contactDeals.data ?? []),\n ...(roleDeals.data ?? []),\n ...(companyDeals.data ?? []),\n ]) {\n if (deal.status !== 'open') continue\n open.set(deal.$id, {\n kind: 'deal',\n id: deal.$id,\n label: deal.title || 'Untitled deal',\n group: OPEN_DEALS_GROUP,\n })\n }\n const named = (row: Record<string, unknown> & { $id: string }, field: string) =>\n String(row[field] ?? '') || row.$id\n const otherDeals = (deals.data ?? [])\n .filter((row) => !open.has(row.$id))\n .map<RelatedOption>((row) => ({\n kind: 'deal',\n id: row.$id,\n label: named(row, 'title'),\n group: 'Deals',\n }))\n const listed = (companies.data ?? []).map<RelatedOption>((row) => ({\n kind: 'company',\n id: row.$id,\n label: named(row, 'name'),\n group: 'Companies',\n }))\n return [\n ...[...open.values()].sort(byLabel),\n ...listed.sort(byLabel),\n ...otherDeals.sort(byLabel),\n ]\n }, [contactDeals.data, roleDeals.data, companyDeals.data, deals.data, companies.data])\n\n const windowFull =\n (companies.data?.length ?? 0) >= CRM_RECORD_PICKER_LIMIT ||\n (deals.data?.length ?? 0) >= CRM_RECORD_PICKER_LIMIT\n\n const selected = useMemo<RelatedOption | null>(() => {\n if (!value) return null\n return (\n options.find((option) => sameRecord(option, value)) ?? {\n ...value,\n label: valueLabel || (value.kind === 'deal' ? 'Deal' : 'Company'),\n group: '',\n }\n )\n }, [options, value, valueLabel])\n\n return (\n <Autocomplete\n options={options}\n value={selected}\n onChange={(_event, next) =>\n onChange(next ? { kind: next.kind, id: next.id } : null)\n }\n onOpen={() => setOpened(true)}\n getOptionLabel={(option) => option.label}\n getOptionKey={(option) => `${option.kind}:${option.id}`}\n isOptionEqualToValue={(option, current) => sameRecord(option, current)}\n groupBy={(option) => option.group}\n loading={opened && (companies.status === 'loading' || deals.status === 'loading')}\n disabled={disabled}\n size=\"small\"\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Related To\"\n helperText={\n windowFull ? `The ${CRM_RECORD_PICKER_LIMIT} most recently updated — type to narrow.` : undefined\n }\n />\n )}\n />\n )\n}\nCrmRelatedToPicker.displayName = 'CrmRelatedToPicker'\n\nexport default CrmRelatedToPicker\n"],"names":["Autocomplete","TextField","useMemo","useState","useCrmFoldsScope","useContactRoleDeals","useLinkedDeals","CRM_RECORD_PICKER_LIMIT","useCrmRecordWindow","OPEN_DEALS_GROUP","sameRecord","a","b","kind","id","byLabel","label","localeCompare","CrmRelatedToPicker","props","companies","deals","scope","orgId","readTokens","contactId","companyId","value","valueLabel","onChange","disabled","opened","setOpened","foldsScope","contactDeals","roleDeals","companyDeals","options","open","Map","deal","data","status","set","$id","title","group","named","row","field","String","otherDeals","filter","has","map","listed","values","sort","windowFull","length","selected","find","option","_event","next","onOpen","getOptionLabel","getOptionKey","isOptionEqualToValue","current","groupBy","loading","size","renderInput","params","helperText","undefined","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,YAAY,EAAEC,SAAS,QAAQ,gBAAe;AACvD,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACzC,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,mBAAmB,EAAEC,cAAc,QAAQ,wBAAoB;AAExE,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,yBAAqB;AAwBjF,MAAMC,mBAAmB;AAEzB,MAAMC,aAAa,CAACC,GAAuBC,IACzCD,EAAEE,IAAI,KAAKD,EAAEC,IAAI,IAAIF,EAAEG,EAAE,KAAKF,EAAEE,EAAE;AAEpC,MAAMC,UAAU,CAACJ,GAAkBC,IAAqBD,EAAEK,KAAK,CAACC,aAAa,CAACL,EAAEI,KAAK;AAErF;;;;;;;;;;CAUC,GACD,OAAO,SAASE,mBAAmBC,KAA8B;;QA2D5DC,iBACAC;IA3DH,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,EAAEC,SAAS,EAAEC,SAAS,EAAEC,KAAK,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAC7FX;IACF,MAAM,CAACY,QAAQC,UAAU,GAAG7B,SAAS;IACrC,MAAMiB,YAAYZ,mBAAmB,WAAWc,OAAOE,YAAYO;IACnE,MAAMV,QAAQb,mBAAmB,QAAQc,OAAOE,YAAYO;IAC5D,MAAME,aAAa7B,iBAAiBmB,OAAOC;IAC3C,MAAMU,eAAe5B,eAAeiB,OAAOC,YAAY;QACrDC,WAAWM,SAAUN,oBAAAA,YAAa,KAAM;IAC1C;IACA,MAAMU,YAAY9B,oBAChBkB,OACAC,YACAS,YACAF,SAASN,YAAY;IAEvB,MAAMW,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BACZ,KAACzE,wBACKyE;gBACJ1D,OAAM;gBACN2D,YACEjB,aAAa,CAAC,IAAI,EAAEnD,wBAAwB,wCAAwC,CAAC,GAAGqE;;;AAMpG;AACA1D,mBAAmB2D,WAAW,GAAG;AAEjC,eAAe3D,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-related-to-picker.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { Autocomplete, TextField } from '@mui/material'\nimport { useMemo, useState } from 'react'\nimport { useCrmFoldsScope } from '../hooks/use-crm-list-query'\nimport { useContactRoleDeals, useLinkedDeals } from '../hooks/use-deals'\nimport {\n type CrmActivityRelated,\n type CrmPickerRow,\n type CrmRelatedToOption,\n crmRelatedToOptions,\n} from '../model/crm-activity-link'\nimport { CRM_RECORD_PICKER_LIMIT, useCrmRecordWindow } from './crm-record-picker'\n\nexport interface CrmRelatedToPickerProps {\n /** The org root, or `null` until it is known. */\n scope: readonly [string, string] | null\n orgId: string | null\n /** The reader's tokens, or `null` at the organization level. */\n readTokens: readonly string[] | null\n /** The contact the entry is with, whose open deals lead the list. */\n contactId: string | null\n /** The company the entry is about, whose open deals lead the list. */\n companyId: string | null\n value: CrmActivityRelated | null\n /** The current value's name, shown while the lists do not hold the record. */\n valueLabel?: string\n onChange: (next: CrmActivityRelated | null) => void\n disabled?: boolean\n}\n\ntype RelatedOption = CrmRelatedToOption\n\nconst sameRecord = (a: CrmActivityRelated, b: CrmActivityRelated) =>\n a.kind === b.kind && a.id === b.id\n\n/**\n * An activity's **Related To** (AGL-4123), Salesforce's What: one company or\n * one deal.\n *\n * The open deals of the person and the company on the entry lead the list,\n * because logging a call with someone who has a deal in flight is the case\n * this field exists for: naming that deal puts the entry on it too. Below\n * them sit the windows every record picker offers, so an older record stays\n * one search away. Nothing listens until the menu is first opened, because\n * most entries are saved with the field as it opened.\n */\nexport function CrmRelatedToPicker(props: CrmRelatedToPickerProps) {\n const { scope, orgId, readTokens, contactId, companyId, value, valueLabel, onChange, disabled } =\n props\n const [opened, setOpened] = useState(false)\n const companies = useCrmRecordWindow('company', scope, readTokens, opened)\n const deals = useCrmRecordWindow('deal', scope, readTokens, opened)\n const foldsScope = useCrmFoldsScope(orgId, readTokens)\n const contactDeals = useLinkedDeals(orgId, readTokens, {\n contactId: opened ? (contactId ?? '') : '',\n })\n const roleDeals = useContactRoleDeals(\n orgId,\n readTokens,\n foldsScope,\n opened ? contactId : null,\n )\n const companyDeals = useLinkedDeals(orgId, readTokens, {\n companyId: opened ? (companyId ?? '') : '',\n })\n\n const options = useMemo<RelatedOption[]>(\n () =>\n crmRelatedToOptions({\n linkedDeals: [\n ...(contactDeals.data ?? []),\n ...(roleDeals.data ?? []),\n ...(companyDeals.data ?? []),\n ] as unknown as CrmPickerRow[],\n deals: deals.data ?? [],\n companies: companies.data ?? [],\n }),\n [contactDeals.data, roleDeals.data, companyDeals.data, deals.data, companies.data],\n )\n\n const windowFull =\n (companies.data?.length ?? 0) >= CRM_RECORD_PICKER_LIMIT ||\n (deals.data?.length ?? 0) >= CRM_RECORD_PICKER_LIMIT\n\n const selected = useMemo<RelatedOption | null>(() => {\n if (!value) return null\n return (\n options.find((option) => sameRecord(option, value)) ?? {\n ...value,\n label: valueLabel || (value.kind === 'deal' ? 'Deal' : 'Company'),\n group: '',\n }\n )\n }, [options, value, valueLabel])\n\n return (\n <Autocomplete\n options={options}\n value={selected}\n onChange={(_event, next) =>\n onChange(next ? { kind: next.kind, id: next.id } : null)\n }\n onOpen={() => setOpened(true)}\n getOptionLabel={(option) => option.label}\n getOptionKey={(option) => `${option.kind}:${option.id}`}\n isOptionEqualToValue={(option, current) => sameRecord(option, current)}\n groupBy={(option) => option.group}\n loading={opened && (companies.status === 'loading' || deals.status === 'loading')}\n disabled={disabled}\n size=\"small\"\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Related To\"\n helperText={\n windowFull ? `The ${CRM_RECORD_PICKER_LIMIT} most recently updated — type to narrow.` : undefined\n }\n />\n )}\n />\n )\n}\nCrmRelatedToPicker.displayName = 'CrmRelatedToPicker'\n\nexport default CrmRelatedToPicker\n"],"names":["Autocomplete","TextField","useMemo","useState","useCrmFoldsScope","useContactRoleDeals","useLinkedDeals","crmRelatedToOptions","CRM_RECORD_PICKER_LIMIT","useCrmRecordWindow","sameRecord","a","b","kind","id","CrmRelatedToPicker","props","companies","deals","scope","orgId","readTokens","contactId","companyId","value","valueLabel","onChange","disabled","opened","setOpened","foldsScope","contactDeals","roleDeals","companyDeals","options","linkedDeals","data","windowFull","length","selected","find","option","label","group","_event","next","onOpen","getOptionLabel","getOptionKey","isOptionEqualToValue","current","groupBy","loading","status","size","renderInput","params","helperText","undefined","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,YAAY,EAAEC,SAAS,QAAQ,gBAAe;AACvD,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACzC,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,mBAAmB,EAAEC,cAAc,QAAQ,wBAAoB;AACxE,SAIEC,mBAAmB,QACd,gCAA4B;AACnC,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,yBAAqB;AAqBjF,MAAMC,aAAa,CAACC,GAAuBC,IACzCD,EAAEE,IAAI,KAAKD,EAAEC,IAAI,IAAIF,EAAEG,EAAE,KAAKF,EAAEE,EAAE;AAEpC;;;;;;;;;;CAUC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;;QAmC5DC,iBACAC;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M,oBAAI,MAAM9B;IAE/B,MAAM+B,WAAWrC,QAA8B;YAG3CgC;QAFF,IAAI,CAACV,OAAO,OAAO;QACnB,QACEU,gBAAAA,QAAQM,IAAI,CAAC,CAACC,SAAW/B,WAAW+B,QAAQjB,mBAA5CU,gBAAuD,aAClDV;YACHkB,OAAOjB,cAAeD,CAAAA,MAAMX,IAAI,KAAK,SAAS,SAAS,SAAQ;YAC/D8B,OAAO;;IAGb,GAAG;QAACT;QAASV;QAAOC;KAAW;IAE/B,qBACE,KAACzB;QACCkC,SAASA;QACTV,OAAOe;QACPb,UAAU,CAACkB,QAAQC,OACjBnB,SAASmB,OAAO;gBAAEhC,MAAMgC,KAAKhC,IAAI;gBAAEC,IAAI+B,KAAK/B,EAAE;YAAC,IAAI;QAErDgC,QAAQ,IAAMjB,UAAU;QACxBkB,gBAAgB,CAACN,SAAWA,OAAOC,KAAK;QACxCM,cAAc,CAACP,SAAW,GAAGA,OAAO5B,IAAI,CAAC,CAAC,EAAE4B,OAAO3B,EAAE,EAAE;QACvDmC,sBAAsB,CAACR,QAAQS,UAAYxC,WAAW+B,QAAQS;QAC9DC,SAAS,CAACV,SAAWA,OAAOE,KAAK;QACjCS,SAASxB,UAAWX,CAAAA,UAAUoC,MAAM,KAAK,aAAanC,MAAMmC,MAAM,KAAK,SAAQ;QAC/E1B,UAAUA;QACV2B,MAAK;QACLC,aAAa,CAACC,uBACZ,KAACvD,wBACKuD;gBACJd,OAAM;gBACNe,YACEpB,aAAa,CAAC,IAAI,EAAE7B,wBAAwB,wCAAwC,CAAC,GAAGkD;;;AAMpG;AACA3C,mBAAmB4C,WAAW,GAAG;AAEjC,eAAe5C,mBAAkB"}
|
|
@@ -115,3 +115,36 @@ export declare function crmActivityPicksFrom(link: Pick<CrmActivityLink, 'contac
|
|
|
115
115
|
export declare function crmActivityLinkFromPicks(picks: CrmActivityPicks, leadId?: string | null): CrmActivityLink;
|
|
116
116
|
/** Whether two sets of picks name the same records. */
|
|
117
117
|
export declare function crmActivityPicksEqual(a: CrmActivityPicks, b: CrmActivityPicks): boolean;
|
|
118
|
+
/** A record as a picker reads it: its id, and whatever fields it was stored with. */
|
|
119
|
+
export type CrmPickerRow = Record<string, unknown> & {
|
|
120
|
+
$id: string;
|
|
121
|
+
};
|
|
122
|
+
/** One row of **Related To**: the record, the name it shows, and the heading it is listed under. */
|
|
123
|
+
export interface CrmRelatedToOption extends CrmActivityRelated {
|
|
124
|
+
label: string;
|
|
125
|
+
group: string;
|
|
126
|
+
}
|
|
127
|
+
/** Where **Related To** lists the rows it offers. */
|
|
128
|
+
export declare const CRM_RELATED_TO_GROUPS: {
|
|
129
|
+
readonly openDeals: "Open deals";
|
|
130
|
+
readonly companies: "Companies";
|
|
131
|
+
readonly deals: "Deals";
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* What **Related To** offers, in the order its menu lists it (AGL-4123).
|
|
135
|
+
*
|
|
136
|
+
* The open deals of the person and the company on the entry lead, because
|
|
137
|
+
* logging a call with someone who has a deal in flight is the case the field
|
|
138
|
+
* exists for: `linkedDeals` is every deal that names them (as Primary, in a
|
|
139
|
+
* contact role, or as the company's), and only the open ones are listed, each
|
|
140
|
+
* once. Then the companies the reader may see, then every other deal, each
|
|
141
|
+
* group by name.
|
|
142
|
+
*
|
|
143
|
+
* A deal or company with no name reads as its id, so a row is never blank,
|
|
144
|
+
* and an open deal with no title as "Untitled deal".
|
|
145
|
+
*/
|
|
146
|
+
export declare function crmRelatedToOptions(input: {
|
|
147
|
+
linkedDeals: readonly CrmPickerRow[];
|
|
148
|
+
deals: readonly CrmPickerRow[];
|
|
149
|
+
companies: readonly CrmPickerRow[];
|
|
150
|
+
}): CrmRelatedToOption[];
|
|
@@ -109,5 +109,59 @@ import { contactPrimaryGroup } from "./contact-holder.js";
|
|
|
109
109
|
var _a_related, _b_related, _a_related1, _b_related1;
|
|
110
110
|
return a.contactId === b.contactId && ((_a_related = a.related) == null ? void 0 : _a_related.kind) === ((_b_related = b.related) == null ? void 0 : _b_related.kind) && ((_a_related1 = a.related) == null ? void 0 : _a_related1.id) === ((_b_related1 = b.related) == null ? void 0 : _b_related1.id);
|
|
111
111
|
}
|
|
112
|
+
/** Where **Related To** lists the rows it offers. */ export const CRM_RELATED_TO_GROUPS = {
|
|
113
|
+
openDeals: 'Open deals',
|
|
114
|
+
companies: 'Companies',
|
|
115
|
+
deals: 'Deals'
|
|
116
|
+
};
|
|
117
|
+
const byOptionLabel = (a, b)=>a.label.localeCompare(b.label);
|
|
118
|
+
/**
|
|
119
|
+
* What **Related To** offers, in the order its menu lists it (AGL-4123).
|
|
120
|
+
*
|
|
121
|
+
* The open deals of the person and the company on the entry lead, because
|
|
122
|
+
* logging a call with someone who has a deal in flight is the case the field
|
|
123
|
+
* exists for: `linkedDeals` is every deal that names them (as Primary, in a
|
|
124
|
+
* contact role, or as the company's), and only the open ones are listed, each
|
|
125
|
+
* once. Then the companies the reader may see, then every other deal, each
|
|
126
|
+
* group by name.
|
|
127
|
+
*
|
|
128
|
+
* A deal or company with no name reads as its id, so a row is never blank,
|
|
129
|
+
* and an open deal with no title as "Untitled deal".
|
|
130
|
+
*/ export function crmRelatedToOptions(input) {
|
|
131
|
+
const open = new Map();
|
|
132
|
+
for (const deal of input.linkedDeals){
|
|
133
|
+
var _deal_title;
|
|
134
|
+
if (deal['status'] !== 'open') continue;
|
|
135
|
+
open.set(deal.$id, {
|
|
136
|
+
kind: 'deal',
|
|
137
|
+
id: deal.$id,
|
|
138
|
+
label: String((_deal_title = deal['title']) != null ? _deal_title : '') || 'Untitled deal',
|
|
139
|
+
group: CRM_RELATED_TO_GROUPS.openDeals
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const named = (row, field)=>{
|
|
143
|
+
var _row_field;
|
|
144
|
+
return String((_row_field = row[field]) != null ? _row_field : '') || row.$id;
|
|
145
|
+
};
|
|
146
|
+
const companies = input.companies.map((row)=>({
|
|
147
|
+
kind: 'company',
|
|
148
|
+
id: row.$id,
|
|
149
|
+
label: named(row, 'name'),
|
|
150
|
+
group: CRM_RELATED_TO_GROUPS.companies
|
|
151
|
+
}));
|
|
152
|
+
const deals = input.deals.filter((row)=>!open.has(row.$id)).map((row)=>({
|
|
153
|
+
kind: 'deal',
|
|
154
|
+
id: row.$id,
|
|
155
|
+
label: named(row, 'title'),
|
|
156
|
+
group: CRM_RELATED_TO_GROUPS.deals
|
|
157
|
+
}));
|
|
158
|
+
return [
|
|
159
|
+
...[
|
|
160
|
+
...open.values()
|
|
161
|
+
].sort(byOptionLabel),
|
|
162
|
+
...companies.sort(byOptionLabel),
|
|
163
|
+
...deals.sort(byOptionLabel)
|
|
164
|
+
];
|
|
165
|
+
}
|
|
112
166
|
|
|
113
167
|
//# sourceMappingURL=crm-activity-link.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-activity-link.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 { ORG_CONTACT_HOLDER_ID, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport type { CrmActivityLink } from '@aglyn/aglyn/app-utils/crm'\nimport { contactPrimaryGroup } from './contact-holder'\n\n/**\n * WHO, WHAT AND WHICH ACCOUNT AN ACTIVITY IS ABOUT (AGL-4123).\n *\n * Salesforce's activity model, on the three links an activity already had:\n * `contactId` is its Who (the **Name** field), `dealId` or `companyId` its\n * What (the **Related To** field), and `companyId` its Account, the rollup\n * that puts a call with a person, or about a deal, on the timeline of the\n * company behind them. Each timeline lists by its own field, so an entry\n * that carries all three shows on all three pages.\n *\n * Every writer of `crmActivities` stamps the Account here. A rollup a writer\n * spelled for itself is the one that would disagree: a company's timeline is\n * only as complete as the least careful door that writes to it.\n *\n * ## The order\n *\n * A company the writer named stands: it was said on purpose. Otherwise the\n * deal's, because the deal is the thing the entry is about; otherwise the\n * contact's.\n *\n * ## A contact's company is one holder's knowledge\n *\n * Which company a person is at lives in a holder's facet, and that is what is\n * read. `companyIds` is the facet's mirror for queries, and carries every\n * holder's link, so reading it here would file one business's call under a\n * company only a sibling brand knows the person by. A writer standing on a\n * site names that site's group; one standing at the organization names none\n * and reads the person's primary holder, the one their page shows. The facet\n * of a person the organization added itself (AGL-4122) is the one exception:\n * it is the whole org's, so it answers for any site that has no link of its\n * own.\n */\n\n/** What the Account is worked out from, as the writer already holds it. */\nexport interface CrmActivityCompanySources {\n /** The deal the activity names, when the writer has read it. */\n deal?: Record<string, unknown> | null\n /** The contact the activity names, when the writer has read it. */\n contact?: Record<string, unknown> | null\n /** The holder whose facet is read; absent, the contact's primary holder. */\n groupId?: string | null\n /** The org document, for the primary holder when {@link groupId} is absent. */\n org?: Record<string, unknown> | null\n}\n\n/** A link as a stamp hands it back: what went in, and the company it found. */\nexport type StampedCrmActivityLink<Link extends CrmActivityLink> = Link &\n Pick<CrmActivityLink, 'companyId'>\n\n/** A stored id, or `''` for anything that is not one. */\nconst idOf = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The company an activity rolls up to, or `null` when nothing names one. */\nexport function crmActivityCompanyId(\n link: Pick<CrmActivityLink, 'companyId'>,\n sources: CrmActivityCompanySources,\n): string | null {\n const named = idOf(link.companyId) || idOf(sources.deal?.['companyId'])\n if (named) return named\n const { contact, org } = sources\n if (!contact) return null\n const groupId = sources.groupId || contactPrimaryGroup(contact, org).groupId\n return (\n idOf(readContactFacet(contact, groupId).companyId) ||\n idOf(readContactFacet(contact, ORG_CONTACT_HOLDER_ID).companyId) ||\n null\n )\n}\n\n/**\n * `link` with its Account stamped. A link with no company to find comes back\n * as it went in, with no blank key: Firestore refuses `undefined`.\n */\nexport function stampCrmActivityCompany<Link extends CrmActivityLink>(\n link: Link,\n sources: CrmActivityCompanySources,\n): StampedCrmActivityLink<Link> {\n const companyId = crmActivityCompanyId(link, sources)\n return companyId && companyId !== link.companyId ? { ...link, companyId } : link\n}\n\n/** Each side's own way to read a record by id: the Admin SDK's, or the client's. */\nexport interface CrmActivityRecordReads {\n deal(id: string): Promise<Record<string, unknown> | null>\n contact(id: string): Promise<Record<string, unknown> | null>\n}\n\n/**\n * {@link stampCrmActivityCompany}, reading what the writer does not hold.\n *\n * The deal is read first and the contact only when the deal names no company,\n * so an activity costs the fewest reads that answer it, and none when a\n * company was named.\n *\n * **Never throws.** The rollup is bookkeeping beside the entry, and a record\n * this reader may not open, or a read that fails, must not cost the person\n * the call they are logging. The entry is written with the links it has, and\n * the company's timeline is the one thing it misses.\n */\nexport async function resolveCrmActivityCompany<Link extends CrmActivityLink>(\n link: Link,\n sources: CrmActivityCompanySources,\n reads: CrmActivityRecordReads,\n): Promise<StampedCrmActivityLink<Link>> {\n if (link.companyId) return link\n const attempt = async (read: () => Promise<Record<string, unknown> | null>) => {\n try {\n return await read()\n } catch (error) {\n console.warn('[crm] a record could not be read for the activity rollup', error)\n return null\n }\n }\n const dealId = idOf(link.dealId)\n const deal = sources.deal ?? (dealId ? await attempt(() => reads.deal(dealId)) : null)\n const contactId = idOf(link.contactId)\n const contact =\n sources.contact ??\n (contactId && !idOf(deal?.['companyId'])\n ? await attempt(() => reads.contact(contactId))\n : null)\n return stampCrmActivityCompany(link, { ...sources, deal, contact })\n}\n\n/** What **Related To** names: one company or one deal, Salesforce's What. */\nexport interface CrmActivityRelated {\n kind: 'company' | 'deal'\n id: string\n}\n\n/** The two fields of the log dialog, as a person leaves them. */\nexport interface CrmActivityPicks {\n /** **Name**: the contact it was with, Salesforce's Who. */\n contactId: string | null\n /** **Related To**. */\n related: CrmActivityRelated | null\n}\n\n/**\n * The fields as they open on `link`: a new activity's record, or an activity\n * being edited. A deal outranks the company stamped beside it, because the\n * deal is the What and the company only its rollup.\n *\n * Opened from a deal, **Name** defaults to the deal's Primary, so the entry\n * lands on that person's timeline too. A link that already names a contact\n * keeps them.\n */\nexport function crmActivityPicksFrom(\n link: Pick<CrmActivityLink, 'contactId' | 'companyId' | 'dealId'>,\n primaryContactId?: string | null,\n): CrmActivityPicks {\n const contactId = idOf(link.contactId) || idOf(primaryContactId)\n const dealId = idOf(link.dealId)\n const companyId = idOf(link.companyId)\n return {\n contactId: contactId || null,\n related: dealId\n ? { kind: 'deal', id: dealId }\n : companyId\n ? { kind: 'company', id: companyId }\n : null,\n }\n}\n\n/**\n * The links the fields name, before the Account is stamped. A lead's own log\n * keeps its lead: a person not yet converted is not a contact the field could\n * name.\n */\nexport function crmActivityLinkFromPicks(\n picks: CrmActivityPicks,\n leadId?: string | null,\n): CrmActivityLink {\n const { contactId, related } = picks\n return {\n ...(contactId ? { contactId } : {}),\n ...(related?.kind === 'deal' ? { dealId: related.id } : {}),\n ...(related?.kind === 'company' ? { companyId: related.id } : {}),\n ...(leadId ? { leadId } : {}),\n }\n}\n\n/** Whether two sets of picks name the same records. */\nexport function crmActivityPicksEqual(a: CrmActivityPicks, b: CrmActivityPicks): boolean {\n return (\n a.contactId === b.contactId &&\n a.related?.kind === b.related?.kind &&\n a.related?.id === b.related?.id\n )\n}\n"],"names":["ORG_CONTACT_HOLDER_ID","readContactFacet","contactPrimaryGroup","idOf","value","trim","crmActivityCompanyId","link","sources","named","companyId","deal","contact","org","groupId","stampCrmActivityCompany","resolveCrmActivityCompany","reads","attempt","read","error","console","warn","dealId","contactId","crmActivityPicksFrom","primaryContactId","related","kind","id","crmActivityLinkFromPicks","picks","leadId","crmActivityPicksEqual","a","b"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,kCAAiC;AAEzF,SAASC,mBAAmB,QAAQ,sBAA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,qBAATO,YAAWL,EAAE,QAAKM,cAAAA,EAAER,OAAO,qBAATQ,YAAWN,EAAE;AAEnC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-activity-link.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 { ORG_CONTACT_HOLDER_ID, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport type { CrmActivityLink } from '@aglyn/aglyn/app-utils/crm'\nimport { contactPrimaryGroup } from './contact-holder'\n\n/**\n * WHO, WHAT AND WHICH ACCOUNT AN ACTIVITY IS ABOUT (AGL-4123).\n *\n * Salesforce's activity model, on the three links an activity already had:\n * `contactId` is its Who (the **Name** field), `dealId` or `companyId` its\n * What (the **Related To** field), and `companyId` its Account, the rollup\n * that puts a call with a person, or about a deal, on the timeline of the\n * company behind them. Each timeline lists by its own field, so an entry\n * that carries all three shows on all three pages.\n *\n * Every writer of `crmActivities` stamps the Account here. A rollup a writer\n * spelled for itself is the one that would disagree: a company's timeline is\n * only as complete as the least careful door that writes to it.\n *\n * ## The order\n *\n * A company the writer named stands: it was said on purpose. Otherwise the\n * deal's, because the deal is the thing the entry is about; otherwise the\n * contact's.\n *\n * ## A contact's company is one holder's knowledge\n *\n * Which company a person is at lives in a holder's facet, and that is what is\n * read. `companyIds` is the facet's mirror for queries, and carries every\n * holder's link, so reading it here would file one business's call under a\n * company only a sibling brand knows the person by. A writer standing on a\n * site names that site's group; one standing at the organization names none\n * and reads the person's primary holder, the one their page shows. The facet\n * of a person the organization added itself (AGL-4122) is the one exception:\n * it is the whole org's, so it answers for any site that has no link of its\n * own.\n */\n\n/** What the Account is worked out from, as the writer already holds it. */\nexport interface CrmActivityCompanySources {\n /** The deal the activity names, when the writer has read it. */\n deal?: Record<string, unknown> | null\n /** The contact the activity names, when the writer has read it. */\n contact?: Record<string, unknown> | null\n /** The holder whose facet is read; absent, the contact's primary holder. */\n groupId?: string | null\n /** The org document, for the primary holder when {@link groupId} is absent. */\n org?: Record<string, unknown> | null\n}\n\n/** A link as a stamp hands it back: what went in, and the company it found. */\nexport type StampedCrmActivityLink<Link extends CrmActivityLink> = Link &\n Pick<CrmActivityLink, 'companyId'>\n\n/** A stored id, or `''` for anything that is not one. */\nconst idOf = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The company an activity rolls up to, or `null` when nothing names one. */\nexport function crmActivityCompanyId(\n link: Pick<CrmActivityLink, 'companyId'>,\n sources: CrmActivityCompanySources,\n): string | null {\n const named = idOf(link.companyId) || idOf(sources.deal?.['companyId'])\n if (named) return named\n const { contact, org } = sources\n if (!contact) return null\n const groupId = sources.groupId || contactPrimaryGroup(contact, org).groupId\n return (\n idOf(readContactFacet(contact, groupId).companyId) ||\n idOf(readContactFacet(contact, ORG_CONTACT_HOLDER_ID).companyId) ||\n null\n )\n}\n\n/**\n * `link` with its Account stamped. A link with no company to find comes back\n * as it went in, with no blank key: Firestore refuses `undefined`.\n */\nexport function stampCrmActivityCompany<Link extends CrmActivityLink>(\n link: Link,\n sources: CrmActivityCompanySources,\n): StampedCrmActivityLink<Link> {\n const companyId = crmActivityCompanyId(link, sources)\n return companyId && companyId !== link.companyId ? { ...link, companyId } : link\n}\n\n/** Each side's own way to read a record by id: the Admin SDK's, or the client's. */\nexport interface CrmActivityRecordReads {\n deal(id: string): Promise<Record<string, unknown> | null>\n contact(id: string): Promise<Record<string, unknown> | null>\n}\n\n/**\n * {@link stampCrmActivityCompany}, reading what the writer does not hold.\n *\n * The deal is read first and the contact only when the deal names no company,\n * so an activity costs the fewest reads that answer it, and none when a\n * company was named.\n *\n * **Never throws.** The rollup is bookkeeping beside the entry, and a record\n * this reader may not open, or a read that fails, must not cost the person\n * the call they are logging. The entry is written with the links it has, and\n * the company's timeline is the one thing it misses.\n */\nexport async function resolveCrmActivityCompany<Link extends CrmActivityLink>(\n link: Link,\n sources: CrmActivityCompanySources,\n reads: CrmActivityRecordReads,\n): Promise<StampedCrmActivityLink<Link>> {\n if (link.companyId) return link\n const attempt = async (read: () => Promise<Record<string, unknown> | null>) => {\n try {\n return await read()\n } catch (error) {\n console.warn('[crm] a record could not be read for the activity rollup', error)\n return null\n }\n }\n const dealId = idOf(link.dealId)\n const deal = sources.deal ?? (dealId ? await attempt(() => reads.deal(dealId)) : null)\n const contactId = idOf(link.contactId)\n const contact =\n sources.contact ??\n (contactId && !idOf(deal?.['companyId'])\n ? await attempt(() => reads.contact(contactId))\n : null)\n return stampCrmActivityCompany(link, { ...sources, deal, contact })\n}\n\n/** What **Related To** names: one company or one deal, Salesforce's What. */\nexport interface CrmActivityRelated {\n kind: 'company' | 'deal'\n id: string\n}\n\n/** The two fields of the log dialog, as a person leaves them. */\nexport interface CrmActivityPicks {\n /** **Name**: the contact it was with, Salesforce's Who. */\n contactId: string | null\n /** **Related To**. */\n related: CrmActivityRelated | null\n}\n\n/**\n * The fields as they open on `link`: a new activity's record, or an activity\n * being edited. A deal outranks the company stamped beside it, because the\n * deal is the What and the company only its rollup.\n *\n * Opened from a deal, **Name** defaults to the deal's Primary, so the entry\n * lands on that person's timeline too. A link that already names a contact\n * keeps them.\n */\nexport function crmActivityPicksFrom(\n link: Pick<CrmActivityLink, 'contactId' | 'companyId' | 'dealId'>,\n primaryContactId?: string | null,\n): CrmActivityPicks {\n const contactId = idOf(link.contactId) || idOf(primaryContactId)\n const dealId = idOf(link.dealId)\n const companyId = idOf(link.companyId)\n return {\n contactId: contactId || null,\n related: dealId\n ? { kind: 'deal', id: dealId }\n : companyId\n ? { kind: 'company', id: companyId }\n : null,\n }\n}\n\n/**\n * The links the fields name, before the Account is stamped. A lead's own log\n * keeps its lead: a person not yet converted is not a contact the field could\n * name.\n */\nexport function crmActivityLinkFromPicks(\n picks: CrmActivityPicks,\n leadId?: string | null,\n): CrmActivityLink {\n const { contactId, related } = picks\n return {\n ...(contactId ? { contactId } : {}),\n ...(related?.kind === 'deal' ? { dealId: related.id } : {}),\n ...(related?.kind === 'company' ? { companyId: related.id } : {}),\n ...(leadId ? { leadId } : {}),\n }\n}\n\n/** Whether two sets of picks name the same records. */\nexport function crmActivityPicksEqual(a: CrmActivityPicks, b: CrmActivityPicks): boolean {\n return (\n a.contactId === b.contactId &&\n a.related?.kind === b.related?.kind &&\n a.related?.id === b.related?.id\n )\n}\n\n/** A record as a picker reads it: its id, and whatever fields it was stored with. */\nexport type CrmPickerRow = Record<string, unknown> & { $id: string }\n\n/** One row of **Related To**: the record, the name it shows, and the heading it is listed under. */\nexport interface CrmRelatedToOption extends CrmActivityRelated {\n label: string\n group: string\n}\n\n/** Where **Related To** lists the rows it offers. */\nexport const CRM_RELATED_TO_GROUPS = {\n openDeals: 'Open deals',\n companies: 'Companies',\n deals: 'Deals',\n} as const\n\nconst byOptionLabel = (a: CrmRelatedToOption, b: CrmRelatedToOption) => a.label.localeCompare(b.label)\n\n/**\n * What **Related To** offers, in the order its menu lists it (AGL-4123).\n *\n * The open deals of the person and the company on the entry lead, because\n * logging a call with someone who has a deal in flight is the case the field\n * exists for: `linkedDeals` is every deal that names them (as Primary, in a\n * contact role, or as the company's), and only the open ones are listed, each\n * once. Then the companies the reader may see, then every other deal, each\n * group by name.\n *\n * A deal or company with no name reads as its id, so a row is never blank,\n * and an open deal with no title as \"Untitled deal\".\n */\nexport function crmRelatedToOptions(input: {\n linkedDeals: readonly CrmPickerRow[]\n deals: readonly CrmPickerRow[]\n companies: readonly CrmPickerRow[]\n}): CrmRelatedToOption[] {\n const open = new Map<string, CrmRelatedToOption>()\n for (const deal of input.linkedDeals) {\n if (deal['status'] !== 'open') continue\n open.set(deal.$id, {\n kind: 'deal',\n id: deal.$id,\n label: String(deal['title'] ?? '') || 'Untitled deal',\n group: CRM_RELATED_TO_GROUPS.openDeals,\n })\n }\n const named = (row: CrmPickerRow, field: string) => String(row[field] ?? '') || row.$id\n const companies = input.companies.map<CrmRelatedToOption>((row) => ({\n kind: 'company',\n id: row.$id,\n label: named(row, 'name'),\n group: CRM_RELATED_TO_GROUPS.companies,\n }))\n const deals = input.deals\n .filter((row) => !open.has(row.$id))\n .map<CrmRelatedToOption>((row) => ({\n kind: 'deal',\n id: row.$id,\n label: named(row, 'title'),\n group: CRM_RELATED_TO_GROUPS.deals,\n }))\n return [...[...open.values()].sort(byOptionLabel), ...companies.sort(byOptionLabel), ...deals.sort(byOptionLabel)]\n}\n"],"names":["ORG_CONTACT_HOLDER_ID","readContactFacet","contactPrimaryGroup","idOf","value","trim","crmActivityCompanyId","link","sources","named","companyId","deal","contact","org","groupId","stampCrmActivityCompany","resolveCrmActivityCompany","reads","attempt","read","error","console","warn","dealId","contactId","crmActivityPicksFrom","primaryContactId","related","kind","id","crmActivityLinkFromPicks","picks","leadId","crmActivityPicksEqual","a","b","CRM_RELATED_TO_GROUPS","openDeals","companies","deals","byOptionLabel","label","localeCompare","crmRelatedToOptions","input","open","Map","linkedDeals","set","$id","String","group","row","field","map","filter","has","values","sort"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,kCAAiC;AAEzF,SAASC,mBAAmB,QAAQ,sBAAkB;AAmDtD,uDAAuD,GACvD,MAAMC,OAAO,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAErF,2EAA2E,GAC3E,OAAO,SAASC,qBACdC,IAAwC,EACxCC,OAAkC;QAESA;IAA3C,MAAMC,QAAQN,KAAKI,KAAKG,SAAS,KAAKP,MAAKK,gBAAAA,QAAQG,IAAI,qBAAZH,aAAc,CAAC,YAAY;IACtE,IAAIC,OAAO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D,OAAO,SAASE,oBAAoBC,KAInC;IACC,MAAMC,OAAO,IAAIC;IACjB,KAAK,MAAMnC,QAAQiC,MAAMG,WAAW,CAAE;YAKpBpC;QAJhB,IAAIA,IAAI,CAAC,SAAS,KAAK,QAAQ;QAC/BkC,KAAKG,GAAG,CAACrC,KAAKsC,GAAG,EAAE;YACjBrB,MAAM;YACNC,IAAIlB,KAAKsC,GAAG;YACZR,OAAOS,QAAOvC,cAAAA,IAAI,CAAC,QAAQ,YAAbA,cAAiB,OAAO;YACtCwC,OAAOf,sBAAsBC,SAAS;QACxC;IACF;IACA,MAAM5B,QAAQ,CAAC2C,KAAmBC;YAAyBD;eAAPF,QAAOE,aAAAA,GAAG,CAACC,MAAM,YAAVD,aAAc,OAAOA,IAAIH,GAAG;;IACvF,MAAMX,YAAYM,MAAMN,SAAS,CAACgB,GAAG,CAAqB,CAACF,MAAS,CAAA;YAClExB,MAAM;YACNC,IAAIuB,IAAIH,GAAG;YACXR,OAAOhC,MAAM2C,KAAK;YAClBD,OAAOf,sBAAsBE,SAAS;QACxC,CAAA;IACA,MAAMC,QAAQK,MAAML,KAAK,CACtBgB,MAAM,CAAC,CAACH,MAAQ,CAACP,KAAKW,GAAG,CAACJ,IAAIH,GAAG,GACjCK,GAAG,CAAqB,CAACF,MAAS,CAAA;YACjCxB,MAAM;YACNC,IAAIuB,IAAIH,GAAG;YACXR,OAAOhC,MAAM2C,KAAK;YAClBD,OAAOf,sBAAsBG,KAAK;QACpC,CAAA;IACF,OAAO;WAAI;eAAIM,KAAKY,MAAM;SAAG,CAACC,IAAI,CAAClB;WAAmBF,UAAUoB,IAAI,CAAClB;WAAmBD,MAAMmB,IAAI,CAAClB;KAAe;AACpH"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type CrmDealContactRole, type CrmPicklist } from '@aglyn/aglyn';
|
|
17
|
+
import { type CrmDealContactRole, type CrmPicklist } from '@aglyn/aglyn/app-utils/crm';
|
|
18
18
|
/** Why a contact cannot be added to the deal, or `null` when it can. */
|
|
19
19
|
export declare function dealContactRoleAddProblem(roles: readonly CrmDealContactRole[], contactId: string, noun?: 'deal' | 'company'): string | null;
|
|
20
20
|
/** `roles` with one contact added — as the Primary, when asked, which every other row then is not. */
|
|
@@ -14,7 +14,7 @@ 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 { crmDealContactRoleListFields, DEAL_CONTACT_ROLES_MAX, dealContactRoleFields, dealContactRolesOf, judgeDealContactRoles, readDealContactRoles } from "@aglyn/aglyn";
|
|
17
|
+
*/ import { crmDealContactRoleListFields, DEAL_CONTACT_ROLES_MAX, dealContactRoleFields, dealContactRolesOf, judgeDealContactRoles, readDealContactRoles } from "@aglyn/aglyn/app-utils/crm";
|
|
18
18
|
/*
|
|
19
19
|
* THE DEAL PAGE'S CONTACT ROLES CARD (AGL-3521), as pure functions: what
|
|
20
20
|
* each edit makes of the list, and the fields one save writes.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deal-contact-roles.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 CrmDealContactRole,\n type CrmPicklist,\n crmDealContactRoleListFields,\n DEAL_CONTACT_ROLES_MAX,\n dealContactRoleFields,\n dealContactRolesOf,\n judgeDealContactRoles,\n readDealContactRoles,\n} from '@aglyn/aglyn'\n\n/*\n * THE DEAL PAGE'S CONTACT ROLES CARD (AGL-3521), as pure functions: what\n * each edit makes of the list, and the fields one save writes.\n */\n\n/** Why a contact cannot be added to the deal, or `null` when it can. */\nexport function dealContactRoleAddProblem(\n roles: readonly CrmDealContactRole[],\n contactId: string,\n noun: 'deal' | 'company' = 'deal',\n): string | null {\n if (!contactId) return 'Pick a contact.'\n if (roles.some((row) => row.contactId === contactId)) {\n return `That contact is already on this ${noun}.`\n }\n if (roles.length >= DEAL_CONTACT_ROLES_MAX) {\n return `A ${noun} names at most ${DEAL_CONTACT_ROLES_MAX} contacts.`\n }\n return null\n}\n\n/** `roles` with one contact added — as the Primary, when asked, which every other row then is not. */\nexport function dealContactRolesAdded(\n roles: readonly CrmDealContactRole[],\n added: { contactId: string; role?: string; primary: boolean },\n): CrmDealContactRole[] {\n const row: CrmDealContactRole = {\n contactId: added.contactId,\n ...(added.role ? { role: added.role } : {}),\n primary: added.primary,\n }\n return [...roles.map((entry) => (added.primary ? { ...entry, primary: false } : entry)), row]\n}\n\n/** `roles` with one contact's role set — `''` for none. */\nexport function dealContactRolesWithRole(\n roles: readonly CrmDealContactRole[],\n contactId: string,\n role: string,\n): CrmDealContactRole[] {\n return roles.map((row) => {\n if (row.contactId !== contactId) return row\n return { contactId: row.contactId, ...(role ? { role } : {}), primary: row.primary }\n })\n}\n\n/**\n * What a save of the card writes: the roles judged against the org's list\n * (a contact's current role kept), `contactId` as their Primary — `null`\n * for a field the caller deletes — and whether the Primary changed, which\n * is when the name the drawer copied beside `contactId` goes stale.\n */\nexport function dealContactRolesSave(\n deal: { contactId?: unknown; contactRoles?: unknown },\n next: readonly CrmDealContactRole[],\n picklist: CrmPicklist,\n):\n | {\n ok: true\n contactRoles: CrmDealContactRole[]\n contactId: string | null\n primaryChanged: boolean\n }\n | { ok: false; error: string } {\n const judged = judgeDealContactRoles(picklist, next, dealContactRolesOf(deal))\n if (judged.ok === false) return judged\n const fields = dealContactRoleFields(judged.roles)\n const before = typeof deal.contactId === 'string' && deal.contactId ? deal.contactId : null\n return { ok: true, ...fields, primaryChanged: fields.contactId !== before }\n}\n\n/**\n * The roles a company holds, as stored. A deal's reader takes the Primary from\n * the deal's `contactId`; a company has none, so its Primary is on the row.\n */\nexport function companyContactRolesOf(company: { contactRoles?: unknown }): CrmDealContactRole[] {\n return readDealContactRoles(company.contactRoles)\n}\n\n/**\n * What a save of a company's card writes: the roles judged against the org's\n * list, the ids a merge or an erasure finds the company by, and the keys a\n * rename of a role does. A company has no `contactId` beside them, so nothing\n * else moves with the Primary.\n */\nexport function companyContactRolesSave(\n company: { contactRoles?: unknown },\n next: readonly CrmDealContactRole[],\n picklist: CrmPicklist,\n):\n | {\n ok: true\n contactRoles: CrmDealContactRole[]\n contactRoleContactIds: string[]\n contactRoleKeys: string[]\n }\n | { ok: false; error: string } {\n const judged = judgeDealContactRoles(picklist, next, companyContactRolesOf(company))\n if (judged.ok === false) return judged\n const { contactRoleContactIds, contactRoleKeys } = crmDealContactRoleListFields({\n contactRoles: judged.roles,\n })\n return { ok: true, contactRoles: judged.roles, contactRoleContactIds, contactRoleKeys }\n}\n"],"names":["crmDealContactRoleListFields","DEAL_CONTACT_ROLES_MAX","dealContactRoleFields","dealContactRolesOf","judgeDealContactRoles","readDealContactRoles","dealContactRoleAddProblem","roles","contactId","noun","some","row","length","dealContactRolesAdded","added","role","primary","map","entry","dealContactRolesWithRole","dealContactRolesSave","deal","next","picklist","judged","ok","fields","before","primaryChanged","companyContactRolesOf","company","contactRoles","companyContactRolesSave","contactRoleContactIds","contactRoleKeys"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAGEA,4BAA4B,EAC5BC,sBAAsB,EACtBC,qBAAqB,EACrBC,kBAAkB,EAClBC,qBAAqB,EACrBC,oBAAoB,QACf,
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/deal-contact-roles.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 CrmDealContactRole,\n type CrmPicklist,\n crmDealContactRoleListFields,\n DEAL_CONTACT_ROLES_MAX,\n dealContactRoleFields,\n dealContactRolesOf,\n judgeDealContactRoles,\n readDealContactRoles,\n} from '@aglyn/aglyn/app-utils/crm'\n\n/*\n * THE DEAL PAGE'S CONTACT ROLES CARD (AGL-3521), as pure functions: what\n * each edit makes of the list, and the fields one save writes.\n */\n\n/** Why a contact cannot be added to the deal, or `null` when it can. */\nexport function dealContactRoleAddProblem(\n roles: readonly CrmDealContactRole[],\n contactId: string,\n noun: 'deal' | 'company' = 'deal',\n): string | null {\n if (!contactId) return 'Pick a contact.'\n if (roles.some((row) => row.contactId === contactId)) {\n return `That contact is already on this ${noun}.`\n }\n if (roles.length >= DEAL_CONTACT_ROLES_MAX) {\n return `A ${noun} names at most ${DEAL_CONTACT_ROLES_MAX} contacts.`\n }\n return null\n}\n\n/** `roles` with one contact added — as the Primary, when asked, which every other row then is not. */\nexport function dealContactRolesAdded(\n roles: readonly CrmDealContactRole[],\n added: { contactId: string; role?: string; primary: boolean },\n): CrmDealContactRole[] {\n const row: CrmDealContactRole = {\n contactId: added.contactId,\n ...(added.role ? { role: added.role } : {}),\n primary: added.primary,\n }\n return [...roles.map((entry) => (added.primary ? { ...entry, primary: false } : entry)), row]\n}\n\n/** `roles` with one contact's role set — `''` for none. */\nexport function dealContactRolesWithRole(\n roles: readonly CrmDealContactRole[],\n contactId: string,\n role: string,\n): CrmDealContactRole[] {\n return roles.map((row) => {\n if (row.contactId !== contactId) return row\n return { contactId: row.contactId, ...(role ? { role } : {}), primary: row.primary }\n })\n}\n\n/**\n * What a save of the card writes: the roles judged against the org's list\n * (a contact's current role kept), `contactId` as their Primary — `null`\n * for a field the caller deletes — and whether the Primary changed, which\n * is when the name the drawer copied beside `contactId` goes stale.\n */\nexport function dealContactRolesSave(\n deal: { contactId?: unknown; contactRoles?: unknown },\n next: readonly CrmDealContactRole[],\n picklist: CrmPicklist,\n):\n | {\n ok: true\n contactRoles: CrmDealContactRole[]\n contactId: string | null\n primaryChanged: boolean\n }\n | { ok: false; error: string } {\n const judged = judgeDealContactRoles(picklist, next, dealContactRolesOf(deal))\n if (judged.ok === false) return judged\n const fields = dealContactRoleFields(judged.roles)\n const before = typeof deal.contactId === 'string' && deal.contactId ? deal.contactId : null\n return { ok: true, ...fields, primaryChanged: fields.contactId !== before }\n}\n\n/**\n * The roles a company holds, as stored. A deal's reader takes the Primary from\n * the deal's `contactId`; a company has none, so its Primary is on the row.\n */\nexport function companyContactRolesOf(company: { contactRoles?: unknown }): CrmDealContactRole[] {\n return readDealContactRoles(company.contactRoles)\n}\n\n/**\n * What a save of a company's card writes: the roles judged against the org's\n * list, the ids a merge or an erasure finds the company by, and the keys a\n * rename of a role does. A company has no `contactId` beside them, so nothing\n * else moves with the Primary.\n */\nexport function companyContactRolesSave(\n company: { contactRoles?: unknown },\n next: readonly CrmDealContactRole[],\n picklist: CrmPicklist,\n):\n | {\n ok: true\n contactRoles: CrmDealContactRole[]\n contactRoleContactIds: string[]\n contactRoleKeys: string[]\n }\n | { ok: false; error: string } {\n const judged = judgeDealContactRoles(picklist, next, companyContactRolesOf(company))\n if (judged.ok === false) return judged\n const { contactRoleContactIds, contactRoleKeys } = crmDealContactRoleListFields({\n contactRoles: judged.roles,\n })\n return { ok: true, contactRoles: judged.roles, contactRoleContactIds, contactRoleKeys }\n}\n"],"names":["crmDealContactRoleListFields","DEAL_CONTACT_ROLES_MAX","dealContactRoleFields","dealContactRolesOf","judgeDealContactRoles","readDealContactRoles","dealContactRoleAddProblem","roles","contactId","noun","some","row","length","dealContactRolesAdded","added","role","primary","map","entry","dealContactRolesWithRole","dealContactRolesSave","deal","next","picklist","judged","ok","fields","before","primaryChanged","companyContactRolesOf","company","contactRoles","companyContactRolesSave","contactRoleContactIds","contactRoleKeys"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAGEA,4BAA4B,EAC5BC,sBAAsB,EACtBC,qBAAqB,EACrBC,kBAAkB,EAClBC,qBAAqB,EACrBC,oBAAoB,QACf,6BAA4B;AAEnC;;;CAGC,GAED,sEAAsE,GACtE,OAAO,SAASC,0BACdC,KAAoC,EACpCC,SAAiB,EACjBC,OAA2B,MAAM;IAEjC,IAAI,CAACD,WAAW,OAAO;IACvB,IAAID,MAAMG,IAAI,CAAC,CAACC,MAAQA,IAAIH,SAAS,KAAKA,YAAY;QACpD,OAAO,CAAC,gCAAgC,EAAEC,KAAK,CAAC,CAAC;IACnD;IACA,IAAIF,MAAMK,MAAM,IAAIX,wBAAwB;QAC1C,OAAO,CAAC,EAAE,EAAEQ,KAAK,eAAe,EAAER,uBAAuB,UAAU,CAAC;IACtE;IACA,OAAO;AACT;AAEA,oGAAoG,GACpG,OAAO,SAASY,sBACdN,KAAoC,EACpCO,KAA6D;IAE7D,MAAMH,MAA0B;QAC9BH,WAAWM,MAAMN,SAAS;OACtBM,MAAMC,IAAI,GAAG;QAAEA,MAAMD,MAAMC,IAAI;IAAC,IAAI,CAAC;QACzCC,SAASF,MAAME,OAAO;;IAExB,OAAO;WAAIT,MAAMU,GAAG,CAAC,CAACC,QAAWJ,MAAME,OAAO,GAAG,aAAKE;gBAAOF,SAAS;iBAAUE;QAASP;KAAI;AAC/F;AAEA,yDAAyD,GACzD,OAAO,SAASQ,yBACdZ,KAAoC,EACpCC,SAAiB,EACjBO,IAAY;IAEZ,OAAOR,MAAMU,GAAG,CAAC,CAACN;QAChB,IAAIA,IAAIH,SAAS,KAAKA,WAAW,OAAOG;QACxC,OAAO;YAAEH,WAAWG,IAAIH,SAAS;WAAMO,OAAO;YAAEA;QAAK,IAAI,CAAC;YAAIC,SAASL,IAAIK,OAAO;;IACpF;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASI,qBACdC,IAAqD,EACrDC,IAAmC,EACnCC,QAAqB;IASrB,MAAMC,SAASpB,sBAAsBmB,UAAUD,MAAMnB,mBAAmBkB;IACxE,IAAIG,OAAOC,EAAE,KAAK,OAAO,OAAOD;IAChC,MAAME,SAASxB,sBAAsBsB,OAAOjB,KAAK;IACjD,MAAMoB,SAAS,OAAON,KAAKb,SAAS,KAAK,YAAYa,KAAKb,SAAS,GAAGa,KAAKb,SAAS,GAAG;IACvF,OAAO;QAAEiB,IAAI;OAASC;QAAQE,gBAAgBF,OAAOlB,SAAS,KAAKmB;;AACrE;AAEA;;;CAGC,GACD,OAAO,SAASE,sBAAsBC,OAAmC;IACvE,OAAOzB,qBAAqByB,QAAQC,YAAY;AAClD;AAEA;;;;;CAKC,GACD,OAAO,SAASC,wBACdF,OAAmC,EACnCR,IAAmC,EACnCC,QAAqB;IASrB,MAAMC,SAASpB,sBAAsBmB,UAAUD,MAAMO,sBAAsBC;IAC3E,IAAIN,OAAOC,EAAE,KAAK,OAAO,OAAOD;IAChC,MAAM,EAAES,qBAAqB,EAAEC,eAAe,EAAE,GAAGlC,6BAA6B;QAC9E+B,cAAcP,OAAOjB,KAAK;IAC5B;IACA,OAAO;QAAEkB,IAAI;QAAMM,cAAcP,OAAOjB,KAAK;QAAE0B;QAAuBC;IAAgB;AACxF"}
|
|
@@ -384,15 +384,18 @@ const refused = (contactId, error)=>({
|
|
|
384
384
|
if (namesSent && composed) update[path('name')] = composed;
|
|
385
385
|
else if (fields.name !== undefined && !composed) update[path('name')] = text(fields.name);
|
|
386
386
|
if (fields.salutation !== undefined) update[path('salutation')] = text(fields.salutation);
|
|
387
|
-
if (fields.phone !== undefined)
|
|
388
|
-
update[path('phone')] = text(fields.phone);
|
|
389
|
-
// The search echo — see `HostContact.phone`.
|
|
390
|
-
update['phone'] = text(fields.phone);
|
|
391
|
-
}
|
|
387
|
+
if (fields.phone !== undefined) update[path('phone')] = text(fields.phone);
|
|
392
388
|
for (const key of CONTACT_EXTRA_PHONE_FIELDS){
|
|
393
389
|
var _fields_key;
|
|
394
390
|
if (fields[key] !== undefined) update[path(key)] = text((_fields_key = fields[key]) != null ? _fields_key : '');
|
|
395
391
|
}
|
|
392
|
+
if (fields.phone !== undefined || fields.mobilePhone !== undefined) {
|
|
393
|
+
var _ref, _fields_phone, _ref1, _fields_mobilePhone;
|
|
394
|
+
// The search echo — see `HostContact.phone`: the Phone, or the mobile of
|
|
395
|
+
// a person who gave no other number, as New contact stores it. The card
|
|
396
|
+
// sends an empty Phone on every save, and the mobile must outlive it.
|
|
397
|
+
update['phone'] = text(((_ref = (_fields_phone = fields.phone) != null ? _fields_phone : stored.phone) != null ? _ref : '') || ((_ref1 = (_fields_mobilePhone = fields.mobilePhone) != null ? _fields_mobilePhone : stored.mobilePhone) != null ? _ref1 : ''));
|
|
398
|
+
}
|
|
396
399
|
if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle);
|
|
397
400
|
if (fields.department !== undefined) update[path('department')] = text(fields.department);
|
|
398
401
|
if (fields.birthdate !== undefined) update[path('birthdate')] = text(fields.birthdate);
|
|
@@ -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 composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_PHONE_FIELD_LABELS,\n consentGroupForHost,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ContactCompanyLinkPlan,\n type ContactCustomValue,\n type ContactFieldDefinition,\n ORG_CONTACT_HOLDER_ID,\n containerMembershipValue,\n contactContainerFieldPath,\n contactFacetPath,\n CRM_COLLECTIONS,\n CRM_LEAD_SOURCE_PICKLIST,\n CRM_MEDIA_IDS_FIELD,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n effectiveCrmLeadSourcePicklist,\n isOrgWideMember,\n judgeCrmLeadSource,\n judgeCrmPicklistValue,\n normalizeAddress,\n normalizeContactBirthdate,\n normalizeContactEmail,\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 restampCrmListFieldsOf,\n} from '@aglyn/tenant-data-admin'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { scheduleCapturedEmailCheck } from '@aglyn/tenant-data-admin/server/capture-email-check'\nimport {\n emailIndexBeside,\n findContactByEmail,\n writeContactEmailIndex,\n} from '@aglyn/tenant-data-admin/server/contact-email-index'\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'\nimport { contactPrimaryGroup } from '../model/contact-holder'\nimport {\n cachedContactReader,\n CONTACT_REPORTS_TO_LOOP_REFUSAL,\n CONTACT_REPORTS_TO_SELF_REFUSAL,\n contactReportsToLoops,\n} from './contact-reports-to'\nimport { readCrmPicklist } from './read-picklist'\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 salutation: \"Editing a contact's profile\",\n firstName: \"Editing a contact's profile\",\n lastName: \"Editing a contact's profile\",\n email: \"Editing a contact's profile\",\n phone: \"Editing a contact's profile\",\n mobilePhone: \"Editing a contact's profile\",\n homePhone: \"Editing a contact's profile\",\n otherPhone: \"Editing a contact's profile\",\n fax: \"Editing a contact's profile\",\n jobTitle: \"Editing a contact's profile\",\n department: \"Editing a contact's profile\",\n birthdate: \"Editing a contact's profile\",\n assistantName: \"Editing a contact's profile\",\n assistantPhone: \"Editing a contact's profile\",\n reportsToContactId: \"Editing a contact's profile\",\n leadSource: \"Editing a contact's profile\",\n address: \"Editing a contact's profile\",\n otherAddress: \"Editing a contact's profile\",\n doNotCall: \"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/** The sentence a `name` that contradicts the holder's first and last names is refused with. */\nexport const CONTACT_COMPOSED_NAME_REFUSAL =\n \"This person's name is made of their first and last name — change those instead.\"\n\n/** The sentence an address another contact already has is refused with. */\nexport const CONTACT_EMAIL_TAKEN_REFUSAL =\n 'Another contact already has that email. Open them and merge the two.'\n\n/** The sentence a change to a shared address is refused with below the whole workspace. */\nexport const CONTACT_EMAIL_CHANGE_REFUSAL =\n 'Every site shares this email, so changing it needs access to the whole workspace.'\n\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 ('email' in raw) {\n const email = normalizeContactEmail(raw['email'])\n if (!email) return { ok: false, error: 'Enter a valid email address.' }\n fields.email = email\n }\n if ('name' in raw) fields.name = typed(raw['name'], 120)\n for (const key of ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const) {\n if (!(key in raw)) continue\n const text = typed(raw[key], 40)\n const phone = text ? normalizePhone(text) : ''\n if (phone === null) {\n return {\n ok: false,\n error:\n key === 'phone'\n ? CONTACT_PHONE_REFUSAL\n : `${CONTACT_PHONE_FIELD_LABELS[key]}: ${CONTACT_PHONE_REFUSAL}`,\n }\n }\n fields[key] = phone\n }\n if ('jobTitle' in raw) fields.jobTitle = typed(raw['jobTitle'], 120)\n // Held to the label's shape here and judged against the org's list by the\n // handler, like the lead source (AGL-3515).\n if ('salutation' in raw) fields.salutation = normalizeCrmPicklistLabel(raw['salutation'])\n if ('firstName' in raw) fields.firstName = composeContactName(raw['firstName'], '')\n if ('lastName' in raw) fields.lastName = composeContactName('', raw['lastName'])\n if ('department' in raw) fields.department = typed(raw['department'], 120)\n if ('assistantName' in raw) fields.assistantName = typed(raw['assistantName'], 120)\n if ('birthdate' in raw) {\n const birthdate = normalizeContactBirthdate(raw['birthdate'])\n if (birthdate === null) return { ok: false, error: CONTACT_BIRTHDATE_REFUSAL }\n fields.birthdate = birthdate\n }\n if ('reportsToContactId' in raw) {\n const reportsTo =\n raw['reportsToContactId'] === null ? '' : typed(raw['reportsToContactId'], 200)\n if (reportsTo.includes('/')) {\n return { ok: false, error: 'The contact this person reports to could not be read.' }\n }\n fields.reportsToContactId = reportsTo || null\n }\n if ('doNotCall' in raw) {\n if (typeof raw['doNotCall'] !== 'boolean') {\n return { ok: false, error: 'Do not call must be true or false.' }\n }\n fields.doNotCall = raw['doNotCall']\n }\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 for (const key of ['address', 'otherAddress'] as const) {\n if (!(key in raw)) continue\n const address = raw[key]\n fields[key] =\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 = containerMembershipValue(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/**\n * Salesforce's standard contact fields (AGL-3515) a create may carry beside\n * the identity — every one `upsertHostContact` writes into the capturing\n * facet. The reports-to is not one: it names another record, which only\n * this route checks the holder can see.\n */\nexport const CONTACT_CREATE_PROFILE_FIELDS = [\n 'salutation',\n 'firstName',\n 'lastName',\n 'department',\n 'mobilePhone',\n 'homePhone',\n 'otherPhone',\n 'fax',\n 'birthdate',\n 'assistantName',\n 'assistantPhone',\n 'otherAddress',\n 'doNotCall',\n] as const satisfies ReadonlyArray<keyof ContactUpdateFields>\n\n/**\n * Those fields of a create's body, read by the same rules an update reads\n * them with — or the sentence refusing one. A body naming none of them\n * reads as no fields.\n */\nexport function readContactCreateProfile(\n body: Record<string, unknown>,\n): { ok: true; fields: ContactUpdateFields } | { ok: false; error: string } {\n const given = Object.fromEntries(\n CONTACT_CREATE_PROFILE_FIELDS.filter((key) => body[key] !== undefined).map((key) => [\n key,\n body[key],\n ]),\n )\n if (!Object.keys(given).length) return { ok: true, fields: {} }\n return readContactUpdateFields(given)\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\n/** One contact's planned write, and the company counts it moves. */\nexport interface 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 */\nexport function 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 const stored = readContactFacet(contact, groupId)\n\n /*\n * THE NAME FOLLOWS THE FIRST AND LAST NAMES (AGL-3515). While the holder\n * keeps either, the facet's `name` is their composition, written whenever\n * either moves; a `name` sent beside them must agree, because a save that\n * stored one and showed the other would read as a save that kept both.\n * Both cleared leaves the name as it stands, unless one was sent.\n */\n const namesSent = fields.firstName !== undefined || fields.lastName !== undefined\n const composed = composeContactName(\n fields.firstName ?? stored.firstName,\n fields.lastName ?? stored.lastName,\n )\n if (composed && fields.name !== undefined && fields.name !== composed) {\n return { refused: CONTACT_COMPOSED_NAME_REFUSAL }\n }\n if (fields.firstName !== undefined) update[path('firstName')] = text(fields.firstName)\n if (fields.lastName !== undefined) update[path('lastName')] = text(fields.lastName)\n if (namesSent && composed) update[path('name')] = composed\n else if (fields.name !== undefined && !composed) update[path('name')] = text(fields.name)\n\n if (fields.salutation !== undefined) update[path('salutation')] = text(fields.salutation)\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 for (const key of CONTACT_EXTRA_PHONE_FIELDS) {\n if (fields[key] !== undefined) update[path(key)] = text(fields[key] ?? '')\n }\n if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle)\n if (fields.department !== undefined) update[path('department')] = text(fields.department)\n if (fields.birthdate !== undefined) update[path('birthdate')] = text(fields.birthdate)\n if (fields.assistantName !== undefined) {\n update[path('assistantName')] = text(fields.assistantName)\n }\n if (fields.reportsToContactId !== undefined) {\n update[path('reportsToContactId')] = text(fields.reportsToContactId ?? '')\n }\n if (fields.doNotCall !== undefined) {\n // Stored only as `true` — see `ContactFacet.doNotCall`.\n update[path('doNotCall')] = fields.doNotCall ? true : FieldValue.delete()\n }\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.otherAddress !== undefined) {\n update[path('otherAddress')] = fields.otherAddress ?? 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 = (stored.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[contactContainerFieldPath(groupId, 'campaign')] = 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 let committed = false\n try {\n await batch.commit()\n committed = true\n } catch {\n // A batch names no document; the pass below finds the one it was.\n }\n if (!committed) {\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 }\n // The owner, tags, company and custom values are what the Contacts list\n // filters by through `facetKeys` (AGL-3321): restamped from each row.\n await restampCrmListFieldsOf(\n writes.filter((write) => !failed.has(write.contactId)).map((write) => write.ref),\n 'contacts',\n )\n return failed\n}\n\n/** Each company's contacts count moved once, by the sum of what the written links moved. */\nexport async 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 if (fields.email && contactIds.length !== 1) {\n res.status(400).json({ error: 'An email address belongs to one contact at a time.' })\n return\n }\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 // The org's salutations (AGL-3515), judged per contact like the lead source.\n const salutations = fields.salutation\n ? await readCrmPicklist(firestore, writer.orgId, CRM_SALUTATION_PICKLIST)\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 readContact = cachedContactReader(contacts)\n\n // The manager a reports-to names has to be a contact the caller and the\n // site can see, for the company link's reason (AGL-3515).\n if (fields.reportsToContactId) {\n const manager = await contacts.doc(fields.reportsToContactId).get()\n const tokens = manager.exists ? (manager.get('visibleTo') as string[] | undefined) : undefined\n const visible =\n manager.exists &&\n canReach(writer, tokens) &&\n (!siteTokens || visibleToTokens(tokens, siteTokens))\n if (!visible) {\n res.status(404).json({ error: 'Unknown contact to report to' })\n return\n }\n }\n\n const snapshots = await firestore.getAll(...contactIds.map((id) => contacts.doc(id)))\n const outcomes = new Map<string, ContactUpdateOutcome>()\n const writes: ContactWrite[] = []\n /** What the one contact answered to before an address change. */\n let previousEmail: string | null = null\n /** Whether the row passed and its address really moves. */\n let emailMoved = false\n const rows: Array<{\n contactId: string\n snapshot: FirebaseFirestore.DocumentSnapshot\n data: Record<string, unknown>\n groupId: string\n }> = []\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 // A person no site holds has a profile too, kept for the org (AGL-4122).\n const groupId =\n (siteGroup ?? contactPrimaryGroup(data, writer.org)).groupId || ORG_CONTACT_HOLDER_ID\n rows.push({ contactId, snapshot, data, groupId })\n })\n\n for (const { contactId, snapshot, data, groupId } of rows) {\n if (fields.reportsToContactId) {\n if (fields.reportsToContactId === contactId) {\n outcomes.set(contactId, refused(contactId, CONTACT_REPORTS_TO_SELF_REFUSAL))\n continue\n }\n if (await contactReportsToLoops(readContact, contactId, fields.reportsToContactId, groupId)) {\n outcomes.set(contactId, refused(contactId, CONTACT_REPORTS_TO_LOOP_REFUSAL))\n continue\n }\n }\n let rowFields = fields\n if (salutations && fields.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n salutations,\n fields.salutation,\n readContactFacet(data, groupId).salutation,\n )\n if (judged.ok === false) {\n outcomes.set(contactId, refused(contactId, judged.error))\n continue\n }\n rowFields = { ...rowFields, salutation: judged.value ?? '' }\n }\n if (leadSources && fields.leadSource) {\n const judged = judgeCrmLeadSource(\n leadSources,\n fields.leadSource,\n readContactFacet(data, groupId).leadSource,\n )\n if (judged.ok === false) {\n outcomes.set(contactId, refused(contactId, judged.error))\n continue\n }\n rowFields = { ...rowFields, leadSource: judged.value ?? '' }\n }\n const patch = contactPatch(data, groupId, rowFields, custom, linkedCompanyName)\n if ('refused' in patch) {\n outcomes.set(contactId, refused(contactId, patch.refused))\n continue\n }\n /*\n * THE ADDRESS, the one identity every site shares (AGL-4122). Filling in\n * a blank is anybody's who can edit this person. Replacing one changes\n * who the record is for every site, so it needs the whole workspace.\n * Another contact on the address is the owner's to merge, never a write\n * here, which would leave two records answering to one person.\n */\n if (fields.email) {\n previousEmail = normalizeContactEmail(data['email'])\n const replacing = previousEmail && previousEmail !== fields.email\n if (replacing && scope.level === 'site' && !isOrgWideMember(writer.member)) {\n outcomes.set(contactId, refused(contactId, CONTACT_EMAIL_CHANGE_REFUSAL))\n continue\n }\n const holder = await findContactByEmail(contacts, fields.email)\n if (holder && holder.id !== contactId) {\n outcomes.set(contactId, refused(contactId, CONTACT_EMAIL_TAKEN_REFUSAL))\n continue\n }\n }\n outcomes.set(contactId, { contactId, ok: true })\n emailMoved = Boolean(fields.email) && fields.email !== previousEmail\n const update =\n emailMoved\n ? {\n ...patch.update,\n email: fields.email,\n // The verdict was on the old address, and the next check judges this one.\n emailStatus: FieldValue.delete(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n : patch.update\n if (update) {\n writes.push({ contactId, ref: snapshot.ref, update, counts: patch.counts })\n }\n }\n\n const failed = await commitContactWrites(firestore, writes)\n if (fields.email && emailMoved && !failed.has(contactIds[0])) {\n const index = emailIndexBeside(contacts)\n await writeContactEmailIndex(index, contactIds[0], [fields.email])\n // The old address stops resolving here: this person no longer answers to it.\n const previousKey = previousEmail ? personKey(previousEmail) : null\n if (index && previousKey) {\n await index\n .doc(previousKey)\n .delete()\n .catch((error: unknown) => {\n console.error('[crm] contact-update could not retire an address', error)\n })\n }\n scheduleCapturedEmailCheck({ orgId: writer.orgId, email: fields.email })\n }\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":["composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_PHONE_FIELD_LABELS","consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","ORG_CONTACT_HOLDER_ID","containerMembershipValue","contactContainerFieldPath","contactFacetPath","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","CRM_MEDIA_IDS_FIELD","CRM_SALUTATION_PICKLIST","crmReadTokens","effectiveCrmLeadSourcePicklist","isOrgWideMember","judgeCrmLeadSource","judgeCrmPicklistValue","normalizeAddress","normalizeContactBirthdate","normalizeContactEmail","normalizeCrmMediaIds","normalizeCrmPicklistLabel","normalizePhone","planContactCompanyLink","readContactCompanyLink","readContactFacet","readCrmCustomInput","visibleToTokens","companyContactsCountFields","contactCompanyLinkFields","firebaseAdmin","resolveOrgMembership","restampCrmListFieldsOf","personKey","scheduleCapturedEmailCheck","emailIndexBeside","findContactByEmail","writeContactEmailIndex","FieldValue","CONTACT_UPDATE_FIELDS","CRM_CONTACT_UPDATE_MAX","CONTACT_NOTES_MAX","CONTACT_PHONE_REFUSAL","CONTACT_TAGS_MAX","normalizeTags","readBulkTag","typed","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","canReach","contactPrimaryGroup","cachedContactReader","CONTACT_REPORTS_TO_LOOP_REFUSAL","CONTACT_REPORTS_TO_SELF_REFUSAL","contactReportsToLoops","readCrmPicklist","SUITE_ACTS","name","salutation","firstName","lastName","email","phone","mobilePhone","homePhone","otherPhone","fax","jobTitle","department","birthdate","assistantName","assistantPhone","reportsToContactId","leadSource","address","otherAddress","doNotCall","notes","tags","addTag","removeTag","campaignIds","ownerUid","companyId","companyName","custom","mediaIds","CONTACT_COMPOSED_NAME_REFUSAL","CONTACT_EMAIL_TAKEN_REFUSAL","CONTACT_EMAIL_CHANGE_REFUSAL","contactUpdateSuiteAct","fields","field","find","key","undefined","readContactUpdateFields","input","raw","Array","isArray","ok","error","unknownKey","Object","keys","includes","text","reportsTo","String","slice","filter","length","tag","ids","map","id","CONTACT_CREATE_PROFILE_FIELDS","readContactCreateProfile","body","given","fromEntries","readContactIds","value","some","Set","reachesSite","writer","hostId","staff","member","Boolean","hostAccess","refused","contactId","contactPatch","contact","groupId","linkedCompanyName","stored","path","delete","update","counts","namesSent","composed","held","toLowerCase","arrayUnion","arrayRemove","plan","assign","label","entries","serverTimestamp","commitContactWrites","firestore","writes","failed","batch","write","ref","committed","commit","console","add","has","settleCompanyCounts","companies","deltas","Map","count","set","get","delta","Promise","all","doc","catch","crmContactUpdateHandler","req","res","method","setHeader","status","json","scope","contactIds","read","suiteAct","level","suite","org","app","orgRef","collection","orgId","siteGroup","siteTokens","definitions","contactFields","limit","judged","docs","data","values","errors","leadSources","picklists","salutations","owner","company","tokens","exists","visible","contacts","readContact","manager","snapshots","getAll","outcomes","previousEmail","emailMoved","rows","forEach","snapshot","index","visibleTo","push","rowFields","patch","replacing","holder","emailStatus","updatedAt","previousKey","answer","results"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsDC,GAED,SAEEA,kBAAkB,EAClBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,EAI1BC,qBAAqB,EACrBC,wBAAwB,EACxBC,yBAAyB,EACzBC,gBAAgB,EAChBC,eAAe,EACfC,wBAAwB,EACxBC,mBAAmB,EACnBC,uBAAuB,EACvBC,aAAa,EACbC,8BAA8B,EAC9BC,eAAe,EACfC,kBAAkB,EAClBC,qBAAqB,EACrBC,gBAAgB,EAChBC,yBAAyB,EACzBC,qBAAqB,EACrBC,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,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,0BAA0B,QAAQ,sDAAqD;AAChG,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,sBAAsB,QACjB,sDAAqD;AAC5D,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,qBAAqB,EAIrBC,sBAAsB,QACjB,6BAAyB;AAChC,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,gBA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E,aAAawB,OAAQ;YAC9B8D,SAAShD,GAAG,CAACtC,WAAWD,QAAQC,WAAW;QAC7C;QACA,MAAMiC,oBACJ2B,OAAOC,UAAU,CAAC5L,gBAAgBiK,SAAS,GAC3CX,OAAO9C,MAAM,CAAC,CAACiD,QAAU,CAACF,OAAOQ,GAAG,CAACN,MAAM1B,SAAS;QAGtD,MAAMsG,SAAgC;YACpCvI,IAAI;YACJwI,SAASlD,WAAWxE,GAAG,CACrB,CAACmB;oBAAcsF;wBAAAA,gBAAAA,SAAS/C,GAAG,CAACvC,sBAAbsF,gBAA2BvF,QAAQC,WAAW;;QAEjE;QACA+C,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACmD;IACvB,EAAE,OAAOtI,OAAO;QACd8D,QAAQ9D,KAAK,CAAC,+BAA+BA;QAC7C+E,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEnF,OAAO;QAAkC;IAClE;AACF,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 composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_PHONE_FIELD_LABELS,\n consentGroupForHost,\n CONTACT_FIELDS_MAX_PER_ORG,\n type ContactCompanyLinkPlan,\n type ContactCustomValue,\n type ContactFieldDefinition,\n ORG_CONTACT_HOLDER_ID,\n containerMembershipValue,\n contactContainerFieldPath,\n contactFacetPath,\n CRM_COLLECTIONS,\n CRM_LEAD_SOURCE_PICKLIST,\n CRM_MEDIA_IDS_FIELD,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n effectiveCrmLeadSourcePicklist,\n isOrgWideMember,\n judgeCrmLeadSource,\n judgeCrmPicklistValue,\n normalizeAddress,\n normalizeContactBirthdate,\n normalizeContactEmail,\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 restampCrmListFieldsOf,\n} from '@aglyn/tenant-data-admin'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { scheduleCapturedEmailCheck } from '@aglyn/tenant-data-admin/server/capture-email-check'\nimport {\n emailIndexBeside,\n findContactByEmail,\n writeContactEmailIndex,\n} from '@aglyn/tenant-data-admin/server/contact-email-index'\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'\nimport { contactPrimaryGroup } from '../model/contact-holder'\nimport {\n cachedContactReader,\n CONTACT_REPORTS_TO_LOOP_REFUSAL,\n CONTACT_REPORTS_TO_SELF_REFUSAL,\n contactReportsToLoops,\n} from './contact-reports-to'\nimport { readCrmPicklist } from './read-picklist'\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 salutation: \"Editing a contact's profile\",\n firstName: \"Editing a contact's profile\",\n lastName: \"Editing a contact's profile\",\n email: \"Editing a contact's profile\",\n phone: \"Editing a contact's profile\",\n mobilePhone: \"Editing a contact's profile\",\n homePhone: \"Editing a contact's profile\",\n otherPhone: \"Editing a contact's profile\",\n fax: \"Editing a contact's profile\",\n jobTitle: \"Editing a contact's profile\",\n department: \"Editing a contact's profile\",\n birthdate: \"Editing a contact's profile\",\n assistantName: \"Editing a contact's profile\",\n assistantPhone: \"Editing a contact's profile\",\n reportsToContactId: \"Editing a contact's profile\",\n leadSource: \"Editing a contact's profile\",\n address: \"Editing a contact's profile\",\n otherAddress: \"Editing a contact's profile\",\n doNotCall: \"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/** The sentence a `name` that contradicts the holder's first and last names is refused with. */\nexport const CONTACT_COMPOSED_NAME_REFUSAL =\n \"This person's name is made of their first and last name — change those instead.\"\n\n/** The sentence an address another contact already has is refused with. */\nexport const CONTACT_EMAIL_TAKEN_REFUSAL =\n 'Another contact already has that email. Open them and merge the two.'\n\n/** The sentence a change to a shared address is refused with below the whole workspace. */\nexport const CONTACT_EMAIL_CHANGE_REFUSAL =\n 'Every site shares this email, so changing it needs access to the whole workspace.'\n\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 ('email' in raw) {\n const email = normalizeContactEmail(raw['email'])\n if (!email) return { ok: false, error: 'Enter a valid email address.' }\n fields.email = email\n }\n if ('name' in raw) fields.name = typed(raw['name'], 120)\n for (const key of ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const) {\n if (!(key in raw)) continue\n const text = typed(raw[key], 40)\n const phone = text ? normalizePhone(text) : ''\n if (phone === null) {\n return {\n ok: false,\n error:\n key === 'phone'\n ? CONTACT_PHONE_REFUSAL\n : `${CONTACT_PHONE_FIELD_LABELS[key]}: ${CONTACT_PHONE_REFUSAL}`,\n }\n }\n fields[key] = phone\n }\n if ('jobTitle' in raw) fields.jobTitle = typed(raw['jobTitle'], 120)\n // Held to the label's shape here and judged against the org's list by the\n // handler, like the lead source (AGL-3515).\n if ('salutation' in raw) fields.salutation = normalizeCrmPicklistLabel(raw['salutation'])\n if ('firstName' in raw) fields.firstName = composeContactName(raw['firstName'], '')\n if ('lastName' in raw) fields.lastName = composeContactName('', raw['lastName'])\n if ('department' in raw) fields.department = typed(raw['department'], 120)\n if ('assistantName' in raw) fields.assistantName = typed(raw['assistantName'], 120)\n if ('birthdate' in raw) {\n const birthdate = normalizeContactBirthdate(raw['birthdate'])\n if (birthdate === null) return { ok: false, error: CONTACT_BIRTHDATE_REFUSAL }\n fields.birthdate = birthdate\n }\n if ('reportsToContactId' in raw) {\n const reportsTo =\n raw['reportsToContactId'] === null ? '' : typed(raw['reportsToContactId'], 200)\n if (reportsTo.includes('/')) {\n return { ok: false, error: 'The contact this person reports to could not be read.' }\n }\n fields.reportsToContactId = reportsTo || null\n }\n if ('doNotCall' in raw) {\n if (typeof raw['doNotCall'] !== 'boolean') {\n return { ok: false, error: 'Do not call must be true or false.' }\n }\n fields.doNotCall = raw['doNotCall']\n }\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 for (const key of ['address', 'otherAddress'] as const) {\n if (!(key in raw)) continue\n const address = raw[key]\n fields[key] =\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 = containerMembershipValue(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/**\n * Salesforce's standard contact fields (AGL-3515) a create may carry beside\n * the identity — every one `upsertHostContact` writes into the capturing\n * facet. The reports-to is not one: it names another record, which only\n * this route checks the holder can see.\n */\nexport const CONTACT_CREATE_PROFILE_FIELDS = [\n 'salutation',\n 'firstName',\n 'lastName',\n 'department',\n 'mobilePhone',\n 'homePhone',\n 'otherPhone',\n 'fax',\n 'birthdate',\n 'assistantName',\n 'assistantPhone',\n 'otherAddress',\n 'doNotCall',\n] as const satisfies ReadonlyArray<keyof ContactUpdateFields>\n\n/**\n * Those fields of a create's body, read by the same rules an update reads\n * them with — or the sentence refusing one. A body naming none of them\n * reads as no fields.\n */\nexport function readContactCreateProfile(\n body: Record<string, unknown>,\n): { ok: true; fields: ContactUpdateFields } | { ok: false; error: string } {\n const given = Object.fromEntries(\n CONTACT_CREATE_PROFILE_FIELDS.filter((key) => body[key] !== undefined).map((key) => [\n key,\n body[key],\n ]),\n )\n if (!Object.keys(given).length) return { ok: true, fields: {} }\n return readContactUpdateFields(given)\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\n/** One contact's planned write, and the company counts it moves. */\nexport interface 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 */\nexport function 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 const stored = readContactFacet(contact, groupId)\n\n /*\n * THE NAME FOLLOWS THE FIRST AND LAST NAMES (AGL-3515). While the holder\n * keeps either, the facet's `name` is their composition, written whenever\n * either moves; a `name` sent beside them must agree, because a save that\n * stored one and showed the other would read as a save that kept both.\n * Both cleared leaves the name as it stands, unless one was sent.\n */\n const namesSent = fields.firstName !== undefined || fields.lastName !== undefined\n const composed = composeContactName(\n fields.firstName ?? stored.firstName,\n fields.lastName ?? stored.lastName,\n )\n if (composed && fields.name !== undefined && fields.name !== composed) {\n return { refused: CONTACT_COMPOSED_NAME_REFUSAL }\n }\n if (fields.firstName !== undefined) update[path('firstName')] = text(fields.firstName)\n if (fields.lastName !== undefined) update[path('lastName')] = text(fields.lastName)\n if (namesSent && composed) update[path('name')] = composed\n else if (fields.name !== undefined && !composed) update[path('name')] = text(fields.name)\n\n if (fields.salutation !== undefined) update[path('salutation')] = text(fields.salutation)\n if (fields.phone !== undefined) update[path('phone')] = text(fields.phone)\n for (const key of CONTACT_EXTRA_PHONE_FIELDS) {\n if (fields[key] !== undefined) update[path(key)] = text(fields[key] ?? '')\n }\n if (fields.phone !== undefined || fields.mobilePhone !== undefined) {\n // The search echo — see `HostContact.phone`: the Phone, or the mobile of\n // a person who gave no other number, as New contact stores it. The card\n // sends an empty Phone on every save, and the mobile must outlive it.\n update['phone'] = text(\n (fields.phone ?? stored.phone ?? '') || (fields.mobilePhone ?? stored.mobilePhone ?? ''),\n )\n }\n if (fields.jobTitle !== undefined) update[path('jobTitle')] = text(fields.jobTitle)\n if (fields.department !== undefined) update[path('department')] = text(fields.department)\n if (fields.birthdate !== undefined) update[path('birthdate')] = text(fields.birthdate)\n if (fields.assistantName !== undefined) {\n update[path('assistantName')] = text(fields.assistantName)\n }\n if (fields.reportsToContactId !== undefined) {\n update[path('reportsToContactId')] = text(fields.reportsToContactId ?? '')\n }\n if (fields.doNotCall !== undefined) {\n // Stored only as `true` — see `ContactFacet.doNotCall`.\n update[path('doNotCall')] = fields.doNotCall ? true : FieldValue.delete()\n }\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.otherAddress !== undefined) {\n update[path('otherAddress')] = fields.otherAddress ?? 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 = (stored.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[contactContainerFieldPath(groupId, 'campaign')] = 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 let committed = false\n try {\n await batch.commit()\n committed = true\n } catch {\n // A batch names no document; the pass below finds the one it was.\n }\n if (!committed) {\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 }\n // The owner, tags, company and custom values are what the Contacts list\n // filters by through `facetKeys` (AGL-3321): restamped from each row.\n await restampCrmListFieldsOf(\n writes.filter((write) => !failed.has(write.contactId)).map((write) => write.ref),\n 'contacts',\n )\n return failed\n}\n\n/** Each company's contacts count moved once, by the sum of what the written links moved. */\nexport async 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 if (fields.email && contactIds.length !== 1) {\n res.status(400).json({ error: 'An email address belongs to one contact at a time.' })\n return\n }\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 // The org's salutations (AGL-3515), judged per contact like the lead source.\n const salutations = fields.salutation\n ? await readCrmPicklist(firestore, writer.orgId, CRM_SALUTATION_PICKLIST)\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 readContact = cachedContactReader(contacts)\n\n // The manager a reports-to names has to be a contact the caller and the\n // site can see, for the company link's reason (AGL-3515).\n if (fields.reportsToContactId) {\n const manager = await contacts.doc(fields.reportsToContactId).get()\n const tokens = manager.exists ? (manager.get('visibleTo') as string[] | undefined) : undefined\n const visible =\n manager.exists &&\n canReach(writer, tokens) &&\n (!siteTokens || visibleToTokens(tokens, siteTokens))\n if (!visible) {\n res.status(404).json({ error: 'Unknown contact to report to' })\n return\n }\n }\n\n const snapshots = await firestore.getAll(...contactIds.map((id) => contacts.doc(id)))\n const outcomes = new Map<string, ContactUpdateOutcome>()\n const writes: ContactWrite[] = []\n /** What the one contact answered to before an address change. */\n let previousEmail: string | null = null\n /** Whether the row passed and its address really moves. */\n let emailMoved = false\n const rows: Array<{\n contactId: string\n snapshot: FirebaseFirestore.DocumentSnapshot\n data: Record<string, unknown>\n groupId: string\n }> = []\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 // A person no site holds has a profile too, kept for the org (AGL-4122).\n const groupId =\n (siteGroup ?? contactPrimaryGroup(data, writer.org)).groupId || ORG_CONTACT_HOLDER_ID\n rows.push({ contactId, snapshot, data, groupId })\n })\n\n for (const { contactId, snapshot, data, groupId } of rows) {\n if (fields.reportsToContactId) {\n if (fields.reportsToContactId === contactId) {\n outcomes.set(contactId, refused(contactId, CONTACT_REPORTS_TO_SELF_REFUSAL))\n continue\n }\n if (await contactReportsToLoops(readContact, contactId, fields.reportsToContactId, groupId)) {\n outcomes.set(contactId, refused(contactId, CONTACT_REPORTS_TO_LOOP_REFUSAL))\n continue\n }\n }\n let rowFields = fields\n if (salutations && fields.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n salutations,\n fields.salutation,\n readContactFacet(data, groupId).salutation,\n )\n if (judged.ok === false) {\n outcomes.set(contactId, refused(contactId, judged.error))\n continue\n }\n rowFields = { ...rowFields, salutation: judged.value ?? '' }\n }\n if (leadSources && fields.leadSource) {\n const judged = judgeCrmLeadSource(\n leadSources,\n fields.leadSource,\n readContactFacet(data, groupId).leadSource,\n )\n if (judged.ok === false) {\n outcomes.set(contactId, refused(contactId, judged.error))\n continue\n }\n rowFields = { ...rowFields, leadSource: judged.value ?? '' }\n }\n const patch = contactPatch(data, groupId, rowFields, custom, linkedCompanyName)\n if ('refused' in patch) {\n outcomes.set(contactId, refused(contactId, patch.refused))\n continue\n }\n /*\n * THE ADDRESS, the one identity every site shares (AGL-4122). Filling in\n * a blank is anybody's who can edit this person. Replacing one changes\n * who the record is for every site, so it needs the whole workspace.\n * Another contact on the address is the owner's to merge, never a write\n * here, which would leave two records answering to one person.\n */\n if (fields.email) {\n previousEmail = normalizeContactEmail(data['email'])\n const replacing = previousEmail && previousEmail !== fields.email\n if (replacing && scope.level === 'site' && !isOrgWideMember(writer.member)) {\n outcomes.set(contactId, refused(contactId, CONTACT_EMAIL_CHANGE_REFUSAL))\n continue\n }\n const holder = await findContactByEmail(contacts, fields.email)\n if (holder && holder.id !== contactId) {\n outcomes.set(contactId, refused(contactId, CONTACT_EMAIL_TAKEN_REFUSAL))\n continue\n }\n }\n outcomes.set(contactId, { contactId, ok: true })\n emailMoved = Boolean(fields.email) && fields.email !== previousEmail\n const update =\n emailMoved\n ? {\n ...patch.update,\n email: fields.email,\n // The verdict was on the old address, and the next check judges this one.\n emailStatus: FieldValue.delete(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n : patch.update\n if (update) {\n writes.push({ contactId, ref: snapshot.ref, update, counts: patch.counts })\n }\n }\n\n const failed = await commitContactWrites(firestore, writes)\n if (fields.email && emailMoved && !failed.has(contactIds[0])) {\n const index = emailIndexBeside(contacts)\n await writeContactEmailIndex(index, contactIds[0], [fields.email])\n // The old address stops resolving here: this person no longer answers to it.\n const previousKey = previousEmail ? personKey(previousEmail) : null\n if (index && previousKey) {\n await index\n .doc(previousKey)\n .delete()\n .catch((error: unknown) => {\n console.error('[crm] contact-update could not retire an address', error)\n })\n }\n scheduleCapturedEmailCheck({ orgId: writer.orgId, email: fields.email })\n }\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":["composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_PHONE_FIELD_LABELS","consentGroupForHost","CONTACT_FIELDS_MAX_PER_ORG","ORG_CONTACT_HOLDER_ID","containerMembershipValue","contactContainerFieldPath","contactFacetPath","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","CRM_MEDIA_IDS_FIELD","CRM_SALUTATION_PICKLIST","crmReadTokens","effectiveCrmLeadSourcePicklist","isOrgWideMember","judgeCrmLeadSource","judgeCrmPicklistValue","normalizeAddress","normalizeContactBirthdate","normalizeContactEmail","normalizeCrmMediaIds","normalizeCrmPicklistLabel","normalizePhone","planContactCompanyLink","readContactCompanyLink","readContactFacet","readCrmCustomInput","visibleToTokens","companyContactsCountFields","contactCompanyLinkFields","firebaseAdmin","resolveOrgMembership","restampCrmListFieldsOf","personKey","scheduleCapturedEmailCheck","emailIndexBeside","findContactByEmail","writeContactEmailIndex","FieldValue","CONTACT_UPDATE_FIELDS","CRM_CONTACT_UPDATE_MAX","CONTACT_NOTES_MAX","CONTACT_PHONE_REFUSAL","CONTACT_TAGS_MAX","normalizeTags","readBulkTag","typed","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","canReach","contactPrimaryGroup","cachedContactReader","CONTACT_REPORTS_TO_LOOP_REFUSAL","CONTACT_REPORTS_TO_SELF_REFUSAL","contactReportsToLoops","readCrmPicklist","SUITE_ACTS","name","salutation","firstName","lastName","email","phone","mobilePhone","homePhone","otherPhone","fax","jobTitle","department","birthdate","assistantName","assistantPhone","reportsToContactId","leadSource","address","otherAddress","doNotCall","notes","tags","addTag","removeTag","campaignIds","ownerUid","companyId","companyName","custom","mediaIds","CONTACT_COMPOSED_NAME_REFUSAL","CONTACT_EMAIL_TAKEN_REFUSAL","CONTACT_EMAIL_CHANGE_REFUSAL","contactUpdateSuiteAct","fields","field","find","key","undefined","readContactUpdateFields","input","raw","Array","isArray","ok","error","unknownKey","Object","keys","includes","text","reportsTo","String","slice","filter","length","tag","ids","map","id","CONTACT_CREATE_PROFILE_FIELDS","readContactCreateProfile","body","given","fromEntries","readContactIds","value","some","Set","reachesSite","writer","hostId","staff","member","Boolean","hostAccess","refused","contactId","contactPatch","contact","groupId","linkedCompanyName","stored","path","delete","update","counts","namesSent","composed","held","toLowerCase","arrayUnion","arrayRemove","plan","assign","label","entries","serverTimestamp","commitContactWrites","firestore","writes","failed","batch","write","ref","committed","commit","console","add","has","settleCompanyCounts","companies","deltas","Map","count","set","get","delta","Promise","all","doc","catch","crmContactUpdateHandler","req","res","method","setHeader","status","json","scope","contactIds","read","suiteAct","level","suite","org","app","orgRef","collection","orgId","siteGroup","siteTokens","definitions","contactFields","limit","judged","docs","data","values","errors","leadSources","picklists","salutations","owner","company","tokens","exists","visible","contacts","readContact","manager","snapshots","getAll","outcomes","previousEmail","emailMoved","rows","forEach","snapshot","index","visibleTo","push","rowFields","patch","replacing","holder","emailStatus","updatedAt","previousKey","answer","results"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsDC,GAED,SAEEA,kBAAkB,EAClBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,EAI1BC,qBAAqB,EACrBC,wBAAwB,EACxBC,yBAAyB,EACzBC,gBAAgB,EAChBC,eAAe,EACfC,wBAAwB,EACxBC,mBAAmB,EACnBC,uBAAuB,EACvBC,aAAa,EACbC,8BAA8B,EAC9BC,eAAe,EACfC,kBAAkB,EAClBC,qBAAqB,EACrBC,gBAAgB,EAChBC,yBAAyB,EACzBC,qBAAqB,EACrBC,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,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,0BAA0B,QAAQ,sDAAqD;AAChG,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,sBAAsB,QACjB,sDAAqD;AAC5D,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,EAAE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