@aglyn/plugins-crm 1.0.0-beta.261 → 1.0.0-beta.262

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.261",
3
+ "version": "1.0.0-beta.262",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,19 +25,19 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.261",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.261",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.261",
31
- "@aglyn/shared-ui-jsx": "1.0.0-beta.261",
32
- "@aglyn/shared-ui-next": "1.0.0-beta.261",
33
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.261",
34
- "@aglyn/shared-util-email": "1.0.0-beta.261",
35
- "@aglyn/shared-util-http": "1.0.0-beta.261",
36
- "@aglyn/shared-util-timestamp": "1.0.0-beta.261",
37
- "@aglyn/shared-util-tools": "1.0.0-beta.261",
38
- "@aglyn/tenant-data-admin": "1.0.0-beta.261",
39
- "@aglyn/tenant-feature-instance": "1.0.0-beta.261",
40
- "@aglyn/tenant-runtime": "1.0.0-beta.261",
28
+ "@aglyn/aglyn": "1.0.0-beta.262",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.262",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.262",
31
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.262",
32
+ "@aglyn/shared-ui-next": "1.0.0-beta.262",
33
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.262",
34
+ "@aglyn/shared-util-email": "1.0.0-beta.262",
35
+ "@aglyn/shared-util-http": "1.0.0-beta.262",
36
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.262",
37
+ "@aglyn/shared-util-tools": "1.0.0-beta.262",
38
+ "@aglyn/tenant-data-admin": "1.0.0-beta.262",
39
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.262",
40
+ "@aglyn/tenant-runtime": "1.0.0-beta.262",
41
41
  "@dnd-kit/core": "^6.3.1",
42
42
  "@dnd-kit/utilities": "^3.2.2",
43
43
  "@swc/helpers": "0.5.23",
@@ -14,7 +14,8 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { isPipelineArchived } from "@aglyn/aglyn/app-utils/crm";
17
- import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureChange, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
17
+ import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureCellText, pluginFigureChange, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
18
+ import { figureCount, figureHasColumn, figurePlural, figureRow } from "@aglyn/aglyn/app-utils/weekly-summary";
18
19
  import { scopedToHost } from "@aglyn/tenant-data-admin/server/organizations";
19
20
  import { BUNDLE_ID } from "../constants/bundle-common.js";
20
21
  import { currencyOfDeals, pipelineTotals } from "../model/crm-reports.js";
@@ -61,6 +62,18 @@ export function crmPipelineFigureReader(firestore) {
61
62
  scope: 'org',
62
63
  windows: [],
63
64
  feature: 'crm',
65
+ weeklySummary: {
66
+ order: 20,
67
+ lines: (table)=>{
68
+ var _all_value;
69
+ const all = figureRow(table, 'pipeline', 'All pipelines');
70
+ const deals = figureCount(all == null ? void 0 : all['deals']);
71
+ if (!all || !deals) return [];
72
+ return [
73
+ `Open pipeline: ${figurePlural(deals, 'deal', 'deals')} worth ${pluginFigureCellText(table, 'value', (_all_value = all['value']) != null ? _all_value : 0)}`
74
+ ];
75
+ }
76
+ },
64
77
  read: async (request)=>{
65
78
  const db = firestore();
66
79
  const [open, pipelines] = await Promise.all([
@@ -178,6 +191,20 @@ export function crmClosedDealsFigureReader(firestore) {
178
191
  scope: 'org',
179
192
  windows: WINDOWS,
180
193
  feature: 'crm',
194
+ weeklySummary: {
195
+ order: 10,
196
+ lines: (table)=>{
197
+ var _row_wonValue;
198
+ const row = table.rows[0];
199
+ if (!row || !figureHasColumn(table, 'won')) return [];
200
+ const won = figureCount(row['won']);
201
+ const lost = figureCount(row['lost']);
202
+ if (!won && !lost) return [];
203
+ return [
204
+ `Deals: ${won.toLocaleString('en-US')} won` + (won ? ` (${pluginFigureCellText(table, 'wonValue', (_row_wonValue = row['wonValue']) != null ? _row_wonValue : 0)})` : '') + `, ${lost.toLocaleString('en-US')} lost`
205
+ ];
206
+ }
207
+ },
181
208
  read: async (request)=>{
182
209
  if (!WINDOWS.includes(request.days)) {
183
210
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/deal-figures.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 { isPipelineArchived, type CrmDeal, type CrmPipeline } from '@aglyn/aglyn/app-utils/crm'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { currencyOfDeals, pipelineTotals } from '../model/crm-reports'\n\n/**\n * The organization's deals as figure tables another plugin reads by id\n * (AGL-3603) — the AI plugin's insights answer \"how much is in the pipeline?\"\n * and \"what did we win this month?\" from them.\n *\n * - `crm.pipeline`: the open pipeline as it stands, by pipeline and stage —\n * how many deals, what they are worth, and what they are worth at their\n * stage's odds — with `pipelineTotals`, the Reports page's own arithmetic.\n * - `crm.closed`: deals won and lost over the window, what was won, the win\n * rate, and the change in won deals from the window before.\n *\n * Organization readers: with a site, only the deals shared with that site —\n * `scopedToHost`, the predicate the rules evaluate — and with none, the\n * workspace's. Each read is a Firestore query on `status` (and `closedAtMs`\n * for the window), served by the `deals` composites the index file already\n * carries, projected to the fields counted and capped; a deal's title, its\n * contact and its company never reach a table.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Open deals the pipeline reads; a larger pipeline is told its figures read low. */\nexport const DEAL_FIGURES_OPEN_CEILING = 1_000\n\n/** Deals one window reads of each outcome. */\nexport const DEAL_FIGURES_CLOSED_CEILING = 1_000\n\n/** Pipelines read. */\nexport const DEAL_FIGURES_PIPELINE_CEILING = 20\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\ntype DealRow = Pick<CrmDeal, 'status' | 'stageId' | 'pipelineId' | 'amountCents' | 'currency' | 'probability'>\n\nconst major = (cents: number): number => Math.round(cents) / 100\n\nfunction deals(firestore: Firestore, orgId: string, hostId: string | null): FirebaseFirestore.Query {\n const collection = firestore.collection('orgs').doc(orgId).collection('deals')\n return hostId ? scopedToHost(collection, hostId) : collection\n}\n\nasync function readOpenDeals(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<{ rows: DealRow[]; truncated: boolean }> {\n const snapshot = await deals(firestore, orgId, hostId)\n .where('status', '==', 'open')\n .orderBy('updatedAt', 'desc')\n .select('status', 'stageId', 'pipelineId', 'amountCents', 'currency', 'probability')\n .limit(DEAL_FIGURES_OPEN_CEILING + 1)\n .get()\n return {\n rows: snapshot.docs.slice(0, DEAL_FIGURES_OPEN_CEILING).map((doc) => (doc.data() ?? {}) as DealRow),\n truncated: snapshot.docs.length > DEAL_FIGURES_OPEN_CEILING,\n }\n}\n\nasync function readPipelines(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<Array<{ id: string; pipeline: CrmPipeline }>> {\n const collection = firestore.collection('orgs').doc(orgId).collection('pipelines')\n const snapshot = await (hostId ? scopedToHost(collection, hostId) : collection)\n .limit(DEAL_FIGURES_PIPELINE_CEILING)\n .get()\n return snapshot.docs\n .map((doc) => ({ id: doc.id, pipeline: (doc.data() ?? {}) as CrmPipeline }))\n .filter(({ pipeline }) => !isPipelineArchived(pipeline))\n}\n\nexport function crmPipelineFigureReader(firestore: () => Firestore): PluginFigureReader {\n return {\n id: 'crm.pipeline',\n label: 'Deal pipeline',\n description:\n 'The open deals as they stand, by pipeline and stage: how many, what they are worth, and what they are worth at each stage’s odds. Current totals, with no window.',\n scope: 'org',\n windows: [],\n feature: 'crm',\n read: async (request) => {\n const db = firestore()\n const [open, pipelines] = await Promise.all([\n readOpenDeals(db, request.orgId, request.hostId),\n readPipelines(db, request.orgId, request.hostId),\n ])\n const { currency, mixed } = currencyOfDeals(open.rows)\n const code = currency.toUpperCase()\n const rows: PluginFigureRow[] = []\n let count = 0\n let amount = 0\n let weighted = 0\n let placed = 0\n for (const { id, pipeline } of pipelines) {\n const totals = pipelineTotals(\n open.rows.filter((deal) => deal.pipelineId === id),\n pipeline,\n )\n count += totals.count\n amount += totals.amountCents\n weighted += totals.weightedCents\n for (const stage of totals.stages) {\n placed += 1\n rows.push({\n pipeline: pipeline.name || 'Untitled pipeline',\n stage: stage.stage.name || 'Untitled stage',\n deals: stage.count,\n value: major(stage.amountCents),\n weighted: major(stage.weightedCents),\n })\n }\n }\n const kept = rows.slice(0, PLUGIN_FIGURE_MAX_ROWS - 1)\n return {\n ok: true,\n table: {\n title: 'Deal pipeline',\n source: { label: 'CRM reports', path: 'crm/reports' },\n period: null,\n columns: [\n { key: 'pipeline', label: 'Pipeline', kind: 'text' },\n { key: 'stage', label: 'Stage', kind: 'text' },\n { key: 'deals', label: 'Open deals', kind: 'count' },\n { key: 'value', label: 'Value', kind: 'money', currency: code },\n { key: 'weighted', label: 'Weighted value', kind: 'money', currency: code },\n ],\n rows: [\n { pipeline: 'All pipelines', stage: 'All open stages', deals: count, value: major(amount), weighted: major(weighted) },\n ...kept,\n ],\n omitted: Math.max(0, placed - kept.length),\n notes: [\n 'Only open deals: a won deal is revenue and a lost one is history.',\n ...(mixed ? [`Deals are in more than one currency; every amount is added as ${code}.`] : []),\n ...(open.truncated\n ? [`More than ${DEAL_FIGURES_OPEN_CEILING.toLocaleString('en-US')} deals are open, so the figures count the most recently updated ${DEAL_FIGURES_OPEN_CEILING.toLocaleString('en-US')} and read low.`]\n : []),\n ].slice(0, 3),\n },\n }\n },\n }\n}\n\ninterface ClosedRead {\n count: number\n amountCents: number\n currencies: Array<Pick<CrmDeal, 'currency'>>\n truncated: boolean\n}\n\nasync function readClosed(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n status: 'won' | 'lost',\n startMs: number,\n endMs: number,\n): Promise<ClosedRead> {\n const snapshot = await deals(firestore, orgId, hostId)\n .where('status', '==', status)\n .where('closedAtMs', '>=', startMs)\n .where('closedAtMs', '<', endMs)\n .orderBy('closedAtMs', 'asc')\n .select('amountCents', 'currency')\n .limit(DEAL_FIGURES_CLOSED_CEILING + 1)\n .get()\n const docs = snapshot.docs.slice(0, DEAL_FIGURES_CLOSED_CEILING).map((doc) => (doc.data() ?? {}) as DealRow)\n return {\n count: docs.length,\n amountCents: docs.reduce((sum, deal) => sum + Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0)), 0),\n currencies: docs,\n truncated: snapshot.docs.length > DEAL_FIGURES_CLOSED_CEILING,\n }\n}\n\nexport function crmClosedDealsFigureReader(firestore: () => Firestore): PluginFigureReader {\n return {\n id: 'crm.closed',\n label: 'Deals won and lost',\n description:\n 'Deals closed over the window: how many were won and lost, what was won, the win rate, and the change in deals won from the window before.',\n scope: 'org',\n windows: WINDOWS,\n feature: 'crm',\n read: async (request) => {\n if (!WINDOWS.includes(request.days)) {\n return { ok: false, status: 400, error: 'That window is not one closed deals are read over' }\n }\n const db = firestore()\n const { current, previous } = pluginFigureWindows(request.now, request.days)\n const [won, lost, wonBefore] = await Promise.all([\n readClosed(db, request.orgId, request.hostId, 'won', current.startMs, current.endMs),\n readClosed(db, request.orgId, request.hostId, 'lost', current.startMs, current.endMs),\n readClosed(db, request.orgId, request.hostId, 'won', previous.startMs, previous.endMs),\n ])\n const { currency, mixed } = currencyOfDeals(won.currencies)\n const code = currency.toUpperCase()\n const closed = won.count + lost.count\n return {\n ok: true,\n table: {\n title: 'Deals won and lost',\n source: { label: 'CRM reports', path: 'crm/reports' },\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'won', label: 'Won', kind: 'count' },\n { key: 'lost', label: 'Lost', kind: 'count' },\n { key: 'wonValue', label: 'Value won', kind: 'money', currency: code },\n { key: 'winRate', label: 'Win rate', kind: 'percent' },\n { key: 'change', label: 'Change in deals won', kind: 'change' },\n ],\n rows: [\n {\n won: won.count,\n lost: lost.count,\n wonValue: major(won.amountCents),\n winRate: closed > 0 ? Math.round((won.count / closed) * 1_000) / 10 : null,\n change: pluginFigureChange(won.count, wonBefore.count),\n },\n ],\n omitted: 0,\n notes: [\n 'A deal is counted on the day it closed.',\n ...(mixed ? [`Deals won are in more than one currency; every amount is added as ${code}.`] : []),\n ...(won.truncated || lost.truncated || wonBefore.truncated\n ? [`More than ${DEAL_FIGURES_CLOSED_CEILING.toLocaleString('en-US')} deals closed one way in a window, so the figures count ${DEAL_FIGURES_CLOSED_CEILING.toLocaleString('en-US')} and read low.`]\n : []),\n ].slice(0, 3),\n },\n }\n },\n }\n}\n\n/** Registers the deal readers from the console surface, where insight jobs run. */\nexport function registerDealFigureReaders(firestore: () => Firestore): void {\n for (const reader of [crmPipelineFigureReader(firestore), crmClosedDealsFigureReader(firestore)]) {\n registerPluginFigureReader(reader, { pluginId: BUNDLE_ID })\n }\n}\n"],"names":["isPipelineArchived","PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureWindows","registerPluginFigureReader","scopedToHost","BUNDLE_ID","currencyOfDeals","pipelineTotals","DEAL_FIGURES_OPEN_CEILING","DEAL_FIGURES_CLOSED_CEILING","DEAL_FIGURES_PIPELINE_CEILING","WINDOWS","major","cents","Math","round","deals","firestore","orgId","hostId","collection","doc","readOpenDeals","snapshot","where","orderBy","select","limit","get","rows","docs","slice","map","data","truncated","length","readPipelines","id","pipeline","filter","crmPipelineFigureReader","label","description","scope","windows","feature","read","request","db","open","pipelines","Promise","all","currency","mixed","code","toUpperCase","count","amount","weighted","placed","totals","deal","pipelineId","amountCents","weightedCents","stage","stages","push","name","value","kept","ok","table","title","source","path","period","columns","key","kind","omitted","max","notes","toLocaleString","readClosed","status","startMs","endMs","reduce","sum","Number","currencies","crmClosedDealsFigureReader","includes","days","error","current","previous","now","won","lost","wonBefore","closed","from","to","wonValue","winRate","change","registerDealFigureReaders","reader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAwC,6BAA4B;AAC/F,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SAASC,YAAY,QAAQ,gDAA+C;AAC5E,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,eAAe,EAAEC,cAAc,QAAQ,0BAAsB;AAuBtE,mFAAmF,GACnF,OAAO,MAAMC,4BAA4B,KAAK;AAE9C,4CAA4C,GAC5C,OAAO,MAAMC,8BAA8B,KAAK;AAEhD,oBAAoB,GACpB,OAAO,MAAMC,gCAAgC,GAAE;AAE/C,MAAMC,UAA6B;IAAC;IAAG;IAAI;IAAI;CAAG;AAIlD,MAAMC,QAAQ,CAACC,QAA0BC,KAAKC,KAAK,CAACF,SAAS;AAE7D,SAASG,MAAMC,SAAoB,EAAEC,KAAa,EAAEC,MAAqB;IACvE,MAAMC,aAAaH,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAAC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AChM,EAAE;qBACP,CAACrD,KAAK,CAAC,GAAG;gBACb;YACF;QACF;IACF;AACF;AAEA,iFAAiF,GACjF,OAAO,SAAS8E,0BAA0B5F,SAA0B;IAClE,KAAK,MAAM6F,UAAU;QAACtE,wBAAwBvB;QAAY4E,2BAA2B5E;KAAW,CAAE;QAChGd,2BAA2B2G,QAAQ;YAAEC,UAAU1G;QAAU;IAC3D;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/deal-figures.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 { isPipelineArchived, type CrmDeal, type CrmPipeline } from '@aglyn/aglyn/app-utils/crm'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureCellText,\n pluginFigureChange,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { figureCount, figureHasColumn, figurePlural, figureRow } from '@aglyn/aglyn/app-utils/weekly-summary'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { currencyOfDeals, pipelineTotals } from '../model/crm-reports'\n\n/**\n * The organization's deals as figure tables another plugin reads by id\n * (AGL-3603) — the AI plugin's insights answer \"how much is in the pipeline?\"\n * and \"what did we win this month?\" from them.\n *\n * - `crm.pipeline`: the open pipeline as it stands, by pipeline and stage —\n * how many deals, what they are worth, and what they are worth at their\n * stage's odds — with `pipelineTotals`, the Reports page's own arithmetic.\n * - `crm.closed`: deals won and lost over the window, what was won, the win\n * rate, and the change in won deals from the window before.\n *\n * Organization readers: with a site, only the deals shared with that site —\n * `scopedToHost`, the predicate the rules evaluate — and with none, the\n * workspace's. Each read is a Firestore query on `status` (and `closedAtMs`\n * for the window), served by the `deals` composites the index file already\n * carries, projected to the fields counted and capped; a deal's title, its\n * contact and its company never reach a table.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Open deals the pipeline reads; a larger pipeline is told its figures read low. */\nexport const DEAL_FIGURES_OPEN_CEILING = 1_000\n\n/** Deals one window reads of each outcome. */\nexport const DEAL_FIGURES_CLOSED_CEILING = 1_000\n\n/** Pipelines read. */\nexport const DEAL_FIGURES_PIPELINE_CEILING = 20\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\ntype DealRow = Pick<CrmDeal, 'status' | 'stageId' | 'pipelineId' | 'amountCents' | 'currency' | 'probability'>\n\nconst major = (cents: number): number => Math.round(cents) / 100\n\nfunction deals(firestore: Firestore, orgId: string, hostId: string | null): FirebaseFirestore.Query {\n const collection = firestore.collection('orgs').doc(orgId).collection('deals')\n return hostId ? scopedToHost(collection, hostId) : collection\n}\n\nasync function readOpenDeals(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<{ rows: DealRow[]; truncated: boolean }> {\n const snapshot = await deals(firestore, orgId, hostId)\n .where('status', '==', 'open')\n .orderBy('updatedAt', 'desc')\n .select('status', 'stageId', 'pipelineId', 'amountCents', 'currency', 'probability')\n .limit(DEAL_FIGURES_OPEN_CEILING + 1)\n .get()\n return {\n rows: snapshot.docs.slice(0, DEAL_FIGURES_OPEN_CEILING).map((doc) => (doc.data() ?? {}) as DealRow),\n truncated: snapshot.docs.length > DEAL_FIGURES_OPEN_CEILING,\n }\n}\n\nasync function readPipelines(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<Array<{ id: string; pipeline: CrmPipeline }>> {\n const collection = firestore.collection('orgs').doc(orgId).collection('pipelines')\n const snapshot = await (hostId ? scopedToHost(collection, hostId) : collection)\n .limit(DEAL_FIGURES_PIPELINE_CEILING)\n .get()\n return snapshot.docs\n .map((doc) => ({ id: doc.id, pipeline: (doc.data() ?? {}) as CrmPipeline }))\n .filter(({ pipeline }) => !isPipelineArchived(pipeline))\n}\n\nexport function crmPipelineFigureReader(firestore: () => Firestore): PluginFigureReader {\n return {\n id: 'crm.pipeline',\n label: 'Deal pipeline',\n description:\n 'The open deals as they stand, by pipeline and stage: how many, what they are worth, and what they are worth at each stage’s odds. Current totals, with no window.',\n scope: 'org',\n windows: [],\n feature: 'crm',\n weeklySummary: {\n order: 20,\n lines: (table) => {\n const all = figureRow(table, 'pipeline', 'All pipelines')\n const deals = figureCount(all?.['deals'])\n if (!all || !deals) return []\n return [`Open pipeline: ${figurePlural(deals, 'deal', 'deals')} worth ${pluginFigureCellText(table, 'value', all['value'] ?? 0)}`]\n },\n },\n read: async (request) => {\n const db = firestore()\n const [open, pipelines] = await Promise.all([\n readOpenDeals(db, request.orgId, request.hostId),\n readPipelines(db, request.orgId, request.hostId),\n ])\n const { currency, mixed } = currencyOfDeals(open.rows)\n const code = currency.toUpperCase()\n const rows: PluginFigureRow[] = []\n let count = 0\n let amount = 0\n let weighted = 0\n let placed = 0\n for (const { id, pipeline } of pipelines) {\n const totals = pipelineTotals(\n open.rows.filter((deal) => deal.pipelineId === id),\n pipeline,\n )\n count += totals.count\n amount += totals.amountCents\n weighted += totals.weightedCents\n for (const stage of totals.stages) {\n placed += 1\n rows.push({\n pipeline: pipeline.name || 'Untitled pipeline',\n stage: stage.stage.name || 'Untitled stage',\n deals: stage.count,\n value: major(stage.amountCents),\n weighted: major(stage.weightedCents),\n })\n }\n }\n const kept = rows.slice(0, PLUGIN_FIGURE_MAX_ROWS - 1)\n return {\n ok: true,\n table: {\n title: 'Deal pipeline',\n source: { label: 'CRM reports', path: 'crm/reports' },\n period: null,\n columns: [\n { key: 'pipeline', label: 'Pipeline', kind: 'text' },\n { key: 'stage', label: 'Stage', kind: 'text' },\n { key: 'deals', label: 'Open deals', kind: 'count' },\n { key: 'value', label: 'Value', kind: 'money', currency: code },\n { key: 'weighted', label: 'Weighted value', kind: 'money', currency: code },\n ],\n rows: [\n { pipeline: 'All pipelines', stage: 'All open stages', deals: count, value: major(amount), weighted: major(weighted) },\n ...kept,\n ],\n omitted: Math.max(0, placed - kept.length),\n notes: [\n 'Only open deals: a won deal is revenue and a lost one is history.',\n ...(mixed ? [`Deals are in more than one currency; every amount is added as ${code}.`] : []),\n ...(open.truncated\n ? [`More than ${DEAL_FIGURES_OPEN_CEILING.toLocaleString('en-US')} deals are open, so the figures count the most recently updated ${DEAL_FIGURES_OPEN_CEILING.toLocaleString('en-US')} and read low.`]\n : []),\n ].slice(0, 3),\n },\n }\n },\n }\n}\n\ninterface ClosedRead {\n count: number\n amountCents: number\n currencies: Array<Pick<CrmDeal, 'currency'>>\n truncated: boolean\n}\n\nasync function readClosed(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n status: 'won' | 'lost',\n startMs: number,\n endMs: number,\n): Promise<ClosedRead> {\n const snapshot = await deals(firestore, orgId, hostId)\n .where('status', '==', status)\n .where('closedAtMs', '>=', startMs)\n .where('closedAtMs', '<', endMs)\n .orderBy('closedAtMs', 'asc')\n .select('amountCents', 'currency')\n .limit(DEAL_FIGURES_CLOSED_CEILING + 1)\n .get()\n const docs = snapshot.docs.slice(0, DEAL_FIGURES_CLOSED_CEILING).map((doc) => (doc.data() ?? {}) as DealRow)\n return {\n count: docs.length,\n amountCents: docs.reduce((sum, deal) => sum + Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0)), 0),\n currencies: docs,\n truncated: snapshot.docs.length > DEAL_FIGURES_CLOSED_CEILING,\n }\n}\n\nexport function crmClosedDealsFigureReader(firestore: () => Firestore): PluginFigureReader {\n return {\n id: 'crm.closed',\n label: 'Deals won and lost',\n description:\n 'Deals closed over the window: how many were won and lost, what was won, the win rate, and the change in deals won from the window before.',\n scope: 'org',\n windows: WINDOWS,\n feature: 'crm',\n weeklySummary: {\n order: 10,\n lines: (table) => {\n const row = table.rows[0]\n if (!row || !figureHasColumn(table, 'won')) return []\n const won = figureCount(row['won'])\n const lost = figureCount(row['lost'])\n if (!won && !lost) return []\n return [\n `Deals: ${won.toLocaleString('en-US')} won` +\n (won ? ` (${pluginFigureCellText(table, 'wonValue', row['wonValue'] ?? 0)})` : '') +\n `, ${lost.toLocaleString('en-US')} lost`,\n ]\n },\n },\n read: async (request) => {\n if (!WINDOWS.includes(request.days)) {\n return { ok: false, status: 400, error: 'That window is not one closed deals are read over' }\n }\n const db = firestore()\n const { current, previous } = pluginFigureWindows(request.now, request.days)\n const [won, lost, wonBefore] = await Promise.all([\n readClosed(db, request.orgId, request.hostId, 'won', current.startMs, current.endMs),\n readClosed(db, request.orgId, request.hostId, 'lost', current.startMs, current.endMs),\n readClosed(db, request.orgId, request.hostId, 'won', previous.startMs, previous.endMs),\n ])\n const { currency, mixed } = currencyOfDeals(won.currencies)\n const code = currency.toUpperCase()\n const closed = won.count + lost.count\n return {\n ok: true,\n table: {\n title: 'Deals won and lost',\n source: { label: 'CRM reports', path: 'crm/reports' },\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'won', label: 'Won', kind: 'count' },\n { key: 'lost', label: 'Lost', kind: 'count' },\n { key: 'wonValue', label: 'Value won', kind: 'money', currency: code },\n { key: 'winRate', label: 'Win rate', kind: 'percent' },\n { key: 'change', label: 'Change in deals won', kind: 'change' },\n ],\n rows: [\n {\n won: won.count,\n lost: lost.count,\n wonValue: major(won.amountCents),\n winRate: closed > 0 ? Math.round((won.count / closed) * 1_000) / 10 : null,\n change: pluginFigureChange(won.count, wonBefore.count),\n },\n ],\n omitted: 0,\n notes: [\n 'A deal is counted on the day it closed.',\n ...(mixed ? [`Deals won are in more than one currency; every amount is added as ${code}.`] : []),\n ...(won.truncated || lost.truncated || wonBefore.truncated\n ? [`More than ${DEAL_FIGURES_CLOSED_CEILING.toLocaleString('en-US')} deals closed one way in a window, so the figures count ${DEAL_FIGURES_CLOSED_CEILING.toLocaleString('en-US')} and read low.`]\n : []),\n ].slice(0, 3),\n },\n }\n },\n }\n}\n\n/** Registers the deal readers from the console surface, where insight jobs run. */\nexport function registerDealFigureReaders(firestore: () => Firestore): void {\n for (const reader of [crmPipelineFigureReader(firestore), crmClosedDealsFigureReader(firestore)]) {\n registerPluginFigureReader(reader, { pluginId: BUNDLE_ID })\n }\n}\n"],"names":["isPipelineArchived","PLUGIN_FIGURE_MAX_ROWS","pluginFigureCellText","pluginFigureChange","pluginFigureWindows","registerPluginFigureReader","figureCount","figureHasColumn","figurePlural","figureRow","scopedToHost","BUNDLE_ID","currencyOfDeals","pipelineTotals","DEAL_FIGURES_OPEN_CEILING","DEAL_FIGURES_CLOSED_CEILING","DEAL_FIGURES_PIPELINE_CEILING","WINDOWS","major","cents","Math","round","deals","firestore","orgId","hostId","collection","doc","readOpenDeals","snapshot","where","orderBy","select","limit","get","rows","docs","slice","map","data","truncated","length","readPipelines","id","pipeline","filter","crmPipelineFigureReader","label","description","scope","windows","feature","weeklySummary","order","lines","table","all","read","request","db","open","pipelines","Promise","currency","mixed","code","toUpperCase","count","amount","weighted","placed","totals","deal","pipelineId","amountCents","weightedCents","stage","stages","push","name","value","kept","ok","title","source","path","period","columns","key","kind","omitted","max","notes","toLocaleString","readClosed","status","startMs","endMs","reduce","sum","Number","currencies","crmClosedDealsFigureReader","row","won","lost","includes","days","error","current","previous","now","wonBefore","closed","from","to","wonValue","winRate","change","registerDealFigureReaders","reader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAwC,6BAA4B;AAC/F,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SAASC,WAAW,EAAEC,eAAe,EAAEC,YAAY,EAAEC,SAAS,QAAQ,wCAAuC;AAC7G,SAASC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EC,KAAK,CAAC,CAAC;yBAAC,GAAG,EAAE;2BAC3FuC,IAAIhE,SAAS,IAAIiE,KAAKjE,SAAS,IAAIwE,UAAUxE,SAAS,GACtD;4BAAC,CAAC,UAAU,EAAEzB,4BAA4B8E,cAAc,CAAC,SAAS,wDAAwD,EAAE9E,4BAA4B8E,cAAc,CAAC,SAAS,cAAc,CAAC;yBAAC,GAChM,EAAE;qBACP,CAACxD,KAAK,CAAC,GAAG;gBACb;YACF;QACF;IACF;AACF;AAEA,iFAAiF,GACjF,OAAO,SAASkF,0BAA0BhG,SAA0B;IAClE,KAAK,MAAMiG,UAAU;QAAC1E,wBAAwBvB;QAAY+E,2BAA2B/E;KAAW,CAAE;QAChGlB,2BAA2BmH,QAAQ;YAAEC,UAAU9G;QAAU;IAC3D;AACF"}
@@ -0,0 +1,39 @@
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 PluginFigureReader } from '@aglyn/aglyn/plugin-manager/plugin-figures';
18
+ /**
19
+ * The people the CRM gained over a window, as a figure table another plugin
20
+ * or the platform reads by id (AGL-3867): the weekly summary's "new leads"
21
+ * and "new contacts" lines, and an insight's answer to "are we getting more
22
+ * leads?".
23
+ *
24
+ * An organization reader, like the deal readers: with a site, only the
25
+ * records shared with that site (`scopedToHost`, the predicate the rules
26
+ * evaluate); with none, the workspace's. Each figure is one `count()`
27
+ * aggregation over the window, so a busy CRM costs the same as a quiet one,
28
+ * and no record — let alone a name or an address — ever reaches the table.
29
+ *
30
+ * A lead is counted on the day it was first seen (`firstSeenAtMs`), a contact
31
+ * on the day its record was created (`createdAt`), which are the fields the
32
+ * Leads and Contacts lists sort their newest by. Both are served by the
33
+ * `visibleTo` composites the index file already carries.
34
+ */
35
+ type Firestore = FirebaseFirestore.Firestore;
36
+ export declare function crmPeopleFigureReader(firestore: () => Firestore): PluginFigureReader;
37
+ /** Registers the reader from the console surface, where insight jobs and the weekly summary run. */
38
+ export declare function registerPeopleFigureReader(firestore: () => Firestore): void;
39
+ export {};
@@ -0,0 +1,153 @@
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 { pluginFigureChange, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
17
+ import { figureCount, figureRow, figureWithChange } from "@aglyn/aglyn/app-utils/weekly-summary";
18
+ import { scopedToHost } from "@aglyn/tenant-data-admin/server/organizations";
19
+ import { Timestamp } from "firebase-admin/firestore";
20
+ import { BUNDLE_ID } from "../constants/bundle-common.js";
21
+ const WINDOWS = [
22
+ 7,
23
+ 14,
24
+ 30,
25
+ 90
26
+ ];
27
+ function scoped(collection, hostId) {
28
+ return hostId ? scopedToHost(collection, hostId) : collection;
29
+ }
30
+ async function countLeads(firestore, orgId, hostId, startMs, endMs) {
31
+ const leads = firestore.collection('orgs').doc(orgId).collection('leads');
32
+ const snapshot = await scoped(leads, hostId).where('firstSeenAtMs', '>=', startMs).where('firstSeenAtMs', '<', endMs).count().get();
33
+ return snapshot.data().count;
34
+ }
35
+ async function countContacts(firestore, orgId, hostId, startMs, endMs) {
36
+ const contacts = firestore.collection('orgs').doc(orgId).collection('contacts');
37
+ const snapshot = await scoped(contacts, hostId).where('createdAt', '>=', Timestamp.fromMillis(startMs)).where('createdAt', '<', Timestamp.fromMillis(endMs)).count().get();
38
+ return snapshot.data().count;
39
+ }
40
+ export function crmPeopleFigureReader(firestore) {
41
+ return {
42
+ id: 'crm.people',
43
+ label: 'New leads and contacts',
44
+ description: 'How many leads were first seen and how many contacts were added over the window, against the window before.',
45
+ scope: 'org',
46
+ windows: WINDOWS,
47
+ feature: 'crm',
48
+ // Under each site: the leads a site captured are that site's news.
49
+ weeklySummary: {
50
+ per: 'site',
51
+ order: 50,
52
+ lines: (table)=>{
53
+ const leads = figureRow(table, 'figure', 'New leads');
54
+ const contacts = figureRow(table, 'figure', 'New contacts');
55
+ const parts = [
56
+ leads && figureCount(leads['current']) ? `New leads: ${figureWithChange(table, leads, 'current', 'change')}` : null,
57
+ contacts && figureCount(contacts['current']) ? `New contacts: ${figureWithChange(table, contacts, 'current', 'change')}` : null
58
+ ].filter(Boolean);
59
+ return parts.length ? [
60
+ parts.join(' · ')
61
+ ] : [];
62
+ },
63
+ headline: (table)=>{
64
+ var _figureRow;
65
+ const count = figureCount((_figureRow = figureRow(table, 'figure', 'New leads')) == null ? void 0 : _figureRow['current']);
66
+ return count ? {
67
+ count,
68
+ one: 'new lead',
69
+ many: 'new leads'
70
+ } : null;
71
+ }
72
+ },
73
+ read: async (request)=>{
74
+ if (!WINDOWS.includes(request.days)) {
75
+ return {
76
+ ok: false,
77
+ status: 400,
78
+ error: 'That window is not one new leads and contacts are read over'
79
+ };
80
+ }
81
+ const db = firestore();
82
+ const { current, previous } = pluginFigureWindows(request.now, request.days);
83
+ const [leads, leadsBefore, contacts, contactsBefore] = await Promise.all([
84
+ countLeads(db, request.orgId, request.hostId, current.startMs, current.endMs),
85
+ countLeads(db, request.orgId, request.hostId, previous.startMs, previous.endMs),
86
+ countContacts(db, request.orgId, request.hostId, current.startMs, current.endMs),
87
+ countContacts(db, request.orgId, request.hostId, previous.startMs, previous.endMs)
88
+ ]);
89
+ return {
90
+ ok: true,
91
+ table: {
92
+ title: 'New leads and contacts',
93
+ source: {
94
+ label: 'CRM',
95
+ path: 'crm'
96
+ },
97
+ period: {
98
+ from: current.from,
99
+ to: current.to,
100
+ days: request.days
101
+ },
102
+ columns: [
103
+ {
104
+ key: 'figure',
105
+ label: 'Figure',
106
+ kind: 'text'
107
+ },
108
+ {
109
+ key: 'current',
110
+ label: 'This window',
111
+ kind: 'count'
112
+ },
113
+ {
114
+ key: 'previous',
115
+ label: 'Window before',
116
+ kind: 'count'
117
+ },
118
+ {
119
+ key: 'change',
120
+ label: 'Change',
121
+ kind: 'change'
122
+ }
123
+ ],
124
+ rows: [
125
+ {
126
+ figure: 'New leads',
127
+ current: leads,
128
+ previous: leadsBefore,
129
+ change: pluginFigureChange(leads, leadsBefore)
130
+ },
131
+ {
132
+ figure: 'New contacts',
133
+ current: contacts,
134
+ previous: contactsBefore,
135
+ change: pluginFigureChange(contacts, contactsBefore)
136
+ }
137
+ ],
138
+ omitted: 0,
139
+ notes: [
140
+ 'A lead is counted on the day it was first seen, a contact on the day it was added.'
141
+ ]
142
+ }
143
+ };
144
+ }
145
+ };
146
+ }
147
+ /** Registers the reader from the console surface, where insight jobs and the weekly summary run. */ export function registerPeopleFigureReader(firestore) {
148
+ registerPluginFigureReader(crmPeopleFigureReader(firestore), {
149
+ pluginId: BUNDLE_ID
150
+ });
151
+ }
152
+
153
+ //# sourceMappingURL=people-figures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/people-figures.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginFigureChange,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { figureCount, figureRow, figureWithChange } from '@aglyn/aglyn/app-utils/weekly-summary'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { Timestamp } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * The people the CRM gained over a window, as a figure table another plugin\n * or the platform reads by id (AGL-3867): the weekly summary's \"new leads\"\n * and \"new contacts\" lines, and an insight's answer to \"are we getting more\n * leads?\".\n *\n * An organization reader, like the deal readers: with a site, only the\n * records shared with that site (`scopedToHost`, the predicate the rules\n * evaluate); with none, the workspace's. Each figure is one `count()`\n * aggregation over the window, so a busy CRM costs the same as a quiet one,\n * and no record — let alone a name or an address — ever reaches the table.\n *\n * A lead is counted on the day it was first seen (`firstSeenAtMs`), a contact\n * on the day its record was created (`createdAt`), which are the fields the\n * Leads and Contacts lists sort their newest by. Both are served by the\n * `visibleTo` composites the index file already carries.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\nfunction scoped(collection: FirebaseFirestore.CollectionReference, hostId: string | null) {\n return hostId ? scopedToHost(collection, hostId) : collection\n}\n\nasync function countLeads(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n startMs: number,\n endMs: number,\n): Promise<number> {\n const leads = firestore.collection('orgs').doc(orgId).collection('leads')\n const snapshot = await scoped(leads, hostId)\n .where('firstSeenAtMs', '>=', startMs)\n .where('firstSeenAtMs', '<', endMs)\n .count()\n .get()\n return snapshot.data().count\n}\n\nasync function countContacts(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n startMs: number,\n endMs: number,\n): Promise<number> {\n const contacts = firestore.collection('orgs').doc(orgId).collection('contacts')\n const snapshot = await scoped(contacts, hostId)\n .where('createdAt', '>=', Timestamp.fromMillis(startMs))\n .where('createdAt', '<', Timestamp.fromMillis(endMs))\n .count()\n .get()\n return snapshot.data().count\n}\n\nexport function crmPeopleFigureReader(firestore: () => Firestore): PluginFigureReader {\n return {\n id: 'crm.people',\n label: 'New leads and contacts',\n description:\n 'How many leads were first seen and how many contacts were added over the window, against the window before.',\n scope: 'org',\n windows: WINDOWS,\n feature: 'crm',\n // Under each site: the leads a site captured are that site's news.\n weeklySummary: {\n per: 'site',\n order: 50,\n lines: (table) => {\n const leads = figureRow(table, 'figure', 'New leads')\n const contacts = figureRow(table, 'figure', 'New contacts')\n const parts = [\n leads && figureCount(leads['current']) ? `New leads: ${figureWithChange(table, leads, 'current', 'change')}` : null,\n contacts && figureCount(contacts['current'])\n ? `New contacts: ${figureWithChange(table, contacts, 'current', 'change')}`\n : null,\n ].filter(Boolean)\n return parts.length ? [parts.join(' · ')] : []\n },\n headline: (table) => {\n const count = figureCount(figureRow(table, 'figure', 'New leads')?.['current'])\n return count ? { count, one: 'new lead', many: 'new leads' } : null\n },\n },\n read: async (request) => {\n if (!WINDOWS.includes(request.days)) {\n return { ok: false, status: 400, error: 'That window is not one new leads and contacts are read over' }\n }\n const db = firestore()\n const { current, previous } = pluginFigureWindows(request.now, request.days)\n const [leads, leadsBefore, contacts, contactsBefore] = await Promise.all([\n countLeads(db, request.orgId, request.hostId, current.startMs, current.endMs),\n countLeads(db, request.orgId, request.hostId, previous.startMs, previous.endMs),\n countContacts(db, request.orgId, request.hostId, current.startMs, current.endMs),\n countContacts(db, request.orgId, request.hostId, previous.startMs, previous.endMs),\n ])\n return {\n ok: true,\n table: {\n title: 'New leads and contacts',\n source: { label: 'CRM', path: 'crm' },\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'figure', label: 'Figure', kind: 'text' },\n { key: 'current', label: 'This window', kind: 'count' },\n { key: 'previous', label: 'Window before', kind: 'count' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows: [\n { figure: 'New leads', current: leads, previous: leadsBefore, change: pluginFigureChange(leads, leadsBefore) },\n {\n figure: 'New contacts',\n current: contacts,\n previous: contactsBefore,\n change: pluginFigureChange(contacts, contactsBefore),\n },\n ],\n omitted: 0,\n notes: ['A lead is counted on the day it was first seen, a contact on the day it was added.'],\n },\n }\n },\n }\n}\n\n/** Registers the reader from the console surface, where insight jobs and the weekly summary run. */\nexport function registerPeopleFigureReader(firestore: () => Firestore): void {\n registerPluginFigureReader(crmPeopleFigureReader(firestore), { pluginId: BUNDLE_ID })\n}\n"],"names":["pluginFigureChange","pluginFigureWindows","registerPluginFigureReader","figureCount","figureRow","figureWithChange","scopedToHost","Timestamp","BUNDLE_ID","WINDOWS","scoped","collection","hostId","countLeads","firestore","orgId","startMs","endMs","leads","doc","snapshot","where","count","get","data","countContacts","contacts","fromMillis","crmPeopleFigureReader","id","label","description","scope","windows","feature","weeklySummary","per","order","lines","table","parts","filter","Boolean","length","join","headline","one","many","read","request","includes","days","ok","status","error","db","current","previous","now","leadsBefore","contactsBefore","Promise","all","title","source","path","period","from","to","columns","key","kind","rows","figure","change","omitted","notes","registerPeopleFigureReader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAErB,6CAA4C;AACnD,SAASC,WAAW,EAAEC,SAAS,EAAEC,gBAAgB,QAAQ,wCAAuC;AAChG,SAASC,YAAY,QAAQ,gDAA+C;AAC5E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,SAAS,QAAQ,gCAA4B;AAsBtD,MAAMC,UAA6B;IAAC;IAAG;IAAI;IAAI;CAAG;AAElD,SAASC,OAAOC,UAAiD,EAAEC,MAAqB;IACtF,OAAOA,SAASN,aAAaK,YAAYC,UAAUD;AACrD;AAEA,eAAeE,W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AAMX,QAAQW,IAAI;wBAAEC,IAAIZ,QAAQY,EAAE;wBAAEjB,MAAMF,QAAQE,IAAI;oBAAC;oBACjEkB,SAAS;wBACP;4BAAEC,KAAK;4BAAUxC,OAAO;4BAAUyC,MAAM;wBAAO;wBAC/C;4BAAED,KAAK;4BAAWxC,OAAO;4BAAeyC,MAAM;wBAAQ;wBACtD;4BAAED,KAAK;4BAAYxC,OAAO;4BAAiByC,MAAM;wBAAQ;wBACzD;4BAAED,KAAK;4BAAUxC,OAAO;4BAAUyC,MAAM;wBAAS;qBAClD;oBACDC,MAAM;wBACJ;4BAAEC,QAAQ;4BAAajB,SAAStC;4BAAOuC,UAAUE;4BAAae,QAAQ1E,mBAAmBkB,OAAOyC;wBAAa;wBAC7G;4BACEc,QAAQ;4BACRjB,SAAS9B;4BACT+B,UAAUG;4BACVc,QAAQ1E,mBAAmB0B,UAAUkC;wBACvC;qBACD;oBACDe,SAAS;oBACTC,OAAO;wBAAC;qBAAqF;gBAC/F;YACF;QACF;IACF;AACF;AAEA,kGAAkG,GAClG,OAAO,SAASC,2BAA2B/D,SAA0B;IACnEZ,2BAA2B0B,sBAAsBd,YAAY;QAAEgE,UAAUtE;IAAU;AACrF"}
package/src/lib/server.js CHANGED
@@ -52,6 +52,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
52
52
  * contact go: the refusals the document holds are kept, which a client
53
53
  * write could not be trusted to do.
54
54
  */ import { registerDealFigureReaders } from "./server/deal-figures.js";
55
+ import { registerPeopleFigureReader } from "./server/people-figures.js";
55
56
  import { CONTACT_ERASED_MESSAGE, contactFacetPath, composeContactName, CRM_COLLECTIONS, CRM_SALUTATION_PICKLIST, crmReadTokens, isContactLifecycleStage, isOrgWideMember, judgeCrmPicklistValue, normalizeAddress, normalizeContactEmail, normalizePhone, readContactFacet, registerPluginApiRoute, visibleToHost } from "@aglyn/aglyn/server";
56
57
  import { consentGroupForSite, firebaseAdmin, getOrgForHost, logHostActivity, memberHasOrgPermission, orgDataCollectionForHost, resolveOrgMembership, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
57
58
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
@@ -604,6 +605,9 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
604
605
  // The pipeline and the deals closed, as figure tables (AGL-3603), for the
605
606
  // AI plugin's insights to read by id; the console runs insight jobs.
606
607
  registerDealFigureReaders(()=>firebaseAdmin.app().firestore());
608
+ // And the leads and contacts gained over a window (AGL-3867), for the
609
+ // weekly summary and for insights.
610
+ registerPeopleFigureReader(()=>firebaseAdmin.app().firestore());
607
611
  /*
608
612
  * The contact-capture writer, again (AGL-3080). Both apps run it at boot
609
613
  * from their generated server-declarations manifest, and this is the
@@ -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. Every CRM file is imported through the\n * transfer framework (AGL-3527, AGL-3528, `transfer/`), whose writes go\n * through the same doors every other server path 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, and the plan is asked here about the fields\n * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a\n * contact go: the refusals the document holds are kept, which a client\n * write could not be trusted to do.\n */\n\nimport { registerDealFigureReaders } from './server/deal-figures'\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n composeContactName,\n CRM_COLLECTIONS,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n judgeCrmPicklistValue,\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 restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { captureHostContact } from './server/capture-host-contact'\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_LIST_FIELDS_ROUTE } from './model/list-fields'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE, CRM_PICKLIST_VALUES_ROUTE } from './model/picklist-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmListFieldsHandler } from './server/list-fields-routes'\nimport { crmLeadSourceValuesHandler, crmPicklistValuesHandler } from './server/picklist-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler } from './server/email-check'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\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 { crmSharingHandler } from './server/crm-sharing'\nimport { CRM_SHARING_ROUTE } from './model/crm-sharing'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler, readContactCreateProfile } from './server/contact-update'\nimport { readCrmPicklist } from './server/read-picklist'\nimport { crmContactRemoveHandler } from './server/contact-remove'\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; email: string | null } | 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 let email: string | null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n email = typeof decoded.email === 'string' ? decoded.email : null\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, email }\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 // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\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(\n hostId,\n 'contactStageChanged',\n {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n },\n { actor: { kind: 'member', uid: caller.uid, email: caller.email } },\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?, disclosedConsentGroup? }`, plus any of Salesforce's\n * standard contact fields `crm/contact-update` reads but the reports-to\n * (`CONTACT_CREATE_PROFILE_FIELDS`, AGL-3515) — read by the same rules, the\n * salutation judged against the org's list, and the holder's name composed\n * from a first and last name when either is given. Answers\n * `{ 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 profile = readContactCreateProfile(body)\n if (profile.ok === false) {\n res.status(400).json({ error: profile.error })\n return\n }\n const extras = profile.fields\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 // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\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 // The salutation, judged against the org's list (AGL-3515).\n let salutation = ''\n if (extras.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n await readCrmPicklist(\n firebaseAdmin.app().firestore(),\n resolved.orgId,\n CRM_SALUTATION_PICKLIST,\n ),\n extras.salutation,\n )\n if (judged.ok === false) {\n res.status(400).json({ error: judged.error })\n return\n }\n salutation = judged.value ?? ''\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 actor: {\n kind: 'member',\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n // Salesforce's standard fields (AGL-3515); the capture composes the\n // holder's name from the first and last names.\n ...Object.fromEntries(\n Object.entries({ ...extras, salutation }).filter(\n ([key, value]) =>\n key !== 'doNotCall' && key !== 'otherAddress' && typeof value === 'string' && value,\n ),\n ),\n ...(extras.otherAddress ? { otherAddress: extras.otherAddress } : {}),\n ...(extras.doNotCall ? { doNotCall: true } : {}),\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 // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contacts.doc(result.contactId), 'contacts')\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 {\n type: 'contact',\n id: result.contactId,\n name: name || composeContactName(extras.firstName, extras.lastName) || email,\n },\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 // The pipeline and the deals closed, as figure tables (AGL-3603), for the\n // AI plugin's insights to read by id; the console runs insight jobs.\n registerDealFigureReaders(() => firebaseAdmin.app().firestore())\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 registerPluginApiRoute(CRM_API_ROUTES.contactRemove, crmContactRemoveHandler)\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 // What a client-direct write the browser cannot follow up asks for: the\n // fields the CRM lists query, restamped from the record (AGL-3321).\n registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler)\n // Sharing records with other sites (AGL-3336): a manager's share and\n // unshare, the org's sharing rules and their recompute, and the rules'\n // re-evaluation a client-direct write owes.\n registerPluginApiRoute(CRM_SHARING_ROUTE, crmSharingHandler)\n // A picklist value renamed or deleted (AGL-3298, AGL-3510): the list and\n // every record holding the old label, in one request. The lead source's\n // own address stays registered for a request that names no picklist.\n registerPluginApiRoute(CRM_PICKLIST_VALUES_ROUTE, crmPicklistValuesHandler)\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\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 // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\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 // What the platform knows about one address before somebody writes to it\n // (AGL-3328): the gateway chip on a record page, and the composer's\n // warning about a domain with no mail server or a gateway holding this\n // site's mail. DNS and the ledger are the server's.\n registerPluginApiRoute(CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler)\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 /*\n * The three doors a MACHINE calls (AGL-3080), at the paths they have\n * always answered on: the scheduler's daily digest and hourly task\n * reminders, on the cron secret, and the mail provider's capture webhook,\n * on its signature. None names a site or a member, so each is registered\n * as a machine's route — the dispatcher leaves the plugin's release and\n * enablement gates and its write limit to it — and each judges the CRM's\n * plan and flag for every organization it resolves. Loaded with the\n * first call, not with the surface.\n */\n registerPluginApiRoute(\n CRM_API_ROUTES.dailyDigest,\n {\n web: async (request) =>\n (await import('./server/daily-digest-route')).crmDailyDigestRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.taskReminders,\n {\n web: async (request) =>\n (await import('./server/task-reminders-route')).crmTaskRemindersRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.inbound,\n {\n web: async (request) => (await import('./server/inbound-route')).crmInboundRoute(request),\n },\n { machine: true },\n )\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 // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { crmPlanEntitlements } from './plan-entitlements'\n"],"names":["registerDealFigureReaders","CONTACT_ERASED_MESSAGE","contactFacetPath","composeContactName","CRM_COLLECTIONS","CRM_SALUTATION_PICKLIST","crmReadTokens","isContactLifecycleStage","isOrgWideMember","judgeCrmPicklistValue","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","emitHostEvent","captureHostContact","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_PICKLIST_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","crmPicklistValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmDealStageHandler","crmEmailSendHandler","CRM_EMAIL_CHECK_ROUTE","crmEmailCheckHandler","leadConvertHandler","leadCreateHandler","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","crmSharingHandler","CRM_SHARING_ROUTE","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","readContactCreateProfile","readCrmPicklist","crmContactRemoveHandler","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","email","decoded","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","actor","kind","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","profile","extras","fields","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","salutation","judged","value","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","Object","fromEntries","entries","filter","key","otherAddress","doNotCall","refused","reason","contacts","arrayUnion","created","type","id","firstName","lastName","registerCrmConsoleApi","ping","contactStage","contactUpdate","contactRemove","companyDelete","save","complete","emailSend","dailyDigest","web","request","crmDailyDigestRoute","machine","taskReminders","crmTaskRemindersRoute","inbound","crmInboundRoute"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,yBAAyB,QAAQ,2BAAuB;AACjE,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,kBAAkB,EAClBC,eAAe,EACfC,uBAAuB,EACvBC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,qBAAqB,EACrBC,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,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,kBAAkB,QAAQ,mCAA+B;AAClE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAA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yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE/B;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;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. Every CRM file is imported through the\n * transfer framework (AGL-3527, AGL-3528, `transfer/`), whose writes go\n * through the same doors every other server path 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, and the plan is asked here about the fields\n * a save carries. `crm/contact-remove` (AGL-3338) is a holder letting a\n * contact go: the refusals the document holds are kept, which a client\n * write could not be trusted to do.\n */\n\nimport { registerDealFigureReaders } from './server/deal-figures'\nimport { registerPeopleFigureReader } from './server/people-figures'\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n composeContactName,\n CRM_COLLECTIONS,\n CRM_SALUTATION_PICKLIST,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n judgeCrmPicklistValue,\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 restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { captureHostContact } from './server/capture-host-contact'\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_LIST_FIELDS_ROUTE } from './model/list-fields'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE, CRM_PICKLIST_VALUES_ROUTE } from './model/picklist-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmListFieldsHandler } from './server/list-fields-routes'\nimport { crmLeadSourceValuesHandler, crmPicklistValuesHandler } from './server/picklist-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler } from './server/email-check'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\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 { crmSharingHandler } from './server/crm-sharing'\nimport { CRM_SHARING_ROUTE } from './model/crm-sharing'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler, readContactCreateProfile } from './server/contact-update'\nimport { readCrmPicklist } from './server/read-picklist'\nimport { crmContactRemoveHandler } from './server/contact-remove'\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; email: string | null } | 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 let email: string | null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n email = typeof decoded.email === 'string' ? decoded.email : null\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, email }\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 // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\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(\n hostId,\n 'contactStageChanged',\n {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n },\n { actor: { kind: 'member', uid: caller.uid, email: caller.email } },\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?, disclosedConsentGroup? }`, plus any of Salesforce's\n * standard contact fields `crm/contact-update` reads but the reports-to\n * (`CONTACT_CREATE_PROFILE_FIELDS`, AGL-3515) — read by the same rules, the\n * salutation judged against the org's list, and the holder's name composed\n * from a first and last name when either is given. Answers\n * `{ 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 profile = readContactCreateProfile(body)\n if (profile.ok === false) {\n res.status(400).json({ error: profile.error })\n return\n }\n const extras = profile.fields\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 // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\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 // The salutation, judged against the org's list (AGL-3515).\n let salutation = ''\n if (extras.salutation) {\n const judged = judgeCrmPicklistValue(\n CRM_SALUTATION_PICKLIST,\n await readCrmPicklist(\n firebaseAdmin.app().firestore(),\n resolved.orgId,\n CRM_SALUTATION_PICKLIST,\n ),\n extras.salutation,\n )\n if (judged.ok === false) {\n res.status(400).json({ error: judged.error })\n return\n }\n salutation = judged.value ?? ''\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 actor: {\n kind: 'member',\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n // Salesforce's standard fields (AGL-3515); the capture composes the\n // holder's name from the first and last names.\n ...Object.fromEntries(\n Object.entries({ ...extras, salutation }).filter(\n ([key, value]) =>\n key !== 'doNotCall' && key !== 'otherAddress' && typeof value === 'string' && value,\n ),\n ),\n ...(extras.otherAddress ? { otherAddress: extras.otherAddress } : {}),\n ...(extras.doNotCall ? { doNotCall: true } : {}),\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 // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contacts.doc(result.contactId), 'contacts')\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 {\n type: 'contact',\n id: result.contactId,\n name: name || composeContactName(extras.firstName, extras.lastName) || email,\n },\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 // The pipeline and the deals closed, as figure tables (AGL-3603), for the\n // AI plugin's insights to read by id; the console runs insight jobs.\n registerDealFigureReaders(() => firebaseAdmin.app().firestore())\n // And the leads and contacts gained over a window (AGL-3867), for the\n // weekly summary and for insights.\n registerPeopleFigureReader(() => firebaseAdmin.app().firestore())\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 registerPluginApiRoute(CRM_API_ROUTES.contactRemove, crmContactRemoveHandler)\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 // What a client-direct write the browser cannot follow up asks for: the\n // fields the CRM lists query, restamped from the record (AGL-3321).\n registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler)\n // Sharing records with other sites (AGL-3336): a manager's share and\n // unshare, the org's sharing rules and their recompute, and the rules'\n // re-evaluation a client-direct write owes.\n registerPluginApiRoute(CRM_SHARING_ROUTE, crmSharingHandler)\n // A picklist value renamed or deleted (AGL-3298, AGL-3510): the list and\n // every record holding the old label, in one request. The lead source's\n // own address stays registered for a request that names no picklist.\n registerPluginApiRoute(CRM_PICKLIST_VALUES_ROUTE, crmPicklistValuesHandler)\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\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 // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\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 // What the platform knows about one address before somebody writes to it\n // (AGL-3328): the gateway chip on a record page, and the composer's\n // warning about a domain with no mail server or a gateway holding this\n // site's mail. DNS and the ledger are the server's.\n registerPluginApiRoute(CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler)\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 /*\n * The three doors a MACHINE calls (AGL-3080), at the paths they have\n * always answered on: the scheduler's daily digest and hourly task\n * reminders, on the cron secret, and the mail provider's capture webhook,\n * on its signature. None names a site or a member, so each is registered\n * as a machine's route — the dispatcher leaves the plugin's release and\n * enablement gates and its write limit to it — and each judges the CRM's\n * plan and flag for every organization it resolves. Loaded with the\n * first call, not with the surface.\n */\n registerPluginApiRoute(\n CRM_API_ROUTES.dailyDigest,\n {\n web: async (request) =>\n (await import('./server/daily-digest-route')).crmDailyDigestRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.taskReminders,\n {\n web: async (request) =>\n (await import('./server/task-reminders-route')).crmTaskRemindersRoute(request),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n CRM_API_ROUTES.inbound,\n {\n web: async (request) => (await import('./server/inbound-route')).crmInboundRoute(request),\n },\n { machine: true },\n )\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 // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { crmPlanEntitlements } from './plan-entitlements'\n"],"names":["registerDealFigureReaders","registerPeopleFigureReader","CONTACT_ERASED_MESSAGE","contactFacetPath","composeContactName","CRM_COLLECTIONS","CRM_SALUTATION_PICKLIST","crmReadTokens","isContactLifecycleStage","isOrgWideMember","judgeCrmPicklistValue","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","emitHostEvent","captureHostContact","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_PICKLIST_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","crmPicklistValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmDealStageHandler","crmEmailSendHandler","CRM_EMAIL_CHECK_ROUTE","crmEmailCheckHandler","leadConvertHandler","leadCreateHandler","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","crmSharingHandler","CRM_SHARING_ROUTE","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","readContactCreateProfile","readCrmPicklist","crmContactRemoveHandler","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","email","decoded","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","actor","kind","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","profile","extras","fields","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","salutation","judged","value","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","Object","fromEntries","entries","filter","key","otherAddress","doNotCall","refused","reason","contacts","arrayUnion","created","type","id","firstName","lastName","registerCrmConsoleApi","ping","contactStage","contactUpdate","contactRemove","companyDelete","save","complete","emailSend","dailyDigest","web","request","crmDailyDigestRoute","machine","taskReminders","crmTaskRemindersRoute","inbound","crmInboundRoute"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,kBAAkB,EAClBC,eAAe,EACfC,uBAAuB,EACvBC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,qBAAqB,EACrBC,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,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,kBAAkB,QAAQ,mCAA+B;AAClE,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,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,4BAA4B,EAAEC,yBAAyB,QAAQ,6BAAyB;AACjG,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,S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