@aglyn/plugins-crm 1.0.0-beta.147 → 1.0.0-beta.150

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.147",
3
+ "version": "1.0.0-beta.150",
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.147",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.147",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.147",
31
- "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.147",
32
- "@aglyn/shared-ui-jsx": "1.0.0-beta.147",
33
- "@aglyn/shared-ui-next": "1.0.0-beta.147",
34
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.147",
35
- "@aglyn/shared-util-email": "1.0.0-beta.147",
36
- "@aglyn/shared-util-http": "1.0.0-beta.147",
37
- "@aglyn/tenant-data-admin": "1.0.0-beta.147",
38
- "@aglyn/tenant-feature-instance": "1.0.0-beta.147",
39
- "@aglyn/tenant-runtime": "1.0.0-beta.147",
28
+ "@aglyn/aglyn": "1.0.0-beta.150",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.150",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.150",
31
+ "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.150",
32
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.150",
33
+ "@aglyn/shared-ui-next": "1.0.0-beta.150",
34
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.150",
35
+ "@aglyn/shared-util-email": "1.0.0-beta.150",
36
+ "@aglyn/shared-util-http": "1.0.0-beta.150",
37
+ "@aglyn/tenant-data-admin": "1.0.0-beta.150",
38
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.150",
39
+ "@aglyn/tenant-runtime": "1.0.0-beta.150",
40
40
  "@dnd-kit/core": "^6.3.1",
41
41
  "@dnd-kit/utilities": "^3.2.2",
42
42
  "@swc/helpers": "0.5.23",
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type PluginContactCaptureWriter } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture';
18
+ /**
19
+ * The CRM as the plugin that keeps people.
20
+ *
21
+ * Light by construction, the way the workflows listener is: the capture
22
+ * itself is imported when the first one arrives, not when the process
23
+ * starts, so a process that never captures anybody pays for this object and
24
+ * nothing else. That matters because this registers in EVERY server process,
25
+ * including ones that will never touch the CRM.
26
+ */
27
+ export declare const crmContactCaptureWriter: PluginContactCaptureWriter;
28
+ /**
29
+ * The plugin's SERVER declarations: what the server must know at boot, before
30
+ * any door of the CRM has been called.
31
+ *
32
+ * ## Why a declaration and not a `tenantApi` registration
33
+ *
34
+ * The doors that meet a person mostly never load this plugin. A form
35
+ * submission is a core route; an order and a booking are captured inside
36
+ * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry
37
+ * filled by a surface that did not load answers `null` — which
38
+ * `capturePluginContact` defines as "this workspace has no record system", a
39
+ * sentence that would be false and silent. Orders would stop creating
40
+ * contacts with nothing red anywhere, which is the AGL-3025 shape.
41
+ *
42
+ * Running from both apps' generated server-declarations manifest at boot is
43
+ * what makes the answer true in every process. It is also called from the
44
+ * plugin's own API register functions, so a process whose boot did not run it
45
+ * still registers the writer the first time a CRM door loads. Registering
46
+ * twice replaces in place.
47
+ *
48
+ * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A
49
+ * second plugin's is refused naming both, and the incumbent keeps serving.
50
+ */
51
+ export declare function registerCrmServerDeclarations(): void;
@@ -0,0 +1,62 @@
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
+ */ // The contract from its own module, not the plugin-manager barrel: boot needs
17
+ // the registry and nothing else, and the barrel reaches the client contexts.
18
+ import { registerPluginContactCaptureWriter } from "@aglyn/aglyn/plugin-manager/plugin-contact-capture";
19
+ import { BUNDLE_ID } from "./constants/bundle-common.js";
20
+ /**
21
+ * The CRM as the plugin that keeps people.
22
+ *
23
+ * Light by construction, the way the workflows listener is: the capture
24
+ * itself is imported when the first one arrives, not when the process
25
+ * starts, so a process that never captures anybody pays for this object and
26
+ * nothing else. That matters because this registers in EVERY server process,
27
+ * including ones that will never touch the CRM.
28
+ */ export const crmContactCaptureWriter = {
29
+ async capture (request) {
30
+ const { captureContactForCrm } = await import("./server/capture-contact.js");
31
+ return await captureContactForCrm(request);
32
+ }
33
+ };
34
+ /**
35
+ * The plugin's SERVER declarations: what the server must know at boot, before
36
+ * any door of the CRM has been called.
37
+ *
38
+ * ## Why a declaration and not a `tenantApi` registration
39
+ *
40
+ * The doors that meet a person mostly never load this plugin. A form
41
+ * submission is a core route; an order and a booking are captured inside
42
+ * STRIPE WEBHOOKS. None of them has a reason to load the CRM, and a registry
43
+ * filled by a surface that did not load answers `null` — which
44
+ * `capturePluginContact` defines as "this workspace has no record system", a
45
+ * sentence that would be false and silent. Orders would stop creating
46
+ * contacts with nothing red anywhere, which is the AGL-3025 shape.
47
+ *
48
+ * Running from both apps' generated server-declarations manifest at boot is
49
+ * what makes the answer true in every process. It is also called from the
50
+ * plugin's own API register functions, so a process whose boot did not run it
51
+ * still registers the writer the first time a CRM door loads. Registering
52
+ * twice replaces in place.
53
+ *
54
+ * ⚠️ The registry holds ONE writer: a workspace keeps one set of people. A
55
+ * second plugin's is refused naming both, and the incumbent keeps serving.
56
+ */ export function registerCrmServerDeclarations() {
57
+ registerPluginContactCaptureWriter(crmContactCaptureWriter, {
58
+ pluginId: BUNDLE_ID
59
+ });
60
+ }
61
+
62
+ //# sourceMappingURL=declarations.server.js.map
@@ -0,0 +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 {\n registerPluginContactCaptureWriter,\n type PluginContactCaptureWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { BUNDLE_ID } from './constants/bundle-common'\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 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}\n"],"names":["registerPluginContactCaptureWriter","BUNDLE_ID","crmContactCaptureWriter","capture","request","captureContactForCrm","registerCrmServerDeclarations","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,6EAA6E;AAC7E,SACEA,kCAAkC,QAE7B,qDAAoD;AAC3D,SAASC,SAAS,QAAQ,+BAA2B;AAErD;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASE;IACdN,mCAAmCE,yBAAyB;QAC1DK,UAAUN;IACZ;AACF"}
@@ -47,7 +47,7 @@ function writeRememberedPick(orgId, hostId) {
47
47
  * how a surface tells the two levels apart without a second prop.
48
48
  */ export function CrmOrgMountProvider(props) {
49
49
  const { mount, children } = props;
50
- const { orgId, hosts, hostsReady, hostsPath } = mount;
50
+ const { orgId, orgSlug, hosts, hostsReady, hostsPath } = mount;
51
51
  const [picked, setPicked] = useState(null);
52
52
  // Read after mount rather than in the initializer, so the server and the
53
53
  // first client paint agree: the pick only ever affects a drawer somebody
@@ -109,6 +109,7 @@ function writeRememberedPick(orgId, hostId) {
109
109
  ]);
110
110
  const value = useMemo(()=>({
111
111
  orgId,
112
+ orgSlug,
112
113
  hosts,
113
114
  hostsReady,
114
115
  hostsPath,
@@ -119,6 +120,7 @@ function writeRememberedPick(orgId, hostId) {
119
120
  siteHubHref
120
121
  }), [
121
122
  orgId,
123
+ orgSlug,
122
124
  hosts,
123
125
  hostsReady,
124
126
  hostsPath,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-org-mount.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 { ConsolePluginOrgHost, ConsolePluginOrgMount } from '@aglyn/aglyn'\nimport {\n type ComponentType,\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react'\n\n/**\n * The organization-level mount, as every CRM surface beneath the hub reads\n * it (AGL-2630).\n *\n * The shell hands the hub page an org and its sites; the hub publishes them\n * through this context so a drawer four components down — the one that has\n * to ask which site a new record is captured by — reaches them without four\n * components threading a prop they never read. `useCrmScope` reads it too:\n * a surface handed `hostId: null` learns from here which org it is under,\n * which is what lets every existing `useCrmScope({ hostId, org })` call\n * serve the org level unchanged.\n */\nexport interface CrmOrgMount extends ConsolePluginOrgMount {\n /**\n * The site the next create stamps from: the reader's last pick this\n * session, or the org's only site when it has exactly one, else `null`\n * until somebody picks. A record is always captured BY a site — its\n * `hostId`, its `visibleTo`, the consent group its profile lives on all\n * come from one — and at the org level nothing else can say which.\n */\n createHostId: string | null\n setCreateHostId: (hostId: string) => void\n /** How a site reads on screen — its name, or its id when the list cannot name it. */\n siteName: (hostId: string) => string\n /**\n * The subdomain a console URL under `/hosts/[host]` takes, or `null` for\n * a site the list did not answer for — named, never linked.\n */\n siteSubdomain: (hostId: string) => string | null\n /**\n * The site's own CRM hub — `${hostsPath}/${subdomain}/crm` — or `null`\n * for a site whose subdomain the list could not answer, which is named\n * and not linked.\n */\n siteHubHref: (hostId: string) => string | null\n}\n\nconst CrmOrgMountContext = createContext<CrmOrgMount | null>(null)\n\n/**\n * The session's memory of the picked site, per org. Session storage rather\n * than local: the pick is a working convenience for one sitting, and a\n * site remembered across weeks would stamp a record onto a site the reader\n * had forgotten choosing.\n */\nconst pickStorageKey = (orgId: string) => `aglyn.crm.createSite.${orgId}`\n\nfunction readRememberedPick(orgId: string): string | null {\n try {\n return window.sessionStorage.getItem(pickStorageKey(orgId))\n } catch {\n return null\n }\n}\n\nfunction writeRememberedPick(orgId: string, hostId: string): void {\n try {\n window.sessionStorage.setItem(pickStorageKey(orgId), hostId)\n } catch {\n // A browser that refuses storage still gets the pick for this page.\n }\n}\n\n/**\n * Publishes the org-level mount to every surface beneath it.\n *\n * Mounted by the hub page ONLY when the shell handed it an `orgMount`; under\n * a site there is no provider and `useCrmOrgMount` answers `null`, which is\n * how a surface tells the two levels apart without a second prop.\n */\nexport function CrmOrgMountProvider(props: {\n mount: ConsolePluginOrgMount\n children: ReactNode\n}) {\n const { mount, children } = props\n const { orgId, hosts, hostsReady, hostsPath } = mount\n const [picked, setPicked] = useState<string | null>(null)\n // Read after mount rather than in the initializer, so the server and the\n // first client paint agree: the pick only ever affects a drawer somebody\n // has since opened.\n useEffect(() => {\n setPicked(readRememberedPick(orgId))\n }, [orgId])\n\n const byId = useMemo(() => {\n const index = new Map<string, ConsolePluginOrgHost>()\n for (const host of hosts) index.set(host.id, host)\n return index\n }, [hosts])\n\n /*\n * A remembered site the list no longer carries is forgotten rather than\n * stamped — the reader may have lost the site, or the site may be gone.\n * An org with exactly one site needs no picker at all; nothing else is\n * picked silently, because a wrong guess files a person under a brand\n * that never met them.\n */\n const createHostId = useMemo(() => {\n if (picked && byId.has(picked)) return picked\n if (hostsReady && hosts.length === 1) return hosts[0].id\n return null\n }, [picked, byId, hostsReady, hosts])\n\n const setCreateHostId = useCallback(\n (hostId: string) => {\n setPicked(hostId)\n writeRememberedPick(orgId, hostId)\n },\n [orgId],\n )\n const siteName = useCallback(\n (hostId: string) => byId.get(hostId)?.name || hostId,\n [byId],\n )\n const siteSubdomain = useCallback(\n (hostId: string) => byId.get(hostId)?.subdomain ?? null,\n [byId],\n )\n const siteHubHref = useCallback(\n (hostId: string) => {\n const subdomain = byId.get(hostId)?.subdomain\n return subdomain ? `${hostsPath}/${encodeURIComponent(subdomain)}/crm` : null\n },\n [byId, hostsPath],\n )\n\n const value = useMemo<CrmOrgMount>(\n () => ({\n orgId,\n hosts,\n hostsReady,\n hostsPath,\n createHostId,\n setCreateHostId,\n siteName,\n siteSubdomain,\n siteHubHref,\n }),\n [\n orgId,\n hosts,\n hostsReady,\n hostsPath,\n createHostId,\n setCreateHostId,\n siteName,\n siteSubdomain,\n siteHubHref,\n ],\n )\n return (\n <CrmOrgMountContext.Provider value={value}>\n {children}\n </CrmOrgMountContext.Provider>\n )\n}\nCrmOrgMountProvider.displayName = 'CrmOrgMountProvider'\n\n/** The org-level mount, or `null` under a site. */\nexport function useCrmOrgMount(): CrmOrgMount | null {\n return useContext(CrmOrgMountContext)\n}\n\n/**\n * `Card` beneath the org-level mount the SHELL hands it as a prop (AGL-2636).\n *\n * The hub page mounts the provider itself, because the shell hands the hub\n * page an `orgMount` and the page owns everything under it. A widget on the\n * org's `orgDashboard` slot is dropped into a console page the CRM does not\n * own — the org's sites list — and the console never imports a plugin, so\n * the page cannot mount this plugin's provider around the slot. The slot\n * hands each widget the same `orgMount` instead, and this puts the provider\n * where the hub page puts it: around the surface, one level down. `Card`\n * then reads `useCrmOrgMount()` and `useCrmScope({ hostId: null })` exactly\n * as it does under the hub, and stays one component for both mounts.\n *\n * Handed no mount — a slot that names a site, or a shell older than the org\n * zone — the card renders as it is, and `useCrmOrgMount` answers `null` the\n * way it does under a site.\n */\nexport function withCrmOrgMount<P extends object>(\n Card: ComponentType<P>,\n): ComponentType<P & { orgMount?: ConsolePluginOrgMount }> {\n function CrmOrgMounted(props: P & { orgMount?: ConsolePluginOrgMount }) {\n const { orgMount, ...rest } = props\n const card = <Card {...(rest as P)} />\n return orgMount ? (\n <CrmOrgMountProvider mount={orgMount}>{card}</CrmOrgMountProvider>\n ) : (\n card\n )\n }\n CrmOrgMounted.displayName = `CrmOrgMounted(${\n Card.displayName ?? (Card as { name?: string }).name ?? 'Card'\n })`\n return CrmOrgMounted\n}\n\n/**\n * THE SITE A CREATE OPENED FROM A RECORD DEFAULTS TO (AGL-2630).\n *\n * A task, an activity or a deal filed from a contact's page belongs, nine\n * times in ten, with the site that captured the contact — not with the\n * site the reader last picked in a list's drawer. So a record page wraps\n * its cards in this, naming its record's own capturing site, and every\n * create under it defaults its Site picker there. A pick the reader makes\n * INSIDE such a create is held for that page alone; the session's pick,\n * which a create opened from a list keeps defaulting to, is untouched.\n *\n * Nothing under a site, nothing for a record no site has captured, and\n * nothing for a site the mount's list does not carry — the reader may not\n * have it: the children render as they are and the session's pick stands.\n */\nexport function CrmCreateSiteDefault(props: {\n hostId: string | null | undefined\n children: ReactNode\n}) {\n const { hostId, children } = props\n const mount = useContext(CrmOrgMountContext)\n const [picked, setPicked] = useState<string | null>(null)\n // Another record on the same page starts from its own site again.\n useEffect(() => {\n setPicked(null)\n }, [hostId])\n const value = useMemo<CrmOrgMount | null>(() => {\n if (!mount || !hostId) return mount\n if (!mount.hosts.some((host) => host.id === hostId)) return mount\n return {\n ...mount,\n createHostId: picked ?? hostId,\n setCreateHostId: setPicked,\n }\n }, [mount, hostId, picked])\n return (\n <CrmOrgMountContext.Provider value={value}>\n {children}\n </CrmOrgMountContext.Provider>\n )\n}\nCrmCreateSiteDefault.displayName = 'CrmCreateSiteDefault'\n\nexport default useCrmOrgMount\n"],"names":["createContext","useCallback","useContext","useEffect","useMemo","useState","CrmOrgMountContext","pickStorageKey","orgId","readRememberedPick","window","sessionStorage","getItem","writeRememberedPick","hostId","setItem","CrmOrgMountProvider","props","mount","children","hosts","hostsReady","hostsPath","picked","setPicked","byId","index","Map","host","set","id","createHostId","has","length","setCreateHostId","siteName","get","name","siteSubdomain","subdomain","siteHubHref","encodeURIComponent","value","Provider","displayName","useCrmOrgMount","withCrmOrgMount","Card","CrmOrgMounted","orgMount","rest","card","CrmCreateSiteDefault","some"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAGA,SAEEA,aAAa,EAEbC,WAAW,EACXC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,QAAO;AAuCd,MAAMC,mCAAqBN,cAAkC;AAE7D;;;;;CAKC,GACD,MAAMO,iBAAiB,CAACC,QAAkB,CAAC,qBAAqB,EAAEA,OAAO;AAEzE,SAASC,mBAAmBD,KAAa;IACvC,IAAI;QACF,OAAOE,OAAOC,cAAc,CAACC,OAAO,CAACL,eAAeC;IACtD,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASK,oBAAoBL,KAAa,EAAEM,MAAc;IACxD,IAAI;QACFJ,OAAOC,cAAc,CAACI,OAAO,CAACR,eAAeC,QAAQM;IACvD,EAAE,eAAM;IACN,oEAAoE;IACtE;AACF;AAEA;;;;;;CAMC,GACD,O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AKE,EAAE,KAAKhB,SAAS,OAAOI;QAC5D,OAAO,aACFA;YACHa,YAAY,EAAER,iBAAAA,SAAUT;YACxBoB,iBAAiBV;;IAErB,GAAG;QAACN;QAAOJ;QAAQS;KAAO;IAC1B,qBACE,KAACjB,mBAAmBqC,QAAQ;QAACD,OAAOA;kBACjCvB;;AAGP;AACAiC,qBAAqBR,WAAW,GAAG;AAEnC,eAAeC,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/hooks/use-crm-org-mount.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 { ConsolePluginOrgHost, ConsolePluginOrgMount } from '@aglyn/aglyn'\nimport {\n type ComponentType,\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from 'react'\n\n/**\n * The organization-level mount, as every CRM surface beneath the hub reads\n * it (AGL-2630).\n *\n * The shell hands the hub page an org and its sites; the hub publishes them\n * through this context so a drawer four components down — the one that has\n * to ask which site a new record is captured by — reaches them without four\n * components threading a prop they never read. `useCrmScope` reads it too:\n * a surface handed `hostId: null` learns from here which org it is under,\n * which is what lets every existing `useCrmScope({ hostId, org })` call\n * serve the org level unchanged.\n */\nexport interface CrmOrgMount extends ConsolePluginOrgMount {\n /**\n * The site the next create stamps from: the reader's last pick this\n * session, or the org's only site when it has exactly one, else `null`\n * until somebody picks. A record is always captured BY a site — its\n * `hostId`, its `visibleTo`, the consent group its profile lives on all\n * come from one — and at the org level nothing else can say which.\n */\n createHostId: string | null\n setCreateHostId: (hostId: string) => void\n /** How a site reads on screen — its name, or its id when the list cannot name it. */\n siteName: (hostId: string) => string\n /**\n * The subdomain a console URL under `/hosts/[host]` takes, or `null` for\n * a site the list did not answer for — named, never linked.\n */\n siteSubdomain: (hostId: string) => string | null\n /**\n * The site's own CRM hub — `${hostsPath}/${subdomain}/crm` — or `null`\n * for a site whose subdomain the list could not answer, which is named\n * and not linked.\n */\n siteHubHref: (hostId: string) => string | null\n}\n\nconst CrmOrgMountContext = createContext<CrmOrgMount | null>(null)\n\n/**\n * The session's memory of the picked site, per org. Session storage rather\n * than local: the pick is a working convenience for one sitting, and a\n * site remembered across weeks would stamp a record onto a site the reader\n * had forgotten choosing.\n */\nconst pickStorageKey = (orgId: string) => `aglyn.crm.createSite.${orgId}`\n\nfunction readRememberedPick(orgId: string): string | null {\n try {\n return window.sessionStorage.getItem(pickStorageKey(orgId))\n } catch {\n return null\n }\n}\n\nfunction writeRememberedPick(orgId: string, hostId: string): void {\n try {\n window.sessionStorage.setItem(pickStorageKey(orgId), hostId)\n } catch {\n // A browser that refuses storage still gets the pick for this page.\n }\n}\n\n/**\n * Publishes the org-level mount to every surface beneath it.\n *\n * Mounted by the hub page ONLY when the shell handed it an `orgMount`; under\n * a site there is no provider and `useCrmOrgMount` answers `null`, which is\n * how a surface tells the two levels apart without a second prop.\n */\nexport function CrmOrgMountProvider(props: {\n mount: ConsolePluginOrgMount\n children: ReactNode\n}) {\n const { mount, children } = props\n const { orgId, orgSlug, hosts, hostsReady, hostsPath } = mount\n const [picked, setPicked] = useState<string | null>(null)\n // Read after mount rather than in the initializer, so the server and the\n // first client paint agree: the pick only ever affects a drawer somebody\n // has since opened.\n useEffect(() => {\n setPicked(readRememberedPick(orgId))\n }, [orgId])\n\n const byId = useMemo(() => {\n const index = new Map<string, ConsolePluginOrgHost>()\n for (const host of hosts) index.set(host.id, host)\n return index\n }, [hosts])\n\n /*\n * A remembered site the list no longer carries is forgotten rather than\n * stamped — the reader may have lost the site, or the site may be gone.\n * An org with exactly one site needs no picker at all; nothing else is\n * picked silently, because a wrong guess files a person under a brand\n * that never met them.\n */\n const createHostId = useMemo(() => {\n if (picked && byId.has(picked)) return picked\n if (hostsReady && hosts.length === 1) return hosts[0].id\n return null\n }, [picked, byId, hostsReady, hosts])\n\n const setCreateHostId = useCallback(\n (hostId: string) => {\n setPicked(hostId)\n writeRememberedPick(orgId, hostId)\n },\n [orgId],\n )\n const siteName = useCallback(\n (hostId: string) => byId.get(hostId)?.name || hostId,\n [byId],\n )\n const siteSubdomain = useCallback(\n (hostId: string) => byId.get(hostId)?.subdomain ?? null,\n [byId],\n )\n const siteHubHref = useCallback(\n (hostId: string) => {\n const subdomain = byId.get(hostId)?.subdomain\n return subdomain ? `${hostsPath}/${encodeURIComponent(subdomain)}/crm` : null\n },\n [byId, hostsPath],\n )\n\n const value = useMemo<CrmOrgMount>(\n () => ({\n orgId,\n orgSlug,\n hosts,\n hostsReady,\n hostsPath,\n createHostId,\n setCreateHostId,\n siteName,\n siteSubdomain,\n siteHubHref,\n }),\n [\n orgId,\n orgSlug,\n hosts,\n hostsReady,\n hostsPath,\n createHostId,\n setCreateHostId,\n siteName,\n siteSubdomain,\n siteHubHref,\n ],\n )\n return (\n <CrmOrgMountContext.Provider value={value}>\n {children}\n </CrmOrgMountContext.Provider>\n )\n}\nCrmOrgMountProvider.displayName = 'CrmOrgMountProvider'\n\n/** The org-level mount, or `null` under a site. */\nexport function useCrmOrgMount(): CrmOrgMount | null {\n return useContext(CrmOrgMountContext)\n}\n\n/**\n * `Card` beneath the org-level mount the SHELL hands it as a prop (AGL-2636).\n *\n * The hub page mounts the provider itself, because the shell hands the hub\n * page an `orgMount` and the page owns everything under it. A widget on the\n * org's `orgDashboard` slot is dropped into a console page the CRM does not\n * own — the org's sites list — and the console never imports a plugin, so\n * the page cannot mount this plugin's provider around the slot. The slot\n * hands each widget the same `orgMount` instead, and this puts the provider\n * where the hub page puts it: around the surface, one level down. `Card`\n * then reads `useCrmOrgMount()` and `useCrmScope({ hostId: null })` exactly\n * as it does under the hub, and stays one component for both mounts.\n *\n * Handed no mount — a slot that names a site, or a shell older than the org\n * zone — the card renders as it is, and `useCrmOrgMount` answers `null` the\n * way it does under a site.\n */\nexport function withCrmOrgMount<P extends object>(\n Card: ComponentType<P>,\n): ComponentType<P & { orgMount?: ConsolePluginOrgMount }> {\n function CrmOrgMounted(props: P & { orgMount?: ConsolePluginOrgMount }) {\n const { orgMount, ...rest } = props\n const card = <Card {...(rest as P)} />\n return orgMount ? (\n <CrmOrgMountProvider mount={orgMount}>{card}</CrmOrgMountProvider>\n ) : (\n card\n )\n }\n CrmOrgMounted.displayName = `CrmOrgMounted(${\n Card.displayName ?? (Card as { name?: string }).name ?? 'Card'\n })`\n return CrmOrgMounted\n}\n\n/**\n * THE SITE A CREATE OPENED FROM A RECORD DEFAULTS TO (AGL-2630).\n *\n * A task, an activity or a deal filed from a contact's page belongs, nine\n * times in ten, with the site that captured the contact — not with the\n * site the reader last picked in a list's drawer. So a record page wraps\n * its cards in this, naming its record's own capturing site, and every\n * create under it defaults its Site picker there. A pick the reader makes\n * INSIDE such a create is held for that page alone; the session's pick,\n * which a create opened from a list keeps defaulting to, is untouched.\n *\n * Nothing under a site, nothing for a record no site has captured, and\n * nothing for a site the mount's list does not carry — the reader may not\n * have it: the children render as they are and the session's pick stands.\n */\nexport function CrmCreateSiteDefault(props: {\n hostId: string | null | undefined\n children: ReactNode\n}) {\n const { hostId, children } = props\n const mount = useContext(CrmOrgMountContext)\n const [picked, setPicked] = useState<string | null>(null)\n // Another record on the same page starts from its own site again.\n useEffect(() => {\n setPicked(null)\n }, [hostId])\n const value = useMemo<CrmOrgMount | null>(() => {\n if (!mount || !hostId) return mount\n if (!mount.hosts.some((host) => host.id === hostId)) return mount\n return {\n ...mount,\n createHostId: picked ?? hostId,\n setCreateHostId: setPicked,\n }\n }, [mount, hostId, picked])\n return (\n <CrmOrgMountContext.Provider value={value}>\n {children}\n </CrmOrgMountContext.Provider>\n )\n}\nCrmCreateSiteDefault.displayName = 'CrmCreateSiteDefault'\n\nexport default useCrmOrgMount\n"],"names":["createContext","useCallback","useContext","useEffect","useMemo","useState","CrmOrgMountContext","pickStorageKey","orgId","readRememberedPick","window","sessionStorage","getItem","writeRememberedPick","hostId","setItem","CrmOrgMountProvider","props","mount","children","orgSlug","hosts","hostsReady","hostsPath","picked","setPicked","byId","index","Map","host","set","id","createHostId","has","length","setCreateHostId","siteName","get","name","siteSubdomain","subdomain","siteHubHref","encodeURIComponent","value","Provider","displayName","useCrmOrgMount","withCrmOrgMount","Card","CrmOrgMounted","orgMount","rest","card","CrmCreateSiteDefault","some"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAGA,SAEEA,aAAa,EAEbC,WAAW,EACXC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,QAAO;AAuCd,MAAMC,mCAAqBN,cAAkC;AAE7D;;;;;CAKC,GACD,MAAMO,iBAAiB,CAACC,QAAkB,CAAC,qBAAqB,EAAEA,OAAO;AAEzE,SAASC,mBAAmBD,KAAa;IACvC,IAAI;QACF,OAAOE,OAAOC,cAAc,CAACC,OAAO,CAACL,eAAeC;IACtD,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASK,oBAAoBL,KAAa,EAAEM,MAAc;IACxD,IAAI;QACFJ,OAAOC,cAAc,CAACI,OAAO,CAACR,eAAeC,QAAQM;IACvD,EAAE,eAAM;IACN,oEAAoE;IACtE;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASE,oBAAoBC,KAGnC;IACC,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAE,GAAGF;IAC5B,MAAM,EAAET,KAAK,EAAEY,OAAO,EAAEC,KAAK,EAAEC,UAAU,EAAEC,SAAS,EAAE,GAAGL;IACzD,MAAM,CAACM,QAAQC,UAAU,GAAGpB,SAAwB;IACpD,yEAAyE;IACzE,yEAAyE;IACzE,oBAAoB;IACpBF,UAAU;Q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eAAeC,eAAc"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { PluginContactCaptureRequest, PluginContactCaptured } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture';
18
+ import { type ContactSource } from '@aglyn/aglyn/app-utils/contacts';
19
+ /**
20
+ * The CRM answering the platform's contact-capture contract (AGL-3080).
21
+ *
22
+ * Four silos meet the same person — a form submission, a member signing up,
23
+ * an order, a booking — and none of them is the record system. Each holds an
24
+ * address, a name and the fact that something happened, and each wants the
25
+ * workspace's person record to know. Today each imports `captureHostContact`
26
+ * directly, which is the highest fan-in edge in the repo and makes the CRM
27
+ * something a storefront cannot take a payment without.
28
+ *
29
+ * So this is the CRM's side of the seam: the silo reports what it saw, and
30
+ * the plugin that keeps people decides everything a record system decides —
31
+ * keying the address, whether this is somebody new, the audience band, the
32
+ * erasure rows, the company, the owner, and what a new person sets off.
33
+ * `captureHostContact` already does all of that; this translates the
34
+ * contract's vocabulary into its options and its verdict back.
35
+ *
36
+ * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is
37
+ * recording — the submission was accepted, the order was paid — so a refusal
38
+ * is RETURNED and costs the silo nothing. A throw here would lose an order
39
+ * for a contact that could not be filed.
40
+ */
41
+ export declare function captureContactForCrm(request: PluginContactCaptureRequest): Promise<PluginContactCaptured>;
42
+ /**
43
+ * The silo's word for its door, as a source the CRM stores.
44
+ *
45
+ * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open
46
+ * string, deliberately: a silo declares its door with
47
+ * `registerPluginContactSource` rather than core enumerating every plugin's.
48
+ * The two meet here, and a word outside the union is passed through rather
49
+ * than rejected — refusing it would lose a third-party plugin's capture over
50
+ * a label, and the capture is the part that matters.
51
+ *
52
+ * ⛔ What it costs, until the union is widened: the console's source filter
53
+ * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw
54
+ * and matches no filter. Every first-party silo uses a word in the union, so
55
+ * nothing does that today.
56
+ */
57
+ export declare function contactSourceOf(source: string): ContactSource;
@@ -0,0 +1,180 @@
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 { _ as _extends } from "@swc/helpers/_/_extends";
17
+ import { CONTACT_SOURCE_LABELS } from "@aglyn/aglyn/app-utils/contacts";
18
+ import { captureHostContact } from "@aglyn/tenant-runtime/capture-host-contact";
19
+ /**
20
+ * The CRM answering the platform's contact-capture contract (AGL-3080).
21
+ *
22
+ * Four silos meet the same person — a form submission, a member signing up,
23
+ * an order, a booking — and none of them is the record system. Each holds an
24
+ * address, a name and the fact that something happened, and each wants the
25
+ * workspace's person record to know. Today each imports `captureHostContact`
26
+ * directly, which is the highest fan-in edge in the repo and makes the CRM
27
+ * something a storefront cannot take a payment without.
28
+ *
29
+ * So this is the CRM's side of the seam: the silo reports what it saw, and
30
+ * the plugin that keeps people decides everything a record system decides —
31
+ * keying the address, whether this is somebody new, the audience band, the
32
+ * erasure rows, the company, the owner, and what a new person sets off.
33
+ * `captureHostContact` already does all of that; this translates the
34
+ * contract's vocabulary into its options and its verdict back.
35
+ *
36
+ * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is
37
+ * recording — the submission was accepted, the order was paid — so a refusal
38
+ * is RETURNED and costs the silo nothing. A throw here would lose an order
39
+ * for a contact that could not be filed.
40
+ */ export async function captureContactForCrm(request) {
41
+ try {
42
+ var _request_tags, _request_campaignIds;
43
+ const verdict = await captureHostContact(_extends({
44
+ hostId: request.hostId,
45
+ email: request.identity.email
46
+ }, request.identity.name ? {
47
+ name: request.identity.name
48
+ } : {}, {
49
+ source: contactSourceOf(request.interaction.source),
50
+ interaction: _extends({}, request.interaction.atMs === undefined ? {} : {
51
+ atMs: request.interaction.atMs
52
+ }, request.interaction.refId ? {
53
+ refId: request.interaction.refId
54
+ } : {}, request.interaction.summary ? {
55
+ summary: request.interaction.summary
56
+ } : {}, entryPointOf(request.detail))
57
+ }, campaignTouchOf(request.detail), request.marketingConsent === undefined ? {} : {
58
+ marketingConsent: request.marketingConsent
59
+ }, ((_request_tags = request.tags) == null ? void 0 : _request_tags.length) ? {
60
+ tags: request.tags
61
+ } : {}, ((_request_campaignIds = request.campaignIds) == null ? void 0 : _request_campaignIds.length) ? {
62
+ campaignIds: request.campaignIds
63
+ } : {}, request.purchaseCents === undefined ? {} : {
64
+ purchaseCents: request.purchaseCents
65
+ }, request.purchaseCurrency ? {
66
+ purchaseCurrency: request.purchaseCurrency
67
+ } : {}, request.lifecycleFloor ? {
68
+ initialLifecycleStage: request.lifecycleFloor
69
+ } : {}, request.profile ? {
70
+ facet: request.profile
71
+ } : {}));
72
+ if ('refused' in verdict) {
73
+ return {
74
+ ok: false,
75
+ reason: verdict.refused,
76
+ error: refusalText(verdict.refused)
77
+ };
78
+ }
79
+ return {
80
+ ok: true,
81
+ contactId: verdict.contactId,
82
+ created: verdict.created
83
+ };
84
+ } catch (error) {
85
+ /*
86
+ * The contract's `error` is the last state, not a channel for a stack:
87
+ * a silo may show or log it as it stands, so it says what happened and
88
+ * names nothing internal. The detail goes to the log, where whoever is
89
+ * debugging a missing contact will look.
90
+ */ console.error('crm contact capture failed', error);
91
+ return {
92
+ ok: false,
93
+ reason: 'error',
94
+ error: 'The contact could not be recorded. Nothing else was affected.'
95
+ };
96
+ }
97
+ }
98
+ /**
99
+ * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).
100
+ *
101
+ * The contract carries a capture's silo-side facts opaquely, so the two the
102
+ * CRM models are picked out here rather than typed into the platform. Both
103
+ * ride the INTERACTION, which is where `upsertHostContact` already keeps
104
+ * them: which form a person came in through routes the owner-assignment
105
+ * rules and rides the `contactCreated` payload, and the page is what a
106
+ * timeline row says about where they were.
107
+ *
108
+ * Absent, misspelled or the wrong type is the same answer as a door that
109
+ * never had one — a capture without an entry point, which is every capture
110
+ * that did not come through a form. It is never a reason to refuse: the
111
+ * person is the part that matters.
112
+ */ function entryPointOf(detail) {
113
+ const text = (value)=>typeof value === 'string' && value.trim() ? value : undefined;
114
+ const formId = text(detail == null ? void 0 : detail['formId']);
115
+ const path = text(detail == null ? void 0 : detail['path']);
116
+ return _extends({}, formId ? {
117
+ formId
118
+ } : {}, path ? {
119
+ path
120
+ } : {});
121
+ }
122
+ /**
123
+ * WHERE THE VISITOR CAME FROM, off the same bag.
124
+ *
125
+ * ⚠️ A different fact from `campaignIds` and the two must never be folded
126
+ * together — `upsert-contact.ts` says so at the field itself. A touch is the
127
+ * ad or the link the visitor arrived by, already resolved through the
128
+ * allowlist by the silo; `campaignIds` is which campaigns the merchant filed
129
+ * the capture SURFACE under, which is true of everybody who fills that form
130
+ * in. Folding them would credit a campaign for a visitor who typed the
131
+ * address.
132
+ *
133
+ * Passed through as the silo resolved it, unread: the touch's shape belongs
134
+ * to whatever resolves it, and re-validating it here would be a second copy
135
+ * of a rule that has already run. Only its presence is decided here, because
136
+ * `null` and absent mean the same thing to the writer and a caller should
137
+ * not have to know which one it sends.
138
+ */ function campaignTouchOf(detail) {
139
+ const touch = detail == null ? void 0 : detail['campaignTouch'];
140
+ return touch ? {
141
+ campaignTouch: touch
142
+ } : {};
143
+ }
144
+ /**
145
+ * The silo's word for its door, as a source the CRM stores.
146
+ *
147
+ * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open
148
+ * string, deliberately: a silo declares its door with
149
+ * `registerPluginContactSource` rather than core enumerating every plugin's.
150
+ * The two meet here, and a word outside the union is passed through rather
151
+ * than rejected — refusing it would lose a third-party plugin's capture over
152
+ * a label, and the capture is the part that matters.
153
+ *
154
+ * ⛔ What it costs, until the union is widened: the console's source filter
155
+ * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw
156
+ * and matches no filter. Every first-party silo uses a word in the union, so
157
+ * nothing does that today.
158
+ */ export function contactSourceOf(source) {
159
+ const word = String(source != null ? source : '').trim();
160
+ if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {
161
+ // Said once, where somebody debugging an unlabelled row will find it.
162
+ // Not a refusal: the capture is worth more than the label.
163
+ console.warn(`crm contact capture: source "${word}" has no label, so it will render ` + 'raw and match no filter in the console.');
164
+ }
165
+ return word;
166
+ }
167
+ /** What a refused caller is told — customer-safe, and never a key. */ function refusalText(reason) {
168
+ switch(reason){
169
+ case 'invalid-email':
170
+ return 'That address could not be read, so no contact was recorded.';
171
+ case 'band':
172
+ return 'This workspace is at the number of contacts its plan holds.';
173
+ case 'erased':
174
+ return 'This person was erased from this workspace and was not recreated.';
175
+ default:
176
+ return 'The contact could not be recorded. Nothing else was affected.';
177
+ }
178
+ }
179
+
180
+ //# sourceMappingURL=capture-contact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-contact.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 {\n PluginContactCaptureRequest,\n PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport { captureHostContact } from '@aglyn/tenant-runtime/capture-host-contact'\nimport type { UpsertHostContactOptions } from '@aglyn/tenant-data-admin'\nimport type { ResolvedCampaignTouch } from '@aglyn/tenant-data-admin/server/campaign-conversion-attribution'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...campaignTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...(request.campaignIds?.length ? { campaignIds: request.campaignIds } : {}),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return { ok: true, contactId: verdict.contactId, created: verdict.created }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved through the\n * allowlist by the silo; `campaignIds` is which campaigns the merchant filed\n * the capture SURFACE under, which is true of everybody who fills that form\n * in. Folding them would credit a campaign for a visitor who typed the\n * address.\n *\n * Passed through as the silo resolved it, unread: the touch's shape belongs\n * to whatever resolves it, and re-validating it here would be a second copy\n * of a rule that has already run. Only its presence is decided here, because\n * `null` and absent mean the same thing to the writer and a caller should\n * not have to know which one it sends.\n */\nfunction campaignTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'campaignTouch'> {\n const touch = detail?.['campaignTouch']\n return touch ? { campaignTouch: touch as ResolvedCampaignTouch } : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * ⛔ What it costs, until the union is widened: the console's source filter\n * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw\n * and matches no filter. Every first-party silo uses a word in the union, so\n * nothing does that today.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["CONTACT_SOURCE_LABELS","captureHostContact","captureContactForCrm","request","verdict","hostId","email","identity","name","source","contactSourceOf","interaction","atMs","undefined","refId","summary","entryPointOf","detail","campaignTouchOf","marketingConsent","tags","length","campaignIds","purchaseCents","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","ok","reason","refused","error","refusalText","contactId","created","console","text","value","trim","formId","path","touch","campaignTouch","word","String","Object","hasOwn","warn"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SACEA,qBAAqB,QAEhB,kCAAiC;AACxC,SAASC,kBAAkB,QAAQ,6CAA4C;AAI/E;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,eAAeC,qBACpBC,OAAoC;IAEpC,IAAI;YAoBIA,eACAA;QApBN,MAAMC,UAAU,MAAMH,mBAAmB;YACvCI,QAAQF,QAAQE,MAAM;YACtBC,OAAOH,QAAQI,QAAQ,CAACD,KAAK;WACzBH,QAAQI,QAAQ,CAACC,IAAI,GAAG;YAAEA,MAAML,QAAQI,QAAQ,CAACC,IAAI;QAAC,IAAI,CAAC;YAC/DC,QAAQC,gBAAgBP,QAAQQ,WAAW,CAACF,MAAM;YAClDE,aAAa,aACPR,QAAQQ,WAAW,CAACC,IAAI,KAAKC,YAC7B,CAAC,IACD;gBAAED,MAAMT,QAAQQ,WAAW,CAACC,IAAI;YAAC,GACjCT,QAAQQ,WAAW,CAACG,KAAK,GAAG;gBAAEA,OAAOX,QAAQQ,WAAW,CAACG,KAAK;YAAC,IAAI,CAAC,GACpEX,QAAQQ,WAAW,CAACI,OAAO,GAC3B;gBAAEA,SAASZ,QAAQQ,WAAW,CAACI,OAAO;YAAC,IACvC,CAAC,GACFC,aAAab,QAAQc,MAAM;WAE7BC,gBAAgBf,QAAQc,MAAM,GAC7Bd,QAAQgB,gBAAgB,KAAKN,YAC7B,CAA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AClC,OAAO,aACDuB,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvBC,OAAO;QAAEA;IAAK,IAAI,CAAC;AAE3B;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,SAASvB,gBACPD,MAAqD;IAErD,MAAMyB,QAAQzB,0BAAAA,MAAQ,CAAC,gBAAgB;IACvC,OAAOyB,QAAQ;QAAEC,eAAeD;IAA+B,IAAI,CAAC;AACtE;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAAShC,gBAAgBD,MAAc;IAC5C,MAAMmC,OAAOC,OAAOpC,iBAAAA,SAAU,IAAI8B,IAAI;IACtC,IAAI,CAACO,OAAOC,MAAM,CAAC/C,uBAAuB4C,OAAO;QAC/C,sEAAsE;QACtE,2DAA2D;QAC3DR,QAAQY,IAAI,CACV,CAAC,6BAA6B,EAAEJ,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAASX,YAAYH,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
package/src/lib/server.js CHANGED
@@ -54,6 +54,7 @@ import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refus
54
54
  import { captureHostContact, emitHostEvent } from "@aglyn/tenant-runtime";
55
55
  import { FieldValue } from "firebase-admin/firestore";
56
56
  import { CRM_API_ROUTES } from "./constants/api-routes.js";
57
+ import { registerCrmServerDeclarations } from "./declarations.server.js";
57
58
  import { BUNDLE_ID } from "./constants/bundle-common.js";
58
59
  import { CRM_NEXT_ACTIVITY_ROUTE } from "./model/next-activity.js";
59
60
  import { CRM_TASK_ROUTES } from "./model/task-routes.js";
@@ -531,6 +532,12 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
531
532
  }
532
533
  };
533
534
  /** Console API registration, named in `plugins.config.json` as `consoleApi`. */ export function registerCrmConsoleApi() {
535
+ /*
536
+ * The contact-capture writer, again (AGL-3080). Both apps run it at boot
537
+ * from their generated server-declarations manifest, and this is the
538
+ * backstop for a process whose boot did not: the first CRM door to load
539
+ * registers it. Registering twice replaces in place.
540
+ */ registerCrmServerDeclarations();
534
541
  registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler);
535
542
  registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler);
536
543
  // Every other console write to a contact's facets (AGL-2804): the rules
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/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/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there but letting a holder go, and the plan is\n * asked here about the fields a save carries.\n */\n\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { leadConvertHandler } from './server/lead-convert'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler } from './server/contact-update'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: 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 hostId = String(req.body?.hostId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if (!hostId || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(hostId, 'contactStageChanged', {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n })\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent? }`. Answers `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: 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\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body['email'])\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const name = typed(body['name'], 120)\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\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\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n if (companyId) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const readable = new Set<string>(crmReadTokens(group))\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const result = await captureHostContact({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n marketingConsent,\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\n },\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (tags.length || companyName) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n result.created ? 'Added contact' : 'Updated contact',\n { type: 'contact', id: result.contactId, name: name || email },\n )\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n}\n"],"names":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","crmDealStageHandler","crmEmailSendHandler","leadConvertHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","contactId","requested","lifecycleStage","clearing","caller","facet","owner","suite","org","contactsRef","snapshot","group","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","email","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","decoded","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","companyDelete","save","complete","emailSend"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,sBAAsB,EACtBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,SAASC,+BAA+B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AAiC;IACjCrB,uBAAuB,oBAAoBuB;IAC3CvB,uBAAuB,oBAAoByB;IAC3C,wEAAwE;IACxE,uEAAuE;IACvE,wEAAwE;IACxE,wBAAwB;IACxBzB,uBAAuB,oBAAoBwB;IAC3C,yEAAyE;IACzE,iEAAiE;IACjE,0BAA0B;IAC1BxB,uBAAuB,kBAAkB0B;IACzC,qEAAqE;IACrE,yEAAyE;IACzE,sCAAsC;IACtC1B,uBAAuB,uBAAuB8G;IAC9C,0EAA0E;IAC1E,0EAA0E;IAC1E,6CAA6C;IAC7C9G,uBAAuB,oBAAoB4B;IAC3C,yEAAyE;IACzE,wEAAwE;IACxE5B,uBAAuB6B,6BAA6BC;IACpD,yEAAyE;IACzE,oEAAoE;IACpE,iEAAiE;IACjE9B,uBAAuBa,eAAeoJ,SAAS,EAAEtI;IACjD,yEAAyE;IACzE,uEAAuE;IACvE,0EAA0E;IAC1E3B,uBAAuB+B,sBAAsBC;IAC7C,iEAAiE;IACjE,yBAAyB;IACzBhC,uBAAuBiC,wBAAwBC;IAC/C,wEAAwE;IACxE,yEAAyE;IACzE,6CAA6C;IAC7ClC,uBAAuBmC,wBAAwBC;IAC/C,qEAAqE;IACrE,yEAAyE;IACzE,wEAAwE;IACxEpC,uBAAuBgD,0BAA0BE;IACjDlD,uBAAuBiD,yBAAyBE;IAChD,wEAAwE;IACxE,yEAAyE;IACzE,wCAAwC;IACxCnD,uBAAuBqC,2BAA2BC;IAClDtC,uBACE4C,oCACAC;IAEF,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/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/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there but letting a holder go, and the plan is\n * asked here about the fields a save carries.\n */\n\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { registerCrmServerDeclarations } from './declarations.server'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { leadConvertHandler } from './server/lead-convert'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler } from './server/contact-update'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: 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 hostId = String(req.body?.hostId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if (!hostId || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(hostId, 'contactStageChanged', {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n })\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent? }`. Answers `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: 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\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body['email'])\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const name = typed(body['name'], 120)\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\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\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n if (companyId) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const readable = new Set<string>(crmReadTokens(group))\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const result = await captureHostContact({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n marketingConsent,\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\n },\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (tags.length || companyName) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n result.created ? 'Added contact' : 'Updated contact',\n { type: 'contact', id: result.contactId, name: name || email },\n )\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n /*\n * The contact-capture writer, again (AGL-3080). Both apps run it at boot\n * from their generated server-declarations manifest, and this is the\n * backstop for a process whose boot did not: the first CRM door to load\n * registers it. Registering twice replaces in place.\n */\n registerCrmServerDeclarations()\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n}\n"],"names":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","crmDealStageHandler","crmEmailSendHandler","leadConvertHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","contactId","requested","lifecycleStage","clearing","caller","facet","owner","suite","org","contactsRef","snapshot","group","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","email","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","decoded","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","companyDelete","save","complete","emailSend"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,sBAAsB,EACtBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,SAASC,+BAA+B,QAAQ,8BAA0B;AAC1E,SAASC,sBAAsB,EAAEC,kBAAkB,QAAQ,0BAAsB;AACjF,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,wBAAwB,QAAQ,8BAA0B;AACnE,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,mBAAmB,QAAQ,yBAAqB;AACzD,SAASC,mBA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