@aglyn/plugins-crm 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-crm",
3
- "version": "1.12.0",
3
+ "version": "1.14.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.12.0",
29
- "@aglyn/shared-data-enums": "1.12.0",
30
- "@aglyn/shared-data-mdi": "1.12.0",
31
- "@aglyn/shared-ui-jsx": "1.12.0",
32
- "@aglyn/shared-ui-next": "1.12.0",
33
- "@aglyn/shared-ui-snackstack": "1.12.0",
34
- "@aglyn/shared-util-email": "1.12.0",
35
- "@aglyn/shared-util-http": "1.12.0",
36
- "@aglyn/shared-util-timestamp": "1.12.0",
37
- "@aglyn/shared-util-tools": "1.12.0",
38
- "@aglyn/tenant-data-admin": "1.12.0",
39
- "@aglyn/tenant-feature-instance": "1.12.0",
40
- "@aglyn/tenant-runtime": "1.12.0",
28
+ "@aglyn/aglyn": "1.14.0",
29
+ "@aglyn/shared-data-enums": "1.14.0",
30
+ "@aglyn/shared-data-mdi": "1.14.0",
31
+ "@aglyn/shared-ui-jsx": "1.14.0",
32
+ "@aglyn/shared-ui-next": "1.14.0",
33
+ "@aglyn/shared-ui-snackstack": "1.14.0",
34
+ "@aglyn/shared-util-email": "1.14.0",
35
+ "@aglyn/shared-util-http": "1.14.0",
36
+ "@aglyn/shared-util-timestamp": "1.14.0",
37
+ "@aglyn/shared-util-tools": "1.14.0",
38
+ "@aglyn/tenant-data-admin": "1.14.0",
39
+ "@aglyn/tenant-feature-instance": "1.14.0",
40
+ "@aglyn/tenant-runtime": "1.14.0",
41
41
  "@dnd-kit/core": "^6.3.1",
42
42
  "@dnd-kit/utilities": "^3.2.2",
43
43
  "@swc/helpers": "0.5.23",
@@ -16,7 +16,8 @@
16
16
  */ 'use client';
17
17
  import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
19
- import { CONTACT_SOURCE_LABELS, newAssignmentRuleId, readCrmAssignmentRule, crmMemberPickerLabel } from "@aglyn/aglyn";
19
+ import { newAssignmentRuleId, readCrmAssignmentRule, crmMemberPickerLabel } from "@aglyn/aglyn";
20
+ import { listContactSourceOptions } from "@aglyn/aglyn/plugin-manager/plugin-contact-capture";
20
21
  import { Button, Drawer, FormControl, FormControlLabel, FormHelperText, FormLabel, MenuItem, Radio, RadioGroup, Stack, TextField, Typography } from "@mui/material";
21
22
  import { useCallback, useEffect, useState } from "react";
22
23
  /** The `value` of the source picker's "any door" entry. */ const ANY_SOURCE = '';
@@ -162,10 +163,10 @@ import { useCallback, useEffect, useState } from "react";
162
163
  value: ANY_SOURCE,
163
164
  children: 'Any source'
164
165
  }),
165
- Object.keys(CONTACT_SOURCE_LABELS).map((option)=>/*#__PURE__*/ _jsx(MenuItem, {
166
- value: option,
167
- children: CONTACT_SOURCE_LABELS[option]
168
- }, option))
166
+ listContactSourceOptions().map((option)=>/*#__PURE__*/ _jsx(MenuItem, {
167
+ value: option.value,
168
+ children: option.label
169
+ }, option.value))
169
170
  ]
170
171
  }),
171
172
  /*#__PURE__*/ _jsx(TextField, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/assignment-rule-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n type CrmAssignmentRule,\n newAssignmentRuleId,\n readCrmAssignmentRule,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport {\n Button,\n Drawer,\n FormControl,\n FormControlLabel,\n FormHelperText,\n FormLabel,\n MenuItem,\n Radio,\n RadioGroup,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { OrgMemberOption } from '../hooks/use-org-member-directory'\n\n/** The `value` of the source picker's \"any door\" entry. */\nconst ANY_SOURCE = ''\n\nexport interface AssignmentRuleDrawerProps {\n open: boolean\n onClose: () => void\n /** The roster the member target is picked from. */\n members: readonly OrgMemberOption[]\n membersLoading: boolean\n /** How many people the round-robin pool holds, for the target's helper text. */\n poolSize: number\n /** The ids the org already holds, so the new one is minted apart from them. */\n existingIds: readonly string[]\n /** Receives the rule; closing on success is the caller's job. */\n onSubmit: (rule: CrmAssignmentRule) => Promise<void> | void\n}\n\n/**\n * The one form an assignment rule is written through (AGL-2618).\n *\n * ## Every condition is optional, and none is a form above the list\n *\n * A rule names the captures it claims — a source, a form, an email domain,\n * a tag — and a field left blank is not a condition, so a rule with every\n * field blank is the catch-all, which is a rule a team writes on purpose\n * (\"everything else goes to Sam\"). The drawer says so rather than refusing\n * it. The email domain is typed the way a person sees one in an address,\n * `@acme.com` or `acme.com`, and the reader strips the `@`; what it cannot\n * read as a domain is refused here, with the field, rather than stored as\n * a condition nothing will ever match.\n *\n * ## The target is a member, or the rotation\n *\n * A member is picked from the roster by name, never typed as an address —\n * an address is resolved at run time and a rule must not depend on a\n * resolution that can change. The rotation is offered whatever the pool\n * holds, with the pool's size beside it: an empty pool is a rule the pass\n * steps over until somebody fills the pool, which the card below explains,\n * and refusing the rule here would make the two cards order-dependent.\n */\nexport function AssignmentRuleDrawer(props: AssignmentRuleDrawerProps) {\n const { open, onClose, members, membersLoading, poolSize, existingIds, onSubmit } =\n props\n const [source, setSource] = useState<string>(ANY_SOURCE)\n const [formId, setFormId] = useState('')\n const [emailDomain, setEmailDomain] = useState('')\n const [tag, setTag] = useState('')\n const [target, setTarget] = useState<'member' | 'roundRobin'>('member')\n const [memberUid, setMemberUid] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Seeded on every open, so a drawer that was cancelled halfway does not\n // offer the abandoned draft as the next rule.\n useEffect(() => {\n if (!open) return\n setSource(ANY_SOURCE)\n setFormId('')\n setEmailDomain('')\n setTag('')\n setTarget('member')\n setMemberUid('')\n setBusy(false)\n setError(null)\n }, [open])\n\n const domainTyped = emailDomain.trim().length > 0\n const domainReadable =\n !domainTyped ||\n readCrmAssignmentRule({\n id: 'probe',\n when: { emailDomain },\n assign: { roundRobin: true },\n })?.when.emailDomain !== undefined\n const canSubmit =\n !busy && domainReadable && (target === 'roundRobin' || memberUid.length > 0)\n\n const handleSubmit = useCallback(async () => {\n if (!canSubmit) return\n const rule = readCrmAssignmentRule({\n id: newAssignmentRuleId(existingIds),\n when: {\n ...(source ? { source } : {}),\n ...(formId.trim() ? { formId: formId.trim() } : {}),\n ...(emailDomain.trim() ? { emailDomain: emailDomain.trim() } : {}),\n ...(tag.trim() ? { tag: tag.trim() } : {}),\n },\n assign: target === 'roundRobin' ? { roundRobin: true } : { memberUid },\n })\n if (!rule) {\n setError('The rule could not be read back. Check each field.')\n return\n }\n setBusy(true)\n setError(null)\n try {\n await onSubmit(rule)\n } catch (caught) {\n console.error(caught)\n setError('Could not save the rule. Try again.')\n } finally {\n setBusy(false)\n }\n }, [canSubmit, existingIds, source, formId, emailDomain, tag, target, memberUid, onSubmit])\n\n const conditions = [source, formId.trim(), emailDomain.trim(), tag.trim()].filter(Boolean)\n\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n <Stack spacing={2} sx={{ width: 380, maxWidth: '100vw', p: 3 }}>\n <Typography variant=\"h6\">{'New assignment rule'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'When a new contact matches every condition below, it is assigned ' +\n 'as the rule says. Leave every condition blank for a rule that ' +\n 'catches everything the rules above it did not.'}\n </Typography>\n <TextField\n select\n size=\"small\"\n label=\"Source\"\n value={source}\n onChange={(event) => setSource(event.target.value)}\n fullWidth\n >\n <MenuItem value={ANY_SOURCE}>{'Any source'}</MenuItem>\n {(Object.keys(CONTACT_SOURCE_LABELS) as ContactSource[]).map((option) => (\n <MenuItem key={option} value={option}>\n {CONTACT_SOURCE_LABELS[option]}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Form\"\n value={formId}\n onChange={(event) => setFormId(event.target.value)}\n helperText=\"The form's id, from its address in Forms. Blank for any form.\"\n slotProps={{ htmlInput: { maxLength: 128, spellCheck: false } }}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Email domain\"\n value={emailDomain}\n onChange={(event) => setEmailDomain(event.target.value)}\n error={!domainReadable}\n helperText={\n domainReadable\n ? 'acme.com — the domain of the captured address. Public mailboxes such as gmail.com count.'\n : 'That does not look like a domain.'\n }\n slotProps={{ htmlInput: { maxLength: 253, spellCheck: false } }}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Tag\"\n value={tag}\n onChange={(event) => setTag(event.target.value)}\n helperText=\"A tag the capture carries, or the contact already has.\"\n slotProps={{ htmlInput: { maxLength: 60 } }}\n fullWidth\n />\n <FormControl>\n <FormLabel id=\"assignment-rule-target\">{'Assign to'}</FormLabel>\n <RadioGroup\n aria-labelledby=\"assignment-rule-target\"\n value={target}\n onChange={(event) =>\n setTarget(event.target.value === 'roundRobin' ? 'roundRobin' : 'member')\n }\n >\n <FormControlLabel value=\"member\" control={<Radio size=\"small\" />} label=\"A team member\" />\n <FormControlLabel\n value=\"roundRobin\"\n control={<Radio size=\"small\" />}\n label=\"Round robin — the next member of the pool\"\n />\n </RadioGroup>\n {target === 'roundRobin' ? (\n <FormHelperText>\n {poolSize > 0\n ? `The pool has ${poolSize} ${poolSize === 1 ? 'member' : 'members'}; each new contact goes to the next in turn.`\n : 'The pool is empty. This rule is skipped until somebody is added to it below.'}\n </FormHelperText>\n ) : null}\n </FormControl>\n {target === 'member' ? (\n <TextField\n select\n size=\"small\"\n label=\"Member\"\n value={memberUid}\n onChange={(event) => setMemberUid(event.target.value)}\n disabled={membersLoading}\n helperText={\n membersLoading\n ? 'Loading the team…'\n : members.length\n ? undefined\n : 'The team could not be listed.'\n }\n fullWidth\n >\n {members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {conditions.length === 0 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No conditions: this rule matches every new contact the rules above it did not claim.'}\n </Typography>\n ) : null}\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSubmit} onClick={handleSubmit}>\n {'Add rule'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Drawer>\n )\n}\nAssignmentRuleDrawer.displayName = 'AssignmentRuleDrawer'\n\nexport default AssignmentRuleDrawer\n"],"names":["CONTACT_SOURCE_LABELS","newAssignmentRuleId","readCrmAssignmentRule","crmMemberPickerLabel","Button","Drawer","FormControl","FormControlLabel","FormHelperText","FormLabel","MenuItem","Radio","RadioGroup","Stack","TextField","Typography","useCallback","useEffect","useState","ANY_SOURCE","AssignmentRuleDrawer","props","open","onClose","members","membersLoading","poolSize","existingIds","onSubmit","source","setSource","formId","setFormId","emailDomain","setEmailDomain","tag","setTag","target","setTarget","memberUid","setMemberUid","busy","setBusy","error","setError","domainTyped","trim","length","domainReadable","id","when","assign","roundRobin","undefined","canSubmit","handleSubmit","rule","caught","console","conditions","filter","Boolean","anchor","spacing","sx","width","maxWidth","p","variant","color","select","size","label","value","onChange","event","fullWidth","Object","keys","map","option","helperText","slotProps","htmlInput","maxLength","spellCheck","aria-labelledby","control","disabled","member","uid","direction","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,qBAAqB,EAGrBC,mBAAmB,EACnBC,qBAAqB,EACrBC,oBAAoB,QACf,eAAc;AACrB,SACEC,MAAM,EACNC,MAAM,EACNC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,EACdC,SAAS,EACTC,QAAQ,EACRC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAGxD,yDAAyD,GACzD,MAAMC,aAAa;AAgBnB;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QA6BjEnB;IA5BF,MAAM,EAAEoB,IAAI,EAAEC,OAAO,EAAEC,OAAO,EAAEC,cAAc,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,QAAQ,EAAE,GAC/EP;IACF,MAAM,CAACQ,QAAQC,UAAU,GAAGZ,SAAiBC;IAC7C,MAAM,CAACY,QAAQC,UAAU,GAAGd,SAAS;IACrC,MAAM,CAACe,aAAaC,eAAe,GAAGhB,SAAS;IAC/C,MAAM,CAACiB,KAAKC,OAAO,GAAGlB,SAAS;IAC/B,MAAM,CAACmB,QAAQC,UAAU,GAAGpB,SAAkC;IAC9D,MAAM,CAACqB,WAAWC,aAAa,GAAGtB,SAAS;IAC3C,MAAM,CAACuB,MAAMC,QAAQ,GAAGxB,SAAS;IACjC,MAAM,CAACyB,OAAOC,SAAS,GAAG1B,SAAwB;IAElD,wEAAwE;IACxE,8CAA8C;IAC9CD,UAAU;QACR,IAAI,CAACK,MAAM;QACXQ,UAAUX;QACVa,UAAU;QACVE,eAAe;QACfE,OAAO;QACPE,UAAU;Q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AClC;4BAAWsC,SAASrC;sCACxE;;sCAEH,KAACnD;4BAAOwF,SAASrE;4BAASiE,UAAU/C;sCACjC;;;;;;;AAMb;AACArB,qBAAqByE,WAAW,GAAG;AAEnC,eAAezE,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/assignment-rule-drawer.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type CrmAssignmentRule,\n newAssignmentRuleId,\n readCrmAssignmentRule,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { listContactSourceOptions } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n Button,\n Drawer,\n FormControl,\n FormControlLabel,\n FormHelperText,\n FormLabel,\n MenuItem,\n Radio,\n RadioGroup,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { OrgMemberOption } from '../hooks/use-org-member-directory'\n\n/** The `value` of the source picker's \"any door\" entry. */\nconst ANY_SOURCE = ''\n\nexport interface AssignmentRuleDrawerProps {\n open: boolean\n onClose: () => void\n /** The roster the member target is picked from. */\n members: readonly OrgMemberOption[]\n membersLoading: boolean\n /** How many people the round-robin pool holds, for the target's helper text. */\n poolSize: number\n /** The ids the org already holds, so the new one is minted apart from them. */\n existingIds: readonly string[]\n /** Receives the rule; closing on success is the caller's job. */\n onSubmit: (rule: CrmAssignmentRule) => Promise<void> | void\n}\n\n/**\n * The one form an assignment rule is written through (AGL-2618).\n *\n * ## Every condition is optional, and none is a form above the list\n *\n * A rule names the captures it claims — a source, a form, an email domain,\n * a tag — and a field left blank is not a condition, so a rule with every\n * field blank is the catch-all, which is a rule a team writes on purpose\n * (\"everything else goes to Sam\"). The drawer says so rather than refusing\n * it. The email domain is typed the way a person sees one in an address,\n * `@acme.com` or `acme.com`, and the reader strips the `@`; what it cannot\n * read as a domain is refused here, with the field, rather than stored as\n * a condition nothing will ever match.\n *\n * ## The target is a member, or the rotation\n *\n * A member is picked from the roster by name, never typed as an address —\n * an address is resolved at run time and a rule must not depend on a\n * resolution that can change. The rotation is offered whatever the pool\n * holds, with the pool's size beside it: an empty pool is a rule the pass\n * steps over until somebody fills the pool, which the card below explains,\n * and refusing the rule here would make the two cards order-dependent.\n */\nexport function AssignmentRuleDrawer(props: AssignmentRuleDrawerProps) {\n const { open, onClose, members, membersLoading, poolSize, existingIds, onSubmit } =\n props\n const [source, setSource] = useState<string>(ANY_SOURCE)\n const [formId, setFormId] = useState('')\n const [emailDomain, setEmailDomain] = useState('')\n const [tag, setTag] = useState('')\n const [target, setTarget] = useState<'member' | 'roundRobin'>('member')\n const [memberUid, setMemberUid] = useState('')\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Seeded on every open, so a drawer that was cancelled halfway does not\n // offer the abandoned draft as the next rule.\n useEffect(() => {\n if (!open) return\n setSource(ANY_SOURCE)\n setFormId('')\n setEmailDomain('')\n setTag('')\n setTarget('member')\n setMemberUid('')\n setBusy(false)\n setError(null)\n }, [open])\n\n const domainTyped = emailDomain.trim().length > 0\n const domainReadable =\n !domainTyped ||\n readCrmAssignmentRule({\n id: 'probe',\n when: { emailDomain },\n assign: { roundRobin: true },\n })?.when.emailDomain !== undefined\n const canSubmit =\n !busy && domainReadable && (target === 'roundRobin' || memberUid.length > 0)\n\n const handleSubmit = useCallback(async () => {\n if (!canSubmit) return\n const rule = readCrmAssignmentRule({\n id: newAssignmentRuleId(existingIds),\n when: {\n ...(source ? { source } : {}),\n ...(formId.trim() ? { formId: formId.trim() } : {}),\n ...(emailDomain.trim() ? { emailDomain: emailDomain.trim() } : {}),\n ...(tag.trim() ? { tag: tag.trim() } : {}),\n },\n assign: target === 'roundRobin' ? { roundRobin: true } : { memberUid },\n })\n if (!rule) {\n setError('The rule could not be read back. Check each field.')\n return\n }\n setBusy(true)\n setError(null)\n try {\n await onSubmit(rule)\n } catch (caught) {\n console.error(caught)\n setError('Could not save the rule. Try again.')\n } finally {\n setBusy(false)\n }\n }, [canSubmit, existingIds, source, formId, emailDomain, tag, target, memberUid, onSubmit])\n\n const conditions = [source, formId.trim(), emailDomain.trim(), tag.trim()].filter(Boolean)\n\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n <Stack spacing={2} sx={{ width: 380, maxWidth: '100vw', p: 3 }}>\n <Typography variant=\"h6\">{'New assignment rule'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'When a new contact matches every condition below, it is assigned ' +\n 'as the rule says. Leave every condition blank for a rule that ' +\n 'catches everything the rules above it did not.'}\n </Typography>\n <TextField\n select\n size=\"small\"\n label=\"Source\"\n value={source}\n onChange={(event) => setSource(event.target.value)}\n fullWidth\n >\n <MenuItem value={ANY_SOURCE}>{'Any source'}</MenuItem>\n {listContactSourceOptions().map((option) => (\n <MenuItem key={option.value} value={option.value}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Form\"\n value={formId}\n onChange={(event) => setFormId(event.target.value)}\n helperText=\"The form's id, from its address in Forms. Blank for any form.\"\n slotProps={{ htmlInput: { maxLength: 128, spellCheck: false } }}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Email domain\"\n value={emailDomain}\n onChange={(event) => setEmailDomain(event.target.value)}\n error={!domainReadable}\n helperText={\n domainReadable\n ? 'acme.com — the domain of the captured address. Public mailboxes such as gmail.com count.'\n : 'That does not look like a domain.'\n }\n slotProps={{ htmlInput: { maxLength: 253, spellCheck: false } }}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Tag\"\n value={tag}\n onChange={(event) => setTag(event.target.value)}\n helperText=\"A tag the capture carries, or the contact already has.\"\n slotProps={{ htmlInput: { maxLength: 60 } }}\n fullWidth\n />\n <FormControl>\n <FormLabel id=\"assignment-rule-target\">{'Assign to'}</FormLabel>\n <RadioGroup\n aria-labelledby=\"assignment-rule-target\"\n value={target}\n onChange={(event) =>\n setTarget(event.target.value === 'roundRobin' ? 'roundRobin' : 'member')\n }\n >\n <FormControlLabel value=\"member\" control={<Radio size=\"small\" />} label=\"A team member\" />\n <FormControlLabel\n value=\"roundRobin\"\n control={<Radio size=\"small\" />}\n label=\"Round robin — the next member of the pool\"\n />\n </RadioGroup>\n {target === 'roundRobin' ? (\n <FormHelperText>\n {poolSize > 0\n ? `The pool has ${poolSize} ${poolSize === 1 ? 'member' : 'members'}; each new contact goes to the next in turn.`\n : 'The pool is empty. This rule is skipped until somebody is added to it below.'}\n </FormHelperText>\n ) : null}\n </FormControl>\n {target === 'member' ? (\n <TextField\n select\n size=\"small\"\n label=\"Member\"\n value={memberUid}\n onChange={(event) => setMemberUid(event.target.value)}\n disabled={membersLoading}\n helperText={\n membersLoading\n ? 'Loading the team…'\n : members.length\n ? undefined\n : 'The team could not be listed.'\n }\n fullWidth\n >\n {members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {conditions.length === 0 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No conditions: this rule matches every new contact the rules above it did not claim.'}\n </Typography>\n ) : null}\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSubmit} onClick={handleSubmit}>\n {'Add rule'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Drawer>\n )\n}\nAssignmentRuleDrawer.displayName = 'AssignmentRuleDrawer'\n\nexport default AssignmentRuleDrawer\n"],"names":["newAssignmentRuleId","readCrmAssignmentRule","crmMemberPickerLabel","listContactSourceOptions","Button","Drawer","FormControl","FormControlLabel","FormHelperText","FormLabel","MenuItem","Radio","RadioGroup","Stack","TextField","Typography","useCallback","useEffect","useState","ANY_SOURCE","AssignmentRuleDrawer","props","open","onClose","members","membersLoading","poolSize","existingIds","onSubmit","source","setSource","formId","setFormId","emailDomain","setEmailDomain","tag","setTag","target","setTarget","memberUid","setMemberUid","busy","setBusy","error","setError","domainTyped","trim","length","domainReadable","id","when","assign","roundRobin","undefined","canSubmit","handleSubmit","rule","caught","console","conditions","filter","Boolean","anchor","spacing","sx","width","maxWidth","p","variant","color","select","size","label","value","onChange","event","fullWidth","map","option","helperText","slotProps","htmlInput","maxLength","spellCheck","aria-labelledby","control","disabled","member","uid","direction","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,mBAAmB,EACnBC,qBAAqB,EACrBC,oBAAoB,QACf,eAAc;AACrB,SAASC,wBAAwB,QAAQ,qDAAoD;AAC7F,SACEC,MAAM,EACNC,MAAM,EACNC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,EACdC,SAAS,EACTC,QAAQ,EACRC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAGxD,yDAAyD,GACzD,MAAMC,aAAa;AAgBnB;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QA6BjEpB;IA5BF,MAAM,EAAEqB,IAAI,EAAEC,OAAO,EAAEC,OAAO,EAAEC,cAAc,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,QAAQ,EAAE,GAC/EP;IACF,MAAM,CAACQ,QAAQC,UAAU,GAAGZ,SAAiBC;IAC7C,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ACAD,QAAQuB,MAAM,GACZM,YACA;oBAERuB,SAAS;8BAERpD,QAAQqD,GAAG,CAAC,CAACU,uBACZ,KAAC7E;4BAA0B+D,OAAOc,OAAOC,GAAG;sCACzCtF,qBAAqBqF;2BADTA,OAAOC,GAAG;qBAK3B;gBACH7B,WAAWZ,MAAM,KAAK,kBACrB,KAAChC;oBAAWqD,SAAQ;oBAAUC,OAAM;8BACjC;qBAED;gBACH1B,sBACC,KAAC5B;oBAAWqD,SAAQ;oBAAQC,OAAM;8BAC/B1B;qBAED;8BACJ,MAAC9B;oBAAM4E,WAAU;oBAAM1B,SAAS;;sCAC9B,KAAC3D;4BAAOgE,SAAQ;4BAAYC,OAAM;4BAAUiB,UAAU,CAAChC;4BAAWoC,SAASnC;sCACxE;;sCAEH,KAACnD;4BAAOsF,SAASnE;4BAAS+D,UAAU7C;sCACjC;;;;;;;AAMb;AACArB,qBAAqBuE,WAAW,GAAG;AAEnC,eAAevE,qBAAoB"}
@@ -167,7 +167,6 @@ import { nextActivityColumn } from "./crm-next-activity-column.js";
167
167
  headerName: 'Known by',
168
168
  flex: 1.1,
169
169
  minWidth: 200,
170
- sortable: false,
171
170
  filterable: false,
172
171
  valueGetter: (_value, row)=>row.capturedByHostIds.map(siteName).join(', '),
173
172
  renderCell: ({ row })=>row.capturedByHostIds.length ? /*#__PURE__*/ _jsxs(Stack, {
@@ -233,7 +232,6 @@ import { nextActivityColumn } from "./crm-next-activity-column.js";
233
232
  flex: 1,
234
233
  minWidth: 150
235
234
  }, listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'tags'), {
236
- sortable: false,
237
235
  valueGetter: (_value, row)=>{
238
236
  var _row_tags;
239
237
  return ((_row_tags = row.tags) != null ? _row_tags : []).join(', ');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-list-columns.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n activityTimeLabel,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n EMAIL_STATE_LABELS,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n hiddenFilterColumns,\n listFilterColumn,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { Chip, Stack, Tooltip, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n} from '../constants/contact-filters'\nimport { contactRecordLabel, type ContactRecord } from '../model/contact-record'\nimport type { CrmShareChip } from '../model/crm-sharing'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { nextActivityColumn } from './crm-next-activity-column'\n\n/**\n * The filterable fields that get a column. The rest of\n * `CONTACT_LIST_FILTER_FIELDS` still reaches the filter panel, hidden.\n */\n/**\n * The declared filter fields that ARE table columns, so the hidden\n * filter-only columns are built for the others alone. Owner and Stage\n * joined it when the grammar learned them (AGL-2617): each is a shown\n * column already, and a second, hidden one under the same field would be\n * a duplicate the grid refuses.\n */\nexport const CONTACT_FILTER_COLUMNS = [\n 'name',\n 'ownerUid',\n 'lifecycleStage',\n 'sources',\n 'tags',\n 'updatedAt',\n 'nextTaskAtMs',\n 'emailState',\n]\n\n/**\n * The columns that ship HIDDEN, for the grid's visibility model (AGL-2616).\n *\n * \"Last engaged\" is a fact most lists do not need on screen and every list\n * can turn on from the column menu; shipping it visible would widen a\n * table that already carries seven columns for a figure only a marketing\n * reader scans.\n */\nexport const CONTACT_OPTIONAL_COLUMNS = ['lastEmailEngagementAtMs']\n\nexport interface ContactListColumnOptions {\n /** The owner's name for a uid — the roster's, or the uid itself. */\n memberName: (uid: string) => string\n /**\n * How a site reads, by document id — handed in at the ORGANIZATION level\n * only (AGL-2630), where it turns on the \"Known by\" column: the sites\n * that have captured each person. Absent under a site, where every row\n * is known by the site and the column would say so on every line.\n */\n siteName?: (hostId: string) => string\n /** The words of a row's \"Shared by…\" chip (AGL-3336); absent draws none. */\n shareChipLabel?: (chip: CrmShareChip) => string\n /**\n * One clock for every row of one paint, so two contacts engaged a second\n * apart cannot read \"just now\" and \"1 min ago\". Defaults to the paint's\n * own `Date.now()`.\n */\n nowMs?: number\n}\n\n/**\n * The contacts list's columns (AGL-2596), in their own module so the list\n * file stays about the QUERY and the toolbar while other surfaces — a bulk\n * bar, an import — grow beside it.\n *\n * Owner and Stage read off the flattened row, which is already this\n * holder's facet (`contactRecordFromDoc`), so neither column can show\n * another holder's assignment. Filtering by either is the list's: the panel\n * names the field and the list asks the holder's facet key of its query\n * (`contactQueryClause`, AGL-3321).\n */\nexport function contactListColumns(\n options: ContactListColumnOptions,\n): GridColDef[] {\n const { memberName, siteName, shareChipLabel } = options\n const nowMs = options.nowMs ?? Date.now()\n return [\n {\n field: 'name',\n headerName: 'Contact',\n flex: 1.6,\n minWidth: 220,\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'name'),\n valueGetter: (_value, row: ContactRecord) =>\n contactRecordLabel(row),\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Stack sx={{ justifyContent: 'center', height: '100%', lineHeight: 1.25 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Typography variant=\"body2\" sx={{ lineHeight: 1.25 }}>\n {contactRecordLabel(row)}\n </Typography>\n {/* Seen on this site only through a share (AGL-3336). */}\n {row.shareChip && shareChipLabel ? (\n <Chip size=\"small\" variant=\"outlined\" color=\"info\" label={shareChipLabel(row.shareChip)} />\n ) : null}\n </Stack>\n {row.name && (row.email || row.phone || row.mobilePhone) ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ lineHeight: 1.25 }}\n noWrap\n >\n {row.email || row.phone || row.mobilePhone}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'ownerUid',\n headerName: 'Owner',\n flex: 0.9,\n minWidth: 140,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.ownerUid ? memberName(row.ownerUid) : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.ownerUid ? (\n <Typography variant=\"body2\" noWrap>\n {memberName(row.ownerUid)}\n </Typography>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n {\n field: 'lifecycleStage',\n headerName: 'Stage',\n flex: 0.9,\n minWidth: 150,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.lifecycleStage ? CONTACT_LIFECYCLE_STAGE_LABELS[row.lifecycleStage] : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.lifecycleStage ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={CONTACT_LIFECYCLE_STAGE_LABELS[row.lifecycleStage]}\n />\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n /*\n * KNOWN BY (AGL-2630): the sites that have captured this person, which\n * is the cross-site fact the organization-level list exists to show —\n * one deduplicated row per person, and which of the org's sites know\n * them. `capturedByHostIds` is a top-level array precisely so the\n * question can be answered without opening a facet. Not filterable from\n * the panel: an `array-contains` on it would displace the scope clause\n * under a site, and a search or a facet filter at the org level (one\n * array clause per query, AGL-3321). A row that names no site predates attribution and says so,\n * rather than reading as \"every site\".\n */\n ...(siteName\n ? [\n {\n field: 'capturedByHostIds',\n headerName: 'Known by',\n flex: 1.1,\n minWidth: 200,\n sortable: false,\n filterable: false,\n valueGetter: (_value: unknown, row: ContactRecord) =>\n row.capturedByHostIds.map(siteName).join(', '),\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.capturedByHostIds.length ? (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%', flexWrap: 'nowrap' }}\n >\n {row.capturedByHostIds.slice(0, 2).map((hostId) => (\n <Chip key={hostId} size=\"small\" label={siteName(hostId)} />\n ))}\n {row.capturedByHostIds.length > 2 ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={`+${row.capturedByHostIds.length - 2}`}\n />\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No site recorded'}\n </Typography>\n ),\n } satisfies GridColDef,\n ]\n : []),\n {\n field: 'sources',\n headerName: 'Sources',\n flex: 1,\n minWidth: 160,\n // A map of provenance flags, not a scalar — `sources.form == true` is\n // queryable one key at a time, which is a menu of its own rather than\n // a filter on this column. For the same reason the query cannot order\n // by it: the header sorts the page (AGL-3680), by the words on the\n // chips, so `order` sorts where \"Customer\" reads.\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n Object.keys(row.sources ?? {})\n .map((source) => labelContactSource(source))\n .join(', '),\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%' }}\n >\n {Object.keys(row.sources ?? {}).map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n </Stack>\n ),\n },\n {\n field: 'tags',\n headerName: 'Tags',\n flex: 1,\n minWidth: 150,\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'tags'),\n sortable: false,\n valueGetter: (_value, row: ContactRecord) => (row.tags ?? []).join(', '),\n renderCell: ({ row }: { row: ContactRecord }) =>\n (row.tags ?? []).slice(0, 3).join(', '),\n },\n {\n field: 'updatedAt',\n headerName: 'Last activity',\n flex: 0.8,\n minWidth: 150,\n // `type: 'date'` is what gives the panel a date PICKER rather than a\n // free-text box for a value the query reads as a day.\n type: 'date',\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'updatedAt'),\n valueGetter: (_value, row: ContactRecord) => {\n const seconds = (row.updatedAt as { seconds?: number } | undefined)?.seconds\n return seconds ? new Date(seconds * 1000) : null\n },\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {row.interactions?.[0]\n ? new Date(row.interactions[0].atMs).toLocaleDateString()\n : '—'}\n </Typography>\n ),\n },\n // When the earliest open task against the person is due (AGL-2661).\n nextActivityColumn(nowMs),\n {\n /*\n * When the person last opened or clicked one of this holder's\n * campaigns (AGL-2616). Off the facet like Owner and Stage, so it can\n * never show another holder's readers; `filterable: false` for the\n * same reason theirs are — a facet path is not a query the panel can\n * make. A date column, so a sort on it orders by the instant and an\n * export gets a date; the cell prints the relative form the timeline\n * uses and carries the full stamp in its tooltip.\n */\n field: 'lastEmailEngagementAtMs',\n headerName: 'Last engaged',\n flex: 0.8,\n minWidth: 140,\n type: 'date',\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.lastEmailEngagementAtMs ? new Date(row.lastEmailEngagementAtMs) : null,\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(row.lastEmailEngagementAtMs).toLocaleString()}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {activityTimeLabel(row.lastEmailEngagementAtMs, nowMs)}\n </Typography>\n </Tooltip>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n {\n /*\n * The verdict on the address (AGL-3245): the same chip the record page\n * carries, so a bounced or blocked person is told apart in the list a\n * member picks recipients from. Sorted and exported by its label;\n * filtered through the bar's `emailState` clause, not the panel.\n */\n field: 'emailState',\n headerName: 'Email',\n flex: 0.8,\n minWidth: 140,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.emailState ? EMAIL_STATE_LABELS[row.emailState.status] : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.emailState ? (\n <CrmEmailStateChip state={row.emailState} />\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n ...hiddenFilterColumns(\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_FILTER_COLUMNS,\n CONTACT_LIST_FILTER_HEADERS,\n ),\n ]\n}\n"],"names":["activityTimeLabel","CONTACT_LIFECYCLE_STAGE_LABELS","EMAIL_STATE_LABELS","labelContactSource","hiddenFilterColumns","listFilterColumn","Chip","Stack","Tooltip","Typography","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","contactRecordLabel","CrmEmailStateChip","nextActivityColumn","CONTACT_FILTER_COLUMNS","CONTACT_OPTIONAL_COLUMNS","contactListColumns","options","memberName","siteName","shareChipLabel","nowMs","Date","now","field","headerName","flex","minWidth","valueGetter","_value","row","renderCell","sx","justifyContent","height","lineHeight","direction","spacing","alignItems","variant","shareChip","size","color","label","name","email","phone","mobilePhone","noWrap","filterable","ownerUid","lifecycleStage","sortable","capturedByHostIds","map","join","length","flexWrap","slice","hostId","Object","keys","sources","source","tags","type","seconds","updatedAt","interactions","atMs","toLocaleDateString","lastEmailEngagementAtMs","title","toLocaleString","emailState","status","state"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,iBAAiB,EACjBC,8BAA8B,EAC9BC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SACEC,mBAAmB,EACnBC,gBAAgB,QACX,8CAA6C;AACpD,SAASC,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAEC,UAAU,QAAQ,gBAAe;AAEhE,SACEC,0BAA0B,EAC1BC,2BAA2B,QACtB,kCAA8B;AACrC,SAASC,kBAAkB,QAA4B,6BAAyB;AAEhF,SAASC,iBAAiB,QAAQ,4BAAwB;AAC1D,SAASC,kBAAkB,QAAQ,gCAA4B;AAE/D;;;CAG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C,QAAQC,MACpBA,IAAI4C,UAAU,GAAGzE,kBAAkB,CAAC6B,IAAI4C,UAAU,CAACC,MAAM,CAAC,GAAG;YAC/D5C,YAAY,CAAC,EAAED,GAAG,EAA0B,GAC1CA,IAAI4C,UAAU,iBACZ,KAAC9D;oBAAkBgE,OAAO9C,IAAI4C,UAAU;mCAExC,KAAClE;oBAAW+B,SAAQ;oBAAUG,OAAM;8BACjC;;QAGT;WACGvC,oBACDM,4BACAK,wBACAJ;KAEH;AACH"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-list-columns.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n activityTimeLabel,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n EMAIL_STATE_LABELS,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n hiddenFilterColumns,\n listFilterColumn,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { Chip, Stack, Tooltip, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n} from '../constants/contact-filters'\nimport { contactRecordLabel, type ContactRecord } from '../model/contact-record'\nimport type { CrmShareChip } from '../model/crm-sharing'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { nextActivityColumn } from './crm-next-activity-column'\n\n/**\n * The filterable fields that get a column. The rest of\n * `CONTACT_LIST_FILTER_FIELDS` still reaches the filter panel, hidden.\n */\n/**\n * The declared filter fields that ARE table columns, so the hidden\n * filter-only columns are built for the others alone. Owner and Stage\n * joined it when the grammar learned them (AGL-2617): each is a shown\n * column already, and a second, hidden one under the same field would be\n * a duplicate the grid refuses.\n */\nexport const CONTACT_FILTER_COLUMNS = [\n 'name',\n 'ownerUid',\n 'lifecycleStage',\n 'sources',\n 'tags',\n 'updatedAt',\n 'nextTaskAtMs',\n 'emailState',\n]\n\n/**\n * The columns that ship HIDDEN, for the grid's visibility model (AGL-2616).\n *\n * \"Last engaged\" is a fact most lists do not need on screen and every list\n * can turn on from the column menu; shipping it visible would widen a\n * table that already carries seven columns for a figure only a marketing\n * reader scans.\n */\nexport const CONTACT_OPTIONAL_COLUMNS = ['lastEmailEngagementAtMs']\n\nexport interface ContactListColumnOptions {\n /** The owner's name for a uid — the roster's, or the uid itself. */\n memberName: (uid: string) => string\n /**\n * How a site reads, by document id — handed in at the ORGANIZATION level\n * only (AGL-2630), where it turns on the \"Known by\" column: the sites\n * that have captured each person. Absent under a site, where every row\n * is known by the site and the column would say so on every line.\n */\n siteName?: (hostId: string) => string\n /** The words of a row's \"Shared by…\" chip (AGL-3336); absent draws none. */\n shareChipLabel?: (chip: CrmShareChip) => string\n /**\n * One clock for every row of one paint, so two contacts engaged a second\n * apart cannot read \"just now\" and \"1 min ago\". Defaults to the paint's\n * own `Date.now()`.\n */\n nowMs?: number\n}\n\n/**\n * The contacts list's columns (AGL-2596), in their own module so the list\n * file stays about the QUERY and the toolbar while other surfaces — a bulk\n * bar, an import — grow beside it.\n *\n * Owner and Stage read off the flattened row, which is already this\n * holder's facet (`contactRecordFromDoc`), so neither column can show\n * another holder's assignment. Filtering by either is the list's: the panel\n * names the field and the list asks the holder's facet key of its query\n * (`contactQueryClause`, AGL-3321).\n */\nexport function contactListColumns(\n options: ContactListColumnOptions,\n): GridColDef[] {\n const { memberName, siteName, shareChipLabel } = options\n const nowMs = options.nowMs ?? Date.now()\n return [\n {\n field: 'name',\n headerName: 'Contact',\n flex: 1.6,\n minWidth: 220,\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'name'),\n valueGetter: (_value, row: ContactRecord) =>\n contactRecordLabel(row),\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Stack sx={{ justifyContent: 'center', height: '100%', lineHeight: 1.25 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Typography variant=\"body2\" sx={{ lineHeight: 1.25 }}>\n {contactRecordLabel(row)}\n </Typography>\n {/* Seen on this site only through a share (AGL-3336). */}\n {row.shareChip && shareChipLabel ? (\n <Chip size=\"small\" variant=\"outlined\" color=\"info\" label={shareChipLabel(row.shareChip)} />\n ) : null}\n </Stack>\n {row.name && (row.email || row.phone || row.mobilePhone) ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ lineHeight: 1.25 }}\n noWrap\n >\n {row.email || row.phone || row.mobilePhone}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'ownerUid',\n headerName: 'Owner',\n flex: 0.9,\n minWidth: 140,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.ownerUid ? memberName(row.ownerUid) : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.ownerUid ? (\n <Typography variant=\"body2\" noWrap>\n {memberName(row.ownerUid)}\n </Typography>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n {\n field: 'lifecycleStage',\n headerName: 'Stage',\n flex: 0.9,\n minWidth: 150,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.lifecycleStage ? CONTACT_LIFECYCLE_STAGE_LABELS[row.lifecycleStage] : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.lifecycleStage ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={CONTACT_LIFECYCLE_STAGE_LABELS[row.lifecycleStage]}\n />\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n /*\n * KNOWN BY (AGL-2630): the sites that have captured this person, which\n * is the cross-site fact the organization-level list exists to show —\n * one deduplicated row per person, and which of the org's sites know\n * them. `capturedByHostIds` is a top-level array precisely so the\n * question can be answered without opening a facet. Not filterable from\n * the panel: an `array-contains` on it would displace the scope clause\n * under a site, and a search or a facet filter at the org level (one\n * array clause per query, AGL-3321). A row that names no site predates attribution and says so,\n * rather than reading as \"every site\".\n */\n ...(siteName\n ? [\n {\n field: 'capturedByHostIds',\n headerName: 'Known by',\n flex: 1.1,\n minWidth: 200,\n filterable: false,\n valueGetter: (_value: unknown, row: ContactRecord) =>\n row.capturedByHostIds.map(siteName).join(', '),\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.capturedByHostIds.length ? (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%', flexWrap: 'nowrap' }}\n >\n {row.capturedByHostIds.slice(0, 2).map((hostId) => (\n <Chip key={hostId} size=\"small\" label={siteName(hostId)} />\n ))}\n {row.capturedByHostIds.length > 2 ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={`+${row.capturedByHostIds.length - 2}`}\n />\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No site recorded'}\n </Typography>\n ),\n } satisfies GridColDef,\n ]\n : []),\n {\n field: 'sources',\n headerName: 'Sources',\n flex: 1,\n minWidth: 160,\n // A map of provenance flags, not a scalar — `sources.form == true` is\n // queryable one key at a time, which is a menu of its own rather than\n // a filter on this column. For the same reason the query cannot order\n // by it: the header sorts the page (AGL-3680), by the words on the\n // chips, so `order` sorts where \"Customer\" reads.\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n Object.keys(row.sources ?? {})\n .map((source) => labelContactSource(source))\n .join(', '),\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%' }}\n >\n {Object.keys(row.sources ?? {}).map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n </Stack>\n ),\n },\n {\n field: 'tags',\n headerName: 'Tags',\n flex: 1,\n minWidth: 150,\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'tags'),\n valueGetter: (_value, row: ContactRecord) => (row.tags ?? []).join(', '),\n renderCell: ({ row }: { row: ContactRecord }) =>\n (row.tags ?? []).slice(0, 3).join(', '),\n },\n {\n field: 'updatedAt',\n headerName: 'Last activity',\n flex: 0.8,\n minWidth: 150,\n // `type: 'date'` is what gives the panel a date PICKER rather than a\n // free-text box for a value the query reads as a day.\n type: 'date',\n ...listFilterColumn(CONTACT_LIST_FILTER_FIELDS, 'updatedAt'),\n valueGetter: (_value, row: ContactRecord) => {\n const seconds = (row.updatedAt as { seconds?: number } | undefined)?.seconds\n return seconds ? new Date(seconds * 1000) : null\n },\n renderCell: ({ row }: { row: ContactRecord }) => (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {row.interactions?.[0]\n ? new Date(row.interactions[0].atMs).toLocaleDateString()\n : '—'}\n </Typography>\n ),\n },\n // When the earliest open task against the person is due (AGL-2661).\n nextActivityColumn(nowMs),\n {\n /*\n * When the person last opened or clicked one of this holder's\n * campaigns (AGL-2616). Off the facet like Owner and Stage, so it can\n * never show another holder's readers; `filterable: false` for the\n * same reason theirs are — a facet path is not a query the panel can\n * make. A date column, so a sort on it orders by the instant and an\n * export gets a date; the cell prints the relative form the timeline\n * uses and carries the full stamp in its tooltip.\n */\n field: 'lastEmailEngagementAtMs',\n headerName: 'Last engaged',\n flex: 0.8,\n minWidth: 140,\n type: 'date',\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.lastEmailEngagementAtMs ? new Date(row.lastEmailEngagementAtMs) : null,\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(row.lastEmailEngagementAtMs).toLocaleString()}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {activityTimeLabel(row.lastEmailEngagementAtMs, nowMs)}\n </Typography>\n </Tooltip>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n {\n /*\n * The verdict on the address (AGL-3245): the same chip the record page\n * carries, so a bounced or blocked person is told apart in the list a\n * member picks recipients from. Sorted and exported by its label;\n * filtered through the bar's `emailState` clause, not the panel.\n */\n field: 'emailState',\n headerName: 'Email',\n flex: 0.8,\n minWidth: 140,\n filterable: false,\n valueGetter: (_value, row: ContactRecord) =>\n row.emailState ? EMAIL_STATE_LABELS[row.emailState.status] : '',\n renderCell: ({ row }: { row: ContactRecord }) =>\n row.emailState ? (\n <CrmEmailStateChip state={row.emailState} />\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'—'}\n </Typography>\n ),\n },\n ...hiddenFilterColumns(\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_FILTER_COLUMNS,\n CONTACT_LIST_FILTER_HEADERS,\n ),\n ]\n}\n"],"names":["activityTimeLabel","CONTACT_LIFECYCLE_STAGE_LABELS","EMAIL_STATE_LABELS","labelContactSource","hiddenFilterColumns","listFilterColumn","Chip","Stack","Tooltip","Typography","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","contactRecordLabel","CrmEmailStateChip","nextActivityColumn","CONTACT_FILTER_COLUMNS","CONTACT_OPTIONAL_COLUMNS","contactListColumns","options","memberName","siteName","shareChipLabel","nowMs","Date","now","field","headerName","flex","minWidth","valueGetter","_value","row","renderCell","sx","justifyContent","height","lineHeight","direction","spacing","alignItems","variant","shareChip","size","color","label","name","email","phone","mobilePhone","noWrap","filterable","ownerUid","lifecycleStage","capturedByHostIds","map","join","length","flexWrap","slice","hostId","Object","keys","sources","source","tags","type","seconds","updatedAt","interactions","atMs","toLocaleDateString","lastEmailEngagementAtMs","title","toLocaleString","emailState","status","state"],"mappings":"AAAA;;;;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ACxEvC,YAAY,CAAC,EAAED,GAAG,EAA0B,GAC1CA,IAAIwC,uBAAuB,iBACzB,KAAC/D;oBAAQgE,OAAO,IAAIjD,KAAKQ,IAAIwC,uBAAuB,EAAEE,cAAc;8BAClE,cAAA,KAAChE;wBAAW+B,SAAQ;wBAAUG,OAAM;kCACjC3C,kBAAkB+B,IAAIwC,uBAAuB,EAAEjD;;mCAIpD,KAACb;oBAAW+B,SAAQ;oBAAUG,OAAM;8BACjC;;QAGT;QACA;YACE;;;;;OAKC,GACDlB,OAAO;YACPC,YAAY;YACZC,MAAM;YACNC,UAAU;YACVsB,YAAY;YACZrB,aAAa,CAACC,QAAQC,MACpBA,IAAI2C,UAAU,GAAGxE,kBAAkB,CAAC6B,IAAI2C,UAAU,CAACC,MAAM,CAAC,GAAG;YAC/D3C,YAAY,CAAC,EAAED,GAAG,EAA0B,GAC1CA,IAAI2C,UAAU,iBACZ,KAAC7D;oBAAkB+D,OAAO7C,IAAI2C,UAAU;mCAExC,KAACjE;oBAAW+B,SAAQ;oBAAUG,OAAM;8BACjC;;QAGT;WACGvC,oBACDM,4BACAK,wBACAJ;KAEH;AACH"}
@@ -647,7 +647,7 @@ const NO_MERGE_RECORDS = {
647
647
  sx: {
648
648
  mt: 0.5
649
649
  },
650
- children: 'An admin sets this up under Emails › Sending.'
650
+ children: 'A member holding "Organization settings" sets this up under Emails › Sending.'
651
651
  })
652
652
  ]
653
653
  }) : identity.status === 'error' ? /*#__PURE__*/ _jsx(Alert, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-send-email-dialog.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n CRM_EMAIL_BODY_MAX,\n CRM_EMAIL_SUBJECT_MAX,\n normalizeContactEmail,\n consentGroupForHost,\n CRM_COLLECTIONS,\n createResourceUid,\n type CrmEmailTemplateRow,\n type CrmMergeContext,\n type CrmMergeFieldGroup,\n crmMergeUnresolvedMessage,\n hasCrmMergeFields,\n resolveCrmMergeFields,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { pluginRecordListHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport type { ConsoleRecordEmailDraft } from '@aglyn/aglyn/plugin-manager/record-zone-props'\nimport { useSendingApi } from '@aglyn/tenant-feature-instance/hooks/use-sending-identity-api'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useOrgDataScope,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n InputAdornment,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, getDoc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { CrmRecordBookingZone } from './crm-booking-zone'\nimport { insertLinkAtCaret } from './insert-link-at-caret'\nimport {\n CAPTURE_ADDRESS_HELPER,\n CopyCaptureAddressButton,\n} from './copy-capture-address-button'\nimport { CrmSitePicker } from './crm-site-picker'\nimport { CrmEmailCheckAlert, useCrmEmailCheck } from './crm-email-check'\nimport { useCrmApi } from './use-crm-api'\nimport { useCrmInboundAddress } from './use-crm-inbound-address'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport {\n useCrmEmailTemplates,\n useCrmEmailTemplateScope,\n} from '../hooks/use-crm-email-templates'\nimport {\n CrmInsertMenu,\n CrmSaveAsTemplateDialog,\n CrmTemplatePicker,\n} from './crm-email-template-tools'\n\n/**\n * The documents a merge-field preview reads (AGL-2658), fetched once per\n * open and only once the draft names a field: a letter with no fields\n * costs no reads. `site` is the sending site's name; `loaded` says the\n * fetch has answered, so the helper text can tell \"no value\" from \"not\n * yet read\".\n */\ninterface MergeRecords {\n contact: Record<string, unknown> | null\n deal: Record<string, unknown> | null\n lead: Record<string, unknown> | null\n site: string | null\n loaded: boolean\n}\n\nconst NO_MERGE_RECORDS: MergeRecords = {\n contact: null,\n deal: null,\n lead: null,\n site: null,\n loaded: false,\n}\n\n/**\n * What the sending-identity route said about this site, as the dialog\n * needs it: an address to print, or the reason there is none — or, at the\n * organization level, that no site has been picked to ask about.\n */\ntype IdentityState =\n | { status: 'loading' }\n | { status: 'site' }\n | { status: 'ready'; from: string }\n | { status: 'refused'; message: string; canManage: boolean }\n | { status: 'error'; message: string }\n\nexport interface CrmSendEmailDialogProps {\n open: boolean\n onClose: () => void\n /**\n * The site the message leaves from — passed in, never assumed from the\n * URL. At the organization level the record's own capturing site, or\n * `null` for a record no site has captured (AGL-2634): the dialog then\n * offers the org's sites to send from, defaulting to the reader's pick.\n */\n hostId: string | null\n /** The org the shell passed; lets a deal's contact be read without a lookup. */\n org?: Partial<AglynOrgBilling> | null\n contactId?: string\n leadId?: string\n dealId?: string\n /**\n * The recipient as the record shows it. A deal's page holds no address,\n * so a caller with only a `contactId` may leave this out and the dialog\n * reads it off the contact when it opens.\n */\n email?: string | null\n /** What the dialog says it is writing to, beside the address. */\n name?: string | null\n /** Told once the route has accepted the message. */\n onSent?: (result: { activityId: string }) => void\n}\n\n/**\n * One email to one person, from their record (AGL-2615).\n *\n * ## What the reader sees, and what they cannot change\n *\n * To is the record's address and is read-only: the route resolves the\n * recipient off the record again, so an editable field here would be a\n * promise the server does not keep. From is the site's sending identity as\n * the sending-identity route reports it — the same answer the campaign\n * composer prints — and when that route refuses, the dialog says why and\n * points at **Emails › Sending** rather than offering a Send button that\n * 409s. Reply-to is the signed-in user's own address, because a reply to a\n * relationship email belongs in the inbox of the person who wrote it, not\n * the site's shared mailbox. Subject and Body are the whole of what a\n * person writes; the body is plain paragraphs, and the email design system\n * is deliberately not here — this is a letter, not a campaign.\n *\n * ## A refusal stays on screen\n *\n * The route's refusals — the daily cap, a suppressed address, a stated\n * refusal, the ceiling — are answers the rep should read, so they render\n * inside the dialog with the draft intact rather than as a toast over a\n * closed one. Only a send the provider accepted closes it.\n *\n * Mounted on open by its button, so the identity request and the contact\n * read happen when somebody asks and not on every record page paint.\n */\nexport function CrmSendEmailDialog(props: CrmSendEmailDialogProps) {\n const { open, onClose, hostId, org, contactId, leadId, dealId, onSent } = props\n const firestore = useFirestore()\n const mount = useCrmOrgMount()\n const { orgId } = useOrgDataScope({\n hostId: hostId ?? undefined,\n orgId: org?.$id ?? mount?.orgId,\n })\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const sendingApi = useSendingApi()\n /*\n * The site the message LEAVES FROM: the record's own, or at the\n * organization level — for a record no site captured — the site the\n * reader picked (AGL-2634). The identity, the suppression list and the\n * person's stated refusal are each that site's, which is why the org\n * level cannot do without one.\n */\n const sendHostId = hostId ?? mount?.createHostId ?? null\n const crmApi = useCrmApi(sendHostId)\n const sendSite = useSiteRouteContext(sendHostId)\n // The capture address (AGL-2657), for the reply this send will get: the\n // console logs what IT sends, so the address is shown to be forwarded\n // to or copied from a mailbox, never put on this message.\n const capture = useCrmInboundAddress(sendHostId, { enabled: open })\n // Where the site's sending identities are kept — the page that fixes a\n // missing one, at the address the plugin that keeps them publishes as\n // `sendingIdentity` (AGL-3080). `null` on a surface that cannot name the\n // site, or where nothing publishes the kind, so the refusal prints the\n // section's name instead of a link to nowhere.\n const sendingPath = sendSite ? pluginRecordListHref('sendingIdentity', sendSite) : null\n\n const [identity, setIdentity] = useState<IdentityState>({ status: 'loading' })\n const [recipient, setRecipient] = useState<string | null>(\n normalizeContactEmail(props.email) ?? null,\n )\n const [subject, setSubject] = useState('')\n const [body, setBody] = useState('')\n const [sending, setSending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n /*\n * TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658). The listener is the\n * dialog's own scope — the mounted site's tokens, or none at the org\n * level — and what a saved template is stamped with follows the same\n * rule. The message field's element is held so a snippet lands at the\n * caret rather than at the end.\n */\n const { confirm } = useConfirmationContext()\n const templateScope = useCrmEmailTemplateScope({ hostId, org })\n const { templates } = useCrmEmailTemplates({\n scope: templateScope.scope,\n visibleTo: templateScope.visibleTo,\n uid: user?.uid,\n })\n const pickable = useMemo(() => templates.filter((row) => row.kind === 'template'), [templates])\n const snippets = useMemo(() => templates.filter((row) => row.kind === 'snippet'), [templates])\n const [appliedTemplate, setAppliedTemplate] = useState<CrmEmailTemplateRow | null>(null)\n const [saveOpen, setSaveOpen] = useState(false)\n const [records, setRecords] = useState<MergeRecords>(NO_MERGE_RECORDS)\n const messageRef = useRef<HTMLTextAreaElement | null>(null)\n const draftHasFields = hasCrmMergeFields(`${subject}\\n${body}`)\n // The groups the Insert menu offers: what the record can answer.\n const fieldGroups = useMemo<CrmMergeFieldGroup[]>(\n () => [\n ...(contactId || dealId ? (['Contact'] as const) : []),\n ...(leadId && !contactId ? (['Lead'] as const) : []),\n ...(dealId ? (['Deal'] as const) : []),\n 'You',\n 'Site',\n ],\n [contactId, dealId, leadId],\n )\n\n /*\n * The identity, asked for on open. The route is the send path's own\n * resolver, so what it prints here is what the message will leave as; a\n * dialog that derived \"verified\" from the domain list would be a second\n * opinion that drifts from the send.\n */\n useEffect(() => {\n if (!open) return\n let cancelled = false\n setError(null)\n // The draft survives a change of sending site — the site is not the\n // letter — and is cleared only when the dialog opens.\n if (!sendHostId) {\n setIdentity({ status: 'site' })\n return undefined\n }\n setIdentity({ status: 'loading' })\n void (async () => {\n const { response, payload } = await sendingApi({\n path: 'sending-identity',\n method: 'GET',\n query: { hostId: sendHostId },\n })\n if (cancelled) return\n if (!response.ok) {\n setIdentity({\n status: 'error',\n message: String(payload['error'] ?? 'The sending identity could not be read.'),\n })\n return\n }\n const refusal = payload['refusal'] as { message?: string } | null\n if (refusal) {\n setIdentity({\n status: 'refused',\n message: String(refusal.message ?? 'This site has no verified sending identity.'),\n canManage: payload['canManage'] === true,\n })\n return\n }\n const senders = Array.isArray(payload['senders'])\n ? (payload['senders'] as { isDefault?: boolean; from?: string | null }[])\n : []\n const from =\n senders.find((sender) => sender.isDefault && sender.from)?.from ??\n senders.find((sender) => sender.from)?.from ??\n null\n setIdentity(\n from\n ? { status: 'ready', from }\n : {\n status: 'error',\n message: String(payload['identity'] ?? 'No sending address is in effect.'),\n },\n )\n })()\n return () => {\n cancelled = true\n }\n }, [open, sendHostId, sendingApi])\n useEffect(() => {\n if (!open) return\n setSubject('')\n setBody('')\n setAppliedTemplate(null)\n setSaveOpen(false)\n setRecords(NO_MERGE_RECORDS)\n }, [open])\n\n /*\n * The documents a preview reads, fetched the first time the draft names\n * a merge field and kept for the rest of the open: the contact, the\n * deal, the lead, and the sending site's name — off the org mount when\n * it knows the site, off the host document otherwise. The route reads\n * the same documents again for the send; these are what the rep sees.\n */\n useEffect(() => {\n if (!open || !draftHasFields || records.loaded) return\n let cancelled = false\n const read = async (path: string[] | null): Promise<Record<string, unknown> | null> => {\n if (!path) return null\n const snapshot = await getDoc(doc(firestore, path[0], ...path.slice(1)))\n return snapshot.exists() ? ((snapshot.data() ?? null) as Record<string, unknown> | null) : null\n }\n const mountedSite = sendHostId\n ? (mount?.hosts ?? []).find((host) => host.id === sendHostId)\n : undefined\n void Promise.all([\n read(contactId && orgId ? ['orgs', orgId, 'contacts', contactId] : null),\n read(dealId && orgId ? ['orgs', orgId, CRM_COLLECTIONS.deals, dealId] : null),\n // One org row (AGL-3275); the site still decides WHICH lead is offered,\n // but not where it lives.\n read(leadId && orgId ? ['orgs', orgId, 'leads', leadId] : null),\n mountedSite || !sendHostId ? null : read(['hosts', sendHostId]),\n ])\n .then(([contact, deal, lead, host]) => {\n if (cancelled) return\n // A deal's contact, when the page named only the deal.\n const dealContactId = String(deal?.['contactId'] ?? '').trim()\n const withContact =\n !contact && dealContactId && orgId\n ? read(['orgs', orgId, 'contacts', dealContactId])\n : Promise.resolve(contact)\n return withContact.then((resolvedContact) => {\n if (cancelled) return\n setRecords({\n contact: resolvedContact,\n deal,\n lead,\n site: mountedSite?.name ?? (host ? String(host['displayName'] ?? '') : null),\n loaded: true,\n })\n })\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecords({ ...NO_MERGE_RECORDS, loaded: true })\n })\n return () => {\n cancelled = true\n }\n }, [\n open,\n draftHasFields,\n records.loaded,\n firestore,\n orgId,\n contactId,\n dealId,\n leadId,\n sendHostId,\n mount?.hosts,\n ])\n\n const mergeContext = useMemo<CrmMergeContext>(\n () => ({\n contact: records.contact,\n contactGroupId: sendHostId ? consentGroupForHost(org ?? null, sendHostId).groupId : null,\n deal: records.deal,\n lead: records.lead,\n sender: { name: user?.displayName ?? '', email: user?.email ?? '' },\n site: { name: records.site ?? '' },\n }),\n [records, sendHostId, org, user?.displayName, user?.email],\n )\n const preview = useMemo(\n () =>\n draftHasFields && records.loaded\n ? {\n subject: resolveCrmMergeFields(subject, mergeContext),\n body: resolveCrmMergeFields(body, mergeContext),\n }\n : null,\n [draftHasFields, records.loaded, subject, body, mergeContext],\n )\n const unresolved = useMemo(\n () =>\n preview\n ? [...new Set([...preview.subject.unresolved, ...preview.body.unresolved])]\n : [],\n [preview],\n )\n\n /** A template into both fields — asking first when a message is already written. */\n const applyTemplate = useCallback(\n async (template: CrmEmailTemplateRow | null) => {\n if (!template) {\n setAppliedTemplate(null)\n return\n }\n const written = body.trim().length > 0 && body !== appliedTemplate?.body\n if (written) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: `\"${template.name}\" replaces what you have written in the subject and the message.`,\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n if (template.subject) setSubject(template.subject)\n setBody(template.body)\n setAppliedTemplate(template)\n },\n [body, appliedTemplate, confirm],\n )\n\n /*\n * The `recordEmail` zone (AGL-2917), hosted through the shell's renderer: a\n * widget there proposes a subject and a message, which land in the fields\n * above like a template does, asking first when a message is already\n * written. Send is still the only write, and the zone reads the record the\n * message is written from: the deal over its contact, a lead on its own site,\n * and at the organization level a contact or a deal the org reads.\n */\n const EmailDraftSlot = useConsoleWidgetSlot()\n const proposeDraft = useCallback(\n async (draft: ConsoleRecordEmailDraft) => {\n const next = { subject: draft.subject.slice(0, CRM_EMAIL_SUBJECT_MAX), body: draft.body.slice(0, CRM_EMAIL_BODY_MAX) }\n if (body.trim() && body !== next.body) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: 'The draft replaces what you have written in the subject and the message.',\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setSubject(next.subject)\n setBody(next.body)\n setAppliedTemplate(null)\n },\n [body, confirm],\n )\n const draftRecord = dealId\n ? { kind: 'deal', id: dealId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : contactId\n ? { kind: 'contact', id: contactId }\n : null\n\n /** A snippet or a field where the caret is, the caret moved past it. */\n const insertAtCaret = useCallback(\n (text: string) => {\n const element = messageRef.current\n const start = element?.selectionStart ?? body.length\n const end = element?.selectionEnd ?? body.length\n const next = `${body.slice(0, start)}${text}${body.slice(end)}`.slice(0, CRM_EMAIL_BODY_MAX)\n setBody(next)\n const caret = Math.min(start + text.length, next.length)\n window.setTimeout(() => {\n element?.focus()\n element?.setSelectionRange(caret, caret)\n }, 0)\n },\n [body],\n )\n\n /**\n * The draft kept as a template, stamped as this surface's scope stamps\n * every CRM record — the site's tokens under a site, the org token from\n * the organization's hub — and, when personal, owned by the writer.\n */\n const saveAsTemplate = useCallback(\n async (draft: { name: string; visibility: 'shared' | 'personal' }) => {\n const scope = templateScope.scope\n const uid = user?.uid\n if (!scope || !uid || templateScope.createTokens.length === 0) {\n throw new Error('a template needs an organization and a signed-in writer')\n }\n const now = Date.now()\n await setDoc(\n doc(collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.emailTemplates), createResourceUid()),\n {\n name: draft.name,\n subject: subject.trim(),\n body: body.trim(),\n kind: 'template',\n visibility: draft.visibility,\n ...(draft.visibility === 'personal' ? { ownerUid: uid } : {}),\n createdByUid: uid,\n createdAtMs: now,\n updatedAtMs: now,\n hostId: templateScope.createHostId,\n visibleTo: [...templateScope.createTokens],\n createdAt: new Date(now),\n updatedAt: new Date(now),\n },\n )\n enqueueSnackbar(`Template \"${draft.name}\" saved`, { variant: 'success', persist: false })\n setSaveOpen(false)\n },\n [templateScope, user?.uid, firestore, subject, body, enqueueSnackbar],\n )\n\n /*\n * The address, when the caller had none: one read of the contact, on\n * open. The route reads it again for itself; this one is what the To\n * field prints, and a field that printed nothing until the send answered\n * would ask the rep to write to somebody unnamed.\n */\n useEffect(() => {\n if (!open) return\n const given = normalizeContactEmail(props.email)\n if (given) {\n setRecipient(given)\n return\n }\n if (!contactId || !orgId) return\n let cancelled = false\n void getDoc(doc(firestore, 'orgs', orgId, 'contacts', contactId))\n .then((snapshot) => {\n if (cancelled) return\n setRecipient(normalizeContactEmail(snapshot.get('email')) ?? null)\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecipient(null)\n })\n return () => {\n cancelled = true\n }\n }, [open, props.email, contactId, orgId, firestore])\n\n /*\n * What the platform knows about the address before Send (AGL-3328): a\n * domain with no mail server, or a mail gateway that refused this site's\n * sending domain twice this month. Read off the server's cache — the\n * browser does no DNS — and said as a warning; the route decides.\n */\n const deliverability = useCrmEmailCheck(sendHostId, recipient, { enabled: open })\n\n const replyTo = normalizeContactEmail(user?.email) ?? ''\n const canSend =\n identity.status === 'ready' &&\n Boolean(recipient) &&\n subject.trim().length > 0 &&\n body.trim().length > 0 &&\n !sending\n\n const handleSend = useCallback(async () => {\n if (!canSend) return\n setSending(true)\n setError(null)\n try {\n const { response, payload } = await crmApi('email-send', {\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n ...(dealId ? { dealId } : {}),\n subject: subject.trim(),\n body: body.trim(),\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The email could not be sent.'))\n return\n }\n enqueueSnackbar('Email sent', { variant: 'success', persist: false })\n onSent?.({ activityId: String(payload['activityId'] ?? '') })\n onClose()\n } catch (cause) {\n console.error(cause)\n setError('The email could not be sent.')\n } finally {\n setSending(false)\n }\n }, [canSend, crmApi, contactId, leadId, dealId, subject, body, enqueueSnackbar, onSent, onClose])\n\n const toLabel = props.name && recipient ? `${props.name} <${recipient}>` : (recipient ?? '')\n\n /*\n * The booking door (AGL-2660): a link to one of the sending site's\n * services, dropped where the caret is. The link carries the most\n * specific record this message is about — the deal over its contact, so\n * the booking lands on the deal's timeline as the email does.\n */\n const bookingRef = dealId\n ? { kind: 'deal' as const, id: dealId }\n : leadId\n ? { kind: 'lead' as const, id: leadId }\n : contactId\n ? { kind: 'contact' as const, id: contactId }\n : null\n const handleInsertLink = useCallback((link: string) => {\n const input = messageRef.current\n const current = input?.value ?? ''\n const start = input?.selectionStart ?? current.length\n const end = input?.selectionEnd ?? start\n const next = insertLinkAtCaret(current, link, start, end)\n setBody(next.text)\n // Once the new value has painted, typing continues after the link.\n window.setTimeout(() => {\n input?.focus()\n input?.setSelectionRange(next.caret, next.caret)\n }, 0)\n }, [])\n\n return (\n <Dialog open={open} onClose={sending ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{'Send email'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {!hostId ? (\n <CrmSitePicker\n hostId={hostId}\n label=\"Send from\"\n helperText=\"The site whose sending address the email leaves on.\"\n disabled={sending}\n />\n ) : null}\n {identity.status === 'site' ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {'Pick the site the email leaves from.'}\n </Alert>\n ) : identity.status === 'refused' ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n <Typography variant=\"body2\">{identity.message}</Typography>\n {sendingPath ? (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n <AppLink href={sendingPath}>\n {identity.canManage ? 'Set up sending' : 'See sending'}\n </AppLink>\n </Typography>\n ) : (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {'An admin sets this up under Emails › Sending.'}\n </Typography>\n )}\n </Alert>\n ) : identity.status === 'error' ? (\n <Alert severity=\"error\" sx={{ mt: 1 }}>\n {identity.message}\n </Alert>\n ) : null}\n {open && !recipient && (identity.status === 'ready' || identity.status === 'loading') ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n {'This record has no email address.'}\n </Alert>\n ) : null}\n <TextField\n size=\"small\"\n label=\"To\"\n value={toLabel}\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n sx={{ mt: identity.status === 'ready' || identity.status === 'loading' ? 1 : 0 }}\n />\n <CrmEmailCheckAlert check={deliverability} />\n <TextField\n size=\"small\"\n label=\"From\"\n value={\n identity.status === 'ready'\n ? identity.from\n : identity.status === 'loading'\n ? 'Resolving the site’s sending address…'\n : identity.status === 'site'\n ? 'Pick a site to send from'\n : ''\n }\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n <TextField\n size=\"small\"\n label=\"Reply-to\"\n value={replyTo}\n helperText=\"Replies come to you, not to the site's mailbox.\"\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n {capture.status === 'ready' ? (\n <TextField\n size=\"small\"\n label=\"Log replies\"\n value={capture.address}\n helperText={CAPTURE_ADDRESS_HELPER}\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <InputAdornment position=\"end\">\n <CopyCaptureAddressButton address={capture.address} />\n </InputAdornment>\n ),\n },\n inputLabel: { shrink: true },\n }}\n />\n ) : null}\n {pickable.length ? (\n <CrmTemplatePicker\n templates={pickable}\n value={appliedTemplate}\n onChange={(template) => void applyTemplate(template)}\n disabled={sending}\n />\n ) : null}\n <TextField\n size=\"small\"\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n autoFocus\n slotProps={{ htmlInput: { maxLength: CRM_EMAIL_SUBJECT_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <CrmInsertMenu\n snippets={snippets}\n groups={fieldGroups}\n disabled={sending}\n onInsert={insertAtCaret}\n />\n <Button\n size=\"small\"\n disabled={sending || !templateScope.scope || (!subject.trim() && !body.trim())}\n onClick={() => setSaveOpen(true)}\n >\n {'Save as template…'}\n </Button>\n </Stack>\n <TextField\n size=\"small\"\n label=\"Message\"\n value={body}\n onChange={(event) => setBody(event.target.value)}\n multiline\n minRows={6}\n inputRef={messageRef}\n helperText={\n unresolved.length\n ? crmMergeUnresolvedMessage(unresolved)\n : draftHasFields\n ? 'Plain text. Merge fields are filled in from this record when the email is sent.'\n : 'Plain text. A blank line starts a new paragraph.'\n }\n slotProps={{\n htmlInput: { maxLength: CRM_EMAIL_BODY_MAX },\n formHelperText: { sx: unresolved.length ? { color: 'warning.main' } : undefined },\n }}\n />\n {EmailDraftSlot && draftRecord ? (\n <EmailDraftSlot\n slot=\"recordEmail\"\n // A lead is read on its own site; a contact or a deal at the level\n // the composer was opened at.\n hostId={draftRecord.kind === 'lead' || !mount ? hostId : null}\n orgId={orgId ?? undefined}\n record={{ ...draftRecord, name: String(props.name ?? '') }}\n subject={subject}\n body={body}\n proposeDraft={(draft: ConsoleRecordEmailDraft) => void proposeDraft(draft)}\n />\n ) : null}\n {preview ? (\n <Stack spacing={0.5} data-testid=\"crm-email-preview\">\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Preview — as it will be sent'}\n </Typography>\n <Typography variant=\"subtitle2\">{preview.subject.text}</Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-wrap' }}>\n {preview.body.text}\n </Typography>\n </Stack>\n ) : null}\n {bookingRef ? (\n <CrmRecordBookingZone\n variant=\"chip\"\n hostId={sendHostId}\n org={org}\n kind={bookingRef.kind}\n recordId={bookingRef.id}\n onInsert={handleInsertLink}\n />\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n </DialogContent>\n <CrmSaveAsTemplateDialog\n open={saveOpen}\n onClose={() => setSaveOpen(false)}\n onSave={saveAsTemplate}\n />\n <DialogActions>\n <Button onClick={onClose} disabled={sending}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSend} onClick={handleSend}>\n {sending ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nCrmSendEmailDialog.displayName = 'CrmSendEmailDialog'\n\nexport default CrmSendEmailDialog\n"],"names":["CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","normalizeContactEmail","consentGroupForHost","CRM_COLLECTIONS","createResourceUid","crmMergeUnresolvedMessage","hasCrmMergeFields","resolveCrmMergeFields","useConsoleWidgetSlot","pluginRecordListHref","useSendingApi","AppLink","useConfirmationContext","useSnackbar","useFirestore","useOrgDataScope","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","InputAdornment","Stack","TextField","Typography","collection","doc","getDoc","setDoc","useCallback","useEffect","useMemo","useRef","useState","useCrmOrgMount","CrmRecordBookingZone","insertLinkAtCaret","CAPTURE_ADDRESS_HELPER","CopyCaptureAddressButton","CrmSitePicker","CrmEmailCheckAlert","useCrmEmailCheck","useCrmApi","useCrmInboundAddress","useSiteRouteContext","useCrmEmailTemplates","useCrmEmailTemplateScope","CrmInsertMenu","CrmSaveAsTemplateDialog","CrmTemplatePicker","NO_MERGE_RECORDS","contact","deal","lead","site","loaded","CrmSendEmailDialog","props","hostId","open","onClose","org","contactId","leadId","dealId","onSent","firestore","mount","orgId","undefined","$id","data","user","enqueueSnackbar","sendingApi","sendHostId","createHostId","crmApi","sendSite","capture","enabled","sendingPath","identity","setIdentity","status","recipient","setRecipient","email","subject","setSubject","body","setBody","sending","setSending","error","setError","confirm","templateScope","templates","scope","visibleTo","uid","pickable","filter","row","kind","snippets","appliedTemplate","setAppliedTemplate","saveOpen","setSaveOpen","records","setRecords","messageRef","draftHasFields","fieldGroups","cancelled","senders","payload","response","path","method","query","ok","message","String","refusal","canManage","Array","isArray","from","find","sender","isDefault","read","snapshot","slice","exists","mountedSite","hosts","host","id","Promise","all","deals","then","dealContactId","trim","withContact","resolve","resolvedContact","name","catch","cause","console","mergeContext","contactGroupId","groupId","displayName","preview","unresolved","Set","applyTemplate","template","written","length","accepted","title","description","confirmationText","EmailDraftSlot","proposeDraft","draft","next","draftRecord","insertAtCaret","text","element","current","start","selectionStart","end","selectionEnd","caret","Math","min","window","setTimeout","focus","setSelectionRange","saveAsTemplate","createTokens","Error","now","Date","emailTemplates","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","createdAt","updatedAt","variant","persist","given","get","deliverability","replyTo","canSend","Boolean","handleSend","activityId","toLabel","bookingRef","handleInsertLink","link","input","value","maxWidth","fullWidth","sx","display","flexDirection","gap","label","helperText","disabled","severity","mt","href","size","slotProps","readOnly","inputLabel","shrink","check","address","endAdornment","position","onChange","event","target","autoFocus","htmlInput","maxLength","direction","spacing","justifyContent","groups","onInsert","onClick","multiline","minRows","inputRef","formHelperText","color","slot","record","data-testid","whiteSpace","recordId","onSave"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,kBAAkB,EAClBC,qBAAqB,EACrBC,qBAAqB,EACrBC,mBAAmB,EACnBC,eAAe,EACfC,iBAAiB,EAIjBC,yBAAyB,EACzBC,iBAAiB,EACjBC,qBAAqB,QAChB,eAAc;AACrB,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,oBAAoB,QAAQ,mDAAkD;AAEvF,SAASC,aAAa,QAAQ,gEAA+D;AAC7F,SAASC,OAAO,EAAE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AAW,GAAG;AAEjC,eAAetG,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-send-email-dialog.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n CRM_EMAIL_BODY_MAX,\n CRM_EMAIL_SUBJECT_MAX,\n normalizeContactEmail,\n consentGroupForHost,\n CRM_COLLECTIONS,\n createResourceUid,\n type CrmEmailTemplateRow,\n type CrmMergeContext,\n type CrmMergeFieldGroup,\n crmMergeUnresolvedMessage,\n hasCrmMergeFields,\n resolveCrmMergeFields,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { pluginRecordListHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport type { ConsoleRecordEmailDraft } from '@aglyn/aglyn/plugin-manager/record-zone-props'\nimport { useSendingApi } from '@aglyn/tenant-feature-instance/hooks/use-sending-identity-api'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useOrgDataScope,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n InputAdornment,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, getDoc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { CrmRecordBookingZone } from './crm-booking-zone'\nimport { insertLinkAtCaret } from './insert-link-at-caret'\nimport {\n CAPTURE_ADDRESS_HELPER,\n CopyCaptureAddressButton,\n} from './copy-capture-address-button'\nimport { CrmSitePicker } from './crm-site-picker'\nimport { CrmEmailCheckAlert, useCrmEmailCheck } from './crm-email-check'\nimport { useCrmApi } from './use-crm-api'\nimport { useCrmInboundAddress } from './use-crm-inbound-address'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport {\n useCrmEmailTemplates,\n useCrmEmailTemplateScope,\n} from '../hooks/use-crm-email-templates'\nimport {\n CrmInsertMenu,\n CrmSaveAsTemplateDialog,\n CrmTemplatePicker,\n} from './crm-email-template-tools'\n\n/**\n * The documents a merge-field preview reads (AGL-2658), fetched once per\n * open and only once the draft names a field: a letter with no fields\n * costs no reads. `site` is the sending site's name; `loaded` says the\n * fetch has answered, so the helper text can tell \"no value\" from \"not\n * yet read\".\n */\ninterface MergeRecords {\n contact: Record<string, unknown> | null\n deal: Record<string, unknown> | null\n lead: Record<string, unknown> | null\n site: string | null\n loaded: boolean\n}\n\nconst NO_MERGE_RECORDS: MergeRecords = {\n contact: null,\n deal: null,\n lead: null,\n site: null,\n loaded: false,\n}\n\n/**\n * What the sending-identity route said about this site, as the dialog\n * needs it: an address to print, or the reason there is none — or, at the\n * organization level, that no site has been picked to ask about.\n */\ntype IdentityState =\n | { status: 'loading' }\n | { status: 'site' }\n | { status: 'ready'; from: string }\n | { status: 'refused'; message: string; canManage: boolean }\n | { status: 'error'; message: string }\n\nexport interface CrmSendEmailDialogProps {\n open: boolean\n onClose: () => void\n /**\n * The site the message leaves from — passed in, never assumed from the\n * URL. At the organization level the record's own capturing site, or\n * `null` for a record no site has captured (AGL-2634): the dialog then\n * offers the org's sites to send from, defaulting to the reader's pick.\n */\n hostId: string | null\n /** The org the shell passed; lets a deal's contact be read without a lookup. */\n org?: Partial<AglynOrgBilling> | null\n contactId?: string\n leadId?: string\n dealId?: string\n /**\n * The recipient as the record shows it. A deal's page holds no address,\n * so a caller with only a `contactId` may leave this out and the dialog\n * reads it off the contact when it opens.\n */\n email?: string | null\n /** What the dialog says it is writing to, beside the address. */\n name?: string | null\n /** Told once the route has accepted the message. */\n onSent?: (result: { activityId: string }) => void\n}\n\n/**\n * One email to one person, from their record (AGL-2615).\n *\n * ## What the reader sees, and what they cannot change\n *\n * To is the record's address and is read-only: the route resolves the\n * recipient off the record again, so an editable field here would be a\n * promise the server does not keep. From is the site's sending identity as\n * the sending-identity route reports it — the same answer the campaign\n * composer prints — and when that route refuses, the dialog says why and\n * points at **Emails › Sending** rather than offering a Send button that\n * 409s. Reply-to is the signed-in user's own address, because a reply to a\n * relationship email belongs in the inbox of the person who wrote it, not\n * the site's shared mailbox. Subject and Body are the whole of what a\n * person writes; the body is plain paragraphs, and the email design system\n * is deliberately not here — this is a letter, not a campaign.\n *\n * ## A refusal stays on screen\n *\n * The route's refusals — the daily cap, a suppressed address, a stated\n * refusal, the ceiling — are answers the rep should read, so they render\n * inside the dialog with the draft intact rather than as a toast over a\n * closed one. Only a send the provider accepted closes it.\n *\n * Mounted on open by its button, so the identity request and the contact\n * read happen when somebody asks and not on every record page paint.\n */\nexport function CrmSendEmailDialog(props: CrmSendEmailDialogProps) {\n const { open, onClose, hostId, org, contactId, leadId, dealId, onSent } = props\n const firestore = useFirestore()\n const mount = useCrmOrgMount()\n const { orgId } = useOrgDataScope({\n hostId: hostId ?? undefined,\n orgId: org?.$id ?? mount?.orgId,\n })\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const sendingApi = useSendingApi()\n /*\n * The site the message LEAVES FROM: the record's own, or at the\n * organization level — for a record no site captured — the site the\n * reader picked (AGL-2634). The identity, the suppression list and the\n * person's stated refusal are each that site's, which is why the org\n * level cannot do without one.\n */\n const sendHostId = hostId ?? mount?.createHostId ?? null\n const crmApi = useCrmApi(sendHostId)\n const sendSite = useSiteRouteContext(sendHostId)\n // The capture address (AGL-2657), for the reply this send will get: the\n // console logs what IT sends, so the address is shown to be forwarded\n // to or copied from a mailbox, never put on this message.\n const capture = useCrmInboundAddress(sendHostId, { enabled: open })\n // Where the site's sending identities are kept — the page that fixes a\n // missing one, at the address the plugin that keeps them publishes as\n // `sendingIdentity` (AGL-3080). `null` on a surface that cannot name the\n // site, or where nothing publishes the kind, so the refusal prints the\n // section's name instead of a link to nowhere.\n const sendingPath = sendSite ? pluginRecordListHref('sendingIdentity', sendSite) : null\n\n const [identity, setIdentity] = useState<IdentityState>({ status: 'loading' })\n const [recipient, setRecipient] = useState<string | null>(\n normalizeContactEmail(props.email) ?? null,\n )\n const [subject, setSubject] = useState('')\n const [body, setBody] = useState('')\n const [sending, setSending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n /*\n * TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658). The listener is the\n * dialog's own scope — the mounted site's tokens, or none at the org\n * level — and what a saved template is stamped with follows the same\n * rule. The message field's element is held so a snippet lands at the\n * caret rather than at the end.\n */\n const { confirm } = useConfirmationContext()\n const templateScope = useCrmEmailTemplateScope({ hostId, org })\n const { templates } = useCrmEmailTemplates({\n scope: templateScope.scope,\n visibleTo: templateScope.visibleTo,\n uid: user?.uid,\n })\n const pickable = useMemo(() => templates.filter((row) => row.kind === 'template'), [templates])\n const snippets = useMemo(() => templates.filter((row) => row.kind === 'snippet'), [templates])\n const [appliedTemplate, setAppliedTemplate] = useState<CrmEmailTemplateRow | null>(null)\n const [saveOpen, setSaveOpen] = useState(false)\n const [records, setRecords] = useState<MergeRecords>(NO_MERGE_RECORDS)\n const messageRef = useRef<HTMLTextAreaElement | null>(null)\n const draftHasFields = hasCrmMergeFields(`${subject}\\n${body}`)\n // The groups the Insert menu offers: what the record can answer.\n const fieldGroups = useMemo<CrmMergeFieldGroup[]>(\n () => [\n ...(contactId || dealId ? (['Contact'] as const) : []),\n ...(leadId && !contactId ? (['Lead'] as const) : []),\n ...(dealId ? (['Deal'] as const) : []),\n 'You',\n 'Site',\n ],\n [contactId, dealId, leadId],\n )\n\n /*\n * The identity, asked for on open. The route is the send path's own\n * resolver, so what it prints here is what the message will leave as; a\n * dialog that derived \"verified\" from the domain list would be a second\n * opinion that drifts from the send.\n */\n useEffect(() => {\n if (!open) return\n let cancelled = false\n setError(null)\n // The draft survives a change of sending site — the site is not the\n // letter — and is cleared only when the dialog opens.\n if (!sendHostId) {\n setIdentity({ status: 'site' })\n return undefined\n }\n setIdentity({ status: 'loading' })\n void (async () => {\n const { response, payload } = await sendingApi({\n path: 'sending-identity',\n method: 'GET',\n query: { hostId: sendHostId },\n })\n if (cancelled) return\n if (!response.ok) {\n setIdentity({\n status: 'error',\n message: String(payload['error'] ?? 'The sending identity could not be read.'),\n })\n return\n }\n const refusal = payload['refusal'] as { message?: string } | null\n if (refusal) {\n setIdentity({\n status: 'refused',\n message: String(refusal.message ?? 'This site has no verified sending identity.'),\n canManage: payload['canManage'] === true,\n })\n return\n }\n const senders = Array.isArray(payload['senders'])\n ? (payload['senders'] as { isDefault?: boolean; from?: string | null }[])\n : []\n const from =\n senders.find((sender) => sender.isDefault && sender.from)?.from ??\n senders.find((sender) => sender.from)?.from ??\n null\n setIdentity(\n from\n ? { status: 'ready', from }\n : {\n status: 'error',\n message: String(payload['identity'] ?? 'No sending address is in effect.'),\n },\n )\n })()\n return () => {\n cancelled = true\n }\n }, [open, sendHostId, sendingApi])\n useEffect(() => {\n if (!open) return\n setSubject('')\n setBody('')\n setAppliedTemplate(null)\n setSaveOpen(false)\n setRecords(NO_MERGE_RECORDS)\n }, [open])\n\n /*\n * The documents a preview reads, fetched the first time the draft names\n * a merge field and kept for the rest of the open: the contact, the\n * deal, the lead, and the sending site's name — off the org mount when\n * it knows the site, off the host document otherwise. The route reads\n * the same documents again for the send; these are what the rep sees.\n */\n useEffect(() => {\n if (!open || !draftHasFields || records.loaded) return\n let cancelled = false\n const read = async (path: string[] | null): Promise<Record<string, unknown> | null> => {\n if (!path) return null\n const snapshot = await getDoc(doc(firestore, path[0], ...path.slice(1)))\n return snapshot.exists() ? ((snapshot.data() ?? null) as Record<string, unknown> | null) : null\n }\n const mountedSite = sendHostId\n ? (mount?.hosts ?? []).find((host) => host.id === sendHostId)\n : undefined\n void Promise.all([\n read(contactId && orgId ? ['orgs', orgId, 'contacts', contactId] : null),\n read(dealId && orgId ? ['orgs', orgId, CRM_COLLECTIONS.deals, dealId] : null),\n // One org row (AGL-3275); the site still decides WHICH lead is offered,\n // but not where it lives.\n read(leadId && orgId ? ['orgs', orgId, 'leads', leadId] : null),\n mountedSite || !sendHostId ? null : read(['hosts', sendHostId]),\n ])\n .then(([contact, deal, lead, host]) => {\n if (cancelled) return\n // A deal's contact, when the page named only the deal.\n const dealContactId = String(deal?.['contactId'] ?? '').trim()\n const withContact =\n !contact && dealContactId && orgId\n ? read(['orgs', orgId, 'contacts', dealContactId])\n : Promise.resolve(contact)\n return withContact.then((resolvedContact) => {\n if (cancelled) return\n setRecords({\n contact: resolvedContact,\n deal,\n lead,\n site: mountedSite?.name ?? (host ? String(host['displayName'] ?? '') : null),\n loaded: true,\n })\n })\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecords({ ...NO_MERGE_RECORDS, loaded: true })\n })\n return () => {\n cancelled = true\n }\n }, [\n open,\n draftHasFields,\n records.loaded,\n firestore,\n orgId,\n contactId,\n dealId,\n leadId,\n sendHostId,\n mount?.hosts,\n ])\n\n const mergeContext = useMemo<CrmMergeContext>(\n () => ({\n contact: records.contact,\n contactGroupId: sendHostId ? consentGroupForHost(org ?? null, sendHostId).groupId : null,\n deal: records.deal,\n lead: records.lead,\n sender: { name: user?.displayName ?? '', email: user?.email ?? '' },\n site: { name: records.site ?? '' },\n }),\n [records, sendHostId, org, user?.displayName, user?.email],\n )\n const preview = useMemo(\n () =>\n draftHasFields && records.loaded\n ? {\n subject: resolveCrmMergeFields(subject, mergeContext),\n body: resolveCrmMergeFields(body, mergeContext),\n }\n : null,\n [draftHasFields, records.loaded, subject, body, mergeContext],\n )\n const unresolved = useMemo(\n () =>\n preview\n ? [...new Set([...preview.subject.unresolved, ...preview.body.unresolved])]\n : [],\n [preview],\n )\n\n /** A template into both fields — asking first when a message is already written. */\n const applyTemplate = useCallback(\n async (template: CrmEmailTemplateRow | null) => {\n if (!template) {\n setAppliedTemplate(null)\n return\n }\n const written = body.trim().length > 0 && body !== appliedTemplate?.body\n if (written) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: `\"${template.name}\" replaces what you have written in the subject and the message.`,\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n if (template.subject) setSubject(template.subject)\n setBody(template.body)\n setAppliedTemplate(template)\n },\n [body, appliedTemplate, confirm],\n )\n\n /*\n * The `recordEmail` zone (AGL-2917), hosted through the shell's renderer: a\n * widget there proposes a subject and a message, which land in the fields\n * above like a template does, asking first when a message is already\n * written. Send is still the only write, and the zone reads the record the\n * message is written from: the deal over its contact, a lead on its own site,\n * and at the organization level a contact or a deal the org reads.\n */\n const EmailDraftSlot = useConsoleWidgetSlot()\n const proposeDraft = useCallback(\n async (draft: ConsoleRecordEmailDraft) => {\n const next = { subject: draft.subject.slice(0, CRM_EMAIL_SUBJECT_MAX), body: draft.body.slice(0, CRM_EMAIL_BODY_MAX) }\n if (body.trim() && body !== next.body) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: 'The draft replaces what you have written in the subject and the message.',\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setSubject(next.subject)\n setBody(next.body)\n setAppliedTemplate(null)\n },\n [body, confirm],\n )\n const draftRecord = dealId\n ? { kind: 'deal', id: dealId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : contactId\n ? { kind: 'contact', id: contactId }\n : null\n\n /** A snippet or a field where the caret is, the caret moved past it. */\n const insertAtCaret = useCallback(\n (text: string) => {\n const element = messageRef.current\n const start = element?.selectionStart ?? body.length\n const end = element?.selectionEnd ?? body.length\n const next = `${body.slice(0, start)}${text}${body.slice(end)}`.slice(0, CRM_EMAIL_BODY_MAX)\n setBody(next)\n const caret = Math.min(start + text.length, next.length)\n window.setTimeout(() => {\n element?.focus()\n element?.setSelectionRange(caret, caret)\n }, 0)\n },\n [body],\n )\n\n /**\n * The draft kept as a template, stamped as this surface's scope stamps\n * every CRM record — the site's tokens under a site, the org token from\n * the organization's hub — and, when personal, owned by the writer.\n */\n const saveAsTemplate = useCallback(\n async (draft: { name: string; visibility: 'shared' | 'personal' }) => {\n const scope = templateScope.scope\n const uid = user?.uid\n if (!scope || !uid || templateScope.createTokens.length === 0) {\n throw new Error('a template needs an organization and a signed-in writer')\n }\n const now = Date.now()\n await setDoc(\n doc(collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.emailTemplates), createResourceUid()),\n {\n name: draft.name,\n subject: subject.trim(),\n body: body.trim(),\n kind: 'template',\n visibility: draft.visibility,\n ...(draft.visibility === 'personal' ? { ownerUid: uid } : {}),\n createdByUid: uid,\n createdAtMs: now,\n updatedAtMs: now,\n hostId: templateScope.createHostId,\n visibleTo: [...templateScope.createTokens],\n createdAt: new Date(now),\n updatedAt: new Date(now),\n },\n )\n enqueueSnackbar(`Template \"${draft.name}\" saved`, { variant: 'success', persist: false })\n setSaveOpen(false)\n },\n [templateScope, user?.uid, firestore, subject, body, enqueueSnackbar],\n )\n\n /*\n * The address, when the caller had none: one read of the contact, on\n * open. The route reads it again for itself; this one is what the To\n * field prints, and a field that printed nothing until the send answered\n * would ask the rep to write to somebody unnamed.\n */\n useEffect(() => {\n if (!open) return\n const given = normalizeContactEmail(props.email)\n if (given) {\n setRecipient(given)\n return\n }\n if (!contactId || !orgId) return\n let cancelled = false\n void getDoc(doc(firestore, 'orgs', orgId, 'contacts', contactId))\n .then((snapshot) => {\n if (cancelled) return\n setRecipient(normalizeContactEmail(snapshot.get('email')) ?? null)\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecipient(null)\n })\n return () => {\n cancelled = true\n }\n }, [open, props.email, contactId, orgId, firestore])\n\n /*\n * What the platform knows about the address before Send (AGL-3328): a\n * domain with no mail server, or a mail gateway that refused this site's\n * sending domain twice this month. Read off the server's cache — the\n * browser does no DNS — and said as a warning; the route decides.\n */\n const deliverability = useCrmEmailCheck(sendHostId, recipient, { enabled: open })\n\n const replyTo = normalizeContactEmail(user?.email) ?? ''\n const canSend =\n identity.status === 'ready' &&\n Boolean(recipient) &&\n subject.trim().length > 0 &&\n body.trim().length > 0 &&\n !sending\n\n const handleSend = useCallback(async () => {\n if (!canSend) return\n setSending(true)\n setError(null)\n try {\n const { response, payload } = await crmApi('email-send', {\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n ...(dealId ? { dealId } : {}),\n subject: subject.trim(),\n body: body.trim(),\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The email could not be sent.'))\n return\n }\n enqueueSnackbar('Email sent', { variant: 'success', persist: false })\n onSent?.({ activityId: String(payload['activityId'] ?? '') })\n onClose()\n } catch (cause) {\n console.error(cause)\n setError('The email could not be sent.')\n } finally {\n setSending(false)\n }\n }, [canSend, crmApi, contactId, leadId, dealId, subject, body, enqueueSnackbar, onSent, onClose])\n\n const toLabel = props.name && recipient ? `${props.name} <${recipient}>` : (recipient ?? '')\n\n /*\n * The booking door (AGL-2660): a link to one of the sending site's\n * services, dropped where the caret is. The link carries the most\n * specific record this message is about — the deal over its contact, so\n * the booking lands on the deal's timeline as the email does.\n */\n const bookingRef = dealId\n ? { kind: 'deal' as const, id: dealId }\n : leadId\n ? { kind: 'lead' as const, id: leadId }\n : contactId\n ? { kind: 'contact' as const, id: contactId }\n : null\n const handleInsertLink = useCallback((link: string) => {\n const input = messageRef.current\n const current = input?.value ?? ''\n const start = input?.selectionStart ?? current.length\n const end = input?.selectionEnd ?? start\n const next = insertLinkAtCaret(current, link, start, end)\n setBody(next.text)\n // Once the new value has painted, typing continues after the link.\n window.setTimeout(() => {\n input?.focus()\n input?.setSelectionRange(next.caret, next.caret)\n }, 0)\n }, [])\n\n return (\n <Dialog open={open} onClose={sending ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{'Send email'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {!hostId ? (\n <CrmSitePicker\n hostId={hostId}\n label=\"Send from\"\n helperText=\"The site whose sending address the email leaves on.\"\n disabled={sending}\n />\n ) : null}\n {identity.status === 'site' ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {'Pick the site the email leaves from.'}\n </Alert>\n ) : identity.status === 'refused' ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n <Typography variant=\"body2\">{identity.message}</Typography>\n {sendingPath ? (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n <AppLink href={sendingPath}>\n {identity.canManage ? 'Set up sending' : 'See sending'}\n </AppLink>\n </Typography>\n ) : (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {'A member holding \"Organization settings\" sets this up under Emails › Sending.'}\n </Typography>\n )}\n </Alert>\n ) : identity.status === 'error' ? (\n <Alert severity=\"error\" sx={{ mt: 1 }}>\n {identity.message}\n </Alert>\n ) : null}\n {open && !recipient && (identity.status === 'ready' || identity.status === 'loading') ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n {'This record has no email address.'}\n </Alert>\n ) : null}\n <TextField\n size=\"small\"\n label=\"To\"\n value={toLabel}\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n sx={{ mt: identity.status === 'ready' || identity.status === 'loading' ? 1 : 0 }}\n />\n <CrmEmailCheckAlert check={deliverability} />\n <TextField\n size=\"small\"\n label=\"From\"\n value={\n identity.status === 'ready'\n ? identity.from\n : identity.status === 'loading'\n ? 'Resolving the site’s sending address…'\n : identity.status === 'site'\n ? 'Pick a site to send from'\n : ''\n }\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n <TextField\n size=\"small\"\n label=\"Reply-to\"\n value={replyTo}\n helperText=\"Replies come to you, not to the site's mailbox.\"\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n {capture.status === 'ready' ? (\n <TextField\n size=\"small\"\n label=\"Log replies\"\n value={capture.address}\n helperText={CAPTURE_ADDRESS_HELPER}\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <InputAdornment position=\"end\">\n <CopyCaptureAddressButton address={capture.address} />\n </InputAdornment>\n ),\n },\n inputLabel: { shrink: true },\n }}\n />\n ) : null}\n {pickable.length ? (\n <CrmTemplatePicker\n templates={pickable}\n value={appliedTemplate}\n onChange={(template) => void applyTemplate(template)}\n disabled={sending}\n />\n ) : null}\n <TextField\n size=\"small\"\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n autoFocus\n slotProps={{ htmlInput: { maxLength: CRM_EMAIL_SUBJECT_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <CrmInsertMenu\n snippets={snippets}\n groups={fieldGroups}\n disabled={sending}\n onInsert={insertAtCaret}\n />\n <Button\n size=\"small\"\n disabled={sending || !templateScope.scope || (!subject.trim() && !body.trim())}\n onClick={() => setSaveOpen(true)}\n >\n {'Save as template…'}\n </Button>\n </Stack>\n <TextField\n size=\"small\"\n label=\"Message\"\n value={body}\n onChange={(event) => setBody(event.target.value)}\n multiline\n minRows={6}\n inputRef={messageRef}\n helperText={\n unresolved.length\n ? crmMergeUnresolvedMessage(unresolved)\n : draftHasFields\n ? 'Plain text. Merge fields are filled in from this record when the email is sent.'\n : 'Plain text. A blank line starts a new paragraph.'\n }\n slotProps={{\n htmlInput: { maxLength: CRM_EMAIL_BODY_MAX },\n formHelperText: { sx: unresolved.length ? { color: 'warning.main' } : undefined },\n }}\n />\n {EmailDraftSlot && draftRecord ? (\n <EmailDraftSlot\n slot=\"recordEmail\"\n // A lead is read on its own site; a contact or a deal at the level\n // the composer was opened at.\n hostId={draftRecord.kind === 'lead' || !mount ? hostId : null}\n orgId={orgId ?? undefined}\n record={{ ...draftRecord, name: String(props.name ?? '') }}\n subject={subject}\n body={body}\n proposeDraft={(draft: ConsoleRecordEmailDraft) => void proposeDraft(draft)}\n />\n ) : null}\n {preview ? (\n <Stack spacing={0.5} data-testid=\"crm-email-preview\">\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Preview — as it will be sent'}\n </Typography>\n <Typography variant=\"subtitle2\">{preview.subject.text}</Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-wrap' }}>\n {preview.body.text}\n </Typography>\n </Stack>\n ) : null}\n {bookingRef ? (\n <CrmRecordBookingZone\n variant=\"chip\"\n hostId={sendHostId}\n org={org}\n kind={bookingRef.kind}\n recordId={bookingRef.id}\n onInsert={handleInsertLink}\n />\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n </DialogContent>\n <CrmSaveAsTemplateDialog\n open={saveOpen}\n onClose={() => setSaveOpen(false)}\n onSave={saveAsTemplate}\n />\n <DialogActions>\n <Button onClick={onClose} disabled={sending}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSend} onClick={handleSend}>\n {sending ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nCrmSendEmailDialog.displayName = 'CrmSendEmailDialog'\n\nexport default CrmSendEmailDialog\n"],"names":["CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","normalizeContactEmail","consentGroupForHost","CRM_COLLECTIONS","createResourceUid","crmMergeUnresolvedMessage","hasCrmMergeFields","resolveCrmMergeFields","useConsoleWidgetSlot","pluginRecordListHref","useSendingApi","AppLink","useConfirmationContext","useSnackbar","useFirestore","useOrgDataScope","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","InputAdornment","Stack","TextField","Typography","collection","doc","getDoc","setDoc","useCallback","useEffect","useMemo","useRef","useState","useCrmOrgMount","CrmRecordBookingZone","insertLinkAtCaret","CAPTURE_ADDRESS_HELPER","CopyCaptureAddressButton","CrmSitePicker","CrmEmailCheckAlert","useCrmEmailCheck","useCrmApi","useCrmInboundAddress","useSiteRouteContext","useCrmEmailTemplates","useCrmEmailTemplateScope","CrmInsertMenu","CrmSaveAsTemplateDialog","CrmTemplatePicker","NO_MERGE_RECORDS","contact","deal","lead","site","loaded","CrmSendEmailDialog","props","hostId","open","onClose","org","contactId","leadId","dealId","onSent","firestore","mount","orgId","undefined","$id","data","user","enqueueSnackbar","sendingApi","sendHostId","createHostId","crmApi","sendSite","capture","enabled","sendingPath","identity","setIdentity","status","recipient","setRecipient","email","subject","setSubject","body","setBody","sending","setSending","error","setError","confirm","templateScope","templates","scope","visibleTo","uid","pickable","filter","row","kind","snippets","appliedTemplate","setAppliedTemplate","saveOpen","setSaveOpen","records","setRecords","messageRef","draftHasFields","fieldGroups","cancelled","senders","payload","response","path","method","query","ok","message","String","refusal","canManage","Array","isArray","from","find","sender","isDefault","read","snapshot","slice","exists","mountedSite","hosts","host","id","Promise","all","deals","then","dealContactId","trim","withContact","resolve","resolvedContact","name","catch","cause","console","mergeContext","contactGroupId","groupId","displayName","preview","unresolved","Set","applyTemplate","template","written","length","accepted","title","description","confirmationText","EmailDraftSlot","proposeDraft","draft","next","draftRecord","insertAtCaret","text","element","current","start","selectionStart","end","selectionEnd","caret","Math","min","window","setTimeout","focus","setSelectionRange","saveAsTemplate","createTokens","Error","now","Date","emailTemplates","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","createdAt","updatedAt","variant","persist","given","get","deliverability","replyTo","canSend","Boolean","handleSend","activityId","toLabel","bookingRef","handleInsertLink","link","input","value","maxWidth","fullWidth","sx","display","flexDirection","gap","label","helperText","disabled","severity","mt","href","size","slotProps","readOnly","inputLabel","shrink","check","address","endAdornment","position","onChange","event","target","autoFocus","htmlInput","maxLength","direction","spacing","justifyContent","groups","onInsert","onClick","multiline","minRows","inputRef","formHelperText","color","slot","record","data-testid","whiteSpace","rec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,KAAC/E;wBAAMqN,UAAS;kCAAStI;yBAAiB;;;0BAErD,KAAC9C;gBACCW,MAAMkD;gBACNjD,SAAS,IAAMkD,YAAY;gBAC3BwJ,QAAQxE;;0BAEV,MAAC5K;;kCACC,KAACF;wBAAO2O,SAAS/L;wBAASuK,UAAUvI;kCACjC;;kCAEH,KAAC5E;wBAAO2L,SAAQ;wBAAYqD,OAAM;wBAAU7B,UAAU,CAAClB;wBAAS0C,SAASxC;kCACtEvH,UAAU,aAAa;;;;;;AAKlC;AACApC,mBAAmBsG,WAAW,GAAG;AAEjC,eAAetG,mBAAkB"}
@@ -77,6 +77,8 @@ export interface ErasePersonDialogProps {
77
77
  onClose: () => void;
78
78
  /** The site the request is filed from, or `null` beneath the org hub's mount. */
79
79
  hostId: string | null;
80
+ /** The workspace whose plugins answer what an erasure keeps. */
81
+ orgId: string | null | undefined;
80
82
  subject: ErasePersonSubject;
81
83
  /** Called with the request's queue time once the route has filed it. */
82
84
  onFiled: (pendingSinceMs: number) => void;
@@ -87,6 +89,9 @@ export interface ErasePersonDialogProps {
87
89
  * — the address is closed to capture at once, and the sweep runs with the
88
90
  * nightly job. The admin types the address back; the route checks the same
89
91
  * match before it files anything.
92
+ *
93
+ * What a plugin keeps (a signed waiver, AGL-4042) is asked when the dialog
94
+ * opens, not with every record page, and never holds the confirm back.
90
95
  */
91
96
  export declare function ErasePersonDialog(props: ErasePersonDialogProps): import("react").JSX.Element;
92
97
  export declare namespace ErasePersonDialog {
@@ -16,10 +16,12 @@
16
16
  */ 'use client';
17
17
  import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
19
- import { PERSON_ERASURE_NOT_REACHED, PERSON_ERASURE_REMOVES, PERSON_ERASURE_RETAINS, personErasureConfirmationMatches } from "@aglyn/aglyn";
19
+ import { PERSON_ERASURE_NOT_REACHED, PERSON_ERASURE_NOTES_HEADING, PERSON_ERASURE_NOTES_UNAVAILABLE, PERSON_ERASURE_REMOVES, PERSON_ERASURE_RETAINS, personErasureConfirmationMatches } from "@aglyn/aglyn";
20
20
  import { mdiAccountOffOutline } from "@aglyn/shared-data-mdi";
21
21
  import { MdiIcon } from "@aglyn/shared-ui-jsx";
22
22
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
23
+ import { useUser } from "@aglyn/tenant-feature-instance";
24
+ import { usePersonErasureNotes } from "@aglyn/tenant-feature-instance/hooks/use-person-erasure-notes";
23
25
  import { Alert, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, List, ListItem, ListItemText, Stack, TextField, Typography } from "@mui/material";
24
26
  import { useEffect, useMemo, useState } from "react";
25
27
  import { useCrmOrgMount } from "../hooks/use-crm-org-mount.js";
@@ -85,6 +87,7 @@ import { useCrmApi } from "./use-crm-api.js";
85
87
  open: open,
86
88
  onClose: ()=>setOpen(false),
87
89
  hostId: hostId,
90
+ orgId: orgId,
88
91
  subject: subject,
89
92
  onFiled: (atMs)=>setFiledAtMs(atMs)
90
93
  }) : null;
@@ -119,8 +122,13 @@ ErasurePendingBanner.displayName = 'ErasurePendingBanner';
119
122
  * — the address is closed to capture at once, and the sweep runs with the
120
123
  * nightly job. The admin types the address back; the route checks the same
121
124
  * match before it files anything.
125
+ *
126
+ * What a plugin keeps (a signed waiver, AGL-4042) is asked when the dialog
127
+ * opens, not with every record page, and never holds the confirm back.
122
128
  */ export function ErasePersonDialog(props) {
123
- const { open, onClose, hostId, subject, onFiled } = props;
129
+ const { open, onClose, hostId, orgId, subject, onFiled } = props;
130
+ const { data: user } = useUser();
131
+ const erasureNotes = usePersonErasureNotes(user, open ? orgId : null);
124
132
  const call = useCrmApi(hostId);
125
133
  const { enqueueSnackbar } = useSnackbar();
126
134
  const [typed, setTyped] = useState('');
@@ -189,10 +197,18 @@ ErasurePendingBanner.displayName = 'ErasurePendingBanner';
189
197
  heading: "Kept, with the person taken off",
190
198
  lines: PERSON_ERASURE_RETAINS
191
199
  }),
200
+ erasureNotes.lines.length ? /*#__PURE__*/ _jsx(ListBlock, {
201
+ heading: PERSON_ERASURE_NOTES_HEADING,
202
+ lines: erasureNotes.lines
203
+ }) : null,
192
204
  /*#__PURE__*/ _jsx(ListBlock, {
193
205
  heading: "Not reached — finish these by hand",
194
206
  lines: PERSON_ERASURE_NOT_REACHED
195
207
  }),
208
+ erasureNotes.unavailable ? /*#__PURE__*/ _jsx(Alert, {
209
+ severity: "info",
210
+ children: PERSON_ERASURE_NOTES_UNAVAILABLE
211
+ }) : null,
196
212
  /*#__PURE__*/ _jsx(TextField, {
197
213
  label: "Type the email address to confirm",
198
214
  value: typed,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/erase-person-action.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n PERSON_ERASURE_NOT_REACHED,\n PERSON_ERASURE_REMOVES,\n PERSON_ERASURE_RETAINS,\n personErasureConfirmationMatches,\n} from '@aglyn/aglyn'\nimport { mdiAccountOffOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n List,\n ListItem,\n ListItemText,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { type ReactNode, useEffect, useMemo, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCanErasePeople } from './use-can-erase-people'\nimport { useCrmApi } from './use-crm-api'\n\n/** The record the action is offered on: which kind, its id, and its address. */\nexport type ErasePersonSubject =\n | { kind: 'contact'; id: string; email: string }\n | { kind: 'lead'; id: string; email: string }\n\nexport interface UseErasePersonActionProps {\n /**\n * The site the request is filed from — the route logs it on that site's\n * feed. At the organization level the record's own capturing site\n * (AGL-2630), or `null` for a record no site has captured: beneath the\n * org hub's mount the route's org variant files it anyway (AGL-2634), and\n * only a surface mounted nowhere holds the item.\n */\n hostId: string | null\n orgId: string | null | undefined\n /** Null while the record has not loaded; the item is then disabled. */\n subject: ErasePersonSubject | null\n /** The record's marker, when a request is already waiting. */\n requestedAtMs: number | null\n}\n\nexport interface ErasePersonAction {\n /** Zero or one item, to spread into the record header's overflow menu. */\n menuItems: RowActionsMenuItem[]\n /** The pending banner, or null. Render it where the record's cards begin. */\n banner: ReactNode\n /** The dialog. Render it once, anywhere in the page. */\n dialog: ReactNode\n /**\n * When the waiting request was filed, or null while none waits: the\n * record's marker, or the route's answer until the listener carries the\n * marker. What a page gates its other acts on — Convert, on a lead — so\n * they close the moment the item does.\n */\n pendingSinceMs: number | null\n}\n\n/**\n * **Erase this person** on a record page (AGL-2623).\n *\n * Owned by a hook rather than a component because the overflow menu takes\n * items as data: the page spreads `menuItems` into its own list, renders\n * `banner` under the header and `dialog` at the end, and everything the\n * action knows — who may, whether a request is already waiting, what the\n * dialog says, what the route answers — lives here.\n *\n * Offered to whoever holds \"Privacy requests\" (`org.privacy`, AGL-4047) over\n * the whole workspace — owners and admins by default — and the item is\n * present but disabled for everyone else with the reason as its tooltip: an\n * absent item and an inapplicable one look alike, and a site editor who\n * cannot find the action should learn who can rather than conclude it does\n * not exist.\n *\n * Takes the site from the page and the workspace from `useOrgDataScope`,\n * never a route, so an org-level mount can offer the same item.\n */\nexport function useErasePersonAction(props: UseErasePersonActionProps): ErasePersonAction {\n const { hostId, orgId, subject, requestedAtMs } = props\n const { canErase, ready } = useCanErasePeople(orgId ?? undefined)\n const orgMount = useCrmOrgMount()\n // A site to file from, or the org to file as (AGL-2634).\n const canFile = Boolean(hostId) || Boolean(orgMount)\n const [open, setOpen] = useState(false)\n // The marker arrives on the record's own document, so a request filed on\n // this page shows as pending the moment the listener catches up — and,\n // until it does, the moment the route answered.\n const [filedAtMs, setFiledAtMs] = useState<number | null>(null)\n const pendingSince = requestedAtMs ?? filedAtMs\n\n const menuItems = useMemo<RowActionsMenuItem[]>(() => {\n const disabledReason = !subject\n ? 'The record has not loaded'\n : !canFile\n ? 'No site has captured this person to file from'\n : pendingSince\n ? 'An erasure is already pending for this person'\n : !ready\n ? 'Checking your workspace role'\n : !canErase\n ? 'Your role does not include \"Privacy requests\" — ask an organization admin'\n : undefined\n return [\n {\n key: 'erase-person',\n label: 'Erase this person',\n icon: <MdiIcon path={mdiAccountOffOutline.path} size={0.8} />,\n destructive: true,\n disabled: Boolean(disabledReason),\n disabledReason,\n onClick: () => setOpen(true),\n },\n ]\n }, [canErase, canFile, pendingSince, ready, subject])\n\n const banner = pendingSince ? <ErasurePendingBanner requestedAtMs={pendingSince} /> : null\n const dialog = subject && canFile ? (\n <ErasePersonDialog\n open={open}\n onClose={() => setOpen(false)}\n hostId={hostId}\n subject={subject}\n onFiled={(atMs) => setFiledAtMs(atMs)}\n />\n ) : null\n\n return { menuItems, banner, dialog, pendingSinceMs: pendingSince }\n}\n\nexport interface ErasurePendingBannerProps {\n requestedAtMs: number\n}\n\n/**\n * The state a record wears between the request and the run. Says when it\n * was asked and what will happen, so a reader arriving cold neither files\n * it again nor keeps working the record.\n */\nexport function ErasurePendingBanner(props: ErasurePendingBannerProps) {\n const { requestedAtMs } = props\n return (\n <Alert severity=\"warning\" data-testid=\"erasure-pending-banner\">\n <strong>{'Erasure pending. '}</strong>\n {`Requested ${new Date(requestedAtMs).toLocaleString()}. The nightly erasure ` +\n 'job removes this person from every site in the workspace; until then the ' +\n 'record is kept only so the request can be seen. Nothing new should be added ' +\n 'to it.'}\n </Alert>\n )\n}\nErasurePendingBanner.displayName = 'ErasurePendingBanner'\n\nexport interface ErasePersonDialogProps {\n open: boolean\n onClose: () => void\n /** The site the request is filed from, or `null` beneath the org hub's mount. */\n hostId: string | null\n subject: ErasePersonSubject\n /** Called with the request's queue time once the route has filed it. */\n onFiled: (pendingSinceMs: number) => void\n}\n\n/**\n * The confirmation: everything the request removes, everything it keeps\n * and how, what it does not reach, and the two facts that follow the click\n * — the address is closed to capture at once, and the sweep runs with the\n * nightly job. The admin types the address back; the route checks the same\n * match before it files anything.\n */\nexport function ErasePersonDialog(props: ErasePersonDialogProps) {\n const { open, onClose, hostId, subject, onFiled } = props\n const call = useCrmApi(hostId)\n const { enqueueSnackbar } = useSnackbar()\n const [typed, setTyped] = useState('')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (open) setTyped('')\n }, [open])\n const confirmed = personErasureConfirmationMatches(typed, subject.email)\n\n const submit = async () => {\n if (!confirmed || busy) return\n setBusy(true)\n try {\n const { response, payload } = await call('erase-person', {\n ...(subject.kind === 'contact' ? { contactId: subject.id } : { leadId: subject.id }),\n email: typed.trim(),\n })\n if (!response.ok) {\n throw new Error(String(payload['error'] ?? 'The erasure could not be filed'))\n }\n onFiled(Number(payload['pendingSinceMs'] ?? Date.now()))\n enqueueSnackbar(\n payload['alreadyPending']\n ? 'An erasure was already pending for this person'\n : 'Erasure requested — it runs with the nightly job',\n { variant: 'success', persist: false },\n )\n onClose()\n } catch (error) {\n enqueueSnackbar(error instanceof Error ? error.message : 'The erasure could not be filed', {\n variant: 'error',\n })\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{`Erase ${subject.email} from this workspace?`}</DialogTitle>\n <DialogContent>\n <DialogContentText sx={{ mb: 2 }}>\n {'This is a privacy erasure, not a delete: the person is removed from every ' +\n 'site in the workspace, whoever captured them, and it cannot be undone. ' +\n 'The request is filed now and runs with the nightly erasure job; from this ' +\n 'moment the address is closed, so a later form fill or order cannot ' +\n 'recreate the record, and no campaign is sent to it.'}\n </DialogContentText>\n <Stack spacing={2}>\n <ListBlock heading=\"Removed across the workspace\" lines={PERSON_ERASURE_REMOVES} />\n <ListBlock heading=\"Kept, with the person taken off\" lines={PERSON_ERASURE_RETAINS} />\n <ListBlock heading=\"Not reached — finish these by hand\" lines={PERSON_ERASURE_NOT_REACHED} />\n <TextField\n label=\"Type the email address to confirm\"\n value={typed}\n onChange={(event) => setTyped(event.target.value)}\n fullWidth\n autoFocus\n autoComplete=\"off\"\n slotProps={{ htmlInput: { 'aria-label': 'Type the email address to confirm' } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n color=\"error\"\n onClick={() => void submit()}\n disabled={!confirmed || busy}\n >\n {busy ? 'Filing…' : 'Erase permanently'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nErasePersonDialog.displayName = 'ErasePersonDialog'\n\nfunction ListBlock(props: { heading: string; lines: readonly string[] }) {\n return (\n <div>\n <Typography variant=\"subtitle2\">{props.heading}</Typography>\n <List dense disablePadding>\n {props.lines.map((line) => (\n <ListItem key={line} disableGutters sx={{ py: 0 }}>\n <ListItemText\n primary={line}\n slotProps={{ primary: { variant: 'body2', color: 'text.secondary' } }}\n />\n </ListItem>\n ))}\n </List>\n </div>\n )\n}\n"],"names":["PERSON_ERASURE_NOT_REACHED","PERSON_ERASURE_REMOVES","PERSON_ERASURE_RETAINS","personErasureConfirmationMatches","mdiAccountOffOutline","MdiIcon","useSnackbar","Alert","Button","Dialog","DialogActions","DialogContent","DialogContentText","DialogTitle","List","ListItem","ListItemText","Stack","TextField","Typography","useEffect","useMemo","useState","useCrmOrgMount","useCanErasePeople","useCrmApi","useErasePersonAction","props","hostId","orgId","subject","requestedAtMs","canErase","ready","undefined","orgMount","canFile","Boolean","open","setOpen","filedAtMs","setFiledAtMs","pendingSince","menuItems","disabledReason","key","label","icon","path","size","destructive","disabled","onClick","banner","ErasurePendingBanner","dialog","ErasePersonDialog","onClose","onFiled","atMs","pendingSinceMs","severity","data-testid","strong","Date","toLocaleString","displayName","call","enqueueSnackbar","typed","setTyped","busy","setBusy","confirmed","email","submit","payload","response","kind","contactId","id","leadId","trim","ok","Error","String","Number","now","variant","persist","error","message","maxWidth","fullWidth","sx","mb","spacing","ListBlock","heading","lines","value","onChange","event","target","autoFocus","autoComplete","slotProps","htmlInput","color","div","dense","disablePadding","map","line","disableGutters","py","primary"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,0BAA0B,EAC1BC,sBAAsB,EACtBC,sBAAsB,EACtBC,gCAAgC,QAC3B,eAAc;AACrB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,OAAO,QAAQ,uBAAsB;AAE9C,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,iBAAiB,EACjBC,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRC,YAAY,EACZC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAAyBC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpE,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,iBAAiB,QAAQ,4BAAwB;AAC1D,SAASC,SAAS,QAAQ,mBAAe;AAuCzC;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;IACnE,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,OAAO,EAAEC,aAAa,EAAE,GAAGJ;IAClD,MAAM,EAAEK,QAAQ,EAAEC,KAAK,EAAE,GAAGT,kBAAkBK,gBAAAA,QAASK;IACvD,MAAMC,WAAWZ;IACjB,yDAA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"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/erase-person-action.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n PERSON_ERASURE_NOT_REACHED,\n PERSON_ERASURE_NOTES_HEADING,\n PERSON_ERASURE_NOTES_UNAVAILABLE,\n PERSON_ERASURE_REMOVES,\n PERSON_ERASURE_RETAINS,\n personErasureConfirmationMatches,\n} from '@aglyn/aglyn'\nimport { mdiAccountOffOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { usePersonErasureNotes } from '@aglyn/tenant-feature-instance/hooks/use-person-erasure-notes'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n List,\n ListItem,\n ListItemText,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { type ReactNode, useEffect, useMemo, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCanErasePeople } from './use-can-erase-people'\nimport { useCrmApi } from './use-crm-api'\n\n/** The record the action is offered on: which kind, its id, and its address. */\nexport type ErasePersonSubject =\n | { kind: 'contact'; id: string; email: string }\n | { kind: 'lead'; id: string; email: string }\n\nexport interface UseErasePersonActionProps {\n /**\n * The site the request is filed from — the route logs it on that site's\n * feed. At the organization level the record's own capturing site\n * (AGL-2630), or `null` for a record no site has captured: beneath the\n * org hub's mount the route's org variant files it anyway (AGL-2634), and\n * only a surface mounted nowhere holds the item.\n */\n hostId: string | null\n orgId: string | null | undefined\n /** Null while the record has not loaded; the item is then disabled. */\n subject: ErasePersonSubject | null\n /** The record's marker, when a request is already waiting. */\n requestedAtMs: number | null\n}\n\nexport interface ErasePersonAction {\n /** Zero or one item, to spread into the record header's overflow menu. */\n menuItems: RowActionsMenuItem[]\n /** The pending banner, or null. Render it where the record's cards begin. */\n banner: ReactNode\n /** The dialog. Render it once, anywhere in the page. */\n dialog: ReactNode\n /**\n * When the waiting request was filed, or null while none waits: the\n * record's marker, or the route's answer until the listener carries the\n * marker. What a page gates its other acts on — Convert, on a lead — so\n * they close the moment the item does.\n */\n pendingSinceMs: number | null\n}\n\n/**\n * **Erase this person** on a record page (AGL-2623).\n *\n * Owned by a hook rather than a component because the overflow menu takes\n * items as data: the page spreads `menuItems` into its own list, renders\n * `banner` under the header and `dialog` at the end, and everything the\n * action knows — who may, whether a request is already waiting, what the\n * dialog says, what the route answers — lives here.\n *\n * Offered to whoever holds \"Privacy requests\" (`org.privacy`, AGL-4047) over\n * the whole workspace — owners and admins by default — and the item is\n * present but disabled for everyone else with the reason as its tooltip: an\n * absent item and an inapplicable one look alike, and a site editor who\n * cannot find the action should learn who can rather than conclude it does\n * not exist.\n *\n * Takes the site from the page and the workspace from `useOrgDataScope`,\n * never a route, so an org-level mount can offer the same item.\n */\nexport function useErasePersonAction(props: UseErasePersonActionProps): ErasePersonAction {\n const { hostId, orgId, subject, requestedAtMs } = props\n const { canErase, ready } = useCanErasePeople(orgId ?? undefined)\n const orgMount = useCrmOrgMount()\n // A site to file from, or the org to file as (AGL-2634).\n const canFile = Boolean(hostId) || Boolean(orgMount)\n const [open, setOpen] = useState(false)\n // The marker arrives on the record's own document, so a request filed on\n // this page shows as pending the moment the listener catches up — and,\n // until it does, the moment the route answered.\n const [filedAtMs, setFiledAtMs] = useState<number | null>(null)\n const pendingSince = requestedAtMs ?? filedAtMs\n\n const menuItems = useMemo<RowActionsMenuItem[]>(() => {\n const disabledReason = !subject\n ? 'The record has not loaded'\n : !canFile\n ? 'No site has captured this person to file from'\n : pendingSince\n ? 'An erasure is already pending for this person'\n : !ready\n ? 'Checking your workspace role'\n : !canErase\n ? 'Your role does not include \"Privacy requests\" — ask an organization admin'\n : undefined\n return [\n {\n key: 'erase-person',\n label: 'Erase this person',\n icon: <MdiIcon path={mdiAccountOffOutline.path} size={0.8} />,\n destructive: true,\n disabled: Boolean(disabledReason),\n disabledReason,\n onClick: () => setOpen(true),\n },\n ]\n }, [canErase, canFile, pendingSince, ready, subject])\n\n const banner = pendingSince ? <ErasurePendingBanner requestedAtMs={pendingSince} /> : null\n const dialog = subject && canFile ? (\n <ErasePersonDialog\n open={open}\n onClose={() => setOpen(false)}\n hostId={hostId}\n orgId={orgId}\n subject={subject}\n onFiled={(atMs) => setFiledAtMs(atMs)}\n />\n ) : null\n\n return { menuItems, banner, dialog, pendingSinceMs: pendingSince }\n}\n\nexport interface ErasurePendingBannerProps {\n requestedAtMs: number\n}\n\n/**\n * The state a record wears between the request and the run. Says when it\n * was asked and what will happen, so a reader arriving cold neither files\n * it again nor keeps working the record.\n */\nexport function ErasurePendingBanner(props: ErasurePendingBannerProps) {\n const { requestedAtMs } = props\n return (\n <Alert severity=\"warning\" data-testid=\"erasure-pending-banner\">\n <strong>{'Erasure pending. '}</strong>\n {`Requested ${new Date(requestedAtMs).toLocaleString()}. The nightly erasure ` +\n 'job removes this person from every site in the workspace; until then the ' +\n 'record is kept only so the request can be seen. Nothing new should be added ' +\n 'to it.'}\n </Alert>\n )\n}\nErasurePendingBanner.displayName = 'ErasurePendingBanner'\n\nexport interface ErasePersonDialogProps {\n open: boolean\n onClose: () => void\n /** The site the request is filed from, or `null` beneath the org hub's mount. */\n hostId: string | null\n /** The workspace whose plugins answer what an erasure keeps. */\n orgId: string | null | undefined\n subject: ErasePersonSubject\n /** Called with the request's queue time once the route has filed it. */\n onFiled: (pendingSinceMs: number) => void\n}\n\n/**\n * The confirmation: everything the request removes, everything it keeps\n * and how, what it does not reach, and the two facts that follow the click\n * — the address is closed to capture at once, and the sweep runs with the\n * nightly job. The admin types the address back; the route checks the same\n * match before it files anything.\n *\n * What a plugin keeps (a signed waiver, AGL-4042) is asked when the dialog\n * opens, not with every record page, and never holds the confirm back.\n */\nexport function ErasePersonDialog(props: ErasePersonDialogProps) {\n const { open, onClose, hostId, orgId, subject, onFiled } = props\n const { data: user } = useUser()\n const erasureNotes = usePersonErasureNotes(user, open ? orgId : null)\n const call = useCrmApi(hostId)\n const { enqueueSnackbar } = useSnackbar()\n const [typed, setTyped] = useState('')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (open) setTyped('')\n }, [open])\n const confirmed = personErasureConfirmationMatches(typed, subject.email)\n\n const submit = async () => {\n if (!confirmed || busy) return\n setBusy(true)\n try {\n const { response, payload } = await call('erase-person', {\n ...(subject.kind === 'contact' ? { contactId: subject.id } : { leadId: subject.id }),\n email: typed.trim(),\n })\n if (!response.ok) {\n throw new Error(String(payload['error'] ?? 'The erasure could not be filed'))\n }\n onFiled(Number(payload['pendingSinceMs'] ?? Date.now()))\n enqueueSnackbar(\n payload['alreadyPending']\n ? 'An erasure was already pending for this person'\n : 'Erasure requested — it runs with the nightly job',\n { variant: 'success', persist: false },\n )\n onClose()\n } catch (error) {\n enqueueSnackbar(error instanceof Error ? error.message : 'The erasure could not be filed', {\n variant: 'error',\n })\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{`Erase ${subject.email} from this workspace?`}</DialogTitle>\n <DialogContent>\n <DialogContentText sx={{ mb: 2 }}>\n {'This is a privacy erasure, not a delete: the person is removed from every ' +\n 'site in the workspace, whoever captured them, and it cannot be undone. ' +\n 'The request is filed now and runs with the nightly erasure job; from this ' +\n 'moment the address is closed, so a later form fill or order cannot ' +\n 'recreate the record, and no campaign is sent to it.'}\n </DialogContentText>\n <Stack spacing={2}>\n <ListBlock heading=\"Removed across the workspace\" lines={PERSON_ERASURE_REMOVES} />\n <ListBlock heading=\"Kept, with the person taken off\" lines={PERSON_ERASURE_RETAINS} />\n {erasureNotes.lines.length ? (\n <ListBlock heading={PERSON_ERASURE_NOTES_HEADING} lines={erasureNotes.lines} />\n ) : null}\n <ListBlock heading=\"Not reached — finish these by hand\" lines={PERSON_ERASURE_NOT_REACHED} />\n {erasureNotes.unavailable ? (\n <Alert severity=\"info\">{PERSON_ERASURE_NOTES_UNAVAILABLE}</Alert>\n ) : null}\n <TextField\n label=\"Type the email address to confirm\"\n value={typed}\n onChange={(event) => setTyped(event.target.value)}\n fullWidth\n autoFocus\n autoComplete=\"off\"\n slotProps={{ htmlInput: { 'aria-label': 'Type the email address to confirm' } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n color=\"error\"\n onClick={() => void submit()}\n disabled={!confirmed || busy}\n >\n {busy ? 'Filing…' : 'Erase permanently'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nErasePersonDialog.displayName = 'ErasePersonDialog'\n\nfunction ListBlock(props: { heading: string; lines: readonly string[] }) {\n return (\n <div>\n <Typography variant=\"subtitle2\">{props.heading}</Typography>\n <List dense disablePadding>\n {props.lines.map((line) => (\n <ListItem key={line} disableGutters sx={{ py: 0 }}>\n <ListItemText\n primary={line}\n slotProps={{ primary: { variant: 'body2', color: 'text.secondary' } }}\n />\n </ListItem>\n ))}\n </List>\n </div>\n )\n}\n"],"names":["PERSON_ERASURE_NOT_REACHED","PERSON_ERASURE_NOTES_HEADING","PERSON_ERASURE_NOTES_UNAVAILABLE","PERSON_ERASURE_REMOVES","PERSON_ERASURE_RETAINS","personErasureConfirmationMatches","mdiAccountOffOutline","MdiIcon","useSnackbar","useUser","usePersonErasureNotes","Alert","Button","Dialog","DialogActions","DialogContent","DialogContentText","DialogTitle","List","ListItem","ListItemText","Stack","TextField","Typography","useEffect","useMemo","useState","useCrmOrgMount","useCanErasePeople","useCrmApi","useErasePersonAction","props","hostId","orgId","subject","requestedAtMs","canErase","ready","undefined","orgMount","canFile","Boolean","open","setOpen","filedAtMs","setFiledAtMs","pendingSince","menuItems","disabledReason","key","label","icon","path","size","destructive","disabled","onClick","banner","ErasurePendingBanner","dialog","ErasePersonDialog","onClose","onFiled","atMs","pendingSinceMs","severity","data-testid","strong","Date","toLocaleString","displayName","data","user","erasureNotes","call","enqueueSnackbar","typed","setTyped","busy","setBusy","confirmed","email","submit","payload","response","kind","contactId","id","leadId","trim","ok","Error","String","Number","now","variant","persist","error","message","maxWidth","fullWidth","sx","mb","spacing","ListBlock","heading","lines","length","unavailable","value","onChange","event","target","autoFocus","autoComplete","slotProps","htmlInput","color","div","dense","disablePadding","map","line","disableGutters","py","primary"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,0BAA0B,EAC1BC,4BAA4B,EAC5BC,gCAAgC,EAChCC,sBAAsB,EACtBC,sBAAsB,EACtBC,gCAAgC,QAC3B,eAAc;AACrB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,OAAO,QAAQ,uBAAsB;AAE9C,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,qBAAqB,QAAQ,gEAA+D;AACrG,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,iBAAiB,EACjBC,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRC,YAAY,EACZC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAAyBC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpE,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,iBAAiB,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,KAACF;wBAAO4C,SAASK;wBAASN,UAAUuB;kCACjC;;kCAEH,KAAClE;wBACCmF,SAAQ;wBACRsB,OAAM;wBACN7D,SAAS,IAAM,KAAK0B;wBACpB3B,UAAU,CAACyB,aAAaF;kCAEvBA,OAAO,YAAY;;;;;;AAK9B;AACAlB,kBAAkBU,WAAW,GAAG;AAEhC,SAASkC,UAAUzE,KAAoD;IACrE,qBACE,MAACuF;;0BACC,KAAC/F;gBAAWwE,SAAQ;0BAAahE,MAAM0E,OAAO;;0BAC9C,KAACvF;gBAAKqG,KAAK;gBAACC,cAAc;0BACvBzF,MAAM2E,KAAK,CAACe,GAAG,CAAC,CAACC,qBAChB,KAACvG;wBAAoBwG,cAAc;wBAACtB,IAAI;4BAAEuB,IAAI;wBAAE;kCAC9C,cAAA,KAACxG;4BACCyG,SAASH;4BACTP,WAAW;gCAAEU,SAAS;oCAAE9B,SAAS;oCAASsB,OAAO;gCAAiB;4BAAE;;uBAHzDK;;;;AAUzB"}
@@ -25,6 +25,7 @@ import { registerPluginRecordEmailStateWriter } from "@aglyn/aglyn/plugin-manage
25
25
  import { registerPluginRecordOriginWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-origin";
26
26
  import { registerPluginRecordTimelineWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-timeline";
27
27
  import { registerPluginRecordWrittenListener } from "@aglyn/aglyn/plugin-manager/plugin-record-written";
28
+ import { registerPluginScopeSharingPatch } from "@aglyn/aglyn/plugin-manager/plugin-scope-sharing";
28
29
  import { registerServerStepExecutor } from "@aglyn/aglyn/plugin-manager/plugin-server-steps";
29
30
  import { registerPluginUsageMeter } from "@aglyn/aglyn/plugin-manager/plugin-usage-meters";
30
31
  import { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from "./constants/bundle-common.js";
@@ -170,6 +171,21 @@ import { summarizeConsentGroupChange } from "./model/consent-group-summary.js";
170
171
  registerPluginPersonRecords(crmPersonRecordsService, {
171
172
  pluginId: BUNDLE_ID
172
173
  });
174
+ // A record's scoped list fields follow its sites, so the sweep that keeps
175
+ // "all sites except" current restamps them in the same write (AGL-4047).
176
+ // Deferred like the capture.
177
+ registerPluginScopeSharingPatch([
178
+ 'contacts',
179
+ 'leads',
180
+ 'companies',
181
+ 'deals',
182
+ 'crmTasks'
183
+ ], async (collection, next)=>{
184
+ const { crmScopeSharingPatch } = await import("./server/scope-sharing-patch.js");
185
+ return crmScopeSharingPatch(collection, next);
186
+ }, {
187
+ pluginId: BUNDLE_ID
188
+ });
173
189
  // The CRM's own share of a lead conversion (AGL-3254): the lead's
174
190
  // campaigns go onto the contact's facet. Through the seam every door
175
191
  // that converts a lead reaches, and deferred like the capture: the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.server.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// The contract from its own module, not the plugin-manager barrel: boot needs\n// the registry and nothing else, and the barrel reaches the client contexts.\nimport { registerPluginConsentGroupParticipant } from '@aglyn/aglyn/plugin-manager/plugin-consent-group-change'\nimport {\n registerPluginContactCaptureWriter,\n type PluginContactCaptureWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { registerPluginLeadConversionListener } from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { registerPluginPersonMatcher } from '@aglyn/aglyn/plugin-manager/plugin-person-matches'\nimport {\n registerPluginPersonRecords,\n type PluginPersonRecords,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n registerPluginRecordIndex,\n type PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { registerPluginRecordEmailStateWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { registerPluginRecordOriginWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n registerPluginRecordTimelineWriter,\n type PluginRecordTimelineWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { registerPluginRecordWrittenListener } from '@aglyn/aglyn/plugin-manager/plugin-record-written'\nimport { registerServerStepExecutor } from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport { registerPluginUsageMeter } from '@aglyn/aglyn/plugin-manager/plugin-usage-meters'\nimport { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from './constants/bundle-common'\nimport { summarizeConsentGroupChange } from './model/consent-group-summary'\n\n/**\n * The CRM as the plugin that keeps people.\n *\n * Light by construction, the way the workflows listener is: the capture\n * itself is imported when the first one arrives, not when the process\n * starts, so a process that never captures anybody pays for this object and\n * nothing else. That matters because this registers in EVERY server process,\n * including ones that will never touch the CRM.\n */\nexport const crmContactCaptureWriter: PluginContactCaptureWriter = {\n async capture(request) {\n const { captureContactForCrm } = await import('./server/capture-contact')\n return await captureContactForCrm(request)\n },\n}\n\n/**\n * The CRM as the plugin other plugins ask for people (AGL-3080), deferred\n * like the capture: `server/person-records.ts` and the Admin SDK it brings\n * load with the first question, not when the process starts.\n */\nexport const crmPersonRecordsService: PluginPersonRecords = {\n async find(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.find(request)\n },\n async read(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.read(request)\n },\n async fileUnder(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.fileUnder(request)\n },\n async recordRefund(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.recordRefund(request)\n },\n async peopleInView(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.peopleInView(request)\n },\n async wroteIn(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.wroteIn(request)\n },\n async search(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.search(request)\n },\n // The walk a connector copies a site's people out by (AGL-3639).\n async changedSince(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.changedSince(request)\n },\n}\n\n/**\n * The `pipeline` record index, its reads loaded with the first one — see\n * `server/pipeline-record-index.ts` for what it answers.\n */\nexport const crmPipelineRecordIndex: PluginRecordIndex = {\n async list(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.list(request)\n },\n async get(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.get(request)\n },\n}\n\n/** One of `server/crm-record-indexes.ts`'s indexes, its reads loaded with the first one. */\nfunction lazyCrmRecordIndex(kind: 'company' | 'messageTemplate'): PluginRecordIndex {\n return {\n async list(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].list(request)\n },\n async get(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].get(request)\n },\n }\n}\n\n/** The companies a person works for, as another plugin reads them (AGL-3080). */\nexport const crmCompanyRecordIndex = lazyCrmRecordIndex('company')\n\n/** The email templates and snippets reps write, as another plugin reads them (AGL-3080). */\nexport const crmMessageTemplateRecordIndex = lazyCrmRecordIndex('messageTemplate')\n\n/**\n * The CRM's writer on the record-timeline seam (AGL-2981), deferred: the\n * writer and the Admin SDK it brings load with the first entry filed.\n */\nexport const crmRecordTimelineWriter: PluginRecordTimelineWriter = {\n async logActivity(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).logActivity(request)\n },\n async createTask(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).createTask(request)\n },\n async recordEmailDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordEmailDelivery!(request)\n },\n // A delivery event for a message the CRM tagged (AGL-2615, AGL-3080).\n async recordTaggedDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordTaggedDelivery!(request)\n },\n // An automation's email to the person its event is about, filed on that\n // person's timeline with its delivery state (AGL-2615, AGL-3080).\n async prepareEmail(request) {\n const { prepareCrmRecordEmail } = await import('./server/automation-steps')\n return prepareCrmRecordEmail(request)\n },\n}\n\n/**\n * The plugin's SERVER declarations: what the server must know at boot, before\n * any door of the CRM has been called.\n *\n * ## Why a declaration and not a `tenantApi` registration\n *\n * The doors that meet a person mostly never load this plugin. A form\n * submission is a core route; an order and a booking are captured inside\n * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry\n * filled by a surface that did not load answers `null` — which\n * `capturePluginContact` defines as \"this workspace has no record system\", a\n * sentence that would be false and silent. Orders would stop creating\n * contacts with nothing red anywhere, which is the AGL-3025 shape.\n *\n * Running from both apps' generated server-declarations manifest at boot is\n * what makes the answer true in every process. It is also called from the\n * plugin's own API register functions, so a process whose boot did not run it\n * still registers the writer the first time a CRM door loads. Registering\n * twice replaces in place.\n *\n * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A\n * second plugin's is refused naming both, and the incumbent keeps serving.\n */\nexport function registerCrmServerDeclarations(): void {\n registerPluginContactCaptureWriter(crmContactCaptureWriter, {\n pluginId: BUNDLE_ID,\n })\n // The other half of keeping people (AGL-3080): another plugin that holds\n // an address, or a record the CRM handed it, asks here for the person —\n // a flow email's consent read, a refund, an automation filing somebody\n // under a campaign — and never opens the CRM's collections itself.\n registerPluginPersonRecords(crmPersonRecordsService, { pluginId: BUNDLE_ID })\n // The CRM's own share of a lead conversion (AGL-3254): the lead's\n // campaigns go onto the contact's facet. Through the seam every door\n // that converts a lead reaches, and deferred like the capture: the\n // module that writes is loaded when the first conversion arrives, and\n // it brings the Admin SDK with it — this file defers the plugin's OWN\n // module only. A library imported statically across the plugin cannot\n // also be lazy-loaded here: `enforce-module-boundaries` refuses every\n // static import of a library the project lazy-loads anywhere.\n registerPluginLeadConversionListener(\n async (request) => {\n const { carryLeadCampaignsOnConversion } =\n await import('./server/lead-campaign-carry')\n return carryLeadCampaignsOnConversion(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // \"Did this workspace already know this person?\" (AGL-3289), asked by the\n // staff console's acquisition card. Deferred like the rest: the reads load\n // when a staff member first opens a card, not when the process starts.\n registerPluginPersonMatcher(\n async (request) => {\n const { matchCrmPeople } = await import('./server/person-matches')\n return matchCrmPeople(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's share of a consent group change (AGL-3320): a contact's\n // per-site refusal carried across a separation, and the records keyed by a\n // group re-homed after the flip. Registered whether or not a workspace has\n // the CRM switched on, because the contacts — and the refusals on them —\n // outlive the switch. Deferred like the rest; the summary is plain words\n // and answers synchronously.\n // The record email-state writer (AGL-3245), here as well as in the console\n // API so the tenant's doors reach it too: a form submission's capture is\n // checked for deliverability after its response (AGL-3328), and the \"Would\n // bounce\" that check finds is written through this seam. Deferred like the\n // rest; the console's own registration replaces this one with the same\n // writer, loaded eagerly.\n registerPluginRecordEmailStateWriter(\n {\n async stamp(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).stamp(request)\n },\n // A send's first opens and clicks, stamped on the contacts they name\n // (AGL-2616) — the campaign webhook's courtesy, deferred like the rest.\n async engaged(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).engaged!(request)\n },\n // A delivered campaign's leads, moved to Nurturing (AGL-3446).\n async reached(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).reached!(request)\n },\n // A lead that wrote back, moved to Working (AGL-3080).\n async replied(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).replied!(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // The record timeline writer (AGL-2981), here as well as in the API\n // surfaces so a door in either app reaches it: a booking confirmed on the\n // tenant, or by the payment webhook, files its meeting and follow-up\n // through it (AGL-2660). Deferred like the rest; an API registration\n // replaces this one with the same writer, loaded eagerly.\n registerPluginRecordTimelineWriter(crmRecordTimelineWriter, { pluginId: BUNDLE_ID })\n // Where a person came from (AGL-3519): a door the CRM does not run — the\n // platform's account sign-up, a sequence enrolling someone — names its\n // origin, and the CRM stamps the built-in Lead source on a record holding\n // none. Deferred like the rest.\n registerPluginRecordOriginWriter(\n {\n async stamp(request) {\n const { crmRecordOriginWriter } = await import('./server/record-origin')\n return crmRecordOriginWriter.stamp(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // Sharing rules (AGL-3336), re-evaluated after every server write of a\n // lead, a contact, a company or a deal: the core tells its record-written\n // listeners from the list-field restamp every such writer ends with, in\n // both apps — a form's capture on the tenant, an edit in the console.\n // Deferred like the rest: an org with no rules pays one cached read.\n registerPluginRecordWrittenListener(\n async (event) => {\n const { crmSharingRecordWritten } = await import('./server/crm-sharing')\n await crmSharingRecordWritten(event)\n },\n { pluginId: BUNDLE_ID, key: 'sharing' },\n )\n // The organization's pipelines and their stages, as another plugin reads\n // them (AGL-3080): an automation the AI drafts names the stage a deal\n // moves to. Deferred like the rest: the reads load with the first one.\n registerPluginRecordIndex('pipeline', crmPipelineRecordIndex, { pluginId: BUNDLE_ID })\n // The company a person works for, and the templates reps write, as a sales\n // sequence reads them (AGL-3080). Deferred like the rest.\n registerPluginRecordIndex('company', crmCompanyRecordIndex, { pluginId: BUNDLE_ID })\n registerPluginRecordIndex('messageTemplate', crmMessageTemplateRecordIndex, { pluginId: BUNDLE_ID })\n // The automation steps that write the CRM (AGL-2605, AGL-3080), run for the\n // workflows engine through the server-step seam and declared under\n // `serverSteps`. Deferred like the rest: the writes load with the first step.\n registerServerStepExecutor(\n CRM_STEP_TYPES,\n async (request) => (await import('./server/automation-steps')).runCrmAutomationStep(request),\n { pluginId: BUNDLE_ID },\n )\n registerPluginConsentGroupParticipant(\n {\n async preview(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.preview(request)\n },\n async run(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.run(request)\n },\n summarize: summarizeConsentGroupChange,\n },\n { pluginId: BUNDLE_ID },\n )\n // The records band in the monthly usage sweep, a core cron that never\n // loads a CRM door; declared in `usageAxes` so the sweep refuses to bill a\n // month without it. Deferred like the rest: the counts load with the\n // first sweep.\n registerPluginUsageMeter({\n pluginId: BUNDLE_ID,\n id: CRM_RECORDS_METER_ID,\n measure: async (context) => {\n const { measureCrmRecords } = await import('./server/crm-records-meter')\n return measureCrmRecords(context)\n },\n })\n}\n\n"],"names":["registerPluginConsentGroupParticipant","registerPluginContactCaptureWriter","registerPluginLeadConversionListener","registerPluginPersonMatcher","registerPluginPersonRecords","registerPluginRecordIndex","registerPluginRecordEmailStateWriter","registerPluginRecordOriginWriter","registerPluginRecordTimelineWriter","registerPluginRecordWrittenListener","registerServerStepExecutor","registerPluginUsageMeter","BUNDLE_ID","CRM_RECORDS_METER_ID","CRM_STEP_TYPES","summarizeConsentGroupChange","crmContactCaptureWriter","capture","request","captureContactForCrm","crmPersonRecordsService","find","crmPersonRecords","read","fileUnder","recordRefund","peopleInView","wroteIn","search","changedSince","crmPipelineRecordIndex","list","pipelineRecordIndex","get","lazyCrmRecordIndex","kind","crmRecordIndexes","crmCompanyRecordIndex","crmMessageTemplateRecordIndex","crmRecordTimelineWriter","logActivity","createCrmRecordTimelineWriter","defaultCrmRecordTimelineDeps","createTask","recordEmailDelivery","recordTaggedDelivery","prepareEmail","prepareCrmRecordEmail","registerCrmServerDeclarations","pluginId","carryLeadCampaignsOnConversion","matchCrmPeople","stamp","createCrmRecordEmailStateWriter","defaultCrmRecordEmailStateDeps","engaged","reached","replied","crmRecordOriginWriter","event","crmSharingRecordWritten","key","runCrmAutomationStep","preview","consentGroupParticipant","run","summarize","id","measure","context","measureCrmRecords"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,6EAA6E;AAC7E,SAASA,qCAAqC,QAAQ,0DAAyD;AAC/G,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,oCAAoC,QAAQ,qDAAoD;AACzG,SAASC,2BAA2B,QAAQ,oDAAmD;AAC/F,SACEC,2BAA2B,QAEtB,oDAAmD;AAC1D,SACEC,yBAAyB,QAEpB,kDAAiD;AACxD,SAASC,oCAAoC,QAAQ,wDAAuD;AAC5G,SAASC,gCAAgC,QAAQ,mDAAkD;AACnG,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,mCAAmC,QAAQ,oDAAmD;AACvG,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,wBAAwB,QAAQ,kDAAiD;AAC1F,SAASC,SAAS,EAAEC,oBAAoB,EAAEC,cAAc,QAAQ,+BAA2B;AAC3F,SAASC,2BAA2B,QAAQ,mCAA+B;AAE3E;;;;;;;;CAQC,GACD,OAAO,MAAMC,0BAAsD;IACjE,MAAMC,SAAQC,OAAO;QACnB,MAAM,EAAEC,oBAAoB,EAAE,GAAG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BAA0B,YAAYyB,wBAAwB;QAAEmB,UAAUrC;IAAU;IACpF,2EAA2E;IAC3E,0DAA0D;IAC1DP,0BAA0B,WAAWgC,uBAAuB;QAAEY,UAAUrC;IAAU;IAClFP,0BAA0B,mBAAmBiC,+BAA+B;QAAEW,UAAUrC;IAAU;IAClG,4EAA4E;IAC5E,mEAAmE;IACnE,8EAA8E;IAC9EF,2BACEI,gBACA,OAAOI,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA2B,EAAG4C,oBAAoB,CAAC5C,UACpF;QAAE+B,UAAUrC;IAAU;IAExBZ,sCACE;QACE,MAAM+D,SAAQ7C,OAAO;YACnB,MAAM,EAAE8C,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBD,OAAO,CAAC7C;QACzC;QACA,MAAM+C,KAAI/C,OAAO;YACf,MAAM,EAAE8C,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBC,GAAG,CAAC/C;QACrC;QACAgD,WAAWnD;IACb,GACA;QAAEkC,UAAUrC;IAAU;IAExB,sEAAsE;IACtE,2EAA2E;IAC3E,qEAAqE;IACrE,eAAe;IACfD,yBAAyB;QACvBsC,UAAUrC;QACVuD,IAAItD;QACJuD,SAAS,OAAOC;YACd,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC3C,OAAOA,kBAAkBD;QAC3B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/declarations.server.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// The contract from its own module, not the plugin-manager barrel: boot needs\n// the registry and nothing else, and the barrel reaches the client contexts.\nimport { registerPluginConsentGroupParticipant } from '@aglyn/aglyn/plugin-manager/plugin-consent-group-change'\nimport {\n registerPluginContactCaptureWriter,\n type PluginContactCaptureWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { registerPluginLeadConversionListener } from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { registerPluginPersonMatcher } from '@aglyn/aglyn/plugin-manager/plugin-person-matches'\nimport {\n registerPluginPersonRecords,\n type PluginPersonRecords,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n registerPluginRecordIndex,\n type PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { registerPluginRecordEmailStateWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { registerPluginRecordOriginWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n registerPluginRecordTimelineWriter,\n type PluginRecordTimelineWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { registerPluginRecordWrittenListener } from '@aglyn/aglyn/plugin-manager/plugin-record-written'\nimport { registerPluginScopeSharingPatch } from '@aglyn/aglyn/plugin-manager/plugin-scope-sharing'\nimport { registerServerStepExecutor } from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport { registerPluginUsageMeter } from '@aglyn/aglyn/plugin-manager/plugin-usage-meters'\nimport { BUNDLE_ID, CRM_RECORDS_METER_ID, CRM_STEP_TYPES } from './constants/bundle-common'\nimport { summarizeConsentGroupChange } from './model/consent-group-summary'\n\n/**\n * The CRM as the plugin that keeps people.\n *\n * Light by construction, the way the workflows listener is: the capture\n * itself is imported when the first one arrives, not when the process\n * starts, so a process that never captures anybody pays for this object and\n * nothing else. That matters because this registers in EVERY server process,\n * including ones that will never touch the CRM.\n */\nexport const crmContactCaptureWriter: PluginContactCaptureWriter = {\n async capture(request) {\n const { captureContactForCrm } = await import('./server/capture-contact')\n return await captureContactForCrm(request)\n },\n}\n\n/**\n * The CRM as the plugin other plugins ask for people (AGL-3080), deferred\n * like the capture: `server/person-records.ts` and the Admin SDK it brings\n * load with the first question, not when the process starts.\n */\nexport const crmPersonRecordsService: PluginPersonRecords = {\n async find(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.find(request)\n },\n async read(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.read(request)\n },\n async fileUnder(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.fileUnder(request)\n },\n async recordRefund(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.recordRefund(request)\n },\n async peopleInView(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.peopleInView(request)\n },\n async wroteIn(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.wroteIn(request)\n },\n async search(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.search(request)\n },\n // The walk a connector copies a site's people out by (AGL-3639).\n async changedSince(request) {\n const { crmPersonRecords } = await import('./server/person-records')\n return crmPersonRecords.changedSince(request)\n },\n}\n\n/**\n * The `pipeline` record index, its reads loaded with the first one — see\n * `server/pipeline-record-index.ts` for what it answers.\n */\nexport const crmPipelineRecordIndex: PluginRecordIndex = {\n async list(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.list(request)\n },\n async get(request) {\n const { pipelineRecordIndex } = await import('./server/pipeline-record-index')\n return pipelineRecordIndex.get(request)\n },\n}\n\n/** One of `server/crm-record-indexes.ts`'s indexes, its reads loaded with the first one. */\nfunction lazyCrmRecordIndex(kind: 'company' | 'messageTemplate'): PluginRecordIndex {\n return {\n async list(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].list(request)\n },\n async get(request) {\n const { crmRecordIndexes } = await import('./server/crm-record-indexes')\n return crmRecordIndexes()[kind].get(request)\n },\n }\n}\n\n/** The companies a person works for, as another plugin reads them (AGL-3080). */\nexport const crmCompanyRecordIndex = lazyCrmRecordIndex('company')\n\n/** The email templates and snippets reps write, as another plugin reads them (AGL-3080). */\nexport const crmMessageTemplateRecordIndex = lazyCrmRecordIndex('messageTemplate')\n\n/**\n * The CRM's writer on the record-timeline seam (AGL-2981), deferred: the\n * writer and the Admin SDK it brings load with the first entry filed.\n */\nexport const crmRecordTimelineWriter: PluginRecordTimelineWriter = {\n async logActivity(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).logActivity(request)\n },\n async createTask(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).createTask(request)\n },\n async recordEmailDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordEmailDelivery!(request)\n },\n // A delivery event for a message the CRM tagged (AGL-2615, AGL-3080).\n async recordTaggedDelivery(request) {\n const { createCrmRecordTimelineWriter, defaultCrmRecordTimelineDeps } =\n await import('./server/record-timeline')\n return createCrmRecordTimelineWriter(defaultCrmRecordTimelineDeps()).recordTaggedDelivery!(request)\n },\n // An automation's email to the person its event is about, filed on that\n // person's timeline with its delivery state (AGL-2615, AGL-3080).\n async prepareEmail(request) {\n const { prepareCrmRecordEmail } = await import('./server/automation-steps')\n return prepareCrmRecordEmail(request)\n },\n}\n\n/**\n * The plugin's SERVER declarations: what the server must know at boot, before\n * any door of the CRM has been called.\n *\n * ## Why a declaration and not a `tenantApi` registration\n *\n * The doors that meet a person mostly never load this plugin. A form\n * submission is a core route; an order and a booking are captured inside\n * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry\n * filled by a surface that did not load answers `null` — which\n * `capturePluginContact` defines as \"this workspace has no record system\", a\n * sentence that would be false and silent. Orders would stop creating\n * contacts with nothing red anywhere, which is the AGL-3025 shape.\n *\n * Running from both apps' generated server-declarations manifest at boot is\n * what makes the answer true in every process. It is also called from the\n * plugin's own API register functions, so a process whose boot did not run it\n * still registers the writer the first time a CRM door loads. Registering\n * twice replaces in place.\n *\n * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A\n * second plugin's is refused naming both, and the incumbent keeps serving.\n */\nexport function registerCrmServerDeclarations(): void {\n registerPluginContactCaptureWriter(crmContactCaptureWriter, {\n pluginId: BUNDLE_ID,\n })\n // The other half of keeping people (AGL-3080): another plugin that holds\n // an address, or a record the CRM handed it, asks here for the person —\n // a flow email's consent read, a refund, an automation filing somebody\n // under a campaign — and never opens the CRM's collections itself.\n registerPluginPersonRecords(crmPersonRecordsService, { pluginId: BUNDLE_ID })\n // A record's scoped list fields follow its sites, so the sweep that keeps\n // \"all sites except\" current restamps them in the same write (AGL-4047).\n // Deferred like the capture.\n registerPluginScopeSharingPatch(\n ['contacts', 'leads', 'companies', 'deals', 'crmTasks'],\n async (collection, next) => {\n const { crmScopeSharingPatch } = await import('./server/scope-sharing-patch')\n return crmScopeSharingPatch(collection, next)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's own share of a lead conversion (AGL-3254): the lead's\n // campaigns go onto the contact's facet. Through the seam every door\n // that converts a lead reaches, and deferred like the capture: the\n // module that writes is loaded when the first conversion arrives, and\n // it brings the Admin SDK with it — this file defers the plugin's OWN\n // module only. A library imported statically across the plugin cannot\n // also be lazy-loaded here: `enforce-module-boundaries` refuses every\n // static import of a library the project lazy-loads anywhere.\n registerPluginLeadConversionListener(\n async (request) => {\n const { carryLeadCampaignsOnConversion } =\n await import('./server/lead-campaign-carry')\n return carryLeadCampaignsOnConversion(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // \"Did this workspace already know this person?\" (AGL-3289), asked by the\n // staff console's acquisition card. Deferred like the rest: the reads load\n // when a staff member first opens a card, not when the process starts.\n registerPluginPersonMatcher(\n async (request) => {\n const { matchCrmPeople } = await import('./server/person-matches')\n return matchCrmPeople(request)\n },\n { pluginId: BUNDLE_ID },\n )\n // The CRM's share of a consent group change (AGL-3320): a contact's\n // per-site refusal carried across a separation, and the records keyed by a\n // group re-homed after the flip. Registered whether or not a workspace has\n // the CRM switched on, because the contacts — and the refusals on them —\n // outlive the switch. Deferred like the rest; the summary is plain words\n // and answers synchronously.\n // The record email-state writer (AGL-3245), here as well as in the console\n // API so the tenant's doors reach it too: a form submission's capture is\n // checked for deliverability after its response (AGL-3328), and the \"Would\n // bounce\" that check finds is written through this seam. Deferred like the\n // rest; the console's own registration replaces this one with the same\n // writer, loaded eagerly.\n registerPluginRecordEmailStateWriter(\n {\n async stamp(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).stamp(request)\n },\n // A send's first opens and clicks, stamped on the contacts they name\n // (AGL-2616) — the campaign webhook's courtesy, deferred like the rest.\n async engaged(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).engaged!(request)\n },\n // A delivered campaign's leads, moved to Nurturing (AGL-3446).\n async reached(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).reached!(request)\n },\n // A lead that wrote back, moved to Working (AGL-3080).\n async replied(request) {\n const { createCrmRecordEmailStateWriter, defaultCrmRecordEmailStateDeps } =\n await import('./server/record-email-state')\n return createCrmRecordEmailStateWriter(defaultCrmRecordEmailStateDeps()).replied!(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // The record timeline writer (AGL-2981), here as well as in the API\n // surfaces so a door in either app reaches it: a booking confirmed on the\n // tenant, or by the payment webhook, files its meeting and follow-up\n // through it (AGL-2660). Deferred like the rest; an API registration\n // replaces this one with the same writer, loaded eagerly.\n registerPluginRecordTimelineWriter(crmRecordTimelineWriter, { pluginId: BUNDLE_ID })\n // Where a person came from (AGL-3519): a door the CRM does not run — the\n // platform's account sign-up, a sequence enrolling someone — names its\n // origin, and the CRM stamps the built-in Lead source on a record holding\n // none. Deferred like the rest.\n registerPluginRecordOriginWriter(\n {\n async stamp(request) {\n const { crmRecordOriginWriter } = await import('./server/record-origin')\n return crmRecordOriginWriter.stamp(request)\n },\n },\n { pluginId: BUNDLE_ID },\n )\n // Sharing rules (AGL-3336), re-evaluated after every server write of a\n // lead, a contact, a company or a deal: the core tells its record-written\n // listeners from the list-field restamp every such writer ends with, in\n // both apps — a form's capture on the tenant, an edit in the console.\n // Deferred like the rest: an org with no rules pays one cached read.\n registerPluginRecordWrittenListener(\n async (event) => {\n const { crmSharingRecordWritten } = await import('./server/crm-sharing')\n await crmSharingRecordWritten(event)\n },\n { pluginId: BUNDLE_ID, key: 'sharing' },\n )\n // The organization's pipelines and their stages, as another plugin reads\n // them (AGL-3080): an automation the AI drafts names the stage a deal\n // moves to. Deferred like the rest: the reads load with the first one.\n registerPluginRecordIndex('pipeline', crmPipelineRecordIndex, { pluginId: BUNDLE_ID })\n // The company a person works for, and the templates reps write, as a sales\n // sequence reads them (AGL-3080). Deferred like the rest.\n registerPluginRecordIndex('company', crmCompanyRecordIndex, { pluginId: BUNDLE_ID })\n registerPluginRecordIndex('messageTemplate', crmMessageTemplateRecordIndex, { pluginId: BUNDLE_ID })\n // The automation steps that write the CRM (AGL-2605, AGL-3080), run for the\n // workflows engine through the server-step seam and declared under\n // `serverSteps`. Deferred like the rest: the writes load with the first step.\n registerServerStepExecutor(\n CRM_STEP_TYPES,\n async (request) => (await import('./server/automation-steps')).runCrmAutomationStep(request),\n { pluginId: BUNDLE_ID },\n )\n registerPluginConsentGroupParticipant(\n {\n async preview(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.preview(request)\n },\n async run(request) {\n const { consentGroupParticipant } = await import('./server/consent-group-participant')\n return consentGroupParticipant.run(request)\n },\n summarize: summarizeConsentGroupChange,\n },\n { pluginId: BUNDLE_ID },\n )\n // The records band in the monthly usage sweep, a core cron that never\n // loads a CRM door; declared in `usageAxes` so the sweep refuses to bill a\n // month without it. Deferred like the rest: the counts load with the\n // first sweep.\n registerPluginUsageMeter({\n pluginId: BUNDLE_ID,\n id: CRM_RECORDS_METER_ID,\n measure: async (context) => {\n const { measureCrmRecords } = await import('./server/crm-records-meter')\n return measureCrmRecords(context)\n },\n })\n}\n\n"],"names":["registerPluginConsentGroupParticipant","registerPluginContactCaptureWriter","registerPluginLeadConversionListener","registerPluginPersonMatcher","registerPluginPersonRecords","registerPluginRecordIndex","registerPluginRecordEmailStateWriter","registerPluginRecordOriginWriter","registerPluginRecordTimelineWriter","registerPluginRecordWrittenListener","registerPluginScopeSharingPatch","registerServerStepExecutor","registerPluginUsageMeter","BUNDLE_ID","CRM_RECORDS_METER_ID","CRM_STEP_TYPES","summarizeConsentGroupChange","crmContactCaptureWriter","capture","request","captureContactForCrm","crmPersonRecordsService","find","crmPersonRecords","read","fileUnder","recordRefund","peopleInView","wroteIn","search","changedSince","crmPipelineRecordIndex","list","pipelineRecordIndex","get","lazyCrmRecordIndex","kind","crmRecordIndexes","crmCompanyRecordIndex","crmMessageTemplateRecordIndex","crmRecordTimelineWriter","logActivity","createCrmRecordTimelineWriter","defaultCrmRecordTimelineDeps","createTask","recordEmailDelivery","recordTaggedDelivery","prepareEmail","prepareCrmRecordEmail","registerCrmServerDeclarations","pluginId","collection","next","crmScopeSharingPatch","carryLeadCampaignsOnConversion","matchCrmPeople","stamp","createCrmRecordEmailStateWriter","defaultCrmRecordEmailStateDeps","engaged","reached","replied","crmRecordOriginWriter","event","crmSharingRecordWritten","key","runCrmAutomationStep","preview","consentGroupParticipant","run","summarize","id","measure","context","measureCrmRecords"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,6EAA6E;AAC7E,SAASA,qCAAqC,QAAQ,0DAAyD;AAC/G,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,oCAAoC,QAAQ,qDAAoD;AACzG,SAASC,2BAA2B,QAAQ,oDAAmD;AAC/F,SACEC,2BAA2B,QAEtB,oDAAmD;AAC1D,SACEC,yBAAyB,QAEpB,kDAAiD;AACxD,SAASC,oCAAoC,QAAQ,wDAAuD;AAC5G,SAASC,gCAAgC,QAAQ,mDAAkD;AACnG,SACEC,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,mCAAmC,QAAQ,oDAAmD;AACvG,SAASC,+BAA+B,QAAQ,mDAAkD;AAClG,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,wBAAwB,QAAQ,kDAAiD;AAC1F,SAASC,SAAS,EAAEC,oBAAoB,EAAEC,cAAc,QAAQ,+BAA2B;AAC3F,SAASC,2BAA2B,QAAQ,mCAA+B;AAE3E;;;;;;;;CAQC,GACD,OAAO,MAAMC,0BAAsD;IACjE,MAAMC,SAAQC,OAAO;QACnB,MAAM,EAAEC,oBAAoB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC9C,OAAO,MAAMA,qBAAqBD;IACpC;AACF,EAAC;AAED;;;;CAIC,GACD,OAAO,MAAME,0BAA+C;IAC1D,MAAMC,MAAKH,OAAO;QAChB,MAAM,EAAEI,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,OAAOA,iBAAiBD,IAAI,CAACH;IAC/B;IACA,MAAMK,MAAKL,OAAO;QAChB,MAAM,EAAEI,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,OAAOA,iBAAiBC,IAAI,CAACL;IAC/B;IACA,MAAMM,WAAUN,OAAO;QACrB,M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mBAAmBkC,+BAA+B;QAAEW,UAAUrC;IAAU;IAClG,4EAA4E;IAC5E,mEAAmE;IACnE,8EAA8E;IAC9EF,2BACEI,gBACA,OAAOI,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,+BAA2B,EAAG+C,oBAAoB,CAAC/C,UACpF;QAAE+B,UAAUrC;IAAU;IAExBb,sCACE;QACE,MAAMmE,SAAQhD,OAAO;YACnB,MAAM,EAAEiD,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBD,OAAO,CAAChD;QACzC;QACA,MAAMkD,KAAIlD,OAAO;YACf,MAAM,EAAEiD,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAAC;YACjD,OAAOA,wBAAwBC,GAAG,CAAClD;QACrC;QACAmD,WAAWtD;IACb,GACA;QAAEkC,UAAUrC;IAAU;IAExB,sEAAsE;IACtE,2EAA2E;IAC3E,qEAAqE;IACrE,eAAe;IACfD,yBAAyB;QACvBsC,UAAUrC;QACV0D,IAAIzD;QACJ0D,SAAS,OAAOC;YACd,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC3C,OAAOA,kBAAkBD;QAC3B;IACF;AACF"}
@@ -42,9 +42,10 @@ export interface ContactsListSeed {
42
42
  * query built from it is the query a typed filter builds. Nothing here is a
43
43
  * second predicate.
44
44
  *
45
- * Pure, and strict about what it accepts: an unknown source or an address
46
- * that is not one seeds nothing rather than a filter that matches nothing,
47
- * because an empty list under a bad link reads as "no such people".
45
+ * Strict about what it accepts: a source neither the core nor a plugin
46
+ * declares, or an address that is not one, seeds nothing rather than a filter
47
+ * that matches nothing, because an empty list under a bad link reads as "no
48
+ * such people".
48
49
  */
49
50
  export declare function contactsListSeed(params: {
50
51
  get(name: string): string | null;
@@ -13,7 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { CONTACT_SOURCE_LABELS, normalizeContactEmail } from "@aglyn/aglyn";
16
+ */ import { normalizeContactEmail } from "@aglyn/aglyn";
17
+ import { isKnownContactSource } from "@aglyn/aglyn/plugin-manager/plugin-contact-capture";
17
18
  import { CONTACTS_LIST_EMAIL_PARAM, CONTACTS_LIST_FORM_PARAM, CONTACTS_LIST_SOURCE_PARAM } from "./crm-routes.js";
18
19
  const NO_SEED = {
19
20
  filter: null,
@@ -33,14 +34,15 @@ const NO_SEED = {
33
34
  * query built from it is the query a typed filter builds. Nothing here is a
34
35
  * second predicate.
35
36
  *
36
- * Pure, and strict about what it accepts: an unknown source or an address
37
- * that is not one seeds nothing rather than a filter that matches nothing,
38
- * because an empty list under a bad link reads as "no such people".
37
+ * Strict about what it accepts: a source neither the core nor a plugin
38
+ * declares, or an address that is not one, seeds nothing rather than a filter
39
+ * that matches nothing, because an empty list under a bad link reads as "no
40
+ * such people".
39
41
  */ export function contactsListSeed(params) {
40
42
  var _params_get, _params_get1;
41
43
  if (!params) return NO_SEED;
42
44
  const rawSource = (_params_get = params.get(CONTACTS_LIST_SOURCE_PARAM)) != null ? _params_get : '';
43
- const source = rawSource in CONTACT_SOURCE_LABELS ? rawSource : '';
45
+ const source = isKnownContactSource(rawSource) ? rawSource : '';
44
46
  const formId = ((_params_get1 = params.get(CONTACTS_LIST_FORM_PARAM)) != null ? _params_get1 : '').trim() || null;
45
47
  const openEmail = normalizeContactEmail(params.get(CONTACTS_LIST_EMAIL_PARAM));
46
48
  const filter = formId ? {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/contacts-list-seed.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 CONTACT_SOURCE_LABELS,\n type ContactSource,\n normalizeContactEmail,\n} from '@aglyn/aglyn'\nimport type { ListFilterRequest } from '@aglyn/shared-util-tools/list-query/list-filter'\nimport {\n CONTACTS_LIST_EMAIL_PARAM,\n CONTACTS_LIST_FORM_PARAM,\n CONTACTS_LIST_SOURCE_PARAM,\n} from './crm-routes'\n\n/** What the Contacts list opens ON, read off its own address. */\nexport interface ContactsListSeed {\n /** The grid filter to start with — the query's predicate — or none. */\n filter: ListFilterRequest | null\n /** The source select's starting value. */\n source: ContactSource | ''\n /** The form the list was opened for, when it was. */\n formId: string | null\n /**\n * The address the list was asked to OPEN, normalized, when it was — the\n * list moves on to the record itself once exactly one row matches.\n */\n openEmail: string | null\n}\n\nconst NO_SEED: ContactsListSeed = {\n filter: null,\n source: '',\n formId: null,\n openEmail: null,\n}\n\n/**\n * The Contacts list's starting state, from the query string another surface\n * sent it with (AGL-2612).\n *\n * Two surfaces address the list rather than a record: a form's own page,\n * asking for the people that form captured, and an Inbox submission row,\n * asking for the person with this address. Each is a filter the list\n * already speaks — `formIds contains` and `email equals` — so the seed is\n * the SAME `ListFilterRequest` the grid's own panel would produce, and the\n * query built from it is the query a typed filter builds. Nothing here is a\n * second predicate.\n *\n * Pure, and strict about what it accepts: an unknown source or an address\n * that is not one seeds nothing rather than a filter that matches nothing,\n * because an empty list under a bad link reads as \"no such people\".\n */\nexport function contactsListSeed(\n params: { get(name: string): string | null } | null | undefined,\n): ContactsListSeed {\n if (!params) return NO_SEED\n const rawSource = params.get(CONTACTS_LIST_SOURCE_PARAM) ?? ''\n const source =\n rawSource in CONTACT_SOURCE_LABELS ? (rawSource as ContactSource) : ''\n const formId = (params.get(CONTACTS_LIST_FORM_PARAM) ?? '').trim() || null\n const openEmail = normalizeContactEmail(\n params.get(CONTACTS_LIST_EMAIL_PARAM),\n )\n const filter: ListFilterRequest | null = formId\n ? { field: 'formIds', op: 'contains', value: formId }\n : openEmail\n ? { field: 'email', op: 'equals', value: openEmail }\n : null\n return { filter, source, formId, openEmail }\n}\n"],"names":["CONTACT_SOURCE_LABELS","normalizeContactEmail","CONTACTS_LIST_EMAIL_PARAM","CONTACTS_LIST_FORM_PARAM","CONTACTS_LIST_SOURCE_PARAM","NO_SEED","filter","source","formId","openEmail","contactsListSeed","params","rawSource","get","trim","field","op","value"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EAErBC,qBAAqB,QAChB,eAAc;AAErB,SACEC,yBAAyB,EACzBC,wBAAwB,EACxBC,0BAA0B,QACrB,kBAAc;AAiBrB,MAAMC,UAA4B;IAChCC,QAAQ;IACRC,QAAQ;IACRC,QAAQ;IACRC,WAAW;AACb;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,iBACdC,MAA+D;QAG7CA,aAGFA;IAJhB,IAAI,CAACA,QAAQ,OAAON;IACpB,MAAMO,aAAYD,cAAAA,OAAOE,GAAG,CAACT,uCAAXO,cAA0C;IAC5D,MAAMJ,SACJK,aAAaZ,wBAAyBY,YAA8B;IACtE,MAAMJ,SAAS,EAACG,eAAAA,OAAOE,GAAG,CAACV,qCAAXQ,eAAwC,IAAIG,IAAI,MAAM;IACtE,MAAML,YAAYR,sBAChBU,OAAOE,GAAG,CAACX;IAEb,MAAMI,SAAmCE,SACrC;QAAEO,OAAO;QAAWC,IAAI;QAAYC,OAAOT;IAAO,IAClDC,YACE;QAAEM,OAAO;QAASC,IAAI;QAAUC,OAAOR;IAAU,IACjD;IACN,OAAO;QAAEH;QAAQC;QAAQC;QAAQC;IAAU;AAC7C"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/contacts-list-seed.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 { type ContactSource, normalizeContactEmail } from '@aglyn/aglyn'\nimport { isKnownContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport type { ListFilterRequest } from '@aglyn/shared-util-tools/list-query/list-filter'\nimport {\n CONTACTS_LIST_EMAIL_PARAM,\n CONTACTS_LIST_FORM_PARAM,\n CONTACTS_LIST_SOURCE_PARAM,\n} from './crm-routes'\n\n/** What the Contacts list opens ON, read off its own address. */\nexport interface ContactsListSeed {\n /** The grid filter to start with — the query's predicate — or none. */\n filter: ListFilterRequest | null\n /** The source select's starting value. */\n source: ContactSource | ''\n /** The form the list was opened for, when it was. */\n formId: string | null\n /**\n * The address the list was asked to OPEN, normalized, when it was — the\n * list moves on to the record itself once exactly one row matches.\n */\n openEmail: string | null\n}\n\nconst NO_SEED: ContactsListSeed = {\n filter: null,\n source: '',\n formId: null,\n openEmail: null,\n}\n\n/**\n * The Contacts list's starting state, from the query string another surface\n * sent it with (AGL-2612).\n *\n * Two surfaces address the list rather than a record: a form's own page,\n * asking for the people that form captured, and an Inbox submission row,\n * asking for the person with this address. Each is a filter the list\n * already speaks — `formIds contains` and `email equals` — so the seed is\n * the SAME `ListFilterRequest` the grid's own panel would produce, and the\n * query built from it is the query a typed filter builds. Nothing here is a\n * second predicate.\n *\n * Strict about what it accepts: a source neither the core nor a plugin\n * declares, or an address that is not one, seeds nothing rather than a filter\n * that matches nothing, because an empty list under a bad link reads as \"no\n * such people\".\n */\nexport function contactsListSeed(\n params: { get(name: string): string | null } | null | undefined,\n): ContactsListSeed {\n if (!params) return NO_SEED\n const rawSource = params.get(CONTACTS_LIST_SOURCE_PARAM) ?? ''\n const source = isKnownContactSource(rawSource) ? (rawSource as ContactSource) : ''\n const formId = (params.get(CONTACTS_LIST_FORM_PARAM) ?? '').trim() || null\n const openEmail = normalizeContactEmail(\n params.get(CONTACTS_LIST_EMAIL_PARAM),\n )\n const filter: ListFilterRequest | null = formId\n ? { field: 'formIds', op: 'contains', value: formId }\n : openEmail\n ? { field: 'email', op: 'equals', value: openEmail }\n : null\n return { filter, source, formId, openEmail }\n}\n"],"names":["normalizeContactEmail","isKnownContactSource","CONTACTS_LIST_EMAIL_PARAM","CONTACTS_LIST_FORM_PARAM","CONTACTS_LIST_SOURCE_PARAM","NO_SEED","filter","source","formId","openEmail","contactsListSeed","params","rawSource","get","trim","field","op","value"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA6BA,qBAAqB,QAAQ,eAAc;AACxE,SAASC,oBAAoB,QAAQ,qDAAoD;AAEzF,SACEC,yBAAyB,EACzBC,wBAAwB,EACxBC,0BAA0B,QACrB,kBAAc;AAiBrB,MAAMC,UAA4B;IAChCC,QAAQ;IACRC,QAAQ;IACRC,QAAQ;IACRC,WAAW;AACb;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,iBACdC,MAA+D;QAG7CA,aAEFA;IAHhB,IAAI,CAACA,QAAQ,OAAON;IACpB,MAAMO,aAAYD,cAAAA,OAAOE,GAAG,CAACT,uCAAXO,cAA0C;IAC5D,MAAMJ,SAASN,qBAAqBW,aAAcA,YAA8B;IAChF,MAAMJ,SAAS,EAACG,eAAAA,OAAOE,GAAG,CAACV,qCAAXQ,eAAwC,IAAIG,IAAI,MAAM;IACtE,MAAML,YAAYT,sBAChBW,OAAOE,GAAG,CAACX;IAEb,MAAMI,SAAmCE,SACrC;QAAEO,OAAO;QAAWC,IAAI;QAAYC,OAAOT;IAAO,IAClDC,YACE;QAAEM,OAAO;QAASC,IAAI;QAAUC,OAAOR;IAAU,IACjD;IACN,OAAO;QAAEH;QAAQC;QAAQC;QAAQC;IAAU;AAC7C"}
@@ -18,9 +18,19 @@ import type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organiz
18
18
  import type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements';
19
19
  import type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions';
20
20
  /** The CRM's workspace keys, declared by tier. */
21
- export type CrmPermission = 'crm.settings';
21
+ export type CrmPermission = 'crm.settings' | 'crm.colleagueTemplates';
22
22
  /** "Change CRM settings". */
23
23
  export declare const CRM_SETTINGS_PERMISSION: CrmPermission;
24
+ /**
25
+ * "Change colleagues' email templates": the one rule branch that lets a member
26
+ * change or delete a personal template someone else keeps. It asked only whether
27
+ * the member spans the workspace, on top of the "Manage data" every template
28
+ * write asks, so every role holds this by default and those two questions still
29
+ * decide who reaches it: nobody's access moved, and a custom role or a member's
30
+ * own permissions can now refuse it. No route or console control asks it. A
31
+ * colleague's personal template is listed to nobody but its owner.
32
+ */
33
+ export declare const CRM_COLLEAGUE_TEMPLATES_PERMISSION: CrmPermission;
24
34
  /** The keys as the plugin declares them; owners and admins hold it by default. */
25
35
  export declare const CRM_PERMISSIONS: readonly PluginPermission[];
26
36
  /** The refusal a door or a control answers without it: names the permission, never a role. */
@@ -15,6 +15,15 @@
15
15
  * limitations under the License.
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  /** "Change CRM settings". */ export const CRM_SETTINGS_PERMISSION = 'crm.settings';
18
+ /**
19
+ * "Change colleagues' email templates": the one rule branch that lets a member
20
+ * change or delete a personal template someone else keeps. It asked only whether
21
+ * the member spans the workspace, on top of the "Manage data" every template
22
+ * write asks, so every role holds this by default and those two questions still
23
+ * decide who reaches it: nobody's access moved, and a custom role or a member's
24
+ * own permissions can now refuse it. No route or console control asks it. A
25
+ * colleague's personal template is listed to nobody but its owner.
26
+ */ export const CRM_COLLEAGUE_TEMPLATES_PERMISSION = 'crm.colleagueTemplates';
18
27
  /** The keys as the plugin declares them; owners and admins hold it by default. */ export const CRM_PERMISSIONS = [
19
28
  {
20
29
  key: 'crm.settings',
@@ -27,6 +36,18 @@
27
36
  viewer: false
28
37
  },
29
38
  groupLabel: 'CRM'
39
+ },
40
+ {
41
+ key: 'crm.colleagueTemplates',
42
+ pluginId: 'crm',
43
+ label: 'Change colleagues’ email templates',
44
+ description: 'Change or delete an email template or snippet a colleague keeps for themselves, or re-file any template. Asks “Manage data” over the whole workspace as well; a site collaborator never holds it.',
45
+ defaults: {
46
+ admin: true,
47
+ editor: true,
48
+ viewer: true
49
+ },
50
+ groupLabel: 'CRM'
30
51
  }
31
52
  ];
32
53
  /** The refusal a door or a control answers without it: names the permission, never a role. */ export function crmSettingsPermissionRefusal() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-permissions.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 type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/*\n * THE CRM'S SETTINGS FOR THE WHOLE WORKSPACE (AGL-4047).\n *\n * Every card under CRM → Settings that changes what the CRM does for every\n * site (default sharing for new records, creating companies from email\n * domains, default owners, assignment rules, the round-robin pool, the\n * sharing rules), rotating the capture address, and sharing a record with\n * other sites asked whether the member's workspace role was owner or admin:\n * the cards through `canManageOrg(role)`, the routes through\n * `authorizeOrgCaller(…, 'manage-org')` and `canRotate`, and the rules on the\n * workspace document's `crm` map through `canManageOrg()`. Each now asks this\n * key, whose default is exactly those roles (the owner on the admin tier), so\n * nobody's access moved, and a custom role or a member's own permissions can\n * grant or refuse it.\n *\n * Declared through `registerPluginPermissions`, as Sequences and the\n * marketplace's publisher keys are: a key of that registry joins the one\n * catalog, so the role editor offers it and the resolver, the console and the\n * native contracts answer it alike.\n *\n * Type-only imports: the native contracts generator assembles this into\n * `ORG_ROLE_GRANTS`.\n */\n\n/** The CRM's workspace keys, declared by tier. */\nexport type CrmPermission = 'crm.settings'\n\n/** \"Change CRM settings\". */\nexport const CRM_SETTINGS_PERMISSION: CrmPermission = 'crm.settings'\n\n/** The keys as the plugin declares them; owners and admins hold it by default. */\nexport const CRM_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'crm.settings',\n pluginId: 'crm',\n label: 'Change CRM settings',\n description:\n 'Change the CRM’s settings for every site: default sharing for new records, companies from email domains, default owners, assignment rules and the round-robin pool, sharing rules, and rotating the email capture address; and share records with other sites.',\n defaults: { admin: true, editor: false, viewer: false },\n groupLabel: 'CRM',\n },\n]\n\n/** The refusal a door or a control answers without it: names the permission, never a role. */\nexport function crmSettingsPermissionRefusal(): string {\n const label = CRM_PERMISSIONS.find((entry) => entry.key === CRM_SETTINGS_PERMISSION)?.label ?? CRM_SETTINGS_PERMISSION\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/*\n * MOVING A CONTACT OR A DEAL BETWEEN STAGES (AGL-4047).\n *\n * Both stage routes asked for the Admin or Editor role on the site they were\n * called for, and at the organization hub for \"Manage data\" over the whole\n * workspace. That is now this key, read two ways so every member keeps exactly\n * the access they had:\n *\n * - ON A SITE its preset is the member's role there (`presetFromSiteRole`):\n * the site's Admin and Editor, for a collaborator and a member of the whole\n * workspace alike. A site that narrows an editor to Author refuses them\n * and one that makes a viewer its Editor admits them, as the role check\n * did. That preset already follows every site's access, so the key offers\n * no separate narrowing control and declares no `narrowsPerSite`.\n * - WITH NO SITE NAMED, at the organization hub, it follows \"Manage data\"\n * until a custom role or a member's own permissions set it, because that\n * key is what the hub's door asked. A custom role that decided \"Manage\n * data\" keeps deciding it there, and this key can then refuse the hub's\n * stage moves on its own.\n *\n * Moving a deal still asks \"Manage data\" as well, at both levels, as it did\n * before this key: a deal is read through that key anyway.\n */\n\n/** The key both stage routes ask. */\nexport const CRM_MOVE_STAGES_PERMISSION = 'crm.moveStages'\n\n/** Who moved a site's contacts and deals before it was a key: the site's Admin and Editor. */\nexport const CRM_MOVE_STAGES_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/** The CRM's site key, as the plugin declares it into the org permission catalog. */\nexport const CRM_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'crm.moveStages',\n label: 'Move contacts and deals between stages',\n description:\n 'Change a contact’s lifecycle stage and move a deal through its pipeline, including winning, losing and reopening it. Follows the site role on a site, and “Manage data” in the organization hub, unless a role or member sets it.',\n roleDefaults: { owner: true, admin: true, editor: true, viewer: false },\n hostRoleDefaults: { ...CRM_MOVE_STAGES_SITE_ROLE_PRESET },\n follows: 'data.manage',\n group: 'crm',\n groupLabel: 'CRM',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a stage door or control answers without it: names the permission, never a role. */\nexport const CRM_MOVE_STAGES_REFUSAL =\n 'Your role does not include \"Move contacts and deals between stages\" — ask an organization admin'\n"],"names":["CRM_SETTINGS_PERMISSION","CRM_PERMISSIONS","key","pluginId","label","description","defaults","admin","editor","viewer","groupLabel","crmSettingsPermissionRefusal","find","entry","CRM_MOVE_STAGES_PERMISSION","CRM_MOVE_STAGES_SITE_ROLE_PRESET","author","CRM_SITE_PERMISSIONS","roleDefaults","owner","hostRoleDefaults","follows","group","presetFromSiteRole","CRM_MOVE_STAGES_REFUSAL"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAiCD,2BAA2B,GAC3B,OAAO,MAAMA,0BAAyC,eAAc;AAEpE,gFAAgF,GAChF,OAAO,MAAMC,kBAA+C;IAC1D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU;YAAEC,OAAO;YAAMC,QAAQ;YAAOC,QAAQ;QAAM;QACtDC,YAAY;IACd;CACD,CAAA;AAED,4FAA4F,GAC5F,OAAO,SAASC;;QACAV;IAAd,MAAMG,iBAAQH,wBAAAA,gBAAgBW,IAAI,CAAC,CAACC,QAAUA,MAAMX,GAAG,KAAKF,6CAA9CC,sBAAwEG,KAAK,mBAAIJ;IAC/F,OAAO,CAAC,4BAA4B,EAAEI,MAAM,6BAA6B,CAAC;AAC5E;AAEA;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,mCAAmC,GACnC,OAAO,MAAMU,6BAA6B,iBAAgB;AAE1D,4FAA4F,GAC5F,OAAO,MAAMC,mCAA8E;IACzFR,OAAO;IACPC,QAAQ;IACRQ,QAAQ;IACRP,QAAQ;AACV,EAAC;AAED,mFAAmF,GACnF,OAAO,MAAMQ,uBAAkE;IAC7E;QACEf,KAAK;QACLE,OAAO;QACPC,aACE;QACFa,cAAc;YAAEC,OAAO;YAAMZ,OAAO;YAAMC,QAAQ;YAAMC,QAAQ;QAAM;QACtEW,kBAAkB,aAAKL;QACvBM,SAAS;QACTC,OAAO;QACPZ,YAAY;QACZa,oBAAoB;IACtB;CACD,CAAA;AAED,gGAAgG,GAChG,OAAO,MAAMC,0BACX,kGAAiG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-permissions.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 type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/*\n * THE CRM'S SETTINGS FOR THE WHOLE WORKSPACE (AGL-4047).\n *\n * Every card under CRM → Settings that changes what the CRM does for every\n * site (default sharing for new records, creating companies from email\n * domains, default owners, assignment rules, the round-robin pool, the\n * sharing rules), rotating the capture address, and sharing a record with\n * other sites asked whether the member's workspace role was owner or admin:\n * the cards through `canManageOrg(role)`, the routes through\n * `authorizeOrgCaller(…, 'manage-org')` and `canRotate`, and the rules on the\n * workspace document's `crm` map through `canManageOrg()`. Each now asks this\n * key, whose default is exactly those roles (the owner on the admin tier), so\n * nobody's access moved, and a custom role or a member's own permissions can\n * grant or refuse it.\n *\n * Declared through `registerPluginPermissions`, as Sequences and the\n * marketplace's publisher keys are: a key of that registry joins the one\n * catalog, so the role editor offers it and the resolver, the console and the\n * native contracts answer it alike.\n *\n * Type-only imports: the native contracts generator assembles this into\n * `ORG_ROLE_GRANTS`.\n */\n\n/** The CRM's workspace keys, declared by tier. */\nexport type CrmPermission = 'crm.settings' | 'crm.colleagueTemplates'\n\n/** \"Change CRM settings\". */\nexport const CRM_SETTINGS_PERMISSION: CrmPermission = 'crm.settings'\n\n/**\n * \"Change colleagues' email templates\": the one rule branch that lets a member\n * change or delete a personal template someone else keeps. It asked only whether\n * the member spans the workspace, on top of the \"Manage data\" every template\n * write asks, so every role holds this by default and those two questions still\n * decide who reaches it: nobody's access moved, and a custom role or a member's\n * own permissions can now refuse it. No route or console control asks it. A\n * colleague's personal template is listed to nobody but its owner.\n */\nexport const CRM_COLLEAGUE_TEMPLATES_PERMISSION: CrmPermission = 'crm.colleagueTemplates'\n\n/** The keys as the plugin declares them; owners and admins hold it by default. */\nexport const CRM_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'crm.settings',\n pluginId: 'crm',\n label: 'Change CRM settings',\n description:\n 'Change the CRM’s settings for every site: default sharing for new records, companies from email domains, default owners, assignment rules and the round-robin pool, sharing rules, and rotating the email capture address; and share records with other sites.',\n defaults: { admin: true, editor: false, viewer: false },\n groupLabel: 'CRM',\n },\n {\n key: 'crm.colleagueTemplates',\n pluginId: 'crm',\n label: 'Change colleagues’ email templates',\n description:\n 'Change or delete an email template or snippet a colleague keeps for themselves, or re-file any template. Asks “Manage data” over the whole workspace as well; a site collaborator never holds it.',\n defaults: { admin: true, editor: true, viewer: true },\n groupLabel: 'CRM',\n },\n]\n\n/** The refusal a door or a control answers without it: names the permission, never a role. */\nexport function crmSettingsPermissionRefusal(): string {\n const label = CRM_PERMISSIONS.find((entry) => entry.key === CRM_SETTINGS_PERMISSION)?.label ?? CRM_SETTINGS_PERMISSION\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/*\n * MOVING A CONTACT OR A DEAL BETWEEN STAGES (AGL-4047).\n *\n * Both stage routes asked for the Admin or Editor role on the site they were\n * called for, and at the organization hub for \"Manage data\" over the whole\n * workspace. That is now this key, read two ways so every member keeps exactly\n * the access they had:\n *\n * - ON A SITE its preset is the member's role there (`presetFromSiteRole`):\n * the site's Admin and Editor, for a collaborator and a member of the whole\n * workspace alike. A site that narrows an editor to Author refuses them\n * and one that makes a viewer its Editor admits them, as the role check\n * did. That preset already follows every site's access, so the key offers\n * no separate narrowing control and declares no `narrowsPerSite`.\n * - WITH NO SITE NAMED, at the organization hub, it follows \"Manage data\"\n * until a custom role or a member's own permissions set it, because that\n * key is what the hub's door asked. A custom role that decided \"Manage\n * data\" keeps deciding it there, and this key can then refuse the hub's\n * stage moves on its own.\n *\n * Moving a deal still asks \"Manage data\" as well, at both levels, as it did\n * before this key: a deal is read through that key anyway.\n */\n\n/** The key both stage routes ask. */\nexport const CRM_MOVE_STAGES_PERMISSION = 'crm.moveStages'\n\n/** Who moved a site's contacts and deals before it was a key: the site's Admin and Editor. */\nexport const CRM_MOVE_STAGES_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/** The CRM's site key, as the plugin declares it into the org permission catalog. */\nexport const CRM_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'crm.moveStages',\n label: 'Move contacts and deals between stages',\n description:\n 'Change a contact’s lifecycle stage and move a deal through its pipeline, including winning, losing and reopening it. Follows the site role on a site, and “Manage data” in the organization hub, unless a role or member sets it.',\n roleDefaults: { owner: true, admin: true, editor: true, viewer: false },\n hostRoleDefaults: { ...CRM_MOVE_STAGES_SITE_ROLE_PRESET },\n follows: 'data.manage',\n group: 'crm',\n groupLabel: 'CRM',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a stage door or control answers without it: names the permission, never a role. */\nexport const CRM_MOVE_STAGES_REFUSAL =\n 'Your role does not include \"Move contacts and deals between stages\" — ask an organization admin'\n"],"names":["CRM_SETTINGS_PERMISSION","CRM_COLLEAGUE_TEMPLATES_PERMISSION","CRM_PERMISSIONS","key","pluginId","label","description","defaults","admin","editor","viewer","groupLabel","crmSettingsPermissionRefusal","find","entry","CRM_MOVE_STAGES_PERMISSION","CRM_MOVE_STAGES_SITE_ROLE_PRESET","author","CRM_SITE_PERMISSIONS","roleDefaults","owner","hostRoleDefaults","follows","group","presetFromSiteRole","CRM_MOVE_STAGES_REFUSAL"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAiCD,2BAA2B,GAC3B,OAAO,MAAMA,0BAAyC,eAAc;AAEpE;;;;;;;;CAQC,GACD,OAAO,MAAMC,qCAAoD,yBAAwB;AAEzF,gFAAgF,GAChF,OAAO,MAAMC,kBAA+C;IAC1D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU;YAAEC,OAAO;YAAMC,QAAQ;YAAOC,QAAQ;QAAM;QACtDC,YAAY;IACd;IACA;QACER,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU;YAAEC,OAAO;YAAMC,QAAQ;YAAMC,QAAQ;QAAK;QACpDC,YAAY;IACd;CACD,CAAA;AAED,4FAA4F,GAC5F,OAAO,SAASC;;QACAV;IAAd,MAAMG,iBAAQH,wBAAAA,gBAAgBW,IAAI,CAAC,CAACC,QAAUA,MAAMX,GAAG,KAAKH,6CAA9CE,sBAAwEG,KAAK,mBAAIL;IAC/F,OAAO,CAAC,4BAA4B,EAAEK,MAAM,6BAA6B,CAAC;AAC5E;AAEA;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,mCAAmC,GACnC,OAAO,MAAMU,6BAA6B,iBAAgB;AAE1D,4FAA4F,GAC5F,OAAO,MAAMC,mCAA8E;IACzFR,OAAO;IACPC,QAAQ;IACRQ,QAAQ;IACRP,QAAQ;AACV,EAAC;AAED,mFAAmF,GACnF,OAAO,MAAMQ,uBAAkE;IAC7E;QACEf,KAAK;QACLE,OAAO;QACPC,aACE;QACFa,cAAc;YAAEC,OAAO;YAAMZ,OAAO;YAAMC,QAAQ;YAAMC,QAAQ;QAAM;QACtEW,kBAAkB,aAAKL;QACvBM,SAAS;QACTC,OAAO;QACPZ,YAAY;QACZa,oBAAoB;IACtB;CACD,CAAA;AAED,gGAAgG,GAChG,OAAO,MAAMC,0BACX,kGAAiG"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a
19
+ * sweep that changes the sites on a record restamps them in the same write,
20
+ * and a site's search finds the record the moment it can see it.
21
+ */
22
+ export declare function crmScopeSharingPatch(collection: string, next: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { crmListFieldsPatch } from "@aglyn/aglyn/app-utils/crm";
17
+ /**
18
+ * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a
19
+ * sweep that changes the sites on a record restamps them in the same write,
20
+ * and a site's search finds the record the moment it can see it.
21
+ */ export function crmScopeSharingPatch(collection, next) {
22
+ return crmListFieldsPatch(collection, next);
23
+ }
24
+
25
+ //# sourceMappingURL=scope-sharing-patch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/scope-sharing-patch.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 { crmListFieldsPatch, type CrmListCollection } from '@aglyn/aglyn/app-utils/crm'\n\n/**\n * The CRM's scoped list fields are derived from `visibleTo` (AGL-3321), so a\n * sweep that changes the sites on a record restamps them in the same write,\n * and a site's search finds the record the moment it can see it.\n */\nexport function crmScopeSharingPatch(\n collection: string,\n next: Record<string, unknown>,\n): Record<string, unknown> {\n return crmListFieldsPatch(collection as CrmListCollection, next)\n}\n"],"names":["crmListFieldsPatch","crmScopeSharingPatch","collection","next"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAgC,6BAA4B;AAEvF;;;;CAIC,GACD,OAAO,SAASC,qBACdC,UAAkB,EAClBC,IAA6B;IAE7B,OAAOH,mBAAmBE,YAAiCC;AAC7D"}