@aglyn/plugins-crm 1.0.0-beta.203 → 1.0.0-beta.205

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.
Files changed (40) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/contact-detail-page.js +7 -0
  3. package/src/lib/components/contact-detail-page.js.map +1 -1
  4. package/src/lib/components/crm-email-check.d.ts +70 -0
  5. package/src/lib/components/crm-email-check.js +135 -0
  6. package/src/lib/components/crm-email-check.js.map +1 -0
  7. package/src/lib/components/crm-send-email-dialog.js +12 -0
  8. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  9. package/src/lib/components/csv-import-drawer.js +5 -1
  10. package/src/lib/components/csv-import-drawer.js.map +1 -1
  11. package/src/lib/components/lead-properties-card.js +7 -1
  12. package/src/lib/components/lead-properties-card.js.map +1 -1
  13. package/src/lib/components/use-crm-api.d.ts +1 -1
  14. package/src/lib/components/use-crm-api.js.map +1 -1
  15. package/src/lib/declarations.server.js +15 -0
  16. package/src/lib/declarations.server.js.map +1 -1
  17. package/src/lib/model/lead-filters.d.ts +1 -1
  18. package/src/lib/server/capture-contact.js +8 -2
  19. package/src/lib/server/capture-contact.js.map +1 -1
  20. package/src/lib/server/contacts-import.js +18 -2
  21. package/src/lib/server/contacts-import.js.map +1 -1
  22. package/src/lib/server/email-check.d.ts +51 -0
  23. package/src/lib/server/email-check.js +193 -0
  24. package/src/lib/server/email-check.js.map +1 -0
  25. package/src/lib/server/email-send.js +8 -0
  26. package/src/lib/server/email-send.js.map +1 -1
  27. package/src/lib/server/import-context.d.ts +2 -0
  28. package/src/lib/server/import-context.js +1 -0
  29. package/src/lib/server/import-context.js.map +1 -1
  30. package/src/lib/server/leads-import.js +16 -2
  31. package/src/lib/server/leads-import.js.map +1 -1
  32. package/src/lib/server/record-email-state.js +21 -4
  33. package/src/lib/server/record-email-state.js.map +1 -1
  34. package/src/lib/server/task-routes.d.ts +2 -0
  35. package/src/lib/server/task-routes.js +9 -0
  36. package/src/lib/server/task-routes.js.map +1 -1
  37. package/src/lib/server-deal-stage.js +18 -2
  38. package/src/lib/server-deal-stage.js.map +1 -1
  39. package/src/lib/server.js +23 -2
  40. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/record-email-state.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n registerPluginRecordEmailStateWriter,\n type PluginRecordEmailStateReport,\n type PluginRecordEmailStateRequest,\n type PluginRecordEmailStateWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport {\n CRM_EMAIL_STATUS_FIELD,\n EMAIL_STATE_FIELD,\n nextEmailState,\n normalizeContactEmail,\n personKey,\n readEmailState,\n type EmailState,\n} from '@aglyn/aglyn/server'\nimport { findContactByEmail, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * THE CRM'S WRITER ON THE CORE'S RECORD EMAIL-STATE SEAM (AGL-3245).\n *\n * A sender filed a verdict on an address — the outreach runtime's bounce,\n * the campaign webhook's complaint, a member's do-not-contact mark, the\n * unsubscribe link — and says so here; this writes it onto every record\n * the address is, as `emailState`, so the record a person reads and the\n * lists a send consults agree.\n *\n * One address can be several records: the contact the organization holds\n * (found through the address index, `findContactByEmail`), and a lead on\n * each site the organization owns — leads are keyed by `personKey`, so a\n * lead is addressed directly under every host. All of them are stamped;\n * the verdict is about the address, not about which record a rep opened.\n * A caller that knows only the site reads the organization off it.\n *\n * The write keeps the STRONGER verdict (`nextEmailState`): a member's\n * do-not-contact mark is not undone by a later bounce, and `ok` lands only\n * when a caller forces it. `updatedAt` is left alone — a verdict is\n * something that happened to the person, not an edit the team made, and a\n * list sorted on recency must not reshuffle on a bounce.\n *\n * Never throws: the list is the control, and a record that could not be\n * stamped is a chip a page goes without, logged.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CrmRecordEmailStateDeps {\n firestore(): Firestore\n}\n\nconst NONE: PluginRecordEmailStateReport = { records: 0 }\n\n/**\n * Applies the verdict to one record; answers whether it moved. A read then\n * a merge rather than a transaction: two verdicts landing together each\n * compare against a state at least as old as their own, and the ranking\n * makes the order of two writes of the same rank immaterial.\n */\nasync function stampRecord(\n ref: FirebaseFirestore.DocumentReference,\n incoming: EmailState,\n force: boolean,\n): Promise<boolean> {\n const snapshot = await ref.get()\n if (!snapshot.exists) return false\n const current = readEmailState(snapshot.data() as Record<string, unknown>)\n const next = nextEmailState(current, incoming, { force })\n // The current verdict stood, or the same verdict arrived again — a second\n // run of the caller — and there is nothing to write.\n if (\n next === current ||\n (current &&\n next.status === current.status &&\n next.atMs === current.atMs &&\n next.source === current.source &&\n next.detail === current.detail)\n ) {\n return false\n }\n // `emailStatus` beside it: the verdict as the CRM lists filter by it\n // (AGL-3321) — a key a query can ask, where the state is a map.\n await ref.set(\n { [EMAIL_STATE_FIELD]: next, [CRM_EMAIL_STATUS_FIELD]: next.status },\n { merge: true },\n )\n return true\n}\n\n/** The organization a request names, or the one its site belongs to. */\nasync function resolveOrgId(firestore: Firestore, request: PluginRecordEmailStateRequest): Promise<string> {\n const named = String(request.orgId ?? '').trim()\n if (named) return named\n const hostId = String(request.hostId ?? '').trim()\n if (!hostId) return ''\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists ? String(host.get('orgId') ?? '') : ''\n}\n\nexport function createCrmRecordEmailStateWriter(deps: CrmRecordEmailStateDeps): PluginRecordEmailStateWriter {\n return {\n async stamp(request) {\n const email = normalizeContactEmail(request.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return NONE\n const firestore = deps.firestore()\n let orgId: string\n try {\n orgId = await resolveOrgId(firestore, request)\n } catch (error) {\n console.error('[crm] the site’s organization could not be read for an email state', request.hostId, error)\n return NONE\n }\n if (!orgId) return NONE\n const state: EmailState = {\n status: request.state.status,\n atMs: Number.isFinite(request.state.atMs) && request.state.atMs > 0 ? request.state.atMs : Date.now(),\n source: request.state.source,\n detail: request.state.detail\n ? String(request.state.detail).replace(/\\s+/g, ' ').trim().slice(0, 500)\n : null,\n ...(request.state.enrollmentId ? { enrollmentId: request.state.enrollmentId } : {}),\n }\n const force = request.force === true\n let records = 0\n try {\n const contacts = firestore.collection('orgs').doc(orgId).collection('contacts')\n const contact = await findContactByEmail(contacts, email)\n if (contact && (await stampRecord(contact.ref, state, force))) records += 1\n } catch (error) {\n console.error('[crm] the contact could not be stamped with an email state', orgId, error)\n }\n try {\n /*\n * ONE ORG ROW. A bounce or a do-not-contact mark is the platform's\n * verdict on the ADDRESS, and since AGL-3277 there is one document\n * carrying it — the per-site loop beside this had nothing left to\n * find once AGL-3276 emptied the host path.\n */\n if (await stampRecord(\n firestore.collection('orgs').doc(orgId).collection('leads').doc(key),\n state,\n force,\n )) {\n records += 1\n }\n } catch (error) {\n console.error('[crm] the leads could not be stamped with an email state', orgId, error)\n }\n return { records }\n },\n }\n}\n\n/** The platform's own dependencies. Specs build their own. */\nexport function defaultCrmRecordEmailStateDeps(): CrmRecordEmailStateDeps {\n return { firestore: () => firebaseAdmin.app().firestore() }\n}\n\n/** Registers the CRM as the workspace's record system on the email-state seam. */\nexport function registerCrmRecordEmailStateWriter(\n deps: CrmRecordEmailStateDeps = defaultCrmRecordEmailStateDeps(),\n): void {\n registerPluginRecordEmailStateWriter(createCrmRecordEmailStateWriter(deps), { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginRecordEmailStateWriter","CRM_EMAIL_STATUS_FIELD","EMAIL_STATE_FIELD","nextEmailState","normalizeContactEmail","personKey","readEmailState","findContactByEmail","firebaseAdmin","BUNDLE_ID","NONE","records","stampRecord","ref","incoming","force","snapshot","get","exists","current","data","next","status","atMs","source","detail","set","merge","resolveOrgId","firestore","request","host","named","String","orgId","trim","hostId","collection","doc","createCrmRecordEmailStateWriter","deps","stamp","email","key","error","console","state","Number","isFinite","Date","now","replace","slice","enrollmentId","contacts","contact","defaultCrmRecordEmailStateDeps","app","registerCrmRecordEmailStateWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oCAAoC,QAI/B,wDAAuD;AAC9D,SACEC,sBAAsB,EACtBC,iBAAiB,EACjBC,cAAc,EACdC,qBAAqB,EACrBC,SAAS,EACTC,cAAc,QAET,sBAAqB;AAC5B,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,2BAA0B;AAC5E,SAASC,SAAS,QAAQ,gCAA4B;AAkCtD,MAAMC,OAAqC;IAAEC,SAAS;AAAE;AAExD;;;;;CAKC,GACD,eAAeC,YACbC,GAAwC,EACxCC,QAAoB,EACpBC,KAAc;IAEd,MAAMC,WAAW,MAAMH,IAAII,GAAG;IAC9B,IAAI,CAACD,SAASE,MAAM,EAAE,OAAO;IAC7B,MAAMC,UAAUb,eAAeU,SAASI,IAAI;IAC5C,MAAMC,OAAOlB,eAAegB,SAASL,UAAU;QAAEC;IAAM;IACvD,0EAA0E;IAC1E,qDAAqD;IACrD,IACEM,SAASF,WACRA,WACCE,KAAKC,MAAM,KAAKH,QAAQG,MAAM,IAC9BD,KAAKE,IAAI,KAAKJ,QAAQI,IAAI,IAC1BF,KAAKG,MAAM,KAAKL,QAAQK,MAAM,IAC9BH,KAAKI,MAAM,KAAKN,QAAQM,MAAM,EAChC;QACA,OAAO;IACT;IACA,qEAAqE;IACrE,gEAAgE;IAChE,MAAMZ,IAAIa,GAAG,CACX;QAAE,CAACxB,kBAAkB,EAAEmB;QAAM,CAACpB,uBAAuB,EAAEoB,KAAKC,MA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":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n registerPluginRecordEmailStateWriter,\n type PluginRecordEmailStateReport,\n type PluginRecordEmailStateRequest,\n type PluginRecordEmailStateWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport {\n CRM_EMAIL_STATUS_FIELD,\n CRM_EMAIL_STATUS_NONE,\n EMAIL_STATE_FIELD,\n nextEmailState,\n normalizeContactEmail,\n personKey,\n readEmailState,\n type EmailState,\n} from '@aglyn/aglyn/server'\nimport { findContactByEmail, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * THE CRM'S WRITER ON THE CORE'S RECORD EMAIL-STATE SEAM (AGL-3245).\n *\n * A sender filed a verdict on an address — the outreach runtime's bounce,\n * the campaign webhook's complaint, a member's do-not-contact mark, the\n * unsubscribe link — and says so here; this writes it onto every record\n * the address is, as `emailState`, so the record a person reads and the\n * lists a send consults agree.\n *\n * One address can be several records: the contact the organization holds\n * (found through the address index, `findContactByEmail`), and a lead on\n * each site the organization owns — leads are keyed by `personKey`, so a\n * lead is addressed directly under every host. All of them are stamped;\n * the verdict is about the address, not about which record a rep opened.\n * A caller that knows only the site reads the organization off it.\n *\n * The write keeps the STRONGER verdict (`nextEmailState`): a member's\n * do-not-contact mark is not undone by a later bounce, and `ok` lands only\n * when a caller forces it. `updatedAt` is left alone — a verdict is\n * something that happened to the person, not an edit the team made, and a\n * list sorted on recency must not reshuffle on a bounce.\n *\n * Never throws: the list is the control, and a record that could not be\n * stamped is a chip a page goes without, logged.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CrmRecordEmailStateDeps {\n firestore(): Firestore\n}\n\nconst NONE: PluginRecordEmailStateReport = { records: 0 }\n\n/**\n * Applies the verdict to one record; answers whether it moved. A read then\n * a merge rather than a transaction: two verdicts landing together each\n * compare against a state at least as old as their own, and the ranking\n * makes the order of two writes of the same rank immaterial.\n */\nasync function stampRecord(\n ref: FirebaseFirestore.DocumentReference,\n incoming: EmailState,\n force: boolean,\n withdraw = false,\n): Promise<boolean> {\n const snapshot = await ref.get()\n if (!snapshot.exists) return false\n const current = readEmailState(snapshot.data() as Record<string, unknown>)\n /*\n * A WITHDRAWAL takes back the one verdict it names (AGL-3328): the\n * deliverability check's \"Would bounce\" once the domain takes mail again.\n * Any other standing verdict — a bounce DNS cannot see — is left alone.\n */\n if (withdraw) {\n if (current?.status !== incoming.status) return false\n await ref.update({\n [EMAIL_STATE_FIELD]: FieldValue.delete(),\n [CRM_EMAIL_STATUS_FIELD]: CRM_EMAIL_STATUS_NONE,\n })\n return true\n }\n // The deliverability check saying again what the record already holds:\n // the date it was first found is the one worth keeping.\n if (incoming.source === 'check' && current?.status === incoming.status) return false\n const next = nextEmailState(current, incoming, { force })\n // The current verdict stood, or the same verdict arrived again — a second\n // run of the caller — and there is nothing to write.\n if (\n next === current ||\n (current &&\n next.status === current.status &&\n next.atMs === current.atMs &&\n next.source === current.source &&\n next.detail === current.detail)\n ) {\n return false\n }\n // `emailStatus` beside it: the verdict as the CRM lists filter by it\n // (AGL-3321) — a key a query can ask, where the state is a map.\n await ref.set(\n { [EMAIL_STATE_FIELD]: next, [CRM_EMAIL_STATUS_FIELD]: next.status },\n { merge: true },\n )\n return true\n}\n\n/** The organization a request names, or the one its site belongs to. */\nasync function resolveOrgId(firestore: Firestore, request: PluginRecordEmailStateRequest): Promise<string> {\n const named = String(request.orgId ?? '').trim()\n if (named) return named\n const hostId = String(request.hostId ?? '').trim()\n if (!hostId) return ''\n const host = await firestore.collection('hosts').doc(hostId).get()\n return host.exists ? String(host.get('orgId') ?? '') : ''\n}\n\nexport function createCrmRecordEmailStateWriter(deps: CrmRecordEmailStateDeps): PluginRecordEmailStateWriter {\n return {\n async stamp(request) {\n const email = normalizeContactEmail(request.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return NONE\n const firestore = deps.firestore()\n let orgId: string\n try {\n orgId = await resolveOrgId(firestore, request)\n } catch (error) {\n console.error('[crm] the site’s organization could not be read for an email state', request.hostId, error)\n return NONE\n }\n if (!orgId) return NONE\n const state: EmailState = {\n status: request.state.status,\n atMs: Number.isFinite(request.state.atMs) && request.state.atMs > 0 ? request.state.atMs : Date.now(),\n source: request.state.source,\n detail: request.state.detail\n ? String(request.state.detail).replace(/\\s+/g, ' ').trim().slice(0, 500)\n : null,\n ...(request.state.enrollmentId ? { enrollmentId: request.state.enrollmentId } : {}),\n }\n const force = request.force === true\n const withdraw = request.withdraw === true\n let records = 0\n try {\n const contacts = firestore.collection('orgs').doc(orgId).collection('contacts')\n const contact = await findContactByEmail(contacts, email)\n if (contact && (await stampRecord(contact.ref, state, force, withdraw))) records += 1\n } catch (error) {\n console.error('[crm] the contact could not be stamped with an email state', orgId, error)\n }\n try {\n /*\n * ONE ORG ROW. A bounce or a do-not-contact mark is the platform's\n * verdict on the ADDRESS, and since AGL-3277 there is one document\n * carrying it — the per-site loop beside this had nothing left to\n * find once AGL-3276 emptied the host path.\n */\n if (await stampRecord(\n firestore.collection('orgs').doc(orgId).collection('leads').doc(key),\n state,\n force,\n withdraw,\n )) {\n records += 1\n }\n } catch (error) {\n console.error('[crm] the leads could not be stamped with an email state', orgId, error)\n }\n return { records }\n },\n }\n}\n\n/** The platform's own dependencies. Specs build their own. */\nexport function defaultCrmRecordEmailStateDeps(): CrmRecordEmailStateDeps {\n return { firestore: () => firebaseAdmin.app().firestore() }\n}\n\n/** Registers the CRM as the workspace's record system on the email-state seam. */\nexport function registerCrmRecordEmailStateWriter(\n deps: CrmRecordEmailStateDeps = defaultCrmRecordEmailStateDeps(),\n): void {\n registerPluginRecordEmailStateWriter(createCrmRecordEmailStateWriter(deps), { pluginId: BUNDLE_ID })\n}\n"],"names":["registerPluginRecordEmailStateWriter","CRM_EMAIL_STATUS_FIELD","CRM_EMAIL_STATUS_NONE","EMAIL_STATE_FIELD","nextEmailState","normalizeContactEmail","personKey","readEmailState","findContactByEmail","firebaseAdmin","FieldValue","BUNDLE_ID","NONE","records","stampRecord","ref","incoming","force","withdraw","snapshot","get","exists","current","data","status","update","delete","source","next","atMs","detail","set","merge","resolveOrgId","firestore","request","host","named","String","orgId","trim","hostId","collection","doc","createCrmRecordEmailStateWriter","deps","stamp","email","key","error","console","state","Number","isFinite","Date","now","replace","slice","enrollmentId","contacts","contact","defaultCrmRecordEmailStateDeps","app","registerCrmRecordEmailStateWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oCAAoC,QAI/B,wDAAuD;AAC9D,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,qBAAqB,EACrBC,SAAS,EACTC,cAAc,QAET,sBAAqB;AAC5B,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,2BAA0B;AAC5E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AAkCtD,MAAMC,OAAqC;IAAEC,SAAS;AAAE;AAExD;;;;;CAKC,GACD,eAAeC,YACbC,GAAwC,EACxCC,QAAoB,EACpBC,KAAc,EACdC,WAAW,KAAK;IAEhB,MAAMC,WAAW,MAAMJ,IAAIK,GAAG;IAC9B,IAAI,CAACD,SAASE,MAAM,EAAE,OAAO;IAC7B,MAAMC,UAAUf,eAAeY,SAASI,IAAI;IAC5C;;;;GAIC,GACD,IAAIL,UAAU;QACZ,IAAII,CAAAA,2BAAAA,QAASE,MAAM,MAAKR,SAASQ,MAAM,EAAE,OAAO;QAChD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MAAM9C,YAAY8C,QAAQ7C,GAAG,EAAEoC,OAAOlC,OAAOC,WAAYL,WAAW;YACtF,EAAE,OAAOoC,OAAO;gBACdC,QAAQD,KAAK,CAAC,8DAA8DV,OAAOU;YACrF;YACA,IAAI;gBACF;;;;;SAKC,GACD,IAAI,MAAMnC,YACRoB,UAAUQ,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAAC,SAASC,GAAG,CAACK,MAChEG,OACAlC,OACAC,WACC;oBACDL,WAAW;gBACb;YACF,EAAE,OAAOoC,OAAO;gBACdC,QAAQD,KAAK,CAAC,4DAA4DV,OAAOU;YACnF;YACA,OAAO;gBAAEpC;YAAQ;QACnB;IACF;AACF;AAEA,4DAA4D,GAC5D,OAAO,SAASgD;IACd,OAAO;QAAE3B,WAAW,IAAMzB,cAAcqD,GAAG,GAAG5B,SAAS;IAAG;AAC5D;AAEA,gFAAgF,GAChF,OAAO,SAAS6B,kCACdlB,OAAgCgB,gCAAgC;IAEhE7D,qCAAqC4C,gCAAgCC,OAAO;QAAEmB,UAAUrD;IAAU;AACpG"}
@@ -70,6 +70,8 @@ export type Refusal = {
70
70
  export interface Writer {
71
71
  ok: true;
72
72
  uid: string;
73
+ /** The caller's address, for who set off the runs a write causes (AGL-3376). */
74
+ email: string | null;
73
75
  staff: boolean;
74
76
  orgId: string;
75
77
  org: Record<string, unknown>;
@@ -44,6 +44,7 @@ const ORG_REFUSAL = 'Editing tasks at the organization level requires the "Manag
44
44
  var _req_headers_authorization, _ref;
45
45
  const suiteAct = options.suiteAct === undefined ? TASKS_ACT : options.suiteAct;
46
46
  if (scope.level === 'org') {
47
+ var _caller_email;
47
48
  const caller = await authorizeOrgCaller(req, scope.orgId, {
48
49
  needs: 'data.manage',
49
50
  refusal: ORG_REFUSAL
@@ -59,6 +60,7 @@ const ORG_REFUSAL = 'Editing tasks at the organization level requires the "Manag
59
60
  return {
60
61
  ok: true,
61
62
  uid: caller.uid,
63
+ email: (_caller_email = caller.email) != null ? _caller_email : null,
62
64
  staff: caller.staff,
63
65
  orgId: caller.orgId,
64
66
  org: caller.org,
@@ -104,6 +106,7 @@ const ORG_REFUSAL = 'Editing tasks at the organization level requires the "Manag
104
106
  return {
105
107
  ok: true,
106
108
  uid: decoded.uid,
109
+ email: typeof decoded.email === 'string' ? decoded.email : null,
107
110
  staff,
108
111
  orgId,
109
112
  org: org != null ? org : {},
@@ -589,6 +592,12 @@ const tasksCollection = (orgId)=>firebaseAdmin.app().firestore().collection('org
589
592
  companyId: String((_task_companyId = task.companyId) != null ? _task_companyId : ''),
590
593
  dealId: String((_task_dealId = task.dealId) != null ? _task_dealId : ''),
591
594
  taskHostId: String((_task_hostId1 = task.hostId) != null ? _task_hostId1 : '')
595
+ }, {
596
+ actor: {
597
+ kind: 'member',
598
+ uid: writer.uid,
599
+ email: writer.email
600
+ }
592
601
  });
593
602
  }
594
603
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/task-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynOrgMember,\n consentGroupForHost,\n CRM_COLLECTIONS,\n type CrmTask,\n crmScopeTokens,\n crmTaskListFields,\n crmTaskReminderAfterEdit,\n crmTaskReminderPending,\n isOrgWideMember,\n memberCanSee,\n type PluginApiHandler,\n type PluginApiRequest,\n type PluginApiResponse,\n} from '@aglyn/aglyn/server'\nimport {\n crmNextActivityLinksOf,\n firebaseAdmin,\n getOrgForHost,\n memberHasOrgPermission,\n notifyUsers,\n recomputeCrmNextTaskAt,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CRM_TASK_BATCH_MAX,\n type CrmTaskCompleteOutcome,\n type CrmTaskCompleteResponse,\n type CrmTaskFields,\n type CrmTaskSaveOutcome,\n type CrmTaskSaveResponse,\n type CrmTasksCompleteResponse,\n type CrmTasksSaveResponse,\n readCrmTaskFields,\n} from '../model/task-routes'\nimport { CRM_ORG_TASK_SCOPE } from '../model/task-scope'\nimport {\n authorizeOrgCaller,\n type CrmRouteScope,\n readCrmRouteScope,\n} from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/**\n * The two things a task does that a browser must not do alone (AGL-2599).\n *\n * Every other task write is client-direct against the Firestore rules —\n * reopening, deleting, the list's own reads. These two are routes because\n * each has a side effect that lives outside the document:\n *\n * - SAVING a task assigned to somebody else NOTIFIES them, and a\n * notification is an Admin-SDK write into another person's inbox. Rather\n * than a client-direct write followed by a \"please notify\" call — two\n * operations that can disagree about whether the task exists — the route\n * persists the task itself and notifies from the same code path, so a\n * notification can never announce a task that failed to save. It also\n * stamps the scope, the provenance and the timestamps, which is one\n * creator computing `visibleTo` rather than two.\n *\n * - COMPLETING a task EMITS the `taskCompleted` host event, which is what a\n * workflow triggers on. A browser cannot run the workflow runner.\n *\n * Both authenticate the way the other console plugin routes do — the ID\n * token in the `Authorization` header — and then ask the same two questions\n * the rules ask of a `crmTasks` write: is this member allowed to write org\n * data (`owner`/`admin`/`editor`, and `data.manage` resolved through their\n * custom role), and can they reach THIS document's scope.\n *\n * ## The organization variant (AGL-2637)\n *\n * `{ orgId, … }` instead of a site: the org-level hub. The caller is\n * authorized by the ORG — an org-wide member holding `data.manage`, the\n * hub's own gate, never a site collaborator — and reaches every task the\n * org holds, so no scope check is made against the document. A NEW task\n * names the site it is filed from beside the org, or names none and is the\n * organization's own: `hostId: null`, the org scope token alone. Completing\n * emits on the task's OWN site, where its automations live; an\n * organization task has none and emits nothing, as an uncaptured deal's\n * stage change emits nothing.\n *\n * The org variant also takes a BATCH — `taskIds` to complete, `tasks` to\n * save — so the org hub's bulk bar makes one request per action rather\n * than one per task. Each task is answered on its own in `results`; the\n * request as a whole is refused only for what refuses every task alike.\n */\n\nexport type Refusal = {\n ok: false\n status: number\n body: { error: string; reason?: string; code?: string }\n}\n\n/** What the suite gate names when a task route refuses a plan without it. */\nconst TASKS_ACT = \"Working a record's tasks\"\n\nexport interface Writer {\n ok: true\n uid: string\n staff: boolean\n orgId: string\n org: Record<string, unknown>\n /** The member document under a site; `null` at the org level, where the reach is the org's. */\n member: Partial<AglynOrgMember> | null\n level: CrmRouteScope['level']\n}\n\nexport const refuse = (status: number, error: string): Refusal => ({\n ok: false,\n status,\n body: { error },\n})\n\nconst ORG_REFUSAL =\n 'Editing tasks at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.'\n\nexport interface CrmWriterOptions {\n /**\n * The act a plan without the CRM is refused for, named the way\n * `crmSuiteRefusalMessage` takes it. `null` for a route that asks the plan\n * itself, once it knows what the request writes, so the refusal can name\n * that act — a contact update names the first field it carries. Tasks\n * when unsaid.\n */\n suiteAct?: string | null\n}\n\n/**\n * Who is asking, and whether they may write this CRM at all.\n *\n * Under a site: the org resolved from the site and the rules' own role and\n * permission questions. At the organization level: the org the body names,\n * for an org-wide member with the permission. The scope question — may they\n * reach THIS task — is asked by the caller against the document, because on\n * a create the document does not exist yet and its scope is what the route\n * is about to stamp.\n */\nexport async function authorizeCrmWriter(\n req: PluginApiRequest,\n scope: CrmRouteScope,\n options: CrmWriterOptions = {},\n): Promise<Writer | Refusal> {\n const suiteAct = options.suiteAct === undefined ? TASKS_ACT : options.suiteAct\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: ORG_REFUSAL,\n })\n if (caller.ok === false) return refuse(caller.status, caller.error)\n // The plan after the person (AGL-2787): see `suite-gate.ts`.\n const suite = suiteAct ? crmSuiteRefusal(caller.org, suiteAct) : null\n if (suite) return { ok: false, status: suite.status, body: suite.body }\n return {\n ok: true,\n uid: caller.uid,\n staff: caller.staff,\n orgId: caller.orgId,\n org: caller.org as Record<string, unknown>,\n member: null,\n level: 'org',\n }\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return refuse(401, 'Unauthenticated')\n\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const staff = decoded['staff'] === true\n const resolved = await getOrgForHost(scope.hostId).catch(() => null)\n if (!resolved) {\n return refuse(404, 'This site has no organization, so it has no CRM.')\n }\n const { orgId, org } = resolved\n const membership = await resolveOrgMembership(decoded.uid, orgId).catch(\n () => null,\n )\n const member = (membership?.member ?? null) as Partial<AglynOrgMember> | null\n if (!staff) {\n const role = String(member?.role ?? '')\n /*\n * The rules' `canWriteOrgData()` restated: the role list is what an\n * unstamped permission map falls through to, and the permission is the\n * only half a custom role's revocation can reach. A route that checked\n * one and not the other would open a door the rules keep shut.\n */\n const writerRole = role === 'owner' || role === 'admin' || role === 'editor'\n const suspended =\n (member as { orgSuspended?: boolean } | null)?.orgSuspended === true\n if (!member || !writerRole || suspended) {\n return refuse(403, 'Your organization role does not allow editing the CRM.')\n }\n if (!(await memberHasOrgPermission(orgId, member, 'data.manage'))) {\n return refuse(\n 403,\n 'Your organization role does not allow editing the CRM.',\n )\n }\n }\n const suite = suiteAct ? crmSuiteRefusal(org, suiteAct) : null\n if (suite) return { ok: false, status: suite.status, body: suite.body }\n return {\n ok: true,\n uid: decoded.uid,\n staff,\n orgId,\n org: (org ?? {}) as Record<string, unknown>,\n member,\n level: 'site',\n }\n}\n\n/**\n * The rules' `canReadScoped()`, for a document the route has in hand. An\n * org-level writer was admitted as org-wide, and an org-wide member reads\n * every row.\n */\nexport const canReach = (writer: Writer, visibleTo: unknown): boolean =>\n writer.staff ||\n writer.level === 'org' ||\n isOrgWideMember(writer.member) ||\n memberCanSee(writer.member, visibleTo as string[] | undefined)\n\n/**\n * The records the task names carry `nextTaskAtMs` (AGL-2661), recomputed\n * after every write here. Its own catch: the task IS saved by now, and a\n * denormalized figure that could not move is logged and left for the\n * Fields section's recompute, not reported as a task that failed to save.\n */\nasync function settleNextActivity(\n orgId: string,\n links: readonly (Partial<CrmTaskFields> | Record<string, unknown> | null | undefined)[],\n): Promise<void> {\n try {\n await recomputeCrmNextTaskAt(\n firebaseAdmin.app().firestore(),\n orgId,\n links.map((link) => crmNextActivityLinksOf(link as Record<string, unknown>)),\n )\n } catch (error) {\n console.error('[crm] next activity could not be recomputed', orgId, error)\n }\n}\n\n/**\n * The console path the assignee's notification opens: the record the task\n * is for, in the hub, or the tasks list when it is for nobody in particular.\n *\n * In the `/{hostDocId}/rest` shape every host notification uses — the\n * console rewrites it to `/{orgSlug}/hosts/{subdomain}/rest` when the link\n * is followed, which is why `hostId` and `orgId` travel on the document. An\n * organization task has no site to open under, so its link is the `/org`\n * shape the console rewrites onto the organization's own hub.\n */\nfunction assignmentLink(hostId: string | null, fields: CrmTaskFields): string {\n const base = hostId ? `/${hostId}/crm` : '/org/crm'\n if (fields.contactId) return `${base}/contacts/${encodeURIComponent(fields.contactId)}`\n if (fields.dealId) return `${base}/deals/${encodeURIComponent(fields.dealId)}`\n if (fields.companyId) return `${base}/companies/${encodeURIComponent(fields.companyId)}`\n return `${base}/tasks`\n}\n\n/**\n * The editable fields as a Firestore write.\n *\n * The optional ids and the assignee are ABSENT on the document when unset,\n * never `null` — the record cards query `where('contactId', '==', id)` and\n * the \"My tasks\" view `where('assigneeUid', '==', uid)`, and neither is\n * helped by a null. So a create leaves an unset optional out, and an update\n * DELETES it: an assignee cleared in the drawer has to come off the\n * document, and an update that merely omitted the key would keep them.\n * `dueAtMs` is the one field written as `null` when unset, because every\n * view orders by it and a document missing the field drops out of an\n * `orderBy` entirely.\n */\nfunction storedFields(\n fields: CrmTaskFields,\n mode: 'create' | 'update',\n): Record<string, unknown> {\n const absent = mode === 'update' ? FieldValue.delete() : undefined\n const optional = (value: string | null) =>\n value ? { present: true, value } : { present: mode === 'update', value: absent }\n const out: Record<string, unknown> = {\n title: fields.title,\n kind: fields.kind,\n priority: fields.priority,\n dueAtMs: fields.dueAtMs,\n notes: fields.notes,\n }\n for (const [key, value] of [\n ['assigneeUid', fields.assigneeUid],\n ['contactId', fields.contactId],\n ['companyId', fields.companyId],\n ['dealId', fields.dealId],\n ] as const) {\n const slot = optional(value)\n if (slot.present) out[key] = slot.value\n }\n return out\n}\n\n/**\n * The reminder a save leaves (AGL-2659), as a Firestore write.\n *\n * `crmTaskReminderAfterEdit` decides which reminder the task ends up with;\n * this turns the decision into fields. Written as `null` when unset, like\n * `dueAtMs`, so the document says the reminder was decided. A reminder that\n * MOVED — to a new time, or to none — is a reminder not yet sent, so the\n * runner's mark comes off with it; one that stayed keeps its mark, which is\n * what stops a title correction from re-sending last week's reminder.\n */\nfunction reminderFields(\n fields: CrmTaskFields,\n existing: FirebaseFirestore.DocumentSnapshot | null,\n): Record<string, unknown> {\n const previous = existing\n ? {\n dueAtMs: (existing.get('dueAtMs') as number | null | undefined) ?? null,\n remindAtMs: (existing.get('remindAtMs') as number | null | undefined) ?? null,\n }\n : null\n const remindAtMs = crmTaskReminderAfterEdit({\n dueAtMs: fields.dueAtMs,\n remindAtMs: fields.remindAtMs,\n previous,\n })\n const out: Record<string, unknown> = { remindAtMs }\n if (previous && remindAtMs !== previous.remindAtMs) {\n out['reminderSentAtMs'] = FieldValue.delete()\n }\n return out\n}\n\nconst tasksCollection = (orgId: string) =>\n firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(CRM_COLLECTIONS.tasks)\n\ntype TasksCollection = ReturnType<typeof tasksCollection>\n\n/**\n * Whether a uid names a member of the org, answered once per uid across a\n * batch: a bar reassigning forty tasks to one person asks the roster once.\n */\nfunction rosterOf(orgId: string) {\n const known = new Map<string, Promise<boolean>>()\n return (uid: string): Promise<boolean> => {\n let answer = known.get(uid)\n if (!answer) {\n answer = resolveOrgMembership(uid, orgId)\n .then((found) => Boolean(found?.member))\n .catch(() => false)\n known.set(uid, answer)\n }\n return answer\n }\n}\n\n/** Tell the assignee, when they are somebody new and somebody else. */\nasync function notifyAssignee(\n writer: Writer,\n fields: CrmTaskFields,\n previousAssignee: string | null,\n hostId: string | null,\n): Promise<boolean> {\n const assignee = fields.assigneeUid\n const notified = Boolean(\n assignee && assignee !== writer.uid && assignee !== previousAssignee,\n )\n if (!notified || !assignee) return false\n const due =\n typeof fields.dueAtMs === 'number'\n ? ` · due ${new Date(fields.dueAtMs).toLocaleString()}`\n : ''\n await notifyUsers([assignee], {\n type: 'content.taskAssigned',\n title: 'Task assigned to you',\n body: `${fields.title}${due}`,\n link: assignmentLink(hostId, fields),\n orgId: writer.orgId,\n ...(hostId ? { hostId } : {}),\n })\n return true\n}\n\n/**\n * Rewrite one existing task's editable fields, and tell a new assignee.\n *\n * `visibleTo` is not touched: the rules let only an org-wide member move a\n * record's scope, and this route is not the place that does it. `hostId`\n * and `createdByUid` are provenance and never rewritten. The notification\n * opens under the site the caller is on, or — at the organization level —\n * under the task's own site, and under the org hub for a task with none.\n */\nasync function updateTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n taskId: string,\n fields: CrmTaskFields,\n onRoster: (uid: string) => Promise<boolean>,\n): Promise<{ ok: true; notified: boolean } | Refusal> {\n if (fields.assigneeUid && !(await onRoster(fields.assigneeUid))) {\n return refuse(400, 'The assignee is not a member of this organization.')\n }\n const existing = await tasks.doc(taskId).get()\n if (!existing.exists) return refuse(404, 'That task no longer exists.')\n if (!canReach(writer, existing.get('visibleTo'))) {\n return refuse(403, 'That task is not visible to you.')\n }\n const previousAssignee = String(existing.get('assigneeUid') ?? '') || null\n const previousLinks = crmNextActivityLinksOf(existing.data() as Record<string, unknown>)\n const stored = storedFields(fields, 'update')\n await tasks.doc(taskId).update({\n ...stored,\n ...reminderFields(fields, existing),\n // The title is what the Tasks list searches (AGL-3321).\n ...crmTaskListFields({ ...existing.data(), ...stored }),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // Both sides: a task moved off one deal onto another leaves neither stale.\n await settleNextActivity(writer.orgId, [previousLinks, fields])\n const linkHostId =\n scope.level === 'site'\n ? scope.hostId\n : String(existing.get('hostId') ?? '').trim() || null\n const notified = await notifyAssignee(writer, fields, previousAssignee, linkHostId)\n return { ok: true, notified }\n}\n\n/**\n * Where a NEW task is filed from: the mounted site, or at the organization\n * level the site the body names — which has to be one of THIS org's, or an\n * org-wide member of one org could stamp a task with another org's site\n * token — or no site at all, the organization's own.\n */\nasync function resolveFiledFrom(\n writer: Writer,\n scope: CrmRouteScope,\n): Promise<{ ok: true; hostId: string | null } | Refusal> {\n if (scope.level === 'site') return { ok: true, hostId: scope.hostId }\n if (!scope.hostId) return { ok: true, hostId: null }\n const owner = await getOrgForHost(scope.hostId).catch(() => null)\n if (!owner || owner.orgId !== writer.orgId) {\n return refuse(400, 'That site is not one of this organization’s.')\n }\n return { ok: true, hostId: scope.hostId }\n}\n\n/**\n * Create one task, stamped with its scope and provenance.\n *\n * The scope every CRM creator stamps for a task filed from a site: the\n * whole org when the org has chosen that, and otherwise the sites this\n * site presents as one sender with — which, undeclared, is this site\n * alone. A scoped member creating a record they could not then see is\n * refused, which is the rules' `canCreateScoped()` said before the write\n * instead of after. An organization task — no site — carries\n * `CRM_ORG_TASK_SCOPE` and `hostId: null`.\n */\nasync function createTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n fields: CrmTaskFields,\n onRoster: (uid: string) => Promise<boolean>,\n): Promise<{ ok: true; taskId: string; notified: boolean } | Refusal> {\n if (fields.assigneeUid && !(await onRoster(fields.assigneeUid))) {\n return refuse(400, 'The assignee is not a member of this organization.')\n }\n const filed = await resolveFiledFrom(writer, scope)\n if (filed.ok === false) return filed\n const { hostId } = filed\n const visibleTo = hostId\n ? crmScopeTokens(writer.org, consentGroupForHost(writer.org, hostId))\n : [...CRM_ORG_TASK_SCOPE]\n if (!canReach(writer, visibleTo)) {\n return refuse(403, 'Your access to this organization does not reach this site.')\n }\n const ref = tasks.doc()\n await ref.set({\n ...storedFields(fields, 'create'),\n ...reminderFields(fields, null),\n // What the Tasks list searches (AGL-3321).\n ...crmTaskListFields({ ...storedFields(fields, 'create'), visibleTo }),\n status: 'open',\n completedAtMs: null,\n visibleTo,\n hostId,\n createdByUid: writer.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await settleNextActivity(writer.orgId, [fields])\n const notified = await notifyAssignee(writer, fields, null, hostId)\n return { ok: true, taskId: ref.id, notified }\n}\n\n/**\n * `POST crm/task-save` — create or update a task, and tell its assignee.\n *\n * Body: `{ hostId, taskId?, task: CrmTaskFields }` under a site;\n * `{ orgId, hostId?, taskId?, task }` at the organization level; or the\n * org-level batch `{ orgId, tasks: [{ taskId, task }] }`. Answers\n * `{ ok, taskId, notified }`, or `{ ok, results }` for the batch.\n *\n * The NOTIFICATION fires when the saved assignee is somebody other than the\n * person saving AND is not who the task was already assigned to. Assigning\n * a task to yourself is a note to self; re-saving a task's title does not\n * re-announce it to the person who already has it. The assignee must be a\n * member of the org — a uid nobody can find in the roster is refused rather\n * than written, because a notification to a stranger's inbox is the one\n * thing this route must never do.\n */\nexport const crmTaskSaveHandler: 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 scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n if (Array.isArray(req.body?.tasks)) {\n await saveBatch(req, res, scope)\n return\n }\n const taskId = String(req.body?.taskId ?? '').trim()\n const read = readCrmTaskFields(req.body?.task)\n if (read.ok === false) {\n res.status(400).json({ error: read.error })\n return\n }\n const fields = read.fields\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const onRoster = rosterOf(writer.orgId)\n let body: CrmTaskSaveResponse\n if (taskId) {\n const saved = await updateTask(writer, scope, tasks, taskId, fields, onRoster)\n if (saved.ok === false) {\n res.status(saved.status).json(saved.body)\n return\n }\n body = { ok: true, taskId, notified: saved.notified }\n } else {\n const saved = await createTask(writer, scope, tasks, fields, onRoster)\n if (saved.ok === false) {\n res.status(saved.status).json(saved.body)\n return\n }\n body = { ok: true, taskId: saved.taskId, notified: saved.notified }\n }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-save failed', error)\n res.status(500).json({ error: 'The task could not be saved.' })\n }\n}\n\n/**\n * The batch: every entry read before any is written, so a body with one\n * unreadable entry is refused whole rather than half-applied; then each\n * task in order, each answered on its own.\n */\nasync function saveBatch(\n req: PluginApiRequest,\n res: PluginApiResponse,\n scope: CrmRouteScope,\n): Promise<void> {\n if (scope.level !== 'org') {\n res.status(400).json({\n error: 'A batch of tasks is saved at the organization level only.',\n })\n return\n }\n const entries = (req.body?.tasks as unknown[]).slice(0, CRM_TASK_BATCH_MAX + 1)\n if (!entries.length || entries.length > CRM_TASK_BATCH_MAX) {\n res.status(400).json({\n error: `Save between 1 and ${CRM_TASK_BATCH_MAX} tasks at a time.`,\n })\n return\n }\n const parsed: Array<{ taskId: string; fields: CrmTaskFields }> = []\n for (const entry of entries) {\n const raw = (entry ?? {}) as Record<string, unknown>\n const taskId = String(raw['taskId'] ?? '').trim()\n const read = readCrmTaskFields(raw['task'])\n if (!taskId || read.ok === false) {\n res.status(400).json({\n error: read.ok === false ? read.error : 'Every task in a batch names its taskId.',\n })\n return\n }\n parsed.push({ taskId, fields: read.fields })\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const onRoster = rosterOf(writer.orgId)\n const results: CrmTaskSaveOutcome[] = []\n for (const { taskId, fields } of parsed) {\n const saved = await updateTask(writer, scope, tasks, taskId, fields, onRoster)\n results.push(\n saved.ok === false\n ? { taskId, ok: false, error: saved.body.error }\n : { taskId, ok: true, notified: saved.notified },\n )\n }\n const body: CrmTasksSaveResponse = { ok: true, results }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-save batch failed', error)\n res.status(500).json({ error: 'The tasks could not be saved.' })\n }\n}\n\n/**\n * Mark one task done and fire `taskCompleted` on the site whose automations\n * hear it: under a site, the site whose console ticked the box — workflows\n * belong to a site, and the person is on that site's console. At the\n * organization level there is no such console, so the event goes to the\n * task's OWN site, and an organization task, having none, fires nothing.\n * The task's own `hostId` rides in the payload as `taskHostId` either way,\n * for a workflow that cares about the difference.\n *\n * Idempotent on purpose: two people ticking the same box, or one person\n * double-clicking, completes a task once and fires its event once. The\n * second call reads the stored `completedAtMs` back and writes nothing.\n */\nasync function completeTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n taskId: string,\n): Promise<CrmTaskCompleteOutcome> {\n const ref = tasks.doc(taskId)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { taskId, ok: false, error: 'That task no longer exists.' }\n }\n const task = snapshot.data() as Partial<CrmTask>\n if (!canReach(writer, task.visibleTo)) {\n return { taskId, ok: false, error: 'That task is not visible to you.' }\n }\n if (task.status === 'done') {\n return {\n taskId,\n ok: true,\n completedAtMs: Number(task.completedAtMs ?? 0),\n alreadyDone: true,\n }\n }\n\n const completedAtMs = Date.now()\n await ref.update({\n status: 'done',\n completedAtMs,\n completedByUid: writer.uid,\n // A reminder still owed on a task that is done is owed to nobody\n // (AGL-2659); one already sent stays, as a fact about what happened.\n ...(crmTaskReminderPending(task) ? { remindAtMs: null } : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await settleNextActivity(writer.orgId, [task as Record<string, unknown>])\n\n const eventHostId =\n scope.level === 'site' ? scope.hostId : String(task.hostId ?? '').trim()\n if (eventHostId) {\n /*\n * The payload is what a workflow filter can read: every field a string,\n * number or boolean, and every optional one present as an empty string\n * rather than absent, so `contactId != \"\"` is a filter somebody can\n * write without knowing whether the key exists.\n */\n await emitHostEvent(eventHostId, 'taskCompleted', {\n taskId,\n title: String(task.title ?? ''),\n kind: String(task.kind ?? ''),\n priority: String(task.priority ?? ''),\n dueAtMs: typeof task.dueAtMs === 'number' ? task.dueAtMs : 0,\n completedAtMs,\n completedByUid: writer.uid,\n assigneeUid: String(task.assigneeUid ?? ''),\n createdByUid: String(task.createdByUid ?? ''),\n contactId: String(task.contactId ?? ''),\n companyId: String(task.companyId ?? ''),\n dealId: String(task.dealId ?? ''),\n taskHostId: String(task.hostId ?? ''),\n })\n }\n return { taskId, ok: true, completedAtMs }\n}\n\n/** A per-task outcome as the single-task route has always answered. */\nconst completeStatus = (outcome: Extract<CrmTaskCompleteOutcome, { ok: false }>) =>\n outcome.error === 'That task no longer exists.' ? 404 : 403\n\n/**\n * `POST crm/task-complete` — mark a task done and fire `taskCompleted`.\n *\n * Body: `{ hostId, taskId }` under a site, `{ orgId, taskId }` at the\n * organization level, or the org-level batch `{ orgId, taskIds }`. Answers\n * `{ ok, completedAtMs, alreadyDone? }`, or `{ ok, results }` for the batch.\n */\nexport const crmTaskCompleteHandler: 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 scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (Array.isArray(req.body?.taskIds)) {\n await completeBatch(req, res, scope)\n return\n }\n const taskId = String(req.body?.taskId ?? '').trim()\n if (!scope || !taskId) {\n res.status(400).json({ error: 'Missing hostId or taskId' })\n return\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const outcome = await completeTask(writer, scope, tasksCollection(writer.orgId), taskId)\n if (outcome.ok === false) {\n res.status(completeStatus(outcome)).json({ error: outcome.error })\n return\n }\n const body: CrmTaskCompleteResponse = {\n ok: true,\n completedAtMs: outcome.completedAtMs,\n ...(outcome.alreadyDone ? { alreadyDone: true } : {}),\n }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-complete failed', error)\n res.status(500).json({ error: 'The task could not be completed.' })\n }\n}\n\n/**\n * The batch: the ids deduplicated and capped, then each task in order —\n * in order rather than at once, because each completion may run a site's\n * workflows, and two hundred runners started together is the burst the\n * per-task client call was written to avoid.\n */\nasync function completeBatch(\n req: PluginApiRequest,\n res: PluginApiResponse,\n scope: CrmRouteScope | null,\n): Promise<void> {\n if (!scope || scope.level !== 'org') {\n res.status(400).json({\n error: 'A batch of tasks is completed at the organization level only.',\n })\n return\n }\n const taskIds = [\n ...new Set(\n (req.body?.taskIds as unknown[]).map((id) => String(id ?? '').trim()).filter(Boolean),\n ),\n ]\n if (!taskIds.length || taskIds.length > CRM_TASK_BATCH_MAX) {\n res.status(400).json({\n error: `Complete between 1 and ${CRM_TASK_BATCH_MAX} tasks at a time.`,\n })\n return\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const results: CrmTaskCompleteOutcome[] = []\n for (const taskId of taskIds) {\n results.push(await completeTask(writer, scope, tasks, taskId))\n }\n const body: CrmTasksCompleteResponse = { ok: true, results }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-complete batch failed', error)\n res.status(500).json({ error: 'The tasks could not be completed.' })\n }\n}\n"],"names":["consentGroupForHost","CRM_COLLECTIONS","crmScopeTokens","crmTaskListFields","crmTaskReminderAfterEdit","crmTaskReminderPending","isOrgWideMember","memberCanSee","crmNextActivityLinksOf","firebaseAdmin","getOrgForHost","memberHasOrgPermission","notifyUsers","recomputeCrmNextTaskAt","resolveOrgMembership","emitHostEvent","FieldValue","CRM_TASK_BATCH_MAX","readCrmTaskFields","CRM_ORG_TASK_SCOPE","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","TASKS_ACT","refuse","status","error","ok","body","ORG_REFUSAL","authorizeCrmWriter","req","scope","options","suiteAct","undefined","level","caller","orgId","needs","refusal","suite","org","uid","staff","member","authorization","String","headers","idToken","startsWith","slice","length","decoded","app","auth","verifyIdToken","resolved","hostId","catch","membership","role","writerRole","suspended","orgSuspended","canReach","writer","visibleTo","settleNextActivity","links","firestore","map","link","console","assignmentLink","fields","base","contactId","encodeURIComponent","dealId","companyId","storedFields","mode","absent","delete","optional","value","present","out","title","kind","priority","dueAtMs","notes","key","assigneeUid","slot","reminderFields","existing","previous","get","remindAtMs","tasksCollection","collection","doc","tasks","rosterOf","known","Map","answer","then","found","Boolean","set","notifyAssignee","previousAssignee","assignee","notified","due","Date","toLocaleString","type","updateTask","taskId","onRoster","exists","previousLinks","data","stored","update","updatedAt","serverTimestamp","linkHostId","trim","resolveFiledFrom","owner","createTask","filed","ref","completedAtMs","createdByUid","createdAt","id","crmTaskSaveHandler","res","method","setHeader","json","Array","isArray","saveBatch","read","task","saved","entries","parsed","entry","raw","push","results","completeTask","snapshot","Number","alreadyDone","now","completedByUid","eventHostId","taskHostId","completeStatus","outcome","crmTaskCompleteHandler","taskIds","completeBatch","Set","filter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,mBAAmB,EACnBC,eAAe,EAEfC,cAAc,EACdC,iBAAiB,EACjBC,wBAAwB,EACxBC,sBAAsB,EACtBC,eAAe,EACfC,YAAY,QAIP,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,WAAW,EACXC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,kBAAkB,EAQlBC,iBAAiB,QACZ,0BAAsB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,QAAQvH,MAAM,IAAIuH,QAAQvH,MAAM,GAAGnC,oBAAoB;QAC1D+H,IAAIvH,MAAM,CAAC,KAAK0H,IAAI,CAAC;YACnBzH,OAAO,CAAC,uBAAuB,EAAET,mBAAmB,iBAAiB,CAAC;QACxE;QACA;IACF;IAEA,IAAI;QACF,MAAMiD,SAAS,MAAMpC,mBAAmBC,KAAKC;QAC7C,IAAIkC,OAAOvC,EAAE,KAAK,OAAO;YACvBqH,IAAIvH,MAAM,CAACyC,OAAOzC,MAAM,EAAE0H,IAAI,CAACjF,OAAOtC,IAAI;YAC1C;QACF;QACA,MAAM6E,QAAQH,gBAAgBpC,OAAO5B,KAAK;QAC1C,MAAMyH,UAAoC,EAAE;QAC5C,KAAK,MAAMpC,UAAUgD,QAAS;YAC5BZ,QAAQD,IAAI,CAAC,MAAME,aAAa9F,QAAQlC,OAAOyE,OAAOkB;QACxD;QACA,MAAM/F,OAAiC;YAAED,IAAI;YAAMoI;QAAQ;QAC3Df,IAAIvH,MAAM,CAAC,KAAK0H,IAAI,CAACvH;IACvB,EAAE,OAAOF,OAAO;QACd+C,QAAQ/C,KAAK,CAAC,oCAAoCA;QAClDsH,IAAIvH,MAAM,CAAC,KAAK0H,IAAI,CAAC;YAAEzH,OAAO;QAAoC;IACpE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/task-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AglynOrgMember,\n consentGroupForHost,\n CRM_COLLECTIONS,\n type CrmTask,\n crmScopeTokens,\n crmTaskListFields,\n crmTaskReminderAfterEdit,\n crmTaskReminderPending,\n isOrgWideMember,\n memberCanSee,\n type PluginApiHandler,\n type PluginApiRequest,\n type PluginApiResponse,\n} from '@aglyn/aglyn/server'\nimport {\n crmNextActivityLinksOf,\n firebaseAdmin,\n getOrgForHost,\n memberHasOrgPermission,\n notifyUsers,\n recomputeCrmNextTaskAt,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n CRM_TASK_BATCH_MAX,\n type CrmTaskCompleteOutcome,\n type CrmTaskCompleteResponse,\n type CrmTaskFields,\n type CrmTaskSaveOutcome,\n type CrmTaskSaveResponse,\n type CrmTasksCompleteResponse,\n type CrmTasksSaveResponse,\n readCrmTaskFields,\n} from '../model/task-routes'\nimport { CRM_ORG_TASK_SCOPE } from '../model/task-scope'\nimport {\n authorizeOrgCaller,\n type CrmRouteScope,\n readCrmRouteScope,\n} from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/**\n * The two things a task does that a browser must not do alone (AGL-2599).\n *\n * Every other task write is client-direct against the Firestore rules —\n * reopening, deleting, the list's own reads. These two are routes because\n * each has a side effect that lives outside the document:\n *\n * - SAVING a task assigned to somebody else NOTIFIES them, and a\n * notification is an Admin-SDK write into another person's inbox. Rather\n * than a client-direct write followed by a \"please notify\" call — two\n * operations that can disagree about whether the task exists — the route\n * persists the task itself and notifies from the same code path, so a\n * notification can never announce a task that failed to save. It also\n * stamps the scope, the provenance and the timestamps, which is one\n * creator computing `visibleTo` rather than two.\n *\n * - COMPLETING a task EMITS the `taskCompleted` host event, which is what a\n * workflow triggers on. A browser cannot run the workflow runner.\n *\n * Both authenticate the way the other console plugin routes do — the ID\n * token in the `Authorization` header — and then ask the same two questions\n * the rules ask of a `crmTasks` write: is this member allowed to write org\n * data (`owner`/`admin`/`editor`, and `data.manage` resolved through their\n * custom role), and can they reach THIS document's scope.\n *\n * ## The organization variant (AGL-2637)\n *\n * `{ orgId, … }` instead of a site: the org-level hub. The caller is\n * authorized by the ORG — an org-wide member holding `data.manage`, the\n * hub's own gate, never a site collaborator — and reaches every task the\n * org holds, so no scope check is made against the document. A NEW task\n * names the site it is filed from beside the org, or names none and is the\n * organization's own: `hostId: null`, the org scope token alone. Completing\n * emits on the task's OWN site, where its automations live; an\n * organization task has none and emits nothing, as an uncaptured deal's\n * stage change emits nothing.\n *\n * The org variant also takes a BATCH — `taskIds` to complete, `tasks` to\n * save — so the org hub's bulk bar makes one request per action rather\n * than one per task. Each task is answered on its own in `results`; the\n * request as a whole is refused only for what refuses every task alike.\n */\n\nexport type Refusal = {\n ok: false\n status: number\n body: { error: string; reason?: string; code?: string }\n}\n\n/** What the suite gate names when a task route refuses a plan without it. */\nconst TASKS_ACT = \"Working a record's tasks\"\n\nexport interface Writer {\n ok: true\n uid: string\n /** The caller's address, for who set off the runs a write causes (AGL-3376). */\n email: string | null\n staff: boolean\n orgId: string\n org: Record<string, unknown>\n /** The member document under a site; `null` at the org level, where the reach is the org's. */\n member: Partial<AglynOrgMember> | null\n level: CrmRouteScope['level']\n}\n\nexport const refuse = (status: number, error: string): Refusal => ({\n ok: false,\n status,\n body: { error },\n})\n\nconst ORG_REFUSAL =\n 'Editing tasks at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.'\n\nexport interface CrmWriterOptions {\n /**\n * The act a plan without the CRM is refused for, named the way\n * `crmSuiteRefusalMessage` takes it. `null` for a route that asks the plan\n * itself, once it knows what the request writes, so the refusal can name\n * that act — a contact update names the first field it carries. Tasks\n * when unsaid.\n */\n suiteAct?: string | null\n}\n\n/**\n * Who is asking, and whether they may write this CRM at all.\n *\n * Under a site: the org resolved from the site and the rules' own role and\n * permission questions. At the organization level: the org the body names,\n * for an org-wide member with the permission. The scope question — may they\n * reach THIS task — is asked by the caller against the document, because on\n * a create the document does not exist yet and its scope is what the route\n * is about to stamp.\n */\nexport async function authorizeCrmWriter(\n req: PluginApiRequest,\n scope: CrmRouteScope,\n options: CrmWriterOptions = {},\n): Promise<Writer | Refusal> {\n const suiteAct = options.suiteAct === undefined ? TASKS_ACT : options.suiteAct\n if (scope.level === 'org') {\n const caller = await authorizeOrgCaller(req, scope.orgId, {\n needs: 'data.manage',\n refusal: ORG_REFUSAL,\n })\n if (caller.ok === false) return refuse(caller.status, caller.error)\n // The plan after the person (AGL-2787): see `suite-gate.ts`.\n const suite = suiteAct ? crmSuiteRefusal(caller.org, suiteAct) : null\n if (suite) return { ok: false, status: suite.status, body: suite.body }\n return {\n ok: true,\n uid: caller.uid,\n email: caller.email ?? null,\n staff: caller.staff,\n orgId: caller.orgId,\n org: caller.org as Record<string, unknown>,\n member: null,\n level: 'org',\n }\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return refuse(401, 'Unauthenticated')\n\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const staff = decoded['staff'] === true\n const resolved = await getOrgForHost(scope.hostId).catch(() => null)\n if (!resolved) {\n return refuse(404, 'This site has no organization, so it has no CRM.')\n }\n const { orgId, org } = resolved\n const membership = await resolveOrgMembership(decoded.uid, orgId).catch(\n () => null,\n )\n const member = (membership?.member ?? null) as Partial<AglynOrgMember> | null\n if (!staff) {\n const role = String(member?.role ?? '')\n /*\n * The rules' `canWriteOrgData()` restated: the role list is what an\n * unstamped permission map falls through to, and the permission is the\n * only half a custom role's revocation can reach. A route that checked\n * one and not the other would open a door the rules keep shut.\n */\n const writerRole = role === 'owner' || role === 'admin' || role === 'editor'\n const suspended =\n (member as { orgSuspended?: boolean } | null)?.orgSuspended === true\n if (!member || !writerRole || suspended) {\n return refuse(403, 'Your organization role does not allow editing the CRM.')\n }\n if (!(await memberHasOrgPermission(orgId, member, 'data.manage'))) {\n return refuse(\n 403,\n 'Your organization role does not allow editing the CRM.',\n )\n }\n }\n const suite = suiteAct ? crmSuiteRefusal(org, suiteAct) : null\n if (suite) return { ok: false, status: suite.status, body: suite.body }\n return {\n ok: true,\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n staff,\n orgId,\n org: (org ?? {}) as Record<string, unknown>,\n member,\n level: 'site',\n }\n}\n\n/**\n * The rules' `canReadScoped()`, for a document the route has in hand. An\n * org-level writer was admitted as org-wide, and an org-wide member reads\n * every row.\n */\nexport const canReach = (writer: Writer, visibleTo: unknown): boolean =>\n writer.staff ||\n writer.level === 'org' ||\n isOrgWideMember(writer.member) ||\n memberCanSee(writer.member, visibleTo as string[] | undefined)\n\n/**\n * The records the task names carry `nextTaskAtMs` (AGL-2661), recomputed\n * after every write here. Its own catch: the task IS saved by now, and a\n * denormalized figure that could not move is logged and left for the\n * Fields section's recompute, not reported as a task that failed to save.\n */\nasync function settleNextActivity(\n orgId: string,\n links: readonly (Partial<CrmTaskFields> | Record<string, unknown> | null | undefined)[],\n): Promise<void> {\n try {\n await recomputeCrmNextTaskAt(\n firebaseAdmin.app().firestore(),\n orgId,\n links.map((link) => crmNextActivityLinksOf(link as Record<string, unknown>)),\n )\n } catch (error) {\n console.error('[crm] next activity could not be recomputed', orgId, error)\n }\n}\n\n/**\n * The console path the assignee's notification opens: the record the task\n * is for, in the hub, or the tasks list when it is for nobody in particular.\n *\n * In the `/{hostDocId}/rest` shape every host notification uses — the\n * console rewrites it to `/{orgSlug}/hosts/{subdomain}/rest` when the link\n * is followed, which is why `hostId` and `orgId` travel on the document. An\n * organization task has no site to open under, so its link is the `/org`\n * shape the console rewrites onto the organization's own hub.\n */\nfunction assignmentLink(hostId: string | null, fields: CrmTaskFields): string {\n const base = hostId ? `/${hostId}/crm` : '/org/crm'\n if (fields.contactId) return `${base}/contacts/${encodeURIComponent(fields.contactId)}`\n if (fields.dealId) return `${base}/deals/${encodeURIComponent(fields.dealId)}`\n if (fields.companyId) return `${base}/companies/${encodeURIComponent(fields.companyId)}`\n return `${base}/tasks`\n}\n\n/**\n * The editable fields as a Firestore write.\n *\n * The optional ids and the assignee are ABSENT on the document when unset,\n * never `null` — the record cards query `where('contactId', '==', id)` and\n * the \"My tasks\" view `where('assigneeUid', '==', uid)`, and neither is\n * helped by a null. So a create leaves an unset optional out, and an update\n * DELETES it: an assignee cleared in the drawer has to come off the\n * document, and an update that merely omitted the key would keep them.\n * `dueAtMs` is the one field written as `null` when unset, because every\n * view orders by it and a document missing the field drops out of an\n * `orderBy` entirely.\n */\nfunction storedFields(\n fields: CrmTaskFields,\n mode: 'create' | 'update',\n): Record<string, unknown> {\n const absent = mode === 'update' ? FieldValue.delete() : undefined\n const optional = (value: string | null) =>\n value ? { present: true, value } : { present: mode === 'update', value: absent }\n const out: Record<string, unknown> = {\n title: fields.title,\n kind: fields.kind,\n priority: fields.priority,\n dueAtMs: fields.dueAtMs,\n notes: fields.notes,\n }\n for (const [key, value] of [\n ['assigneeUid', fields.assigneeUid],\n ['contactId', fields.contactId],\n ['companyId', fields.companyId],\n ['dealId', fields.dealId],\n ] as const) {\n const slot = optional(value)\n if (slot.present) out[key] = slot.value\n }\n return out\n}\n\n/**\n * The reminder a save leaves (AGL-2659), as a Firestore write.\n *\n * `crmTaskReminderAfterEdit` decides which reminder the task ends up with;\n * this turns the decision into fields. Written as `null` when unset, like\n * `dueAtMs`, so the document says the reminder was decided. A reminder that\n * MOVED — to a new time, or to none — is a reminder not yet sent, so the\n * runner's mark comes off with it; one that stayed keeps its mark, which is\n * what stops a title correction from re-sending last week's reminder.\n */\nfunction reminderFields(\n fields: CrmTaskFields,\n existing: FirebaseFirestore.DocumentSnapshot | null,\n): Record<string, unknown> {\n const previous = existing\n ? {\n dueAtMs: (existing.get('dueAtMs') as number | null | undefined) ?? null,\n remindAtMs: (existing.get('remindAtMs') as number | null | undefined) ?? null,\n }\n : null\n const remindAtMs = crmTaskReminderAfterEdit({\n dueAtMs: fields.dueAtMs,\n remindAtMs: fields.remindAtMs,\n previous,\n })\n const out: Record<string, unknown> = { remindAtMs }\n if (previous && remindAtMs !== previous.remindAtMs) {\n out['reminderSentAtMs'] = FieldValue.delete()\n }\n return out\n}\n\nconst tasksCollection = (orgId: string) =>\n firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(CRM_COLLECTIONS.tasks)\n\ntype TasksCollection = ReturnType<typeof tasksCollection>\n\n/**\n * Whether a uid names a member of the org, answered once per uid across a\n * batch: a bar reassigning forty tasks to one person asks the roster once.\n */\nfunction rosterOf(orgId: string) {\n const known = new Map<string, Promise<boolean>>()\n return (uid: string): Promise<boolean> => {\n let answer = known.get(uid)\n if (!answer) {\n answer = resolveOrgMembership(uid, orgId)\n .then((found) => Boolean(found?.member))\n .catch(() => false)\n known.set(uid, answer)\n }\n return answer\n }\n}\n\n/** Tell the assignee, when they are somebody new and somebody else. */\nasync function notifyAssignee(\n writer: Writer,\n fields: CrmTaskFields,\n previousAssignee: string | null,\n hostId: string | null,\n): Promise<boolean> {\n const assignee = fields.assigneeUid\n const notified = Boolean(\n assignee && assignee !== writer.uid && assignee !== previousAssignee,\n )\n if (!notified || !assignee) return false\n const due =\n typeof fields.dueAtMs === 'number'\n ? ` · due ${new Date(fields.dueAtMs).toLocaleString()}`\n : ''\n await notifyUsers([assignee], {\n type: 'content.taskAssigned',\n title: 'Task assigned to you',\n body: `${fields.title}${due}`,\n link: assignmentLink(hostId, fields),\n orgId: writer.orgId,\n ...(hostId ? { hostId } : {}),\n })\n return true\n}\n\n/**\n * Rewrite one existing task's editable fields, and tell a new assignee.\n *\n * `visibleTo` is not touched: the rules let only an org-wide member move a\n * record's scope, and this route is not the place that does it. `hostId`\n * and `createdByUid` are provenance and never rewritten. The notification\n * opens under the site the caller is on, or — at the organization level —\n * under the task's own site, and under the org hub for a task with none.\n */\nasync function updateTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n taskId: string,\n fields: CrmTaskFields,\n onRoster: (uid: string) => Promise<boolean>,\n): Promise<{ ok: true; notified: boolean } | Refusal> {\n if (fields.assigneeUid && !(await onRoster(fields.assigneeUid))) {\n return refuse(400, 'The assignee is not a member of this organization.')\n }\n const existing = await tasks.doc(taskId).get()\n if (!existing.exists) return refuse(404, 'That task no longer exists.')\n if (!canReach(writer, existing.get('visibleTo'))) {\n return refuse(403, 'That task is not visible to you.')\n }\n const previousAssignee = String(existing.get('assigneeUid') ?? '') || null\n const previousLinks = crmNextActivityLinksOf(existing.data() as Record<string, unknown>)\n const stored = storedFields(fields, 'update')\n await tasks.doc(taskId).update({\n ...stored,\n ...reminderFields(fields, existing),\n // The title is what the Tasks list searches (AGL-3321).\n ...crmTaskListFields({ ...existing.data(), ...stored }),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // Both sides: a task moved off one deal onto another leaves neither stale.\n await settleNextActivity(writer.orgId, [previousLinks, fields])\n const linkHostId =\n scope.level === 'site'\n ? scope.hostId\n : String(existing.get('hostId') ?? '').trim() || null\n const notified = await notifyAssignee(writer, fields, previousAssignee, linkHostId)\n return { ok: true, notified }\n}\n\n/**\n * Where a NEW task is filed from: the mounted site, or at the organization\n * level the site the body names — which has to be one of THIS org's, or an\n * org-wide member of one org could stamp a task with another org's site\n * token — or no site at all, the organization's own.\n */\nasync function resolveFiledFrom(\n writer: Writer,\n scope: CrmRouteScope,\n): Promise<{ ok: true; hostId: string | null } | Refusal> {\n if (scope.level === 'site') return { ok: true, hostId: scope.hostId }\n if (!scope.hostId) return { ok: true, hostId: null }\n const owner = await getOrgForHost(scope.hostId).catch(() => null)\n if (!owner || owner.orgId !== writer.orgId) {\n return refuse(400, 'That site is not one of this organization’s.')\n }\n return { ok: true, hostId: scope.hostId }\n}\n\n/**\n * Create one task, stamped with its scope and provenance.\n *\n * The scope every CRM creator stamps for a task filed from a site: the\n * whole org when the org has chosen that, and otherwise the sites this\n * site presents as one sender with — which, undeclared, is this site\n * alone. A scoped member creating a record they could not then see is\n * refused, which is the rules' `canCreateScoped()` said before the write\n * instead of after. An organization task — no site — carries\n * `CRM_ORG_TASK_SCOPE` and `hostId: null`.\n */\nasync function createTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n fields: CrmTaskFields,\n onRoster: (uid: string) => Promise<boolean>,\n): Promise<{ ok: true; taskId: string; notified: boolean } | Refusal> {\n if (fields.assigneeUid && !(await onRoster(fields.assigneeUid))) {\n return refuse(400, 'The assignee is not a member of this organization.')\n }\n const filed = await resolveFiledFrom(writer, scope)\n if (filed.ok === false) return filed\n const { hostId } = filed\n const visibleTo = hostId\n ? crmScopeTokens(writer.org, consentGroupForHost(writer.org, hostId))\n : [...CRM_ORG_TASK_SCOPE]\n if (!canReach(writer, visibleTo)) {\n return refuse(403, 'Your access to this organization does not reach this site.')\n }\n const ref = tasks.doc()\n await ref.set({\n ...storedFields(fields, 'create'),\n ...reminderFields(fields, null),\n // What the Tasks list searches (AGL-3321).\n ...crmTaskListFields({ ...storedFields(fields, 'create'), visibleTo }),\n status: 'open',\n completedAtMs: null,\n visibleTo,\n hostId,\n createdByUid: writer.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await settleNextActivity(writer.orgId, [fields])\n const notified = await notifyAssignee(writer, fields, null, hostId)\n return { ok: true, taskId: ref.id, notified }\n}\n\n/**\n * `POST crm/task-save` — create or update a task, and tell its assignee.\n *\n * Body: `{ hostId, taskId?, task: CrmTaskFields }` under a site;\n * `{ orgId, hostId?, taskId?, task }` at the organization level; or the\n * org-level batch `{ orgId, tasks: [{ taskId, task }] }`. Answers\n * `{ ok, taskId, notified }`, or `{ ok, results }` for the batch.\n *\n * The NOTIFICATION fires when the saved assignee is somebody other than the\n * person saving AND is not who the task was already assigned to. Assigning\n * a task to yourself is a note to self; re-saving a task's title does not\n * re-announce it to the person who already has it. The assignee must be a\n * member of the org — a uid nobody can find in the roster is refused rather\n * than written, because a notification to a stranger's inbox is the one\n * thing this route must never do.\n */\nexport const crmTaskSaveHandler: 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 scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n if (Array.isArray(req.body?.tasks)) {\n await saveBatch(req, res, scope)\n return\n }\n const taskId = String(req.body?.taskId ?? '').trim()\n const read = readCrmTaskFields(req.body?.task)\n if (read.ok === false) {\n res.status(400).json({ error: read.error })\n return\n }\n const fields = read.fields\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const onRoster = rosterOf(writer.orgId)\n let body: CrmTaskSaveResponse\n if (taskId) {\n const saved = await updateTask(writer, scope, tasks, taskId, fields, onRoster)\n if (saved.ok === false) {\n res.status(saved.status).json(saved.body)\n return\n }\n body = { ok: true, taskId, notified: saved.notified }\n } else {\n const saved = await createTask(writer, scope, tasks, fields, onRoster)\n if (saved.ok === false) {\n res.status(saved.status).json(saved.body)\n return\n }\n body = { ok: true, taskId: saved.taskId, notified: saved.notified }\n }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-save failed', error)\n res.status(500).json({ error: 'The task could not be saved.' })\n }\n}\n\n/**\n * The batch: every entry read before any is written, so a body with one\n * unreadable entry is refused whole rather than half-applied; then each\n * task in order, each answered on its own.\n */\nasync function saveBatch(\n req: PluginApiRequest,\n res: PluginApiResponse,\n scope: CrmRouteScope,\n): Promise<void> {\n if (scope.level !== 'org') {\n res.status(400).json({\n error: 'A batch of tasks is saved at the organization level only.',\n })\n return\n }\n const entries = (req.body?.tasks as unknown[]).slice(0, CRM_TASK_BATCH_MAX + 1)\n if (!entries.length || entries.length > CRM_TASK_BATCH_MAX) {\n res.status(400).json({\n error: `Save between 1 and ${CRM_TASK_BATCH_MAX} tasks at a time.`,\n })\n return\n }\n const parsed: Array<{ taskId: string; fields: CrmTaskFields }> = []\n for (const entry of entries) {\n const raw = (entry ?? {}) as Record<string, unknown>\n const taskId = String(raw['taskId'] ?? '').trim()\n const read = readCrmTaskFields(raw['task'])\n if (!taskId || read.ok === false) {\n res.status(400).json({\n error: read.ok === false ? read.error : 'Every task in a batch names its taskId.',\n })\n return\n }\n parsed.push({ taskId, fields: read.fields })\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const onRoster = rosterOf(writer.orgId)\n const results: CrmTaskSaveOutcome[] = []\n for (const { taskId, fields } of parsed) {\n const saved = await updateTask(writer, scope, tasks, taskId, fields, onRoster)\n results.push(\n saved.ok === false\n ? { taskId, ok: false, error: saved.body.error }\n : { taskId, ok: true, notified: saved.notified },\n )\n }\n const body: CrmTasksSaveResponse = { ok: true, results }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-save batch failed', error)\n res.status(500).json({ error: 'The tasks could not be saved.' })\n }\n}\n\n/**\n * Mark one task done and fire `taskCompleted` on the site whose automations\n * hear it: under a site, the site whose console ticked the box — workflows\n * belong to a site, and the person is on that site's console. At the\n * organization level there is no such console, so the event goes to the\n * task's OWN site, and an organization task, having none, fires nothing.\n * The task's own `hostId` rides in the payload as `taskHostId` either way,\n * for a workflow that cares about the difference.\n *\n * Idempotent on purpose: two people ticking the same box, or one person\n * double-clicking, completes a task once and fires its event once. The\n * second call reads the stored `completedAtMs` back and writes nothing.\n */\nasync function completeTask(\n writer: Writer,\n scope: CrmRouteScope,\n tasks: TasksCollection,\n taskId: string,\n): Promise<CrmTaskCompleteOutcome> {\n const ref = tasks.doc(taskId)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { taskId, ok: false, error: 'That task no longer exists.' }\n }\n const task = snapshot.data() as Partial<CrmTask>\n if (!canReach(writer, task.visibleTo)) {\n return { taskId, ok: false, error: 'That task is not visible to you.' }\n }\n if (task.status === 'done') {\n return {\n taskId,\n ok: true,\n completedAtMs: Number(task.completedAtMs ?? 0),\n alreadyDone: true,\n }\n }\n\n const completedAtMs = Date.now()\n await ref.update({\n status: 'done',\n completedAtMs,\n completedByUid: writer.uid,\n // A reminder still owed on a task that is done is owed to nobody\n // (AGL-2659); one already sent stays, as a fact about what happened.\n ...(crmTaskReminderPending(task) ? { remindAtMs: null } : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await settleNextActivity(writer.orgId, [task as Record<string, unknown>])\n\n const eventHostId =\n scope.level === 'site' ? scope.hostId : String(task.hostId ?? '').trim()\n if (eventHostId) {\n /*\n * The payload is what a workflow filter can read: every field a string,\n * number or boolean, and every optional one present as an empty string\n * rather than absent, so `contactId != \"\"` is a filter somebody can\n * write without knowing whether the key exists.\n */\n await emitHostEvent(\n eventHostId,\n 'taskCompleted',\n {\n taskId,\n title: String(task.title ?? ''),\n kind: String(task.kind ?? ''),\n priority: String(task.priority ?? ''),\n dueAtMs: typeof task.dueAtMs === 'number' ? task.dueAtMs : 0,\n completedAtMs,\n completedByUid: writer.uid,\n assigneeUid: String(task.assigneeUid ?? ''),\n createdByUid: String(task.createdByUid ?? ''),\n contactId: String(task.contactId ?? ''),\n companyId: String(task.companyId ?? ''),\n dealId: String(task.dealId ?? ''),\n taskHostId: String(task.hostId ?? ''),\n },\n { actor: { kind: 'member', uid: writer.uid, email: writer.email } },\n )\n }\n return { taskId, ok: true, completedAtMs }\n}\n\n/** A per-task outcome as the single-task route has always answered. */\nconst completeStatus = (outcome: Extract<CrmTaskCompleteOutcome, { ok: false }>) =>\n outcome.error === 'That task no longer exists.' ? 404 : 403\n\n/**\n * `POST crm/task-complete` — mark a task done and fire `taskCompleted`.\n *\n * Body: `{ hostId, taskId }` under a site, `{ orgId, taskId }` at the\n * organization level, or the org-level batch `{ orgId, taskIds }`. Answers\n * `{ ok, completedAtMs, alreadyDone? }`, or `{ ok, results }` for the batch.\n */\nexport const crmTaskCompleteHandler: 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 scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (Array.isArray(req.body?.taskIds)) {\n await completeBatch(req, res, scope)\n return\n }\n const taskId = String(req.body?.taskId ?? '').trim()\n if (!scope || !taskId) {\n res.status(400).json({ error: 'Missing hostId or taskId' })\n return\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const outcome = await completeTask(writer, scope, tasksCollection(writer.orgId), taskId)\n if (outcome.ok === false) {\n res.status(completeStatus(outcome)).json({ error: outcome.error })\n return\n }\n const body: CrmTaskCompleteResponse = {\n ok: true,\n completedAtMs: outcome.completedAtMs,\n ...(outcome.alreadyDone ? { alreadyDone: true } : {}),\n }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-complete failed', error)\n res.status(500).json({ error: 'The task could not be completed.' })\n }\n}\n\n/**\n * The batch: the ids deduplicated and capped, then each task in order —\n * in order rather than at once, because each completion may run a site's\n * workflows, and two hundred runners started together is the burst the\n * per-task client call was written to avoid.\n */\nasync function completeBatch(\n req: PluginApiRequest,\n res: PluginApiResponse,\n scope: CrmRouteScope | null,\n): Promise<void> {\n if (!scope || scope.level !== 'org') {\n res.status(400).json({\n error: 'A batch of tasks is completed at the organization level only.',\n })\n return\n }\n const taskIds = [\n ...new Set(\n (req.body?.taskIds as unknown[]).map((id) => String(id ?? '').trim()).filter(Boolean),\n ),\n ]\n if (!taskIds.length || taskIds.length > CRM_TASK_BATCH_MAX) {\n res.status(400).json({\n error: `Complete between 1 and ${CRM_TASK_BATCH_MAX} tasks at a time.`,\n })\n return\n }\n\n try {\n const writer = await authorizeCrmWriter(req, scope)\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const tasks = tasksCollection(writer.orgId)\n const results: CrmTaskCompleteOutcome[] = []\n for (const taskId of taskIds) {\n results.push(await completeTask(writer, scope, tasks, taskId))\n }\n const body: CrmTasksCompleteResponse = { ok: true, results }\n res.status(200).json(body)\n } catch (error) {\n console.error('[crm] task-complete batch failed', error)\n res.status(500).json({ error: 'The tasks could not be completed.' })\n }\n}\n"],"names":["consentGroupForHost","CRM_COLLECTIONS","crmScopeTokens","crmTaskListFields","crmTaskReminderAfterEdit","crmTaskReminderPending","isOrgWideMember","memberCanSee","crmNextActivityLinksOf","firebaseAdmin","getOrgForHost","memberHasOrgPermission","notifyUsers","recomputeCrmNextTaskAt","resolveOrgMembership","emitHostEvent","FieldValue","CRM_TASK_BATCH_MAX","readCrmTaskFields","CRM_ORG_TASK_SCOPE","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","TASKS_ACT","refuse","status","error","ok","body","ORG_REFUSAL","authorizeCrmWriter","req","scope","options","suiteAct","undefined","level","caller","orgId","needs","refusal","suite","org","uid","email","staff","member","authorization","String","headers","idToken","startsWith","slice","length","decoded","app","auth","verifyIdToken","resolved","hostId","catch","membership","role","writerRole","suspended","orgSuspended","canReach","writer","visibleTo","settleNextActivity","links","firestore","map","link","console","assignmentLink","fields","base","contactId","encodeURIComponent","dealId","companyId","storedFields","mode","absent","delete","optional","value","present","out","title","kind","priority","dueAtMs","notes","key","assigneeUid","slot","reminderFields","existing","previous","get","remindAtMs","tasksCollection","collection","doc","tasks","rosterOf","known","Map","answer","then","found","Boolean","set","notifyAssignee","previousAssignee","assignee","notified","due","Date","toLocaleString","type","updateTask","taskId","onRoster","exists","previousLinks","data","stored","update","updatedAt","serverTimestamp","linkHostId","trim","resolveFiledFrom","owner","createTask","filed","ref","completedAtMs","createdByUid","createdAt","id","crmTaskSaveHandler","res","method","setHeader","json","Array","isArray","saveBatch","read","task","saved","entries","parsed","entry","raw","push","results","completeTask","snapshot","Number","alreadyDone","now","completedByUid","eventHostId","taskHostId","actor","completeStatus","outcome","crmTaskCompleteHandler","taskIds","completeBatch","Set","filter"],"mappings":";AAAA;;;;;;;;;;;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AC3Df,IAAIxH,MAAM,CAAC,KAAK2H,IAAI,CAACxH;IACvB,EAAE,OAAOF,OAAO;QACdgD,QAAQhD,KAAK,CAAC,oCAAoCA;QAClDuH,IAAIxH,MAAM,CAAC,KAAK2H,IAAI,CAAC;YAAE1H,OAAO;QAAoC;IACpE;AACF"}
@@ -124,6 +124,8 @@ export const crmDealStageHandler = async (req, res)=>{
124
124
  */ let orgId;
125
125
  let org;
126
126
  let actor = null;
127
+ // Who moved the deal, at either level, for the runs it sets off (AGL-3376).
128
+ let eventActor;
127
129
  if (routeScope.level === 'org') {
128
130
  const caller = await authorizeOrgCaller(req, routeScope.orgId, {
129
131
  needs: 'data.manage',
@@ -140,6 +142,7 @@ export const crmDealStageHandler = async (req, res)=>{
140
142
  uid: caller.uid,
141
143
  email: caller.email
142
144
  };
145
+ eventActor = actor;
143
146
  } else {
144
147
  var _req_headers_authorization;
145
148
  const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
@@ -151,7 +154,12 @@ export const crmDealStageHandler = async (req, res)=>{
151
154
  }
152
155
  let uid;
153
156
  try {
154
- uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid;
157
+ const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
158
+ uid = decoded.uid;
159
+ eventActor = {
160
+ uid,
161
+ email: typeof decoded.email === 'string' ? decoded.email : null
162
+ };
155
163
  } catch (error) {
156
164
  // A refused credential is the caller's 401; a failure to check one is
157
165
  // ours and keeps a 5xx (AGL-2852).
@@ -273,7 +281,11 @@ export const crmDealStageHandler = async (req, res)=>{
273
281
  await emitHostEvent(eventHostId, event, dealEventPayload(dealId, _extends({}, deal, {
274
282
  stageId: target.id,
275
283
  lostReason: nextStatus === 'lost' ? lostReason : undefined
276
- }), previousStageId));
284
+ }), previousStageId), {
285
+ actor: _extends({
286
+ kind: 'member'
287
+ }, eventActor)
288
+ });
277
289
  }
278
290
  if ((customer == null ? void 0 : customer.outcome) === 'advanced') {
279
291
  // The stage change is the win's effect, announced after its cause, to
@@ -284,6 +296,10 @@ export const crmDealStageHandler = async (req, res)=>{
284
296
  email: customer.email,
285
297
  lifecycleStage: customer.lifecycleStage,
286
298
  previousStage: customer.previousStage
299
+ }, {
300
+ actor: _extends({
301
+ kind: 'member'
302
+ }, eventActor)
287
303
  });
288
304
  }
289
305
  if (actor) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server-deal-stage.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `POST /api/crm/deal-stage` — the one writer of a deal's stage (AGL-2598).\n *\n * ## Why a route, when the rules would let the browser do it\n *\n * A deal's title, amount and owner are edited client-direct against the\n * Firestore rules, and nothing about a stage change needs a server to be\n * SAFE. What it needs a server for is to be HEARD: a move between stages, a\n * win and a loss are the three moments an automation wants — \"when a deal is\n * won, email the owner\", \"when one reaches negotiation, file a task\" — and a\n * workflow only fires on an event the tenant runtime emits. A stage written\n * by the browser would be a fact nothing could react to. So every surface\n * that moves a deal calls here, and this handler updates the document and\n * then emits `dealStageChanged`, `dealWon` or `dealLost` with a flat payload\n * a workflow filter can read.\n *\n * ## Who may call it\n *\n * Three gates, in the order the cheapest fails first:\n *\n * 1. A verified Firebase session — the console's `authorizedFetch` puts the\n * id token on every call.\n * 2. An admin or editor role ON THIS SITE, resolved by `hostRoleFor` from\n * the org member document, which is the same projection the rules read.\n * 3. The `data.manage` permission in the org — the key the whole CRM is\n * gated on, resolved through the custom-role and per-member layers by\n * `memberHasOrgPermission`, because a member document alone cannot say\n * what a custom role took away.\n *\n * And then the deal has to be VISIBLE to the site: its `visibleTo` must\n * intersect the scope tokens a contact captured on this site would carry.\n * The Admin SDK evaluates no rules, so without this check an editor of one\n * site in an agency could move another client's deals by id.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, dealId, … }` instead of a site: the org-level hub's board. The\n * caller is authorized by the ORG — an org-wide member holding\n * `data.manage`, the org hub's own gate — and no visibility check is made,\n * because an org-wide member reads every row the org holds. The event\n * still goes to the deal's own capturing site, which is where the\n * automations that listen for it live; a deal no site captured has none to\n * tell. And the act is logged in the org's feed, since there is no one\n * site's feed it happened in.\n *\n * ## What it writes\n *\n * `stageId`, `status` (from the target stage's `kind`, never from the body),\n * `stageChangedAtMs`, `closedAtMs` (set on a close, cleared on a reopen) and\n * `lostReason` (kept on a loss, removed on anything else). A move to the\n * stage the deal is already in writes nothing and emits nothing — an\n * automation must not fire twice because a card was dropped where it was.\n *\n * ## A won deal makes its contact a customer (AGL-2641)\n *\n * A win is the same fact as a purchase — the business has decided this\n * person bought — and an order already floors a contact's lifecycle stage\n * at `customer` on capture. So the transition INTO `won` applies the same\n * floor to the contact the deal names, in the same write path, behind no\n * setting: `floorContactLifecycleStage` fills an empty stage or advances an\n * earlier one inside the facet of the site the deal was made on, and never\n * moves anybody back — a customer stays a customer, an evangelist an\n * evangelist. When the stage did move, `contactStageChanged` is announced\n * after `dealWon`, so an automation keyed on \"became a customer\" hears it,\n * and the org's activity line says so. A failure to write the contact does\n * not undo the win: the deal is already closed, and the response reports\n * `customer: null` rather than a 500 for a stage change that did happen.\n */\n\nimport {\n CRM_COLLECTIONS,\n type CrmDeal,\n type CrmPipeline,\n dealStageById,\n hostRoleFor,\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n type ContactLifecycleFloor,\n firebaseAdmin,\n floorContactLifecycleStage,\n getOrgForHost,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n closingStage,\n dealEventName,\n dealEventPayload,\n} from './model/deal-board-model'\nimport { authorizeOrgCaller, readCrmRouteScope } from './server/org-caller'\nimport { crmSuiteRefusal } from './server/suite-gate'\n\n/** The most a lost reason may carry — a sentence or two, not a post-mortem. */\nexport const LOST_REASON_MAX = 500\n\nexport const crmDealStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const routeScope = readCrmRouteScope(req.body as Record<string, unknown>)\n const dealId = String(req.body?.dealId ?? '').trim()\n const stageId =\n typeof req.body?.stageId === 'string' ? req.body.stageId.trim() : ''\n const status = req.body?.status\n const closing = status === 'won' || status === 'lost' ? status : null\n const lostReason = String(req.body?.lostReason ?? '')\n .trim()\n .slice(0, LOST_REASON_MAX)\n if (!routeScope || !dealId) {\n return res.status(400).json({ error: 'Missing hostId or dealId' })\n }\n if (!stageId && !closing) {\n return res.status(400).json({\n error: 'Name a stageId to move to, or a status of won or lost.',\n })\n }\n\n /*\n * Who is calling, and the org whose deal it is. The site variant\n * resolves the org from the site and the caller's role on it; the org\n * variant is authorized by the org itself, and the site the body may\n * name beside it is not consulted — the deal's own site, read off the\n * document, is the one its event goes to.\n */\n let orgId: string\n let org: Record<string, unknown>\n let actor: { uid: string; email: string | null } | null = null\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'data.manage',\n refusal:\n 'Moving a deal at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.',\n })\n if (caller.ok === false) {\n return res.status(caller.status).json({ error: caller.error })\n }\n orgId = caller.orgId\n org = caller.org as Record<string, unknown>\n actor = { uid: caller.uid, email: caller.email }\n } else {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return res.status(401).json({ error: 'Unauthenticated' })\n console.error('[crm] deal-stage could not verify the caller', error)\n return res.status(500).json({ error: 'The sign-in could not be checked. Try again.' })\n }\n\n const owner = await getOrgForHost(routeScope.hostId).catch(() => null)\n if (!owner) {\n return res.status(404).json({\n error: 'This site has no organization, so it has no deals.',\n })\n }\n const membership = await resolveOrgMembership(uid, owner.orgId).catch(\n () => null,\n )\n const member = membership?.member\n const hostRole = hostRoleFor(member, routeScope.hostId)\n if (!member || (hostRole !== 'admin' && hostRole !== 'editor')) {\n return res.status(403).json({\n error: 'Moving a deal needs an admin or editor role on this site.',\n })\n }\n if (!(await memberHasOrgPermission(owner.orgId, member, 'data.manage'))) {\n return res.status(403).json({\n error: 'Moving a deal requires the \"Manage data\" permission.',\n })\n }\n orgId = owner.orgId\n org = owner.org as Record<string, unknown>\n }\n\n // Deals are the CRM suite's, at either level (AGL-2787).\n const suite = crmSuiteRefusal(org, 'Moving a deal through its pipeline')\n if (suite) return res.status(suite.status).json(suite.body)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const dealRef = orgRef.collection(CRM_COLLECTIONS.deals).doc(dealId)\n const dealSnapshot = await dealRef.get()\n if (!dealSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown deal' })\n }\n const deal = dealSnapshot.data() as CrmDeal\n\n if (routeScope.level === 'site') {\n const group = await consentGroupForSite(routeScope.hostId, org)\n const readable = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...group.hostIds.map(hostScopeToken),\n ])\n if (!(deal.visibleTo ?? []).some((token) => readable.has(token))) {\n return res.status(403).json({ error: 'This deal is not visible to this site.' })\n }\n }\n\n const pipelineSnapshot = await orgRef\n .collection(CRM_COLLECTIONS.pipelines)\n .doc(String(deal.pipelineId ?? ''))\n .get()\n if (!pipelineSnapshot.exists) {\n return res.status(409).json({\n error: \"This deal's pipeline no longer exists, so it has no stages to move to.\",\n })\n }\n const pipeline = pipelineSnapshot.data() as CrmPipeline\n const target = stageId\n ? dealStageById(pipeline, stageId)\n : closingStage(pipeline, closing as 'won' | 'lost')\n if (!target) {\n return res.status(400).json({\n error: stageId\n ? 'This pipeline has no such stage.'\n : `This pipeline has no ${closing} stage.`,\n })\n }\n\n const previousStageId = String(deal.stageId ?? '')\n const nextStatus = target.kind\n if (target.id === previousStageId && deal.status === nextStatus) {\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event: null,\n })\n }\n\n const nowMs = Date.now()\n await dealRef.update({\n stageId: target.id,\n status: nextStatus,\n stageChangedAtMs: nowMs,\n closedAtMs: nextStatus === 'open' ? null : nowMs,\n lostReason: nextStatus === 'lost' ? lostReason : FieldValue.delete(),\n updatedAt: new Date(),\n })\n\n const event = dealEventName(nextStatus)\n // The site whose automations hear the move: the mounted site, or at the\n // organization level the deal's own — a deal no site captured has none.\n const eventHostId =\n routeScope.level === 'site' ? routeScope.hostId : String(deal.hostId ?? '').trim()\n\n /*\n * The customer floor, on the transition into `won` alone: a move between\n * open stages, a loss and a reopen say nothing about whether the person\n * bought. The facet written is the site's the deal was made on — under\n * a site the mounted one, at the organization level the deal's own, and\n * for a deal no site captured the person's own capturing site.\n */\n let customer: ContactLifecycleFloor | null = null\n const contactId = String(deal.contactId ?? '').trim()\n if (nextStatus === 'won' && contactId) {\n customer = await floorContactLifecycleStage({\n contactRef: orgRef.collection('contacts').doc(contactId),\n org,\n hostId: eventHostId || null,\n floor: 'customer',\n }).catch((error: unknown) => {\n console.error('[crm] deal-stage: the customer floor failed', dealId, contactId, error)\n return null\n })\n }\n const becameCustomer = customer?.outcome === 'advanced'\n\n if (eventHostId) {\n await emitHostEvent(\n eventHostId,\n event,\n dealEventPayload(\n dealId,\n {\n ...deal,\n stageId: target.id,\n lostReason: nextStatus === 'lost' ? lostReason : undefined,\n },\n previousStageId,\n ),\n )\n }\n if (customer?.outcome === 'advanced') {\n // The stage change is the win's effect, announced after its cause, to\n // the site whose facet moved — the same site as the win's, unless no\n // site captured the deal and the person's own site holds the stage.\n await emitHostEvent(customer.hostId, 'contactStageChanged', {\n contactId: customer.contactId,\n email: customer.email,\n lifecycleStage: customer.lifecycleStage,\n previousStage: customer.previousStage,\n })\n }\n if (actor) {\n await logOrgActivity(\n orgId,\n actor,\n nextStatus === 'won'\n ? becameCustomer\n ? 'Marked deal won — contact now a customer'\n : 'Marked deal won'\n : nextStatus === 'lost'\n ? 'Marked deal lost'\n : `Moved deal to ${target.name}`,\n { type: 'deal', id: dealId, name: String(deal.title ?? '') },\n )\n }\n\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event,\n /*\n * What the win did to the contact: the stage it now holds and whether\n * this call raised it. `null` on anything but a win, on a deal that\n * names no contact, and on a contact write that failed.\n */\n customer:\n customer && (customer.outcome === 'advanced' || customer.outcome === 'held')\n ? {\n contactId: customer.contactId,\n lifecycleStage: customer.lifecycleStage,\n advanced: customer.outcome === 'advanced',\n }\n : null,\n })\n}\n"],"names":["CRM_COLLECTIONS","dealStageById","hostRoleFor","hostScopeToken","ORG_SCOPE_TOKEN","consentGroupForSite","firebaseAdmin","floorContactLifecycleStage","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","emitHostEvent","FieldValue","closingStage","dealEventName","dealEventPayload","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","LOST_REASON_MAX","crmDealStageHandler","req","res","deal","method","setHeader","status","json","error","routeScope","body","dealId","String","trim","stageId","closing","lostReason","slice","orgId","org","actor","level","caller","needs","refusal","ok","uid","email","authorization","headers","idToken","startsWith","length","app","auth","verifyIdToken","console","owner","hostId","catch","membership","member","hostRole","suite","firestore","orgRef","collection","doc","dealRef","deals","dealSnapshot","get","exists","data","group","readable","Set","hostIds","map","visibleTo","some","token","has","pipelineSnapshot","pipelines","pipelineId","pipeline","target","previousStageId","nextStatus","kind","id","event","nowMs","Date","now","update","stageChangedAtMs","closedAtMs","delete","updatedAt","eventHostId","customer","contactId","contactRef","floor","becameCustomer","outcome","undefined","lifecycleStage","previousStage","name","type","title","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SACEA,eAAe,EAGfC,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,eAAe,QAEV,sBAAqB;AAC5B,SACEC,mBAAmB,EAEnBC,aAAa,EACbC,0BAA0B,EAC1BC,aAAa,EACbC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,YAAY,EACZC,aAAa,EACbC,gBAAgB,QACX,8BAA0B;AACjC,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,yBAAqB;AAC3E,SAASC,eAAe,QAAQ,yBAAqB;AAErD,6EAA6E,GAC7E,OAAO,MAAMC,kBAAkB,IAAG;AAElC,OAAO,MAAMC,sBAAwC,OAAOC,KAAKC;qBAqHjDC,kBAmBiBA,eA2B4BA,cAUlCA;QAtKHF,WAEbA,YACMA,YAEWA;IAX1B,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzBF,IAAIG,SAAS,CAAC,SAAS;QACvB,OAAOH,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YA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,UACEA,YAAaA,CAAAA,SAASK,OAAO,KAAK,cAAcL,SAASK,OAAO,KAAK,MAAK,IACtE;YACEJ,WAAWD,SAASC,SAAS;YAC7BM,gBAAgBP,SAASO,cAAc;YACvCK,UAAUZ,SAASK,OAAO,KAAK;QACjC,IACA;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server-deal-stage.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * `POST /api/crm/deal-stage` — the one writer of a deal's stage (AGL-2598).\n *\n * ## Why a route, when the rules would let the browser do it\n *\n * A deal's title, amount and owner are edited client-direct against the\n * Firestore rules, and nothing about a stage change needs a server to be\n * SAFE. What it needs a server for is to be HEARD: a move between stages, a\n * win and a loss are the three moments an automation wants — \"when a deal is\n * won, email the owner\", \"when one reaches negotiation, file a task\" — and a\n * workflow only fires on an event the tenant runtime emits. A stage written\n * by the browser would be a fact nothing could react to. So every surface\n * that moves a deal calls here, and this handler updates the document and\n * then emits `dealStageChanged`, `dealWon` or `dealLost` with a flat payload\n * a workflow filter can read.\n *\n * ## Who may call it\n *\n * Three gates, in the order the cheapest fails first:\n *\n * 1. A verified Firebase session — the console's `authorizedFetch` puts the\n * id token on every call.\n * 2. An admin or editor role ON THIS SITE, resolved by `hostRoleFor` from\n * the org member document, which is the same projection the rules read.\n * 3. The `data.manage` permission in the org — the key the whole CRM is\n * gated on, resolved through the custom-role and per-member layers by\n * `memberHasOrgPermission`, because a member document alone cannot say\n * what a custom role took away.\n *\n * And then the deal has to be VISIBLE to the site: its `visibleTo` must\n * intersect the scope tokens a contact captured on this site would carry.\n * The Admin SDK evaluates no rules, so without this check an editor of one\n * site in an agency could move another client's deals by id.\n *\n * ## The organization variant (AGL-2634)\n *\n * `{ orgId, dealId, … }` instead of a site: the org-level hub's board. The\n * caller is authorized by the ORG — an org-wide member holding\n * `data.manage`, the org hub's own gate — and no visibility check is made,\n * because an org-wide member reads every row the org holds. The event\n * still goes to the deal's own capturing site, which is where the\n * automations that listen for it live; a deal no site captured has none to\n * tell. And the act is logged in the org's feed, since there is no one\n * site's feed it happened in.\n *\n * ## What it writes\n *\n * `stageId`, `status` (from the target stage's `kind`, never from the body),\n * `stageChangedAtMs`, `closedAtMs` (set on a close, cleared on a reopen) and\n * `lostReason` (kept on a loss, removed on anything else). A move to the\n * stage the deal is already in writes nothing and emits nothing — an\n * automation must not fire twice because a card was dropped where it was.\n *\n * ## A won deal makes its contact a customer (AGL-2641)\n *\n * A win is the same fact as a purchase — the business has decided this\n * person bought — and an order already floors a contact's lifecycle stage\n * at `customer` on capture. So the transition INTO `won` applies the same\n * floor to the contact the deal names, in the same write path, behind no\n * setting: `floorContactLifecycleStage` fills an empty stage or advances an\n * earlier one inside the facet of the site the deal was made on, and never\n * moves anybody back — a customer stays a customer, an evangelist an\n * evangelist. When the stage did move, `contactStageChanged` is announced\n * after `dealWon`, so an automation keyed on \"became a customer\" hears it,\n * and the org's activity line says so. A failure to write the contact does\n * not undo the win: the deal is already closed, and the response reports\n * `customer: null` rather than a 500 for a stage change that did happen.\n */\n\nimport {\n CRM_COLLECTIONS,\n type CrmDeal,\n type CrmPipeline,\n dealStageById,\n hostRoleFor,\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n type ContactLifecycleFloor,\n firebaseAdmin,\n floorContactLifecycleStage,\n getOrgForHost,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n closingStage,\n dealEventName,\n dealEventPayload,\n} from './model/deal-board-model'\nimport { authorizeOrgCaller, readCrmRouteScope } from './server/org-caller'\nimport { crmSuiteRefusal } from './server/suite-gate'\n\n/** The most a lost reason may carry — a sentence or two, not a post-mortem. */\nexport const LOST_REASON_MAX = 500\n\nexport const crmDealStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const routeScope = readCrmRouteScope(req.body as Record<string, unknown>)\n const dealId = String(req.body?.dealId ?? '').trim()\n const stageId =\n typeof req.body?.stageId === 'string' ? req.body.stageId.trim() : ''\n const status = req.body?.status\n const closing = status === 'won' || status === 'lost' ? status : null\n const lostReason = String(req.body?.lostReason ?? '')\n .trim()\n .slice(0, LOST_REASON_MAX)\n if (!routeScope || !dealId) {\n return res.status(400).json({ error: 'Missing hostId or dealId' })\n }\n if (!stageId && !closing) {\n return res.status(400).json({\n error: 'Name a stageId to move to, or a status of won or lost.',\n })\n }\n\n /*\n * Who is calling, and the org whose deal it is. The site variant\n * resolves the org from the site and the caller's role on it; the org\n * variant is authorized by the org itself, and the site the body may\n * name beside it is not consulted — the deal's own site, read off the\n * document, is the one its event goes to.\n */\n let orgId: string\n let org: Record<string, unknown>\n let actor: { uid: string; email: string | null } | null = null\n // Who moved the deal, at either level, for the runs it sets off (AGL-3376).\n let eventActor: { uid: string; email: string | null }\n if (routeScope.level === 'org') {\n const caller = await authorizeOrgCaller(req, routeScope.orgId, {\n needs: 'data.manage',\n refusal:\n 'Moving a deal at the organization level requires the \"Manage data\" ' +\n 'permission across the whole workspace.',\n })\n if (caller.ok === false) {\n return res.status(caller.status).json({ error: caller.error })\n }\n orgId = caller.orgId\n org = caller.org as Record<string, unknown>\n actor = { uid: caller.uid, email: caller.email }\n eventActor = actor\n } else {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n let uid: string\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n uid = decoded.uid\n eventActor = {\n uid,\n email: typeof decoded.email === 'string' ? decoded.email : null,\n }\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 res.status(401).json({ error: 'Unauthenticated' })\n console.error('[crm] deal-stage could not verify the caller', error)\n return res.status(500).json({ error: 'The sign-in could not be checked. Try again.' })\n }\n\n const owner = await getOrgForHost(routeScope.hostId).catch(() => null)\n if (!owner) {\n return res.status(404).json({\n error: 'This site has no organization, so it has no deals.',\n })\n }\n const membership = await resolveOrgMembership(uid, owner.orgId).catch(\n () => null,\n )\n const member = membership?.member\n const hostRole = hostRoleFor(member, routeScope.hostId)\n if (!member || (hostRole !== 'admin' && hostRole !== 'editor')) {\n return res.status(403).json({\n error: 'Moving a deal needs an admin or editor role on this site.',\n })\n }\n if (!(await memberHasOrgPermission(owner.orgId, member, 'data.manage'))) {\n return res.status(403).json({\n error: 'Moving a deal requires the \"Manage data\" permission.',\n })\n }\n orgId = owner.orgId\n org = owner.org as Record<string, unknown>\n }\n\n // Deals are the CRM suite's, at either level (AGL-2787).\n const suite = crmSuiteRefusal(org, 'Moving a deal through its pipeline')\n if (suite) return res.status(suite.status).json(suite.body)\n\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const dealRef = orgRef.collection(CRM_COLLECTIONS.deals).doc(dealId)\n const dealSnapshot = await dealRef.get()\n if (!dealSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown deal' })\n }\n const deal = dealSnapshot.data() as CrmDeal\n\n if (routeScope.level === 'site') {\n const group = await consentGroupForSite(routeScope.hostId, org)\n const readable = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...group.hostIds.map(hostScopeToken),\n ])\n if (!(deal.visibleTo ?? []).some((token) => readable.has(token))) {\n return res.status(403).json({ error: 'This deal is not visible to this site.' })\n }\n }\n\n const pipelineSnapshot = await orgRef\n .collection(CRM_COLLECTIONS.pipelines)\n .doc(String(deal.pipelineId ?? ''))\n .get()\n if (!pipelineSnapshot.exists) {\n return res.status(409).json({\n error: \"This deal's pipeline no longer exists, so it has no stages to move to.\",\n })\n }\n const pipeline = pipelineSnapshot.data() as CrmPipeline\n const target = stageId\n ? dealStageById(pipeline, stageId)\n : closingStage(pipeline, closing as 'won' | 'lost')\n if (!target) {\n return res.status(400).json({\n error: stageId\n ? 'This pipeline has no such stage.'\n : `This pipeline has no ${closing} stage.`,\n })\n }\n\n const previousStageId = String(deal.stageId ?? '')\n const nextStatus = target.kind\n if (target.id === previousStageId && deal.status === nextStatus) {\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event: null,\n })\n }\n\n const nowMs = Date.now()\n await dealRef.update({\n stageId: target.id,\n status: nextStatus,\n stageChangedAtMs: nowMs,\n closedAtMs: nextStatus === 'open' ? null : nowMs,\n lostReason: nextStatus === 'lost' ? lostReason : FieldValue.delete(),\n updatedAt: new Date(),\n })\n\n const event = dealEventName(nextStatus)\n // The site whose automations hear the move: the mounted site, or at the\n // organization level the deal's own — a deal no site captured has none.\n const eventHostId =\n routeScope.level === 'site' ? routeScope.hostId : String(deal.hostId ?? '').trim()\n\n /*\n * The customer floor, on the transition into `won` alone: a move between\n * open stages, a loss and a reopen say nothing about whether the person\n * bought. The facet written is the site's the deal was made on — under\n * a site the mounted one, at the organization level the deal's own, and\n * for a deal no site captured the person's own capturing site.\n */\n let customer: ContactLifecycleFloor | null = null\n const contactId = String(deal.contactId ?? '').trim()\n if (nextStatus === 'won' && contactId) {\n customer = await floorContactLifecycleStage({\n contactRef: orgRef.collection('contacts').doc(contactId),\n org,\n hostId: eventHostId || null,\n floor: 'customer',\n }).catch((error: unknown) => {\n console.error('[crm] deal-stage: the customer floor failed', dealId, contactId, error)\n return null\n })\n }\n const becameCustomer = customer?.outcome === 'advanced'\n\n if (eventHostId) {\n await emitHostEvent(\n eventHostId,\n event,\n dealEventPayload(\n dealId,\n {\n ...deal,\n stageId: target.id,\n lostReason: nextStatus === 'lost' ? lostReason : undefined,\n },\n previousStageId,\n ),\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (customer?.outcome === 'advanced') {\n // The stage change is the win's effect, announced after its cause, to\n // the site whose facet moved — the same site as the win's, unless no\n // site captured the deal and the person's own site holds the stage.\n await emitHostEvent(\n customer.hostId,\n 'contactStageChanged',\n {\n contactId: customer.contactId,\n email: customer.email,\n lifecycleStage: customer.lifecycleStage,\n previousStage: customer.previousStage,\n },\n { actor: { kind: 'member', ...eventActor } },\n )\n }\n if (actor) {\n await logOrgActivity(\n orgId,\n actor,\n nextStatus === 'won'\n ? becameCustomer\n ? 'Marked deal won — contact now a customer'\n : 'Marked deal won'\n : nextStatus === 'lost'\n ? 'Marked deal lost'\n : `Moved deal to ${target.name}`,\n { type: 'deal', id: dealId, name: String(deal.title ?? '') },\n )\n }\n\n return res.status(200).json({\n ok: true,\n dealId,\n stageId: target.id,\n status: nextStatus,\n previousStageId,\n event,\n /*\n * What the win did to the contact: the stage it now holds and whether\n * this call raised it. `null` on anything but a win, on a deal that\n * names no contact, and on a contact write that failed.\n */\n customer:\n customer && (customer.outcome === 'advanced' || customer.outcome === 'held')\n ? {\n contactId: customer.contactId,\n lifecycleStage: customer.lifecycleStage,\n advanced: customer.outcome === 'advanced',\n }\n : null,\n })\n}\n"],"names":["CRM_COLLECTIONS","dealStageById","hostRoleFor","hostScopeToken","ORG_SCOPE_TOKEN","consentGroupForSite","firebaseAdmin","floorContactLifecycleStage","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","emitHostEvent","FieldValue","closingStage","dealEventName","dealEventPayload","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","LOST_REASON_MAX","crmDealStageHandler","req","res","deal","method","setHeader","status","json","error","routeScope","body","dealId","String","trim","stageId","closing","lostReason","slice","orgId","org","actor","eventActor","level","caller","needs","refusal","ok","uid","email","authorization","headers","idToken","startsWith","length","decoded","app","auth","verifyIdToken","console","owner","hostId","catch","membership","member","hostRole","suite","firestore","orgRef","collection","doc","dealRef","deals","dealSnapshot","get","exists","data","group","readable","Set","hostIds","map","visibleTo","some","token","has","pipelineSnapshot","pipelines","pipelineId","pipeline","target","previousStageId","nextStatus","kind","id","event","nowMs","Date","now","update","stageChangedAtMs","closedAtMs","delete","updatedAt","eventHostId","customer","contactId","contactRef","floor","becameCustomer","outcome","undefined","lifecycleStage","previousStage","name","type","title","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SACEA,eAAe,EAGfC,aAAa,EACbC,WAAW,EACXC,cAAc,EACdC,eAAe,QAEV,sBAAqB;AAC5B,SACEC,mBAAmB,EAEnBC,aAAa,EACbC,0BAA0B,EAC1BC,aAAa,EACbC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,YAAY,EACZC,aAAa,EACbC,gBAAgB,QACX,8BAA0B;AACjC,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,yBAAqB;AAC3E,SAASC,eAAe,QAAQ,yBAAqB;AAErD,6EAA6E,GAC7E,OAAO,MAAMC,kBAAkB,IAAG;AAElC,OAAO,MAAMC,sBAAwC,OAAOC,KAAKC;qBA6HjDC,kBAmBiBA,eA2B4B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OAAO;YAWkCjB;QAV3C,MAAMhB,eACJ+B,OACAE,OACAmD,eAAe,QACXiB,iBACE,6CACA,oBACFjB,eAAe,SACb,qBACA,CAAC,cAAc,EAAEF,OAAOwB,IAAI,EAAE,EACpC;YAAEC,MAAM;YAAQrB,IAAI9D;YAAQkF,MAAMjF,QAAOT,cAAAA,KAAK4F,KAAK,YAAV5F,cAAc;QAAI;IAE/D;IAEA,OAAOD,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;QAC1BmB,IAAI;QACJf;QACAG,SAASuD,OAAOI,EAAE;QAClBnE,QAAQiE;QACRD;QACAI;QACA;;;;KAIC,GACDU,UACEA,YAAaA,CAAAA,SAASK,OAAO,KAAK,cAAcL,SAASK,OAAO,KAAK,MAAK,IACtE;YACEJ,WAAWD,SAASC,SAAS;YAC7BM,gBAAgBP,SAASO,cAAc;YACvCK,UAAUZ,SAASK,OAAO,KAAK;QACjC,IACA;IACR;AACF,EAAC"}
package/src/lib/server.js CHANGED
@@ -73,6 +73,7 @@ import { crmLeadsImportHandler } from "./server/leads-import.js";
73
73
  import { crmTasksImportHandler } from "./server/tasks-import.js";
74
74
  import { crmDealStageHandler } from "./server-deal-stage.js";
75
75
  import { crmEmailSendHandler } from "./server/email-send.js";
76
+ import { CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler } from "./server/email-check.js";
76
77
  import { leadConvertHandler } from "./server/lead-convert.js";
77
78
  import { leadCreateHandler } from "./server/lead-create.js";
78
79
  import { CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler } from "./server/contact-email-history.js";
@@ -126,8 +127,11 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
126
127
  error: 'Unauthenticated'
127
128
  };
128
129
  let uid;
130
+ let email;
129
131
  try {
130
- uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid;
132
+ const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
133
+ uid = decoded.uid;
134
+ email = typeof decoded.email === 'string' ? decoded.email : null;
131
135
  } catch (error) {
132
136
  // A refused credential is the caller's 401; a failure to check one is
133
137
  // ours and keeps a 5xx (AGL-2852).
@@ -161,7 +165,8 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
161
165
  }
162
166
  return {
163
167
  ok: true,
164
- uid
168
+ uid,
169
+ email
165
170
  };
166
171
  }
167
172
  /**
@@ -272,6 +277,12 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
272
277
  email: String((_snapshot_get = snapshot.get('email')) != null ? _snapshot_get : ''),
273
278
  lifecycleStage,
274
279
  previousStage
280
+ }, {
281
+ actor: {
282
+ kind: 'member',
283
+ uid: caller.uid,
284
+ email: caller.email
285
+ }
275
286
  });
276
287
  }
277
288
  res.status(200).json({
@@ -461,6 +472,11 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
461
472
  interaction: {
462
473
  summary: 'Added by hand'
463
474
  },
475
+ actor: {
476
+ kind: 'member',
477
+ uid: decoded.uid,
478
+ email: typeof decoded.email === 'string' ? decoded.email : null
479
+ },
464
480
  marketingConsent
465
481
  }, marketingConsent && disclosedConsentGroup ? {
466
482
  disclosedConsentGroup
@@ -613,6 +629,11 @@ import { CRM_RECIPE_INSTALL_ROUTE, CRM_RECIPE_STATUS_ROUTE, crmRecipeInstallHand
613
629
  // read off the record, the daily cap and both suppression lists are
614
630
  // judged, and the message leaves on the site's sending identity.
615
631
  registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler);
632
+ // What the platform knows about one address before somebody writes to it
633
+ // (AGL-3328): the gateway chip on a record page, and the composer's
634
+ // warning about a domain with no mail server or a gateway holding this
635
+ // site's mail. DNS and the ledger are the server's.
636
+ registerPluginApiRoute(CRM_EMAIL_CHECK_ROUTE, crmEmailCheckHandler);
616
637
  // Two records for one person become one (AGL-2625): the repoint of every
617
638
  // row naming the merged record and the transaction over both documents
618
639
  // are the server's, and the address index it writes is closed to clients.