@aglyn/plugins-crm 1.0.0-beta.168 → 1.0.0-beta.169

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.0.0-beta.168",
3
+ "version": "1.0.0-beta.169",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,18 +25,18 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.168",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.168",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.168",
31
- "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.168",
32
- "@aglyn/shared-ui-jsx": "1.0.0-beta.168",
33
- "@aglyn/shared-ui-next": "1.0.0-beta.168",
34
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.168",
35
- "@aglyn/shared-util-email": "1.0.0-beta.168",
36
- "@aglyn/shared-util-http": "1.0.0-beta.168",
37
- "@aglyn/tenant-data-admin": "1.0.0-beta.168",
38
- "@aglyn/tenant-feature-instance": "1.0.0-beta.168",
39
- "@aglyn/tenant-runtime": "1.0.0-beta.168",
28
+ "@aglyn/aglyn": "1.0.0-beta.169",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.169",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.169",
31
+ "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.169",
32
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.169",
33
+ "@aglyn/shared-ui-next": "1.0.0-beta.169",
34
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.169",
35
+ "@aglyn/shared-util-email": "1.0.0-beta.169",
36
+ "@aglyn/shared-util-http": "1.0.0-beta.169",
37
+ "@aglyn/tenant-data-admin": "1.0.0-beta.169",
38
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.169",
39
+ "@aglyn/tenant-runtime": "1.0.0-beta.169",
40
40
  "@dnd-kit/core": "^6.3.1",
41
41
  "@dnd-kit/utilities": "^3.2.2",
42
42
  "@swc/helpers": "0.5.23",
@@ -68,10 +68,11 @@ import TasksSection from "./tasks-section.js";
68
68
  * them, so the id alone could not say which record was meant. A lead is
69
69
  * one org row now, and addresses like every other CRM record.
70
70
  *
71
- * The two-segment form is still ACCEPTED, and deliberately: links to a
72
- * lead were shared, bookmarked and mailed while the old shape was live,
73
- * and the id it carries is the same person key either way. The site
74
- * segment is simply dropped.
71
+ * The two-segment form is STILL ACCEPTED, and stays accepted past
72
+ * AGL-3277: links were shared, bookmarked and mailed while the old
73
+ * shape was live, and the id they carry is the same person key. What
74
+ * AGL-3277 removed is the storage behind the old shape, not the
75
+ * courtesy of honoring a link somebody already has.
75
76
  */ return record ? !props.hostId && detail.length >= 2 ? /*#__PURE__*/ _jsx(LeadDetailPage, _extends({}, recordProps, {
76
77
  id: detail[1]
77
78
  })) : /*#__PURE__*/ _jsx(LeadDetailPage, _extends({}, recordProps, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-console-page.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 type { ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { HubSections } from '@aglyn/shared-ui-next'\nimport type { ReactNode } from 'react'\nimport { CrmOrgMountProvider } from '../hooks/use-crm-org-mount'\nimport CompaniesSection from './companies-section'\nimport CompanyDetailPage from './company-detail-page'\nimport ContactDetailPage from './contact-detail-page'\nimport type { CrmConsoleSectionId } from './crm-console-sections'\nimport DealDetailPage from './deal-detail-page'\nimport DealsSection from './deals-section'\nimport FieldsSection from './fields-section'\nimport LeadDetailPage from './lead-detail-page'\nimport LeadsSection from './leads-section'\nimport ContactsSection from './contacts-section'\nimport ReportsSection from './reports-section'\nimport CrmSettingsSection from './settings-section'\nimport TasksSection from './tasks-section'\n\n/**\n * The body of one Contacts section, built only when that section is the one\n * being read (AGL-2595).\n *\n * A function rather than a map of nodes on purpose: a `Record<id, ReactNode>`\n * would CONSTRUCT every section on every render, and the people list alone\n * opens four Firestore listens and an aggregate read on mount. Only the\n * returned branch is ever built.\n *\n * Three sections own a deeper route — a record beneath the list — and read\n * it off `detail`, the segments after the section id. A list section with\n * nothing after it is the list; one segment is the record; the shell has\n * already 404'd anything it could not resolve to this surface.\n */\nfunction sectionBody(\n section: CrmConsoleSectionId,\n props: ConsolePluginPageProps,\n /** The section's OWN segments — `segments[1]` onward. */\n detail: readonly string[],\n basePath: string,\n): ReactNode {\n const record = detail[0]\n const recordProps = {\n hostId: props.hostId,\n org: props.org,\n permissions: props.permissions,\n releaseFlag: props.releaseFlag,\n hostRole: props.hostRole,\n basePath,\n }\n switch (section) {\n case 'contacts':\n return record ? (\n <ContactDetailPage {...recordProps} id={record} />\n ) : (\n <ContactsSection {...props} />\n )\n case 'leads':\n /*\n * ONE SEGMENT, at both levels (AGL-3275).\n *\n * The organization level used to name the site before the id —\n * `leads/{hostId}/{leadId}` (AGL-2630) — because a lead lived under its\n * site and a person key was the same id under each site that had met\n * them, so the id alone could not say which record was meant. A lead is\n * one org row now, and addresses like every other CRM record.\n *\n * The two-segment form is still ACCEPTED, and deliberately: links to a\n * lead were shared, bookmarked and mailed while the old shape was live,\n * and the id it carries is the same person key either way. The site\n * segment is simply dropped.\n */\n return record ? (\n !props.hostId && detail.length >= 2 ? (\n <LeadDetailPage {...recordProps} id={detail[1]} />\n ) : (\n <LeadDetailPage {...recordProps} id={record} />\n )\n ) : (\n <LeadsSection {...props} />\n )\n case 'companies':\n return record ? (\n <CompanyDetailPage {...recordProps} id={record} />\n ) : (\n <CompaniesSection\n hostId={props.hostId}\n org={props.org}\n basePath={basePath}\n />\n )\n case 'deals':\n return record ? (\n <DealDetailPage {...recordProps} id={record} />\n ) : (\n <DealsSection {...props} />\n )\n case 'tasks':\n return <TasksSection {...props} />\n case 'reports':\n // The shell's props whole, like the contacts list: the reports resolve\n // the org scope from `hostId`, the consent group from `org`, and their\n // drill-down links from `basePath` (AGL-2604).\n return <ReportsSection {...props} />\n case 'fields':\n return <FieldsSection hostId={props.hostId} org={props.org} />\n case 'settings':\n // The org-wide switches (AGL-2613): what the CRM does on its own for\n // every site in the workspace, written to the org document.\n return <CrmSettingsSection hostId={props.hostId} org={props.org} />\n default:\n return null\n }\n}\n\n/**\n * Contacts (AGL-109 → AGL-395 → AGL-2595): the CRM hub — people, companies,\n * deals, tasks, reports and fields — owned by the contacts plugin and\n * rendered by the shell's generic plugin route. The shell applies the\n * `release_crm` gate (via the nav tab) and passes the resolved `org`\n * doc, which the people section reads for the `contactsPerHost` quota.\n *\n * Sections are ROUTES, following the hubs that migrated before it (AGL-2501):\n * `/contacts/people` is the v1 list, and every other section is a URL of its\n * own, so the page builds one section's body and the others do not exist to\n * subscribe. The v1 body moved to `contacts-section.tsx` untouched; what this\n * file adds is the rail and the switch.\n */\nexport function CrmConsolePage(props: ConsolePluginPageProps) {\n const { section, sections, basePath, segments, orgMount } = props\n\n /*\n * Nothing until the URL names a section. The shell redirects a bare\n * `/contacts` to the landing section and holds a spinner while it does, so\n * this state is transient — and rendering the people list here instead\n * would pay for its listens on a URL that is already being replaced.\n */\n if (!section || !sections?.length || !basePath) return null\n\n const hub = (\n <HubSections sections={sections}>\n {sectionBody(\n section as CrmConsoleSectionId,\n props,\n // `segments[0]` IS the section — the shell resolved it into `section`\n // already — so what a section owns is everything after it.\n (segments ?? []).slice(1),\n basePath,\n )}\n </HubSections>\n )\n /*\n * THE ORGANIZATION-LEVEL MOUNT (AGL-2630). The shell hands an `orgMount`\n * only from `/[orgSlug]/crm`, where there is no site: the hub publishes it\n * so every section, record page and drawer beneath resolves its scope from\n * the org rather than from the `null` host it was handed. Under a site\n * there is no provider, and `useCrmOrgMount` answering `null` is how a\n * surface knows it is on one.\n */\n return orgMount ? (\n <CrmOrgMountProvider mount={orgMount}>{hub}</CrmOrgMountProvider>\n ) : (\n hub\n )\n}\nCrmConsolePage.displayName = 'CrmConsolePage'\n\nexport default CrmConsolePage\n"],"names":["HubSections","CrmOrgMountProvider","CompaniesSection","CompanyDetailPage","ContactDetailPage","DealDetailPage","DealsSection","FieldsSection","LeadDetailPage","LeadsSection","ContactsSection","ReportsSection","CrmSettingsSection","TasksSection","sectionBody","section","props","detail","basePath","record","recordProps","hostId","org","permissions","releaseFlag","hostRole","id","length","CrmConsolePage","sections","segments","orgMount","hub","slice","mount","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SAASA,WAAW,QAAQ,wBAAuB;AAEnD,SAASC,mBAAmB,QAAQ,gCAA4B;AAChE,OAAOC,sBAAsB,yBAAqB;AAClD,OAAOC,uBAAuB,2BAAuB;AACrD,OAAOC,uBAAuB,2BAAuB;AAErD,OAAOC,oBAAoB,wBAAoB;AAC/C,OAAOC,kBAAkB,qBAAiB;AAC1C,OAAOC,mBAAmB,sBAAkB;AAC5C,OAAOC,oBAAoB,wBAAoB;AAC/C,OAAOC,kBAAkB,qBAAiB;AAC1C,OAAOC,qBAAqB,wBAAoB;AAChD,OAAOC,oBAAoB,uBAAmB;AAC9C,OAAOC,wBAAwB,wBAAoB;AACnD,OAAOC,kBAAkB,qBAAiB;AAE1C;;;;;;;;;;;;;CAaC,GACD,SAASC,YACPC,OAA4B,EAC5BC,KAA6B,EAC7B,uDAAuD,GACvDC,MAAyB,EACzBC,QAAgB;IAEhB,MAAMC,SAASF,MAAM,CAAC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AAEC,QAAQ,EAAE,GAAGf;IAE5D;;;;;GAKC,GACD,IAAI,CAACD,WAAW,EAACc,4BAAAA,SAAUF,MAAM,KAAI,CAACT,UAAU,OAAO;IAEvD,MAAMc,oBACJ,KAAChC;QAAY6B,UAAUA;kBACpBf,YACCC,SACAC,OAGA,CAFA,sEAAsE;QACtE,2DAA2D;QAC1Dc,mBAAAA,WAAY,EAAE,EAAEG,KAAK,CAAC,IACvBf;;IAIN;;;;;;;GAOC,GACD,OAAOa,yBACL,KAAC9B;QAAoBiC,OAAOH;kBAAWC;SAEvCA;AAEJ;AACAJ,eAAeO,WAAW,GAAG;AAE7B,eAAeP,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-console-page.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 type { ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { HubSections } from '@aglyn/shared-ui-next'\nimport type { ReactNode } from 'react'\nimport { CrmOrgMountProvider } from '../hooks/use-crm-org-mount'\nimport CompaniesSection from './companies-section'\nimport CompanyDetailPage from './company-detail-page'\nimport ContactDetailPage from './contact-detail-page'\nimport type { CrmConsoleSectionId } from './crm-console-sections'\nimport DealDetailPage from './deal-detail-page'\nimport DealsSection from './deals-section'\nimport FieldsSection from './fields-section'\nimport LeadDetailPage from './lead-detail-page'\nimport LeadsSection from './leads-section'\nimport ContactsSection from './contacts-section'\nimport ReportsSection from './reports-section'\nimport CrmSettingsSection from './settings-section'\nimport TasksSection from './tasks-section'\n\n/**\n * The body of one Contacts section, built only when that section is the one\n * being read (AGL-2595).\n *\n * A function rather than a map of nodes on purpose: a `Record<id, ReactNode>`\n * would CONSTRUCT every section on every render, and the people list alone\n * opens four Firestore listens and an aggregate read on mount. Only the\n * returned branch is ever built.\n *\n * Three sections own a deeper route — a record beneath the list — and read\n * it off `detail`, the segments after the section id. A list section with\n * nothing after it is the list; one segment is the record; the shell has\n * already 404'd anything it could not resolve to this surface.\n */\nfunction sectionBody(\n section: CrmConsoleSectionId,\n props: ConsolePluginPageProps,\n /** The section's OWN segments — `segments[1]` onward. */\n detail: readonly string[],\n basePath: string,\n): ReactNode {\n const record = detail[0]\n const recordProps = {\n hostId: props.hostId,\n org: props.org,\n permissions: props.permissions,\n releaseFlag: props.releaseFlag,\n hostRole: props.hostRole,\n basePath,\n }\n switch (section) {\n case 'contacts':\n return record ? (\n <ContactDetailPage {...recordProps} id={record} />\n ) : (\n <ContactsSection {...props} />\n )\n case 'leads':\n /*\n * ONE SEGMENT, at both levels (AGL-3275).\n *\n * The organization level used to name the site before the id —\n * `leads/{hostId}/{leadId}` (AGL-2630) — because a lead lived under its\n * site and a person key was the same id under each site that had met\n * them, so the id alone could not say which record was meant. A lead is\n * one org row now, and addresses like every other CRM record.\n *\n * The two-segment form is STILL ACCEPTED, and stays accepted past\n * AGL-3277: links were shared, bookmarked and mailed while the old\n * shape was live, and the id they carry is the same person key. What\n * AGL-3277 removed is the storage behind the old shape, not the\n * courtesy of honoring a link somebody already has.\n */\n return record ? (\n !props.hostId && detail.length >= 2 ? (\n <LeadDetailPage {...recordProps} id={detail[1]} />\n ) : (\n <LeadDetailPage {...recordProps} id={record} />\n )\n ) : (\n <LeadsSection {...props} />\n )\n case 'companies':\n return record ? (\n <CompanyDetailPage {...recordProps} id={record} />\n ) : (\n <CompaniesSection\n hostId={props.hostId}\n org={props.org}\n basePath={basePath}\n />\n )\n case 'deals':\n return record ? (\n <DealDetailPage {...recordProps} id={record} />\n ) : (\n <DealsSection {...props} />\n )\n case 'tasks':\n return <TasksSection {...props} />\n case 'reports':\n // The shell's props whole, like the contacts list: the reports resolve\n // the org scope from `hostId`, the consent group from `org`, and their\n // drill-down links from `basePath` (AGL-2604).\n return <ReportsSection {...props} />\n case 'fields':\n return <FieldsSection hostId={props.hostId} org={props.org} />\n case 'settings':\n // The org-wide switches (AGL-2613): what the CRM does on its own for\n // every site in the workspace, written to the org document.\n return <CrmSettingsSection hostId={props.hostId} org={props.org} />\n default:\n return null\n }\n}\n\n/**\n * Contacts (AGL-109 → AGL-395 → AGL-2595): the CRM hub — people, companies,\n * deals, tasks, reports and fields — owned by the contacts plugin and\n * rendered by the shell's generic plugin route. The shell applies the\n * `release_crm` gate (via the nav tab) and passes the resolved `org`\n * doc, which the people section reads for the `contactsPerHost` quota.\n *\n * Sections are ROUTES, following the hubs that migrated before it (AGL-2501):\n * `/contacts/people` is the v1 list, and every other section is a URL of its\n * own, so the page builds one section's body and the others do not exist to\n * subscribe. The v1 body moved to `contacts-section.tsx` untouched; what this\n * file adds is the rail and the switch.\n */\nexport function CrmConsolePage(props: ConsolePluginPageProps) {\n const { section, sections, basePath, segments, orgMount } = props\n\n /*\n * Nothing until the URL names a section. The shell redirects a bare\n * `/contacts` to the landing section and holds a spinner while it does, so\n * this state is transient — and rendering the people list here instead\n * would pay for its listens on a URL that is already being replaced.\n */\n if (!section || !sections?.length || !basePath) return null\n\n const hub = (\n <HubSections sections={sections}>\n {sectionBody(\n section as CrmConsoleSectionId,\n props,\n // `segments[0]` IS the section — the shell resolved it into `section`\n // already — so what a section owns is everything after it.\n (segments ?? []).slice(1),\n basePath,\n )}\n </HubSections>\n )\n /*\n * THE ORGANIZATION-LEVEL MOUNT (AGL-2630). The shell hands an `orgMount`\n * only from `/[orgSlug]/crm`, where there is no site: the hub publishes it\n * so every section, record page and drawer beneath resolves its scope from\n * the org rather than from the `null` host it was handed. Under a site\n * there is no provider, and `useCrmOrgMount` answering `null` is how a\n * surface knows it is on one.\n */\n return orgMount ? (\n <CrmOrgMountProvider mount={orgMount}>{hub}</CrmOrgMountProvider>\n ) : (\n hub\n )\n}\nCrmConsolePage.displayName = 'CrmConsolePage'\n\nexport default CrmConsolePage\n"],"names":["HubSections","CrmOrgMountProvider","CompaniesSection","CompanyDetailPage","ContactDetailPage","DealDetailPage","DealsSection","FieldsSection","LeadDetailPage","LeadsSection","ContactsSection","ReportsSection","CrmSettingsSection","TasksSection","sectionBody","section","props","detail","basePath","record","recordProps","hostId","org","permissions","releaseFlag","hostRole","id","length","CrmConsolePage","sections","segments","orgMount","hub","slice","mount","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SAASA,WAAW,QAAQ,wBAAuB;AAEnD,SAASC,mBAAmB,QAAQ,gCAA4B;AAChE,OAAOC,sBAAsB,yBAAqB;AAClD,OAAOC,uBAAuB,2BAAuB;AACrD,OAAOC,uBAAuB,2BAAuB;AAErD,OAAOC,oBAAoB,wBAAoB;AAC/C,OAAOC,kBAAkB,qBAAiB;AAC1C,OAAOC,mBAAmB,sBAAkB;AAC5C,OAAOC,oBAAoB,wBAAoB;AAC/C,OAAOC,kBAAkB,qBAAiB;AAC1C,OAAOC,qBAAqB,wBAAoB;AAChD,OAAOC,oBAAoB,uBAAmB;AAC9C,OAAOC,wBAAwB,wBAAoB;AACnD,OAAOC,kBAAkB,qBAAiB;AAE1C;;;;;;;;;;;;;CAaC,GACD,SAASC,YACPC,OAA4B,EAC5BC,KAA6B,EAC7B,uDAAuD,GACvDC,MAAyB,EACzBC,QAAgB;IAEhB,MAAMC,SAASF,MAAM,CAAC,EAAE;IACxB,MAAMG,cAAc;QAClBC,QAAQL,MAAMK,MAAM;QACpBC,KAAKN,MAAMM,GAAG;QACdC,aAAaP,MAAMO,WAAW;QAC9BC,aAAaR,MAAMQ,WAAW;QAC9BC,UAAUT,MAAMS,QAAQ;QACxBP;IACF;IACA,OAAQH;QACN,KAAK;YACH,OAAOI,uBACL,KAACf,gCAAsBgB;gBAAaM,IAAI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AAEG,KAAK,CAAC,IACvBf;;IAIN;;;;;;;GAOC,GACD,OAAOa,yBACL,KAAC9B;QAAoBiC,OAAOH;kBAAWC;SAEvCA;AAEJ;AACAJ,eAAeO,WAAW,GAAG;AAE7B,eAAeP,eAAc"}
@@ -254,14 +254,9 @@ import { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from "./org-caller.
254
254
  });
255
255
  }
256
256
  /*
257
- * THE ORG ROW, AND EVERY LEGACY ROW STILL STANDING.
258
- *
259
- * An erasure may not be the one caller that trusts the migration to be
260
- * finished: until AGL-3276 has folded every site and AGL-3277 has deleted
261
- * the fallback, a person can still be held at `hosts/{siteId}/leads`, and
262
- * a marker that reached only the org row would leave that copy unmarked.
263
- * So this marks whatever exists, in both homes, and the sweep costs one
264
- * read per site exactly as it did before.
257
+ * THE ORG ROW. One document for the person, since AGL-3276 emptied the
258
+ * host path and AGL-3277 removed it — the per-site sweep this used to do
259
+ * beside it had nothing left to find.
265
260
  */ const eraseLeadAt = async (ref, where)=>{
266
261
  await ref.get().then((snapshot)=>snapshot.exists ? ref.update({
267
262
  [CONTACT_ERASURE_REQUESTED_FIELD]: now
@@ -270,9 +265,6 @@ import { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from "./org-caller.
270
265
  });
271
266
  };
272
267
  await eraseLeadAt(firestore.collection('orgs').doc(orgId).collection('leads').doc(key), orgId);
273
- for (const siteId of hostIds){
274
- await eraseLeadAt(firestore.collection('hosts').doc(siteId).collection('leads').doc(key), siteId);
275
- }
276
268
  try {
277
269
  const contacts = await firestore.collection('orgs').doc(orgId).collection('contacts').where('email', '==', recordEmail).get();
278
270
  for (const contact of contacts.docs){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/erase-person.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 canManageOrg,\n CONTACT_ERASURE_REQUESTED_FIELD,\n normalizeContactEmail,\n PERSON_ERASURES_COLLECTION,\n personErasureConfirmationMatches,\n personErasureId,\n type PersonErasureRequest,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n logOrgActivity,\n orgDataCollectionForHost,\n readLeadForHost,\n suppressEmailForHostErasure,\n} from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\n\n/** The route key, as `registerCrmConsoleApi` registers it. */\nexport const CRM_ERASE_PERSON_ROUTE = 'crm/erase-person'\n\nexport interface ErasePersonRequestBody {\n /**\n * The site the request is filed from. At the organization level\n * (AGL-2634) the record's own site, or absent for a contact no site has\n * captured; a LEAD always names one, because a lead lives under its site.\n */\n hostId?: string\n /** The organization, at the organization level (AGL-2634). */\n orgId?: string\n /**\n * At most one of these names the record the request is filed from. Under\n * a site exactly one does; at the organization level neither may, which\n * files the request by `email` alone (AGL-2839).\n */\n contactId?: string\n leadId?: string\n /**\n * The address as the admin typed it — the confirmation of a record's\n * address, or, filed by address alone, the person the request is about.\n */\n email: string\n /** Filed by address alone: the address typed a second time. */\n confirmEmail?: string\n}\n\nexport interface ErasePersonResponse {\n ok: true\n requestId: string\n /** When the request entered the queue. */\n pendingSinceMs: number\n /** True when a request for this person was already waiting; nothing was re-filed. */\n alreadyPending: boolean\n}\n\n/**\n * `POST /api/crm/erase-person` — file a privacy erasure for one person\n * (AGL-2623).\n *\n * ## Who may\n *\n * A workspace admin or owner — `canManageOrg` on the caller's org role —\n * and nobody else. Not a site editor with the data permission, who can\n * detach a contact from their own site but has no standing to remove the\n * person from every site in the workspace; and not staff acting alone,\n * because the workspace is the controller of this data and the instruction\n * has to come from it. Staff who are also admins of the workspace pass on\n * that role, as anyone would.\n *\n * ## What it does, and what it does not\n *\n * It files the request and closes the doors; it deletes nothing. The daily\n * erasure job executes the sweep, so that a workspace's person erasures and\n * its own erasure run through one job, one audit trail and one queue a\n * staff member can watch. What happens here, in order:\n *\n * 1. The record named by the body is read and its address is what the\n * request is about — the body's address must match it, typed, so an\n * admin who opened the wrong record is stopped by the confirmation\n * rather than by luck.\n * 2. The request document is written, or found already pending, in\n * which case nothing is re-filed and the caller is told so.\n * 3. Every site of the workspace gets its suppression row NOW, not when\n * the job runs: from this moment a capture cannot rebuild the person.\n * 4. The contact document and each site's lead are stamped with the\n * request time, so their pages can say \"erasure pending\" off the\n * document they already read.\n * 5. The site's activity feed and the platform audit log each get a row\n * that names the record by id and the person by hash, never by\n * address.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, hostId?, contactId | leadId, email }` from the org-level hub:\n * the same workspace admin, authorized by the org rather than through a\n * site they name, so a contact no site captured can be erased from the\n * page that lists it. The sweep is what it always was — every site of the\n * org, found by `orgId` — and the row goes to the org's feed. A lead still\n * names its site, because that is where a lead lives.\n *\n * ## By address alone (AGL-2839)\n *\n * `{ orgId, email, confirmEmail }` with no record, from the workspace's\n * Privacy settings: the same workspace admin, for any person the workspace\n * may hold — including one no page shows, since the CRM that lists records\n * is included from Starter and a Free workspace has none of it. Nothing is\n * read to file it: the sweep is keyed by the address, the markers are found\n * by it, and the typed address must match its second typing, which is the\n * confirmation a record's address gives the other variants. No plan is\n * asked on any variant: erasure is an obligation, not a CRM feature.\n */\nexport const crmErasePersonHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n const body: Partial<ErasePersonRequestBody> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const routeScope = readCrmRouteScope(body as Record<string, unknown>)\n const contactId = String(body.contactId ?? '').trim()\n const leadId = String(body.leadId ?? '').trim()\n const byAddress = routeScope?.level === 'org' && !contactId && !leadId\n if (!routeScope || (!byAddress && !contactId && !leadId) || (contactId && leadId)) {\n res.status(400).json({ error: 'Name the site and exactly one contact or lead' })\n return\n }\n const { hostId } = routeScope\n if (leadId && !hostId) {\n res.status(400).json({ error: 'Name the site the lead lives under' })\n return\n }\n const refusal = 'Only a workspace admin can erase a person from the workspace'\n\n try {\n let orgId: string\n let actor: { uid: string; email: string | null }\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'manage-org',\n refusal,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n orgId = caller.orgId\n actor = { uid: caller.uid, email: caller.email }\n } else {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!canManageOrg(membership.role)) {\n res.status(403).json({ error: refusal })\n return\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved || resolved.orgId !== membership.orgId) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n orgId = resolved.orgId\n actor = { uid: decoded.uid, email: decoded.email ?? null }\n }\n const firestore = firebaseAdmin.app().firestore()\n\n let recordEmail: string | null = null\n if (byAddress) {\n recordEmail = normalizeContactEmail(body.email)\n } else if (contactId) {\n const contactsRef =\n routeScope.level === 'org'\n ? firestore.collection('orgs').doc(orgId).collection('contacts')\n : await orgDataCollectionForHost(hostId, 'contacts')\n const contact = await contactsRef.doc(contactId).get()\n if (!contact.exists) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n recordEmail = normalizeContactEmail(contact.get('email'))\n } else {\n const lead = await readLeadForHost(hostId, leadId)\n if (!lead) {\n res.status(404).json({ error: 'Unknown lead' })\n return\n }\n recordEmail = normalizeContactEmail(lead.get('email'))\n }\n const key = recordEmail ? personKey(recordEmail) : null\n if (!recordEmail || !key) {\n res.status(byAddress ? 400 : 422).json({\n error: byAddress\n ? 'Enter the email address of the person to erase'\n : 'This record has no usable email address to erase by',\n })\n return\n }\n if (byAddress && !personErasureConfirmationMatches(body.confirmEmail, recordEmail)) {\n res.status(400).json({\n error: 'Type the email address a second time, exactly, to confirm the erasure',\n })\n return\n }\n if (!byAddress && !personErasureConfirmationMatches(body.email, recordEmail)) {\n res.status(400).json({\n error: 'Type the record’s email address exactly to confirm the erasure',\n })\n return\n }\n\n const requestId = personErasureId(orgId, key)\n const requestRef = firestore.collection(PERSON_ERASURES_COLLECTION).doc(requestId)\n const existing = await requestRef.get()\n if (existing.exists && existing.get('status') === 'pending') {\n const answer: ErasePersonResponse = {\n ok: true,\n requestId,\n pendingSinceMs: Number(existing.get('pendingSinceMs') ?? 0),\n alreadyPending: true,\n }\n res.status(200).json(answer)\n return\n }\n\n const now = Date.now()\n const request: PersonErasureRequest = {\n orgId,\n personKey: key,\n status: 'pending',\n email: recordEmail,\n requestedAtMs: now,\n requestedByUid: actor.uid,\n ...(hostId ? { hostId } : {}),\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n pendingSinceMs: now,\n }\n await requestRef.set(\n {\n ...request,\n // A request re-filed after a failed or completed run starts clean.\n erasedAtMs: FieldValue.delete(),\n result: FieldValue.delete(),\n failedAtMs: FieldValue.delete(),\n lastError: FieldValue.delete(),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n const hostIds = await orgHostIds(firestore, orgId)\n /*\n * Suppression stays PER SITE — it is that site's sending list — while the\n * lead marker below is written once, because the lead is one org row now\n * (AGL-3275) rather than one row per site.\n */\n for (const siteId of hostIds) {\n await suppressEmailForHostErasure({ hostId: siteId, email: recordEmail }).catch(\n (error: unknown) => {\n console.error('[crm] erase-person suppression write failed', siteId, error)\n },\n )\n }\n /*\n * THE ORG ROW, AND EVERY LEGACY ROW STILL STANDING.\n *\n * An erasure may not be the one caller that trusts the migration to be\n * finished: until AGL-3276 has folded every site and AGL-3277 has deleted\n * the fallback, a person can still be held at `hosts/{siteId}/leads`, and\n * a marker that reached only the org row would leave that copy unmarked.\n * So this marks whatever exists, in both homes, and the sweep costs one\n * read per site exactly as it did before.\n */\n const eraseLeadAt = async (\n ref: FirebaseFirestore.DocumentReference,\n where: string,\n ) => {\n await ref\n .get()\n .then((snapshot) =>\n snapshot.exists\n ? ref.update({ [CONTACT_ERASURE_REQUESTED_FIELD]: now })\n : undefined,\n )\n .catch((error: unknown) => {\n console.error('[crm] erase-person lead marker failed', where, error)\n })\n }\n await eraseLeadAt(firestore.collection('orgs').doc(orgId).collection('leads').doc(key), orgId)\n for (const siteId of hostIds) {\n await eraseLeadAt(\n firestore.collection('hosts').doc(siteId).collection('leads').doc(key),\n siteId,\n )\n }\n try {\n const contacts = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('contacts')\n .where('email', '==', recordEmail)\n .get()\n for (const contact of contacts.docs) {\n await contact.ref.update({ [CONTACT_ERASURE_REQUESTED_FIELD]: now })\n }\n } catch (error) {\n console.error('[crm] erase-person contact marker failed', orgId, error)\n }\n\n // The feed the act was performed in: the site's under a site, the\n // org's at the organization level.\n const target = { type: contactId ? 'contact' : 'lead', id: contactId || leadId } as const\n if (routeScope.level === 'org') {\n // Filed by address, the line names no record — and never the address.\n await logOrgActivity(\n orgId,\n actor,\n 'Requested privacy erasure',\n byAddress ? { type: 'org' } : target,\n ).catch(() => undefined)\n } else {\n await logHostActivity(hostId, actor, 'Requested privacy erasure', target).catch(\n () => undefined,\n )\n }\n await firestore\n .collection('adminAudit')\n .add({\n actorUid: actor.uid,\n action: 'person.erasure-requested',\n target: `orgs/${orgId}/people/${key}`,\n before: null,\n after: {\n hostId: hostId || null,\n hosts: hostIds.length,\n from: byAddress ? 'address' : contactId ? 'contact' : 'lead',\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n const answer: ErasePersonResponse = {\n ok: true,\n requestId,\n pendingSinceMs: now,\n alreadyPending: false,\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] erase-person failed', routeScope, error)\n res.status(500).json({ error: 'The erasure could not be filed' })\n }\n}\n"],"names":["canManageOrg","CONTACT_ERASURE_REQUESTED_FIELD","normalizeContactEmail","PERSON_ERASURES_COLLECTION","personErasureConfirmationMatches","personErasureId","personKey","firebaseAdmin","getOrgForHost","logHostActivity","logOrgActivity","orgDataCollectionForHost","readLeadForHost","suppressEmailForHostErasure","resolveOrgPermissions","FieldValue","authorizeOrgCaller","orgHostIds","readCrmRouteScope","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","req","res","body","method","setHeader","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","routeScope","contactId","trim","leadId","byAddress","level","hostId","refusal","orgId","actor","caller","needs","ok","uid","email","decoded","app","auth","verifyIdToken","membership","role","resolved","firestore","recordEmail","contactsRef","collection","doc","contact","get","exists","lead","key","confirmEmail","requestId","requestRef","existing","answer","pendingSinceMs","Number","alreadyPending","now","Date","request","requestedAtMs","requestedByUid","set","erasedAtMs","delete","result","failedAtMs","lastError","updatedAt","serverTimestamp","merge","hostIds","siteId","catch","console","eraseLeadAt","ref","where","then","snapshot","update","contacts","docs","target","type","id","add","actorUid","action","before","after","hosts","from","at"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,YAAY,EACZC,+BAA+B,EAC/BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,gCAAgC,EAChCC,eAAe,QAGV,sBAAqB;AAC5B,SAASC,SAAS,QAAQ,oCAAmC;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YAAM,IAAID,QAC9BV,KAAK,CAAC,IAAM3D;QAChB,OAAO;YACL,MAAM3B,gBAAgBoC,QAAQG,OAAO,6BAA6ByD,QAAQV,KAAK,CAC7E,IAAM3D;QAEV;QACA,MAAMyB,UACHG,UAAU,CAAC,cACX4C,GAAG,CAAC;YACHC,UAAU7D,MAAMI,GAAG;YACnB0D,QAAQ;YACRL,QAAQ,CAAC,KAAK,EAAE1D,MAAM,QAAQ,EAAEuB,KAAK;YACrCyC,QAAQ;YACRC,OAAO;gBACLnE,QAAQA,UAAU;gBAClBoE,OAAOpB,QAAQ1D,MAAM;gBACrB+E,MAAMvE,YAAY,YAAYH,YAAY,YAAY;YACxD;YACA2E,IAAIpG,WAAW4E,eAAe;QAChC,GACCI,KAAK,CAAC,IAAM3D;QAEf,MAAMuC,SAA8B;YAClCxB,IAAI;YACJqB;YACAI,gBAAgBG;YAChBD,gBAAgB;QAClB;QACAxD,IAAII,MAAM,CAAC,KAAKC,IAAI,CAACgD;IACvB,EAAE,OAAO/C,OAAO;QACdoE,QAAQpE,KAAK,CAAC,6BAA6BW,YAAYX;QACvDN,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiC;IACjE;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/erase-person.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 canManageOrg,\n CONTACT_ERASURE_REQUESTED_FIELD,\n normalizeContactEmail,\n PERSON_ERASURES_COLLECTION,\n personErasureConfirmationMatches,\n personErasureId,\n type PersonErasureRequest,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n logOrgActivity,\n orgDataCollectionForHost,\n readLeadForHost,\n suppressEmailForHostErasure,\n} from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\n\n/** The route key, as `registerCrmConsoleApi` registers it. */\nexport const CRM_ERASE_PERSON_ROUTE = 'crm/erase-person'\n\nexport interface ErasePersonRequestBody {\n /**\n * The site the request is filed from. At the organization level\n * (AGL-2634) the record's own site, or absent for a contact no site has\n * captured; a LEAD always names one, because a lead lives under its site.\n */\n hostId?: string\n /** The organization, at the organization level (AGL-2634). */\n orgId?: string\n /**\n * At most one of these names the record the request is filed from. Under\n * a site exactly one does; at the organization level neither may, which\n * files the request by `email` alone (AGL-2839).\n */\n contactId?: string\n leadId?: string\n /**\n * The address as the admin typed it — the confirmation of a record's\n * address, or, filed by address alone, the person the request is about.\n */\n email: string\n /** Filed by address alone: the address typed a second time. */\n confirmEmail?: string\n}\n\nexport interface ErasePersonResponse {\n ok: true\n requestId: string\n /** When the request entered the queue. */\n pendingSinceMs: number\n /** True when a request for this person was already waiting; nothing was re-filed. */\n alreadyPending: boolean\n}\n\n/**\n * `POST /api/crm/erase-person` — file a privacy erasure for one person\n * (AGL-2623).\n *\n * ## Who may\n *\n * A workspace admin or owner — `canManageOrg` on the caller's org role —\n * and nobody else. Not a site editor with the data permission, who can\n * detach a contact from their own site but has no standing to remove the\n * person from every site in the workspace; and not staff acting alone,\n * because the workspace is the controller of this data and the instruction\n * has to come from it. Staff who are also admins of the workspace pass on\n * that role, as anyone would.\n *\n * ## What it does, and what it does not\n *\n * It files the request and closes the doors; it deletes nothing. The daily\n * erasure job executes the sweep, so that a workspace's person erasures and\n * its own erasure run through one job, one audit trail and one queue a\n * staff member can watch. What happens here, in order:\n *\n * 1. The record named by the body is read and its address is what the\n * request is about — the body's address must match it, typed, so an\n * admin who opened the wrong record is stopped by the confirmation\n * rather than by luck.\n * 2. The request document is written, or found already pending, in\n * which case nothing is re-filed and the caller is told so.\n * 3. Every site of the workspace gets its suppression row NOW, not when\n * the job runs: from this moment a capture cannot rebuild the person.\n * 4. The contact document and each site's lead are stamped with the\n * request time, so their pages can say \"erasure pending\" off the\n * document they already read.\n * 5. The site's activity feed and the platform audit log each get a row\n * that names the record by id and the person by hash, never by\n * address.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, hostId?, contactId | leadId, email }` from the org-level hub:\n * the same workspace admin, authorized by the org rather than through a\n * site they name, so a contact no site captured can be erased from the\n * page that lists it. The sweep is what it always was — every site of the\n * org, found by `orgId` — and the row goes to the org's feed. A lead still\n * names its site, because that is where a lead lives.\n *\n * ## By address alone (AGL-2839)\n *\n * `{ orgId, email, confirmEmail }` with no record, from the workspace's\n * Privacy settings: the same workspace admin, for any person the workspace\n * may hold — including one no page shows, since the CRM that lists records\n * is included from Starter and a Free workspace has none of it. Nothing is\n * read to file it: the sweep is keyed by the address, the markers are found\n * by it, and the typed address must match its second typing, which is the\n * confirmation a record's address gives the other variants. No plan is\n * asked on any variant: erasure is an obligation, not a CRM feature.\n */\nexport const crmErasePersonHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n const body: Partial<ErasePersonRequestBody> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const routeScope = readCrmRouteScope(body as Record<string, unknown>)\n const contactId = String(body.contactId ?? '').trim()\n const leadId = String(body.leadId ?? '').trim()\n const byAddress = routeScope?.level === 'org' && !contactId && !leadId\n if (!routeScope || (!byAddress && !contactId && !leadId) || (contactId && leadId)) {\n res.status(400).json({ error: 'Name the site and exactly one contact or lead' })\n return\n }\n const { hostId } = routeScope\n if (leadId && !hostId) {\n res.status(400).json({ error: 'Name the site the lead lives under' })\n return\n }\n const refusal = 'Only a workspace admin can erase a person from the workspace'\n\n try {\n let orgId: string\n let actor: { uid: string; email: string | null }\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'manage-org',\n refusal,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n orgId = caller.orgId\n actor = { uid: caller.uid, email: caller.email }\n } else {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!canManageOrg(membership.role)) {\n res.status(403).json({ error: refusal })\n return\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved || resolved.orgId !== membership.orgId) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n orgId = resolved.orgId\n actor = { uid: decoded.uid, email: decoded.email ?? null }\n }\n const firestore = firebaseAdmin.app().firestore()\n\n let recordEmail: string | null = null\n if (byAddress) {\n recordEmail = normalizeContactEmail(body.email)\n } else if (contactId) {\n const contactsRef =\n routeScope.level === 'org'\n ? firestore.collection('orgs').doc(orgId).collection('contacts')\n : await orgDataCollectionForHost(hostId, 'contacts')\n const contact = await contactsRef.doc(contactId).get()\n if (!contact.exists) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n recordEmail = normalizeContactEmail(contact.get('email'))\n } else {\n const lead = await readLeadForHost(hostId, leadId)\n if (!lead) {\n res.status(404).json({ error: 'Unknown lead' })\n return\n }\n recordEmail = normalizeContactEmail(lead.get('email'))\n }\n const key = recordEmail ? personKey(recordEmail) : null\n if (!recordEmail || !key) {\n res.status(byAddress ? 400 : 422).json({\n error: byAddress\n ? 'Enter the email address of the person to erase'\n : 'This record has no usable email address to erase by',\n })\n return\n }\n if (byAddress && !personErasureConfirmationMatches(body.confirmEmail, recordEmail)) {\n res.status(400).json({\n error: 'Type the email address a second time, exactly, to confirm the erasure',\n })\n return\n }\n if (!byAddress && !personErasureConfirmationMatches(body.email, recordEmail)) {\n res.status(400).json({\n error: 'Type the record’s email address exactly to confirm the erasure',\n })\n return\n }\n\n const requestId = personErasureId(orgId, key)\n const requestRef = firestore.collection(PERSON_ERASURES_COLLECTION).doc(requestId)\n const existing = await requestRef.get()\n if (existing.exists && existing.get('status') === 'pending') {\n const answer: ErasePersonResponse = {\n ok: true,\n requestId,\n pendingSinceMs: Number(existing.get('pendingSinceMs') ?? 0),\n alreadyPending: true,\n }\n res.status(200).json(answer)\n return\n }\n\n const now = Date.now()\n const request: PersonErasureRequest = {\n orgId,\n personKey: key,\n status: 'pending',\n email: recordEmail,\n requestedAtMs: now,\n requestedByUid: actor.uid,\n ...(hostId ? { hostId } : {}),\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n pendingSinceMs: now,\n }\n await requestRef.set(\n {\n ...request,\n // A request re-filed after a failed or completed run starts clean.\n erasedAtMs: FieldValue.delete(),\n result: FieldValue.delete(),\n failedAtMs: FieldValue.delete(),\n lastError: FieldValue.delete(),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n const hostIds = await orgHostIds(firestore, orgId)\n /*\n * Suppression stays PER SITE — it is that site's sending list — while the\n * lead marker below is written once, because the lead is one org row now\n * (AGL-3275) rather than one row per site.\n */\n for (const siteId of hostIds) {\n await suppressEmailForHostErasure({ hostId: siteId, email: recordEmail }).catch(\n (error: unknown) => {\n console.error('[crm] erase-person suppression write failed', siteId, error)\n },\n )\n }\n /*\n * THE ORG ROW. One document for the person, since AGL-3276 emptied the\n * host path and AGL-3277 removed it — the per-site sweep this used to do\n * beside it had nothing left to find.\n */\n const eraseLeadAt = async (\n ref: FirebaseFirestore.DocumentReference,\n where: string,\n ) => {\n await ref\n .get()\n .then((snapshot) =>\n snapshot.exists\n ? ref.update({ [CONTACT_ERASURE_REQUESTED_FIELD]: now })\n : undefined,\n )\n .catch((error: unknown) => {\n console.error('[crm] erase-person lead marker failed', where, error)\n })\n }\n await eraseLeadAt(firestore.collection('orgs').doc(orgId).collection('leads').doc(key), orgId)\n try {\n const contacts = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('contacts')\n .where('email', '==', recordEmail)\n .get()\n for (const contact of contacts.docs) {\n await contact.ref.update({ [CONTACT_ERASURE_REQUESTED_FIELD]: now })\n }\n } catch (error) {\n console.error('[crm] erase-person contact marker failed', orgId, error)\n }\n\n // The feed the act was performed in: the site's under a site, the\n // org's at the organization level.\n const target = { type: contactId ? 'contact' : 'lead', id: contactId || leadId } as const\n if (routeScope.level === 'org') {\n // Filed by address, the line names no record — and never the address.\n await logOrgActivity(\n orgId,\n actor,\n 'Requested privacy erasure',\n byAddress ? { type: 'org' } : target,\n ).catch(() => undefined)\n } else {\n await logHostActivity(hostId, actor, 'Requested privacy erasure', target).catch(\n () => undefined,\n )\n }\n await firestore\n .collection('adminAudit')\n .add({\n actorUid: actor.uid,\n action: 'person.erasure-requested',\n target: `orgs/${orgId}/people/${key}`,\n before: null,\n after: {\n hostId: hostId || null,\n hosts: hostIds.length,\n from: byAddress ? 'address' : contactId ? 'contact' : 'lead',\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n const answer: ErasePersonResponse = {\n ok: true,\n requestId,\n pendingSinceMs: now,\n alreadyPending: false,\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] erase-person failed', routeScope, error)\n res.status(500).json({ error: 'The erasure could not be filed' })\n }\n}\n"],"names":["canManageOrg","CONTACT_ERASURE_REQUESTED_FIELD","normalizeContactEmail","PERSON_ERASURES_COLLECTION","personErasureConfirmationMatches","personErasureId","personKey","firebaseAdmin","getOrgForHost","logHostActivity","logOrgActivity","orgDataCollectionForHost","readLeadForHost","suppressEmailForHostErasure","resolveOrgPermissions","FieldValue","authorizeOrgCaller","orgHostIds","readCrmRouteScope","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","req","res","body","method","setHeader","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","routeScope","contactId","trim","leadId","byAddress","level","hostId","refusal","orgId","actor","caller","needs","ok","uid","email","decoded","app","auth","verifyIdToken","membership","role","resolved","firestore","recordEmail","contactsRef","collection","doc","contact","get","exists","lead","key","confirmEmail","requestId","requestRef","existing","answer","pendingSinceMs","Number","alreadyPending","now","Date","request","requestedAtMs","requestedByUid","set","erasedAtMs","delete","result","failedAtMs","lastError","updatedAt","serverTimestamp","merge","hostIds","siteId","catch","console","eraseLeadAt","ref","where","then","snapshot","update","contacts","docs","target","type","id","add","actorUid","action","before","after","hosts","from","at"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,YAAY,EACZC,+BAA+B,EAC/BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,gCAAgC,EAChCC,eAAe,QAGV,sBAAqB;AAC5B,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,wBAAwB,EACxBC,eAAe,EACfC,2BAA2B,QACtB,2BAA0B;AACjC,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,kBAAkB,EAAEC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;AAEhF,4DAA4D,GAC5D,OAAO,MAAMC,yBAAyB,mBAAkB;AAoCxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GACD,OAAO,MAAMC,wBAA0C,OAAOC,KAAKC;QAMpCD,4BAS4BA,WAEhCE,iBACHA;IAjBtB,IAAIF,IAAIG,MAAM,KAAK,QAAQ;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QpE,KAAK,CAAC,6BAA6BW,YAAYX;QACvDN,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiC;IACjE;AACF,EAAC"}
@@ -21,10 +21,6 @@ import { BUNDLE_ID } from "../constants/bundle-common.js";
21
21
  const NONE = {
22
22
  records: 0
23
23
  };
24
- /** The sites an organization owns, by id: `hosts` where `orgId` is the org's. */ async function orgHostIds(firestore, orgId) {
25
- const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).select().get();
26
- return hosts.docs.map((doc)=>doc.id);
27
- }
28
24
  /**
29
25
  * Applies the verdict to one record; answers whether it moved. A read then
30
26
  * a merge rather than a transaction: two verdicts landing together each
@@ -92,19 +88,13 @@ export function createCrmRecordEmailStateWriter(deps) {
92
88
  }
93
89
  try {
94
90
  /*
95
- * ONE ORG ROW, plus any legacy site row the backfill has not reached
96
- * (AGL-3275). A bounce or a do-not-contact mark is the platform's
97
- * verdict on the ADDRESS, so it has to reach every copy that still
98
- * exists an unmarked leftover is a person who asked not to be
99
- * mailed and could be. AGL-3277 drops the second loop with the
100
- * fallback.
91
+ * ONE ORG ROW. A bounce or a do-not-contact mark is the platform's
92
+ * verdict on the ADDRESS, and since AGL-3277 there is one document
93
+ * carrying it the per-site loop beside this had nothing left to
94
+ * find once AGL-3276 emptied the host path.
101
95
  */ if (await stampRecord(firestore.collection('orgs').doc(orgId).collection('leads').doc(key), state, force)) {
102
96
  records += 1;
103
97
  }
104
- for (const hostId of (await orgHostIds(firestore, orgId))){
105
- const lead = firestore.collection('hosts').doc(hostId).collection('leads').doc(key);
106
- if (await stampRecord(lead, state, force)) records += 1;
107
- }
108
98
  } catch (error) {
109
99
  console.error('[crm] the leads could not be stamped with an email state', orgId, error);
110
100
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/record-email-state.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 registerPluginRecordEmailStateWriter,\n type PluginRecordEmailStateReport,\n type PluginRecordEmailStateRequest,\n type PluginRecordEmailStateWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport {\n EMAIL_STATE_FIELD,\n nextEmailState,\n normalizeContactEmail,\n personKey,\n readEmailState,\n type EmailState,\n} from '@aglyn/aglyn/server'\nimport { findContactByEmail, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * THE CRM'S WRITER ON THE CORE'S RECORD EMAIL-STATE SEAM (AGL-3245).\n *\n * A sender filed a verdict on an address — the outreach runtime's bounce,\n * the campaign webhook's complaint, a member's do-not-contact mark, the\n * unsubscribe link — and says so here; this writes it onto every record\n * the address is, as `emailState`, so the record a person reads and the\n * lists a send consults agree.\n *\n * One address can be several records: the contact the organization holds\n * (found through the address index, `findContactByEmail`), and a lead on\n * each site the organization owns — leads are keyed by `personKey`, so a\n * lead is addressed directly under every host. All of them are stamped;\n * the verdict is about the address, not about which record a rep opened.\n * A caller that knows only the site reads the organization off it.\n *\n * The write keeps the STRONGER verdict (`nextEmailState`): a member's\n * do-not-contact mark is not undone by a later bounce, and `ok` lands only\n * when a caller forces it. `updatedAt` is left alone — a verdict is\n * something that happened to the person, not an edit the team made, and a\n * list sorted on recency must not reshuffle on a bounce.\n *\n * Never throws: the list is the control, and a record that could not be\n * stamped is a chip a page goes without, logged.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CrmRecordEmailStateDeps {\n firestore(): Firestore\n}\n\nconst NONE: PluginRecordEmailStateReport = { records: 0 }\n\n/** The sites an organization owns, by id: `hosts` where `orgId` is the org's. */\nasync function orgHostIds(firestore: Firestore, orgId: string): Promise<string[]> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).select().get()\n return hosts.docs.map((doc) => doc.id)\n}\n\n/**\n * Applies the verdict to one record; answers whether it moved. A read then\n * a merge rather than a transaction: two verdicts landing together each\n * compare against a state at least as old as their own, and the ranking\n * makes the order of two writes of the same rank immaterial.\n */\nasync function stampRecord(\n ref: FirebaseFirestore.DocumentReference,\n incoming: EmailState,\n force: boolean,\n): Promise<boolean> {\n const snapshot = await ref.get()\n if (!snapshot.exists) return false\n const current = readEmailState(snapshot.data() as Record<string, unknown>)\n const next = nextEmailState(current, incoming, { force })\n // The current verdict stood, or the same verdict arrived again — a second\n // run of the caller — and there is nothing to write.\n if (\n next === current ||\n (current &&\n next.status === current.status &&\n next.atMs === current.atMs &&\n next.source === current.source &&\n next.detail === current.detail)\n ) {\n return false\n }\n await ref.set({ [EMAIL_STATE_FIELD]: next }, { merge: true })\n return true\n}\n\n/** The organization a request names, or the one its site belongs to. */\nasync function resolveOrgId(firestore: Firestore, request: PluginRecordEmailStateRequest): Promise<string> {\n const named = String(request.orgId ?? '').trim()\n if (named) return named\n const hostId = String(request.hostId ?? '').trim()\n if (!hostId) return ''\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists ? String(host.get('orgId') ?? '') : ''\n}\n\nexport function createCrmRecordEmailStateWriter(deps: CrmRecordEmailStateDeps): PluginRecordEmailStateWriter {\n return {\n async stamp(request) {\n const email = normalizeContactEmail(request.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return NONE\n const firestore = deps.firestore()\n let orgId: string\n try {\n orgId = await resolveOrgId(firestore, request)\n } catch (error) {\n console.error('[crm] the site’s organization could not be read for an email state', request.hostId, error)\n return NONE\n }\n if (!orgId) return NONE\n const state: EmailState = {\n status: request.state.status,\n atMs: Number.isFinite(request.state.atMs) && request.state.atMs > 0 ? request.state.atMs : Date.now(),\n source: request.state.source,\n detail: request.state.detail\n ? String(request.state.detail).replace(/\\s+/g, ' ').trim().slice(0, 500)\n : null,\n ...(request.state.enrollmentId ? { enrollmentId: request.state.enrollmentId } : {}),\n }\n const force = request.force === true\n let records = 0\n try {\n const contacts = firestore.collection('orgs').doc(orgId).collection('contacts')\n const contact = await findContactByEmail(contacts, email)\n if (contact && (await stampRecord(contact.ref, state, force))) records += 1\n } catch (error) {\n console.error('[crm] the contact could not be stamped with an email state', orgId, error)\n }\n try {\n /*\n * ONE ORG ROW, plus any legacy site row the backfill has not reached\n * (AGL-3275). A bounce or a do-not-contact mark is the platform's\n * verdict on the ADDRESS, so it has to reach every copy that still\n * exists — an unmarked leftover is a person who asked not to be\n * mailed and could be. AGL-3277 drops the second loop with the\n * fallback.\n */\n if (await stampRecord(\n firestore.collection('orgs').doc(orgId).collection('leads').doc(key),\n state,\n force,\n )) {\n records += 1\n }\n for (const hostId of await orgHostIds(firestore, orgId)) {\n const lead = firestore.collection('hosts').doc(hostId).collection('leads').doc(key)\n if (await stampRecord(lead, state, force)) records += 1\n }\n } catch (error) {\n console.error('[crm] the leads could not be stamped with an email state', orgId, error)\n }\n return { records }\n },\n }\n}\n\n/** The platform's own dependencies. Specs build their own. */\nexport function defaultCrmRecordEmailStateDeps(): CrmRecordEmailStateDeps {\n return { firestore: () => firebaseAdmin.app().firestore() }\n}\n\n/** Registers the CRM as the workspace's record system on the email-state seam. */\nexport function registerCrmRecordEmailStateWriter(\n deps: CrmRecordEmailStateDeps = defaultCrmRecordEmailStateDeps(),\n): void {\n registerPluginRecordEmailStateWriter(createCrmRecordEmailStateWriter(deps), { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginRecordEmailStateWriter","EMAIL_STATE_FIELD","nextEmailState","normalizeContactEmail","personKey","readEmailState","findContactByEmail","firebaseAdmin","BUNDLE_ID","NONE","records","orgHostIds","firestore","orgId","hosts","collection","where","select","get","docs","map","doc","id","stampRecord","ref","incoming","force","snapshot","exists","current","data","next","status","atMs","source","detail","set","merge","resolveOrgId","request","host","named","String","trim","hostId","createCrmRecordEmailStateWriter","deps","stamp","email","key","error","console","state","Number","isFinite","Date","now","replace","slice","enrollmentId","contacts","contact","lead","defaultCrmRecordEmailStateDeps","app","registerCrmRecordEmailStateWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oCAAoC,QAI/B,wDAAuD;AAC9D,SACEC,iBAAiB,EACjBC,cAAc,EACdC,qBAAqB,EACrBC,SAAS,EACTC,cAAc,QAET,sBAAqB;AAC5B,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,2BAA0B;AAC5E,SAASC,SAAS,QAAQ,gCAA4B;AAkCtD,MAAMC,OAAqC;IAAEC,SAAS;AAAE;AAExD,+EAA+E,GAC/E,eAAeC,WAAWC,SAAoB,EAAEC,KAAa;IAC3D,MAAMC,QAAQ,MAAMF,UAAUG,UAAU,CAAC,SAASC,KAAK,CAAC,SAAS,MAAMH,OAAOI,MAAM,GAAGC,GAAG;IAC1F,OAAOJ,MAAMK,IAAI,CAACC,GAAG,CAAC,CAACC,MAAQA,IAAIC,EAAE;AACvC;AAEA;;;;;CAKC,GACD,eAAeC,YACbC,GAAwC,EACxCC,QAAoB,EACpBC,KAAc;IAEd,MAAMC,WAAW,MAAMH,IAAIN,GAAG;IAC9B,IAAI,CAACS,SAASC,MAAM,EAAE,OAAO;IAC7B,MAAMC,UAAUxB,eAAesB,SAASG,IAAI;IAC5C,MAAMC,OAAO7B,eAAe2B,SAASJ,UAAU;QAAEC;IAAM;IACvD,0EAA0E;IAC1E,qDAAqD;IACrD,IACEK,SAASF,WACRA,WACCE,KAAKC,MAAM,KAAKH,QAAQG,MAAM,IAC9BD,KAAKE,IAAI,KAAKJ,QAAQI,IAAI,IAC1BF,KAAKG,MAAM,KAAKL,QAAQK,MAAM,IAC9BH,KAAKI,MAAM,KAAKN,QAAQM,MAAM,EAChC;QACA,OAAO;IACT;IACA,MAAMX,IA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OAAO,SAASqD;IACd,OAAO;QAAEnD,WAAW,IAAML,cAAcyD,GAAG,GAAGpD,SAAS;IAAG;AAC5D;AAEA,gFAAgF,GAChF,OAAO,SAASqD,kCACdnB,OAAgCiB,gCAAgC;IAEhE/D,qCAAqC6C,gCAAgCC,OAAO;QAAEoB,UAAU1D;IAAU;AACpG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/record-email-state.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 registerPluginRecordEmailStateWriter,\n type PluginRecordEmailStateReport,\n type PluginRecordEmailStateRequest,\n type PluginRecordEmailStateWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport {\n EMAIL_STATE_FIELD,\n nextEmailState,\n normalizeContactEmail,\n personKey,\n readEmailState,\n type EmailState,\n} from '@aglyn/aglyn/server'\nimport { findContactByEmail, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * THE CRM'S WRITER ON THE CORE'S RECORD EMAIL-STATE SEAM (AGL-3245).\n *\n * A sender filed a verdict on an address — the outreach runtime's bounce,\n * the campaign webhook's complaint, a member's do-not-contact mark, the\n * unsubscribe link — and says so here; this writes it onto every record\n * the address is, as `emailState`, so the record a person reads and the\n * lists a send consults agree.\n *\n * One address can be several records: the contact the organization holds\n * (found through the address index, `findContactByEmail`), and a lead on\n * each site the organization owns — leads are keyed by `personKey`, so a\n * lead is addressed directly under every host. All of them are stamped;\n * the verdict is about the address, not about which record a rep opened.\n * A caller that knows only the site reads the organization off it.\n *\n * The write keeps the STRONGER verdict (`nextEmailState`): a member's\n * do-not-contact mark is not undone by a later bounce, and `ok` lands only\n * when a caller forces it. `updatedAt` is left alone — a verdict is\n * something that happened to the person, not an edit the team made, and a\n * list sorted on recency must not reshuffle on a bounce.\n *\n * Never throws: the list is the control, and a record that could not be\n * stamped is a chip a page goes without, logged.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CrmRecordEmailStateDeps {\n firestore(): Firestore\n}\n\nconst NONE: PluginRecordEmailStateReport = { records: 0 }\n\n/**\n * Applies the verdict to one record; answers whether it moved. A read then\n * a merge rather than a transaction: two verdicts landing together each\n * compare against a state at least as old as their own, and the ranking\n * makes the order of two writes of the same rank immaterial.\n */\nasync function stampRecord(\n ref: FirebaseFirestore.DocumentReference,\n incoming: EmailState,\n force: boolean,\n): Promise<boolean> {\n const snapshot = await ref.get()\n if (!snapshot.exists) return false\n const current = readEmailState(snapshot.data() as Record<string, unknown>)\n const next = nextEmailState(current, incoming, { force })\n // The current verdict stood, or the same verdict arrived again — a second\n // run of the caller — and there is nothing to write.\n if (\n next === current ||\n (current &&\n next.status === current.status &&\n next.atMs === current.atMs &&\n next.source === current.source &&\n next.detail === current.detail)\n ) {\n return false\n }\n await ref.set({ [EMAIL_STATE_FIELD]: next }, { merge: true })\n return true\n}\n\n/** The organization a request names, or the one its site belongs to. */\nasync function resolveOrgId(firestore: Firestore, request: PluginRecordEmailStateRequest): Promise<string> {\n const named = String(request.orgId ?? '').trim()\n if (named) return named\n const hostId = String(request.hostId ?? '').trim()\n if (!hostId) return ''\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists ? String(host.get('orgId') ?? '') : ''\n}\n\nexport function createCrmRecordEmailStateWriter(deps: CrmRecordEmailStateDeps): PluginRecordEmailStateWriter {\n return {\n async stamp(request) {\n const email = normalizeContactEmail(request.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return NONE\n const firestore = deps.firestore()\n let orgId: string\n try {\n orgId = await resolveOrgId(firestore, request)\n } catch (error) {\n console.error('[crm] the site’s organization could not be read for an email state', request.hostId, error)\n return NONE\n }\n if (!orgId) return NONE\n const state: EmailState = {\n status: request.state.status,\n atMs: Number.isFinite(request.state.atMs) && request.state.atMs > 0 ? request.state.atMs : Date.now(),\n source: request.state.source,\n detail: request.state.detail\n ? String(request.state.detail).replace(/\\s+/g, ' ').trim().slice(0, 500)\n : null,\n ...(request.state.enrollmentId ? { enrollmentId: request.state.enrollmentId } : {}),\n }\n const force = request.force === true\n let records = 0\n try {\n const contacts = firestore.collection('orgs').doc(orgId).collection('contacts')\n const contact = await findContactByEmail(contacts, email)\n if (contact && (await stampRecord(contact.ref, state, force))) records += 1\n } catch (error) {\n console.error('[crm] the contact could not be stamped with an email state', orgId, error)\n }\n try {\n /*\n * ONE ORG ROW. A bounce or a do-not-contact mark is the platform's\n * verdict on the ADDRESS, and since AGL-3277 there is one document\n * carrying it — the per-site loop beside this had nothing left to\n * find once AGL-3276 emptied the host path.\n */\n if (await stampRecord(\n firestore.collection('orgs').doc(orgId).collection('leads').doc(key),\n state,\n force,\n )) {\n records += 1\n }\n } catch (error) {\n console.error('[crm] the leads could not be stamped with an email state', orgId, error)\n }\n return { records }\n },\n }\n}\n\n/** The platform's own dependencies. Specs build their own. */\nexport function defaultCrmRecordEmailStateDeps(): CrmRecordEmailStateDeps {\n return { firestore: () => firebaseAdmin.app().firestore() }\n}\n\n/** Registers the CRM as the workspace's record system on the email-state seam. */\nexport function registerCrmRecordEmailStateWriter(\n deps: CrmRecordEmailStateDeps = defaultCrmRecordEmailStateDeps(),\n): void {\n registerPluginRecordEmailStateWriter(createCrmRecordEmailStateWriter(deps), { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginRecordEmailStateWriter","EMAIL_STATE_FIELD","nextEmailState","normalizeContactEmail","personKey","readEmailState","findContactByEmail","firebaseAdmin","BUNDLE_ID","NONE","records","stampRecord","ref","incoming","force","snapshot","get","exists","current","data","next","status","atMs","source","detail","set","merge","resolveOrgId","firestore","request","host","named","String","orgId","trim","hostId","collection","doc","createCrmRecordEmailStateWriter","deps","stamp","email","key","error","console","state","Number","isFinite","Date","now","replace","slice","enrollmentId","contacts","contact","defaultCrmRecordEmailStateDeps","app","registerCrmRecordEmailStateWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oCAAoC,QAI/B,wDAAuD;AAC9D,SACEC,iBAAiB,EACjBC,cAAc,EACdC,qBAAqB,EACrBC,SAAS,EACTC,cAAc,QAET,sBAAqB;AAC5B,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,2BAA0B;AAC5E,SAASC,SAAS,QAAQ,gCAA4B;AAkCtD,MAAMC,OAAqC;IAAEC,SAAS;AAAE;AAExD;;;;;CAKC,GACD,eAAeC,YACbC,GAAwC,EACxCC,QAAoB,EACpBC,KAAc;IAEd,MAAMC,WAAW,MAAMH,IAAII,GAAG;IAC9B,IAAI,CAACD,SAASE,MAAM,EAAE,OAAO;IAC7B,MAAMC,UAAUb,eAAeU,SAASI,IAAI;IAC5C,MAAMC,OAAOlB,eAAegB,SAASL,UAAU;QAAEC;IAAM;IACvD,0EAA0E;IAC1E,qDAAqD;IACrD,IACEM,SAASF,WACRA,WACCE,KAAKC,MAAM,KAAKH,QAAQG,MAAM,IAC9BD,KAAKE,IAAI,KAAKJ,QAAQI,IAAI,IAC1BF,KAAKG,MAAM,KAAKL,QAAQK,MAAM,IAC9BH,KAAKI,MAAM,KAAKN,QAAQM,MAAM,EAChC;QACA,OAAO;IACT;IACA,MAAMZ,IAAIa,GAAG,CAAC;QAAE,CAACxB,kBAAkB,EAAEmB;IAAK,GAAG;QAAEM,OAAO;IAAK;IAC3D,OAAO;AACT;AAEA,sEAAsE,GACtE,eAAeC,aAAaC,SAAoB,EAAEC,OAAsC;QACjEA,gBAECA,iBAGMC;IAL5B,MAAMC,QAAQC,QAAOH,iBAAAA,QAAQI,KAAK,YAAbJ,iB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