@aglyn/plugins-crm 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/contact-list-columns.js +4 -3
  3. package/src/lib/components/contact-list-columns.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.js +6 -2
  5. package/src/lib/components/contact-properties-card.js.map +1 -1
  6. package/src/lib/components/contacts-bulk-bar.js +16 -5
  7. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  8. package/src/lib/components/contacts-section.js +6 -13
  9. package/src/lib/components/contacts-section.js.map +1 -1
  10. package/src/lib/components/crm-record-insights-zone.js +7 -0
  11. package/src/lib/components/crm-record-insights-zone.js.map +1 -1
  12. package/src/lib/components/crm-send-email-dialog.js +1 -1
  13. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  14. package/src/lib/components/deal-board.d.ts +2 -0
  15. package/src/lib/components/deal-board.js +20 -11
  16. package/src/lib/components/deal-board.js.map +1 -1
  17. package/src/lib/components/deal-stage-card.js +41 -28
  18. package/src/lib/components/deal-stage-card.js.map +1 -1
  19. package/src/lib/components/deals-bulk-bar.js +20 -10
  20. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  21. package/src/lib/components/deals-section.js +1 -0
  22. package/src/lib/components/deals-section.js.map +1 -1
  23. package/src/lib/components/email-capture-card.d.ts +1 -1
  24. package/src/lib/components/email-capture-card.js +2 -1
  25. package/src/lib/components/email-capture-card.js.map +1 -1
  26. package/src/lib/components/record-sharing-card.d.ts +6 -5
  27. package/src/lib/components/record-sharing-card.js +45 -30
  28. package/src/lib/components/record-sharing-card.js.map +1 -1
  29. package/src/lib/components/settings-section.d.ts +18 -11
  30. package/src/lib/components/settings-section.js +36 -19
  31. package/src/lib/components/settings-section.js.map +1 -1
  32. package/src/lib/components/sharing-rules-card.js +2 -1
  33. package/src/lib/components/sharing-rules-card.js.map +1 -1
  34. package/src/lib/components/use-org-members.d.ts +17 -10
  35. package/src/lib/components/use-org-members.js +31 -66
  36. package/src/lib/components/use-org-members.js.map +1 -1
  37. package/src/lib/declarations.d.ts +6 -2
  38. package/src/lib/declarations.js +14 -2
  39. package/src/lib/declarations.js.map +1 -1
  40. package/src/lib/declarations.server.js +16 -0
  41. package/src/lib/declarations.server.js.map +1 -1
  42. package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
  43. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  44. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  45. package/src/lib/hooks/use-crm-record-names.js +59 -6
  46. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  47. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  48. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  49. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  50. package/src/lib/hooks/use-org-member-directory.js +49 -12
  51. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  52. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  53. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  54. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  55. package/src/lib/model/crm-api.d.ts +1 -1
  56. package/src/lib/model/crm-api.js +1 -1
  57. package/src/lib/model/crm-api.js.map +1 -1
  58. package/src/lib/model/crm-permissions.d.ts +35 -0
  59. package/src/lib/model/crm-permissions.js +87 -0
  60. package/src/lib/model/crm-permissions.js.map +1 -0
  61. package/src/lib/model/crm-sharing.d.ts +1 -1
  62. package/src/lib/model/crm-sharing.js +1 -1
  63. package/src/lib/model/crm-sharing.js.map +1 -1
  64. package/src/lib/plugin.js +4 -5
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/capture-contact.d.ts +3 -3
  67. package/src/lib/server/capture-contact.js +3 -3
  68. package/src/lib/server/capture-contact.js.map +1 -1
  69. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  70. package/src/lib/server/crm-setup-writers.server.js +4 -16
  71. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  72. package/src/lib/server/crm-sharing.d.ts +5 -4
  73. package/src/lib/server/crm-sharing.js +8 -6
  74. package/src/lib/server/crm-sharing.js.map +1 -1
  75. package/src/lib/server/email-template-duplicate.js +7 -7
  76. package/src/lib/server/email-template-duplicate.js.map +1 -1
  77. package/src/lib/server/inbound-address.d.ts +9 -7
  78. package/src/lib/server/inbound-address.js +18 -15
  79. package/src/lib/server/inbound-address.js.map +1 -1
  80. package/src/lib/server/org-caller.d.ts +19 -5
  81. package/src/lib/server/org-caller.js +25 -5
  82. package/src/lib/server/org-caller.js.map +1 -1
  83. package/src/lib/server/recipe-routes.d.ts +0 -34
  84. package/src/lib/server/recipe-routes.js +11 -10
  85. package/src/lib/server/recipe-routes.js.map +1 -1
  86. package/src/lib/server/scope-sharing-patch.d.ts +22 -0
  87. package/src/lib/server/scope-sharing-patch.js +25 -0
  88. package/src/lib/server/scope-sharing-patch.js.map +1 -0
  89. package/src/lib/server/task-routes.d.ts +6 -5
  90. package/src/lib/server/task-routes.js +11 -13
  91. package/src/lib/server/task-routes.js.map +1 -1
  92. package/src/lib/server-deal-stage.d.ts +11 -6
  93. package/src/lib/server-deal-stage.js +18 -16
  94. package/src/lib/server-deal-stage.js.map +1 -1
  95. package/src/lib/server.js +16 -18
  96. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-sharing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The server half of CRM sharing (AGL-3336) — see `model/crm-sharing.ts`\n * for the model.\n *\n * Three writers, one transaction shape. A record's sharing is RECOMPUTED,\n * never patched: the transaction reads the record, keeps its hand shares\n * (changed by the caller when the act is a share or an unshare), matches\n * every active rule against it as it stands, and writes `visibleTo`,\n * `writeTo`, `sharing` and the list fields derived from `visibleTo` only\n * when any of them moves. So the same function serves\n *\n * - a manager's share or unshare (`crm/sharing`, `share`/`unshare`);\n * - a write to the record anywhere on the server, through the core's\n * record-written seam (`crmSharingRecordWritten`), and a client-direct\n * write's follow-up (`evaluate`);\n * - a rule's recompute over existing records (`rule-save`, `rule-continue`),\n * and its removal (`rule-delete`), in budgeted passes with the progress on\n * the rule.\n */\n\nimport {\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActivityLink,\n crmListFieldsPatch,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { hostIdsFromScope } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost, logOrgActivity } from '@aglyn/tenant-data-admin'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n activeSharingRules,\n CRM_SHARING_CRITERIA_FOR,\n CRM_SHARING_CRITERIA_KEYS,\n CRM_SHARING_FIELD,\n CRM_SHARING_IDS_MAX,\n CRM_SHARING_OBJECT_LABELS,\n CRM_SHARING_RULE_IDS_PATH,\n CRM_SHARING_RULES_MAX,\n CRM_WRITE_SCOPE_FIELD,\n type CrmShareAccess,\n type CrmShareGrant,\n type CrmSharingContext,\n type CrmSharingCriteria,\n type CrmSharingObject,\n type CrmSharingResponse,\n type CrmSharingRule,\n type CrmSharingRuleRun,\n type CrmSharingSite,\n describeShareTargets,\n evaluateRecordGrants,\n isCrmShareAccess,\n isCrmSharingObject,\n planRecordSharing,\n readCrmSharingRule,\n readCrmSharingRules,\n recordHeldScope,\n sharingPlanChanges,\n shareTargetsFrom,\n sharingRulesAskLeadSourceDirection,\n withManualShares,\n withoutManualShares,\n} from '../model/crm-sharing'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\nimport { readLeadSourcePicklist } from './lead-source-picklist'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\nimport { authorizeCrmWriter } from './task-routes'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/*==========================================\n * THE RULES, READ OFF THE ORG DOCUMENT.\n *=========================================*/\n\n/**\n * A few seconds of memory per process: every CRM write asks, and an org\n * with no rules should cost it nothing past the first read. A cached list\n * is never the reason a grant is TAKEN away — see `recomputeRecordSharing`.\n */\nconst RULES_TTL_MS = 10_000\nconst rulesCache = new Map<string, { atMs: number; rules: CrmSharingRule[] }>()\n\n/** Test seam, and what a rule write calls so its own process reads it fresh. */\nexport function forgetCrmSharingRules(orgId?: string): void {\n if (orgId) rulesCache.delete(orgId)\n else rulesCache.clear()\n}\n\nexport async function crmSharingRulesOf(\n firestore: Firestore,\n orgId: string,\n options: { fresh?: boolean; nowMs?: number } = {},\n): Promise<{ rules: CrmSharingRule[]; fresh: boolean }> {\n const nowMs = options.nowMs ?? Date.now()\n const cached = rulesCache.get(orgId)\n if (!options.fresh && cached && nowMs - cached.atMs < RULES_TTL_MS) {\n return { rules: cached.rules, fresh: false }\n }\n const snapshot = await firestore.collection('orgs').doc(orgId).get()\n const rules = readCrmSharingRules(snapshot.data() ?? null)\n rulesCache.set(orgId, { atMs: nowMs, rules })\n return { rules, fresh: true }\n}\n\n/**\n * What the rules for `object` are evaluated against beyond the record: the\n * org's Lead source list, read only when an active rule asks a lead source\n * direction (AGL-3511) — an org whose rules never do pays no read for it.\n */\nexport async function crmSharingContextFor(\n firestore: Firestore,\n orgId: string,\n rules: readonly CrmSharingRule[],\n object: CrmSharingObject,\n): Promise<CrmSharingContext> {\n if (!sharingRulesAskLeadSourceDirection(rules, object)) return {}\n return { leadSources: await readLeadSourcePicklist(firestore, orgId) }\n}\n\n/*==========================================\n * ONE RECORD, RECOMPUTED.\n *=========================================*/\n\nexport interface RecomputeRecordSharingInput {\n firestore: Firestore\n orgId: string\n object: CrmSharingObject\n id: string\n /** Every rule the org has, in any state. */\n rules: readonly CrmSharingRule[]\n /** Whether `rules` was read just now; a stale list is re-read before it takes a grant away. */\n fresh: boolean\n /** The hand shares' change, for a share or an unshare. */\n manual?: (grants: Record<string, CrmShareGrant>) => Record<string, CrmShareGrant>\n /** What the rules are evaluated against beyond the record — see {@link crmSharingContextFor}. */\n context?: CrmSharingContext\n atMs: number\n}\n\nexport type RecomputeOutcome = 'changed' | 'unchanged' | 'missing'\n\nexport async function recomputeRecordSharing(\n input: RecomputeRecordSharingInput,\n): Promise<RecomputeOutcome> {\n const { firestore, orgId, object, id, atMs } = input\n const ref = firestore.collection('orgs').doc(orgId).collection(object).doc(id)\n return await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return 'missing' as const\n const record = (snapshot.data() ?? {}) as Record<string, unknown>\n let rules = input.rules\n /*\n * A GRANT IS NEVER TAKEN AWAY ON A STALE ANSWER. A rule grant whose rule\n * the cached list does not name is dropped only once a fresh read of the\n * org agrees: another process may have saved that rule seconds ago and\n * applied it to this very record.\n */\n if (!input.fresh) {\n const known = new Set(rules.map((rule) => rule.id))\n const stored = record[CRM_SHARING_FIELD] as { ruleIds?: unknown } | undefined\n const ruleIds = Array.isArray(stored?.ruleIds) ? (stored.ruleIds as unknown[]) : []\n if (ruleIds.some((ruleId) => !known.has(String(ruleId)))) {\n const org = await tx.get(firestore.collection('orgs').doc(orgId))\n rules = readCrmSharingRules(org.data() ?? null)\n }\n }\n // A rule read afresh above may ask a direction the caller's context was not read for.\n const context =\n input.context?.leadSources || rules === input.rules\n ? input.context\n : await crmSharingContextFor(firestore, orgId, rules, object)\n let grants = evaluateRecordGrants(object, record, rules, atMs, context)\n if (input.manual) grants = input.manual(grants)\n const plan = planRecordSharing(record, grants)\n if (!sharingPlanChanges(record, plan)) return 'unchanged' as const\n const next = {\n ...record,\n visibleTo: plan.visibleTo,\n [CRM_WRITE_SCOPE_FIELD]: plan.writeTo ?? undefined,\n [CRM_SHARING_FIELD]: plan.sharing ?? undefined,\n }\n tx.update(ref, {\n visibleTo: plan.visibleTo,\n [CRM_WRITE_SCOPE_FIELD]: plan.writeTo ?? FieldValue.delete(),\n [CRM_SHARING_FIELD]: plan.sharing ?? FieldValue.delete(),\n // The scoped list fields are derived from `visibleTo` (AGL-3321), so a\n // target site's folded search finds the record the moment it can see it.\n ...crmListFieldsPatch(object, next),\n })\n return 'changed' as const\n })\n}\n\n/** Several records at once, a few in flight. */\nasync function recomputeMany(\n input: Omit<RecomputeRecordSharingInput, 'id'>,\n ids: readonly string[],\n): Promise<{ changed: string[]; missing: number }> {\n const queue = [...new Set(ids)]\n const changed: string[] = []\n let missing = 0\n const worker = async () => {\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n const outcome = await recomputeRecordSharing({ ...input, id })\n if (outcome === 'changed') changed.push(id)\n if (outcome === 'missing') missing += 1\n }\n }\n await Promise.all(Array.from({ length: Math.min(8, queue.length) }, worker))\n return { changed, missing }\n}\n\n/**\n * Re-evaluates the org's rules for these records — the one thing a write\n * anywhere owes the sharing. An org with no active rule for the object\n * costs one cached read and nothing else; grants of a rule switched off\n * are taken away by that rule's own removal pass, not here.\n */\nexport async function evaluateCrmSharing(\n firestore: Firestore,\n orgId: string,\n object: CrmSharingObject,\n ids: readonly string[],\n): Promise<{ changed: number; missing: number }> {\n const { rules, fresh } = await crmSharingRulesOf(firestore, orgId)\n if (!activeSharingRules(rules, object).length) return { changed: 0, missing: 0 }\n const context = await crmSharingContextFor(firestore, orgId, rules, object)\n const outcome = await recomputeMany(\n { firestore, orgId, object, rules, fresh, context, atMs: Date.now() },\n ids,\n )\n return { changed: outcome.changed.length, missing: outcome.missing }\n}\n\n/**\n * The core's record-written seam (AGL-3336): every server writer of a lead,\n * a contact, a company or a deal restamps it, and the restamp tells this.\n * Never throws — the write it is told about already landed.\n */\nexport async function crmSharingRecordWritten(event: {\n path: string\n collection: string\n}): Promise<void> {\n if (!isCrmSharingObject(event.collection)) return\n const segments = event.path.split('/')\n if (segments.length !== 4 || segments[0] !== 'orgs' || segments[2] !== event.collection) return\n try {\n await evaluateCrmSharing(\n firebaseAdmin.app().firestore(),\n segments[1],\n event.collection,\n [segments[3]],\n )\n } catch (error) {\n console.error(`[crm] sharing rules could not be evaluated for ${event.path}`, error)\n }\n}\n\n/*==========================================\n * THE AUDIT: a line on the record, a line in the org's feed.\n *=========================================*/\n\nconst LINK_FIELD: Readonly<Record<CrmSharingObject, keyof CrmActivityLink>> = {\n leads: 'leadId',\n contacts: 'contactId',\n companies: 'companyId',\n deals: 'dealId',\n}\n\nconst ORG_TARGET: Readonly<Record<CrmSharingObject, 'lead' | 'contact' | 'company' | 'deal'>> = {\n leads: 'lead',\n contacts: 'contact',\n companies: 'company',\n deals: 'deal',\n}\n\n/**\n * The entry on the record's Activity: who shared it with which sites, or\n * took a share away. Visible to the sites that hold the record and to the\n * sites it names, so both sides of a share read how it came about.\n */\nasync function fileSharingActivity(\n firestore: Firestore,\n input: {\n orgId: string\n object: CrmSharingObject\n id: string\n body: string\n targets: readonly string[]\n by: { uid: string; name: string }\n atMs: number\n },\n): Promise<void> {\n try {\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const record = (await orgRef.collection(input.object).doc(input.id).get()).data() ?? {}\n const held = recordHeldScope(record)\n const visibleTo = [...new Set([...held, ...input.targets])]\n if (!visibleTo.length) return\n const named: CrmActivityLink = { [LINK_FIELD[input.object]]: input.id }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, named))) return\n // The record just read is the deal or the contact the entry rolls up from.\n const link = stampCrmActivityCompany(named, {\n ...(input.object === 'deals' ? { deal: record } : {}),\n ...(input.object === 'contacts' ? { contact: record } : {}),\n })\n const hostId =\n typeof record['hostId'] === 'string' && record['hostId']\n ? record['hostId']\n : (hostIdsFromScope(held)[0] ?? '')\n await orgRef\n .collection(CRM_COLLECTIONS.activities)\n .doc(createResourceUid())\n .create({\n kind: 'note',\n body: input.body,\n atMs: input.atMs,\n byUid: input.by.uid,\n ...(input.by.name ? { byName: input.by.name } : {}),\n ...link,\n hostId,\n visibleTo,\n sourcePluginId: BUNDLE_ID,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n } catch (error) {\n console.error('[crm] the sharing entry could not be written on the record', input.id, error)\n }\n}\n\n/*==========================================\n * THE ORG'S SITES.\n *=========================================*/\n\nexport async function crmSharingSites(firestore: Firestore, orgId: string): Promise<CrmSharingSite[]> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).get()\n return hosts.docs\n .map((doc) => {\n const displayName = String(doc.get('displayName') ?? '').trim()\n const subdomain = String(doc.get('subdomain') ?? '').trim()\n return { id: String(doc.id), name: displayName || subdomain || String(doc.id) }\n })\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\n/*==========================================\n * A RULE, SAVED FROM A REQUEST.\n *=========================================*/\n\nfunction listFrom(raw: unknown, max: number): string[] {\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw.map((entry) => String(entry ?? '').trim().slice(0, 200)).filter(Boolean),\n ),\n ].slice(0, max)\n}\n\n/**\n * The rule a request describes, judged: an object, a name, sites that are\n * the org's own, targets that are the org's own or all sites. `null` with\n * the reason when it cannot be saved.\n */\nexport function ruleFromRequest(\n raw: unknown,\n context: { hostIds: readonly string[]; existing: CrmSharingRule | null; uid: string; nowMs: number },\n): { rule: CrmSharingRule; error: null } | { rule: null; error: string } {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return { rule: null, error: 'Describe the rule.' }\n }\n const value = raw as Record<string, unknown>\n const object = value['object']\n if (!isCrmSharingObject(object)) {\n return { rule: null, error: 'Choose which records the rule shares.' }\n }\n const name = String(value['name'] ?? '').trim().slice(0, 120)\n if (!name) return { rule: null, error: 'Name the rule.' }\n const own = new Set(context.hostIds)\n const sourceHostIds = listFrom(value['sourceHostIds'], 30)\n if (sourceHostIds.some((id) => !own.has(id))) {\n return { rule: null, error: 'A site the rule names is not one of this organization’s.' }\n }\n const targets = shareTargetsFrom(value['targets'])\n if (!targets) return { rule: null, error: 'Choose the sites to share with, or All sites.' }\n if (hostIdsFromScope(targets).some((id) => !own.has(id))) {\n return { rule: null, error: 'A site the rule shares with is not one of this organization’s.' }\n }\n const access = value['access']\n if (access !== undefined && !isCrmShareAccess(access)) {\n return { rule: null, error: 'Access is read-only, or read and edit.' }\n }\n const rawCriteria = (value['criteria'] ?? {}) as Record<string, unknown>\n const criteria: CrmSharingCriteria = {}\n for (const key of CRM_SHARING_CRITERIA_KEYS) {\n if (!CRM_SHARING_CRITERIA_FOR[object].includes(key)) continue\n const list = listFrom(rawCriteria[key], 20)\n if (list.length) criteria[key] = list\n }\n const existing = context.existing\n const rule = readCrmSharingRule({\n id: existing?.id ?? createResourceUid(),\n name,\n object,\n enabled: value['enabled'] !== false,\n sourceHostIds,\n criteria,\n targets,\n access: (access as CrmShareAccess | undefined) ?? 'read',\n createdByUid: existing?.createdByUid ?? context.uid,\n createdAtMs: existing?.createdAtMs ?? context.nowMs,\n updatedAtMs: context.nowMs,\n })\n if (!rule) return { rule: null, error: 'The rule could not be read.' }\n return { rule, error: null }\n}\n\n/** A rule as the org document stores it — no `undefined` anywhere. */\nfunction storedRule(rule: CrmSharingRule): Record<string, unknown> {\n return JSON.parse(JSON.stringify(rule)) as Record<string, unknown>\n}\n\n/**\n * Writes the org's rule list through `change`, in a transaction over the org\n * document, and answers the list as written.\n */\nasync function writeRules(\n firestore: Firestore,\n orgId: string,\n change: (rules: CrmSharingRule[]) => CrmSharingRule[] | { error: string },\n): Promise<{ rules: CrmSharingRule[]; error: null } | { rules: null; error: string }> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const result = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n const next = change(readCrmSharingRules(snapshot.data() ?? null))\n if ('error' in next) return { rules: null, error: next.error }\n tx.update(orgRef, new FieldPath('crm', 'sharingRules'), next.map(storedRule))\n return { rules: next, error: null }\n })\n forgetCrmSharingRules(orgId)\n return result as { rules: CrmSharingRule[]; error: null } | { rules: null; error: string }\n}\n\n/** Replaces one rule's run, leaving every other rule as it is. */\nasync function writeRun(\n firestore: Firestore,\n orgId: string,\n ruleId: string,\n run: CrmSharingRuleRun,\n options: { dropRule?: boolean } = {},\n): Promise<CrmSharingRule | null> {\n const written = await writeRules(firestore, orgId, (rules) =>\n options.dropRule\n ? rules.filter((rule) => rule.id !== ruleId)\n : rules.map((rule) => (rule.id === ruleId ? { ...rule, run } : rule)),\n )\n return written.rules?.find((rule) => rule.id === ruleId) ?? null\n}\n\n/*==========================================\n * A RULE'S RUN: apply it everywhere, or take it away.\n *=========================================*/\n\nconst RUN_PAGE = 200\n\n/**\n * One budgeted pass of a rule's run, with the progress written on the rule\n * after every page so a reopened settings page shows where it stands and\n * `rule-continue` picks up from the cursor.\n *\n * `apply` walks the object's whole collection by document id — a rule\n * matches on fields no index narrows to (a facet's tags, a site that\n * captured the person) — and writes only the records whose sharing moves.\n * `remove` asks for exactly the records the rule holds a grant on\n * (`sharing.ruleIds`), each of which the recompute then takes it off; a\n * page that makes no progress fails the run rather than looping.\n */\nexport async function advanceSharingRuleRun(\n firestore: Firestore,\n orgId: string,\n ruleId: string,\n deadlineMs: number,\n): Promise<{ rule: CrmSharingRule | null; more: boolean }> {\n const read = await crmSharingRulesOf(firestore, orgId, { fresh: true })\n let rule = read.rules.find((entry) => entry.id === ruleId) ?? null\n if (!rule?.run || rule.run.status !== 'running') return { rule, more: false }\n const records = firestore.collection('orgs').doc(orgId).collection(rule.object)\n let run: CrmSharingRuleRun = { ...rule.run }\n const seen = new Set<string>()\n try {\n while (Date.now() < deadlineMs) {\n const { rules } = await crmSharingRulesOf(firestore, orgId, { fresh: true })\n const context = await crmSharingContextFor(firestore, orgId, rules, rule.object)\n let page: FirebaseFirestore.QuerySnapshot\n if (run.mode === 'apply') {\n let query = records.orderBy(FieldPath.documentId()).limit(RUN_PAGE)\n if (run.cursor) query = query.startAfter(run.cursor)\n page = await query.get()\n } else {\n page = await records.where(CRM_SHARING_RULE_IDS_PATH, 'array-contains', ruleId).limit(RUN_PAGE).get()\n }\n const atMs = Date.now()\n // Only the records whose sharing would move are written.\n const moving = page.docs\n .filter((doc) => {\n const record = (doc.data() ?? {}) as Record<string, unknown>\n const plan = planRecordSharing(\n record,\n evaluateRecordGrants(rule!.object, record, rules, atMs, context),\n )\n return sharingPlanChanges(record, plan)\n })\n .map((doc) => doc.id)\n if (run.mode === 'remove' && page.docs.length && page.docs.every((doc) => seen.has(doc.id))) {\n throw new Error('the rule’s grants did not come off these records')\n }\n for (const doc of page.docs) seen.add(doc.id)\n const outcome = await recomputeMany(\n { firestore, orgId, object: rule.object, rules, fresh: true, context, atMs },\n moving,\n )\n const done = run.mode === 'apply' ? page.size < RUN_PAGE : page.empty\n run = {\n ...run,\n processed: run.processed + page.size,\n changed: run.changed + outcome.changed.length,\n cursor: run.mode === 'apply' ? (page.docs[page.docs.length - 1]?.id ?? run.cursor ?? null) : null,\n ...(done ? { status: 'done' as const, finishedAtMs: Date.now() } : {}),\n }\n rule = await writeRun(firestore, orgId, ruleId, run, {\n dropRule: done && rule.deleting === true,\n })\n if (done || !rule) return { rule, more: false }\n }\n return { rule, more: true }\n } catch (error) {\n console.error('[crm] a sharing rule run failed', orgId, ruleId, error)\n rule = await writeRun(firestore, orgId, ruleId, {\n ...run,\n status: 'failed',\n finishedAtMs: Date.now(),\n error: 'The recompute stopped. Resume it to carry on from where it stopped.',\n })\n return { rule, more: false }\n }\n}\n\n/*==========================================\n * THE ROUTE.\n *=========================================*/\n\n/** How long one request works on a rule before it answers and the page asks again. */\nconst RUN_BUDGET_MS = 20_000\n\nconst MANAGERS_ONLY =\n 'Sharing records across sites is for the workspace’s owners and admins.'\n\nfunction readIds(raw: unknown): string[] | null {\n if (!Array.isArray(raw)) return null\n const ids = [\n ...new Set(\n raw.map((entry) => String(entry ?? '').trim().slice(0, 256)).filter((id) => id && !id.includes('/')),\n ),\n ].slice(0, CRM_SHARING_IDS_MAX)\n return ids.length ? ids : null\n}\n\n/**\n * `POST /api/crm/sharing` — `{ action, hostId | orgId, … }`.\n *\n * Every action but `evaluate` is an org manager's: an OWNER or ADMIN of the\n * whole workspace (`authorizeOrgCaller(…, 'manage-org')`), under a site's\n * hub or the org's. `evaluate` is what a client-direct write owes the rules\n * and is open to whoever may write the CRM. The plan gate is the CRM's own\n * (`crmSuiteRefusal`): sharing is only meaningful across several sites, and\n * the number of sites a workspace may have is already the plan's.\n */\nexport const crmSharingHandler: 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 body = (req.body ?? {}) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const action = String(body['action'] ?? '')\n const firestore = firebaseAdmin.app().firestore()\n try {\n if (action === 'evaluate') {\n const object = body['object']\n const ids = readIds(body['ids'])\n if (!isCrmSharingObject(object) || !ids) {\n res.status(400).json({ error: 'Name the records.' })\n return\n }\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: null })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const outcome = await evaluateCrmSharing(firestore, writer.orgId, object, ids)\n const answer: CrmSharingResponse = { ok: true, ...outcome }\n res.status(200).json(answer)\n return\n }\n\n const orgId =\n scope.level === 'org'\n ? scope.orgId\n : ((await getOrgForHost(scope.hostId).catch(() => null))?.orgId ?? '')\n if (!orgId) {\n res.status(404).json({ error: 'This site has no organization, so it has no CRM.' })\n return\n }\n const caller = await authorizeOrgCaller(req, orgId, {\n needs: 'manage-org',\n refusal: MANAGERS_ONLY,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n const suite = crmSuiteRefusal(caller.org, 'Sharing records across sites')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const actor = { uid: caller.uid, email: caller.email }\n const byName = caller.name || caller.email || ''\n const nowMs = Date.now()\n\n if (action === 'sites') {\n const answer: CrmSharingResponse = { ok: true, sites: await crmSharingSites(firestore, orgId) }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'share' || action === 'unshare') {\n const object = body['object']\n const ids = readIds(body['ids'])\n if (!isCrmSharingObject(object) || !ids) {\n res.status(400).json({ error: 'Name the records to share.' })\n return\n }\n const targets = shareTargetsFrom(body['targets'])\n if (!targets) {\n res.status(400).json({ error: 'Choose the sites, or All sites.' })\n return\n }\n const sites = await crmSharingSites(firestore, orgId)\n const own = new Set(sites.map((site) => site.id))\n if (hostIdsFromScope(targets).some((id) => !own.has(id))) {\n res.status(400).json({ error: 'A site named is not one of this organization’s.' })\n return\n }\n const access: CrmShareAccess = body['access'] === 'edit' ? 'edit' : 'read'\n const { rules, fresh } = await crmSharingRulesOf(firestore, orgId)\n const context = await crmSharingContextFor(firestore, orgId, rules, object)\n const outcome = await recomputeMany(\n {\n firestore,\n orgId,\n object,\n rules,\n fresh,\n context,\n atMs: nowMs,\n manual: (grants) =>\n action === 'share'\n ? withManualShares(grants, targets, access, { uid: caller.uid, name: byName }, nowMs)\n : withoutManualShares(grants, targets),\n },\n ids,\n )\n const siteName = (id: string) => sites.find((site) => site.id === id)?.name ?? 'a site'\n const named = describeShareTargets(targets, siteName)\n const sentence =\n action === 'share'\n ? `Shared with ${named}${access === 'edit' ? ' (read and edit)' : ' (read-only)'}`\n : `Stopped sharing with ${named}`\n await Promise.all(\n outcome.changed.map((id) =>\n fileSharingActivity(firestore, {\n orgId,\n object,\n id,\n body: sentence,\n targets,\n by: { uid: caller.uid, name: byName },\n atMs: nowMs,\n }),\n ),\n )\n if (outcome.changed.length) {\n const label = CRM_SHARING_OBJECT_LABELS[object]\n await logOrgActivity(\n orgId,\n actor,\n outcome.changed.length === 1\n ? `${sentence}: one ${label.one}`\n : `${sentence}: ${outcome.changed.length} ${label.many.toLowerCase()}`,\n {\n type: ORG_TARGET[object],\n ...(outcome.changed.length === 1 ? { id: outcome.changed[0] } : {}),\n },\n ).catch(() => undefined)\n }\n const answer: CrmSharingResponse = {\n ok: true,\n changed: outcome.changed.length,\n missing: outcome.missing,\n }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'rule-save') {\n const hostIds = await orgHostIds(firestore, orgId)\n const raw = body['rule']\n const ruleId = raw && typeof raw === 'object' ? String((raw as Record<string, unknown>)['id'] ?? '') : ''\n let saved: CrmSharingRule | null = null\n let error: string | null = null\n const written = await writeRules(firestore, orgId, (rules) => {\n const existing = ruleId ? (rules.find((rule) => rule.id === ruleId) ?? null) : null\n if (ruleId && !existing) return { error: 'That rule no longer exists.' }\n if (existing?.deleting) return { error: 'That rule is being deleted.' }\n if (!existing && rules.length >= CRM_SHARING_RULES_MAX) {\n return { error: `A workspace keeps at most ${CRM_SHARING_RULES_MAX} sharing rules.` }\n }\n const judged = ruleFromRequest(raw, { hostIds, existing, uid: caller.uid, nowMs })\n if (!judged.rule) {\n error = judged.error\n return { error: judged.error }\n }\n /*\n * An enabled rule walks every record — it may now match some and not\n * others. A disabled one only has grants to take away, and asks for\n * exactly the records holding them.\n */\n saved = {\n ...judged.rule,\n run: {\n status: 'running',\n mode: judged.rule.enabled ? 'apply' : 'remove',\n processed: 0,\n changed: 0,\n cursor: null,\n startedAtMs: nowMs,\n },\n }\n return existing\n ? rules.map((rule) => (rule.id === existing.id ? saved! : rule))\n : [...rules, saved]\n })\n if (!written.rules || !saved) {\n res.status(400).json({ error: error ?? written.error ?? 'The rule could not be saved.' })\n return\n }\n const rule = saved as CrmSharingRule\n await logOrgActivity(\n orgId,\n actor,\n `${ruleId ? 'Changed' : 'Added'} the sharing rule “${rule.name}”`,\n { type: `${BUNDLE_ID}:sharingRule`, id: rule.id, name: rule.name },\n ).catch(() => undefined)\n const advanced = await advanceSharingRuleRun(firestore, orgId, rule.id, Date.now() + RUN_BUDGET_MS)\n const answer: CrmSharingResponse = { ok: true, rule: advanced.rule, more: advanced.more }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'rule-delete' || action === 'rule-continue') {\n const ruleId = String(body['ruleId'] ?? '').trim()\n if (!ruleId) {\n res.status(400).json({ error: 'Name the rule.' })\n return\n }\n if (action === 'rule-delete') {\n let name = ''\n const written = await writeRules(firestore, orgId, (rules) => {\n const existing = rules.find((rule) => rule.id === ruleId)\n if (!existing) return { error: 'That rule no longer exists.' }\n name = existing.name\n return rules.map((rule) =>\n rule.id === ruleId\n ? {\n ...rule,\n enabled: false,\n deleting: true,\n updatedAtMs: nowMs,\n run: {\n status: 'running' as const,\n mode: 'remove' as const,\n processed: 0,\n changed: 0,\n cursor: null,\n startedAtMs: nowMs,\n },\n }\n : rule,\n )\n })\n if (!written.rules) {\n res.status(404).json({ error: written.error })\n return\n }\n await logOrgActivity(orgId, actor, `Deleted the sharing rule “${name}”`, {\n type: `${BUNDLE_ID}:sharingRule`,\n id: ruleId,\n name,\n }).catch(() => undefined)\n } else {\n // A failed run resumes from its cursor.\n await writeRules(firestore, orgId, (rules) =>\n rules.map((rule) =>\n rule.id === ruleId && rule.run?.status === 'failed'\n ? { ...rule, run: { ...rule.run, status: 'running' as const } }\n : rule,\n ),\n )\n }\n const advanced = await advanceSharingRuleRun(firestore, orgId, ruleId, Date.now() + RUN_BUDGET_MS)\n const answer: CrmSharingResponse = { ok: true, rule: advanced.rule, more: advanced.more }\n res.status(200).json(answer)\n return\n }\n\n res.status(400).json({ error: 'Unknown sharing action.' })\n } catch (error) {\n console.error('[crm] sharing failed', action, error)\n res.status(500).json({ error: 'The sharing could not be saved. Try again.' })\n }\n}\n\n"],"names":["CRM_COLLECTIONS","crmActivityLogHasRoom","crmListFieldsPatch","createResourceUid","hostIdsFromScope","firebaseAdmin","getOrgForHost","logOrgActivity","countCrmActivitiesForRecord","FieldPath","FieldValue","BUNDLE_ID","activeSharingRules","CRM_SHARING_CRITERIA_FOR","CRM_SHARING_CRITERIA_KEYS","CRM_SHARING_FIELD","CRM_SHARING_IDS_MAX","CRM_SHARING_OBJECT_LABELS","CRM_SHARING_RULE_IDS_PATH","CRM_SHARING_RULES_MAX","CRM_WRITE_SCOPE_FIELD","describeShareTargets","evaluateRecordGrants","isCrmShareAccess","isCrmSharingObject","planRecordSharing","readCrmSharingRule","readCrmSharingRules","recordHeldScope","sharingPlanChanges","shareTargetsFrom","sharingRulesAskLeadSourceDirection","withManualShares","withoutManualShares","stampCrmActivityCompany","readLeadSourcePicklist","authorizeOrgCaller","orgHostIds","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","RULES_TTL_MS","rulesCache","Map","forgetCrmSharingRules","orgId","delete","clear","crmSharingRulesOf","firestore","options","snapshot","nowMs","Date","now","cached","get","fresh","atMs","rules","collection","doc","data","set","crmSharingContextFor","object","leadSources","recomputeRecordSharing","input","id","ref","runTransaction","tx","plan","exists","record","known","Set","map","rule","stored","ruleIds","Array","isArray","some","ruleId","has","String","org","context","grants","manual","next","visibleTo","writeTo","undefined","sharing","update","recomputeMany","ids","queue","changed","missing","worker","shift","outcome","push","Promise","all","from","length","Math","min","evaluateCrmSharing","crmSharingRecordWritten","event","segments","path","split","app","error","console","LINK_FIELD","leads","contacts","companies","deals","ORG_TARGET","fileSharingActivity","orgRef","held","targets","named","link","deal","contact","hostId","activities","create","kind","body","byUid","by","uid","name","byName","sourcePluginId","createdAt","serverTimestamp","updatedAt","crmSharingSites","hosts","where","docs","displayName","trim","subdomain","sort","a","b","localeCompare","listFrom","raw","max","entry","slice","filter","Boolean","ruleFromRequest","value","own","hostIds","sourceHostIds","access","rawCriteria","criteria","key","includes","list","existing","enabled","createdByUid","createdAtMs","updatedAtMs","storedRule","JSON","parse","stringify","writeRules","change","result","writeRun","run","written","dropRule","find","RUN_PAGE","advanceSharingRuleRun","deadlineMs","read","status","more","records","seen","page","mode","query","orderBy","documentId","limit","cursor","startAfter","moving","every","Error","add","done","size","empty","processed","finishedAtMs","deleting","RUN_BUDGET_MS","MANAGERS_ONLY","readIds","crmSharingHandler","req","res","method","setHeader","json","scope","action","writer","suiteAct","ok","answer","level","catch","caller","needs","refusal","suite","actor","email","sites","site","siteName","sentence","label","one","many","toLowerCase","type","saved","judged","startedAtMs","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC,GAED,SACEA,eAAe,EACfC,qBAAqB,EAErBC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,SAASC,aAAa,EAAEC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACvF,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC,iBAAiB,EACjBC,mBAAmB,EACnBC,yBAAyB,EACzBC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBAAqB,EAUrBC,oBAAoB,EACpBC,oBAAoB,EACpBC,gBAAgB,EAChBC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,EAChBC,kCAAkC,EAClCC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,sBAAsB,QAAQ,4BAAwB;AAC/D,SAASC,kBAAkB,EAAEC,U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AMiH,KAAK,aAAKjH,KAAKiH,GAAG;gCAAEQ,QAAQ;;6BACvCzH;;YAGV;YACA,MAAMkL,WAAW,MAAM5D,sBAAsBpJ,WAAWJ,OAAOwC,QAAQhC,KAAKC,GAAG,KAAKwK;YACpF,MAAMc,SAA6B;gBAAED,IAAI;gBAAM5J,MAAMkL,SAASlL,IAAI;gBAAE0H,MAAMwD,SAASxD,IAAI;YAAC;YACxF0B,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAACM;YACrB;QACF;QAEAT,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAAC;YAAE9G,OAAO;QAA0B;IAC1D,EAAE,OAAOA,OAAO;QACdC,QAAQD,KAAK,CAAC,wBAAwBgH,QAAQhH;QAC9C2G,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAAC;YAAE9G,OAAO;QAA6C;IAC7E;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-sharing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The server half of CRM sharing (AGL-3336) — see `model/crm-sharing.ts`\n * for the model.\n *\n * Three writers, one transaction shape. A record's sharing is RECOMPUTED,\n * never patched: the transaction reads the record, keeps its hand shares\n * (changed by the caller when the act is a share or an unshare), matches\n * every active rule against it as it stands, and writes `visibleTo`,\n * `writeTo`, `sharing` and the list fields derived from `visibleTo` only\n * when any of them moves. So the same function serves\n *\n * - a manager's share or unshare (`crm/sharing`, `share`/`unshare`);\n * - a write to the record anywhere on the server, through the core's\n * record-written seam (`crmSharingRecordWritten`), and a client-direct\n * write's follow-up (`evaluate`);\n * - a rule's recompute over existing records (`rule-save`, `rule-continue`),\n * and its removal (`rule-delete`), in budgeted passes with the progress on\n * the rule.\n */\n\nimport {\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActivityLink,\n crmListFieldsPatch,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { hostIdsFromScope } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost, logOrgActivity } from '@aglyn/tenant-data-admin'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n activeSharingRules,\n CRM_SHARING_CRITERIA_FOR,\n CRM_SHARING_CRITERIA_KEYS,\n CRM_SHARING_FIELD,\n CRM_SHARING_IDS_MAX,\n CRM_SHARING_OBJECT_LABELS,\n CRM_SHARING_RULE_IDS_PATH,\n CRM_SHARING_RULES_MAX,\n CRM_WRITE_SCOPE_FIELD,\n type CrmShareAccess,\n type CrmShareGrant,\n type CrmSharingContext,\n type CrmSharingCriteria,\n type CrmSharingObject,\n type CrmSharingResponse,\n type CrmSharingRule,\n type CrmSharingRuleRun,\n type CrmSharingSite,\n describeShareTargets,\n evaluateRecordGrants,\n isCrmShareAccess,\n isCrmSharingObject,\n planRecordSharing,\n readCrmSharingRule,\n readCrmSharingRules,\n recordHeldScope,\n sharingPlanChanges,\n shareTargetsFrom,\n sharingRulesAskLeadSourceDirection,\n withManualShares,\n withoutManualShares,\n} from '../model/crm-sharing'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\nimport { crmSettingsPermissionRefusal } from '../model/crm-permissions'\nimport { readLeadSourcePicklist } from './lead-source-picklist'\nimport { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\nimport { authorizeCrmWriter } from './task-routes'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/*==========================================\n * THE RULES, READ OFF THE ORG DOCUMENT.\n *=========================================*/\n\n/**\n * A few seconds of memory per process: every CRM write asks, and an org\n * with no rules should cost it nothing past the first read. A cached list\n * is never the reason a grant is TAKEN away — see `recomputeRecordSharing`.\n */\nconst RULES_TTL_MS = 10_000\nconst rulesCache = new Map<string, { atMs: number; rules: CrmSharingRule[] }>()\n\n/** Test seam, and what a rule write calls so its own process reads it fresh. */\nexport function forgetCrmSharingRules(orgId?: string): void {\n if (orgId) rulesCache.delete(orgId)\n else rulesCache.clear()\n}\n\nexport async function crmSharingRulesOf(\n firestore: Firestore,\n orgId: string,\n options: { fresh?: boolean; nowMs?: number } = {},\n): Promise<{ rules: CrmSharingRule[]; fresh: boolean }> {\n const nowMs = options.nowMs ?? Date.now()\n const cached = rulesCache.get(orgId)\n if (!options.fresh && cached && nowMs - cached.atMs < RULES_TTL_MS) {\n return { rules: cached.rules, fresh: false }\n }\n const snapshot = await firestore.collection('orgs').doc(orgId).get()\n const rules = readCrmSharingRules(snapshot.data() ?? null)\n rulesCache.set(orgId, { atMs: nowMs, rules })\n return { rules, fresh: true }\n}\n\n/**\n * What the rules for `object` are evaluated against beyond the record: the\n * org's Lead source list, read only when an active rule asks a lead source\n * direction (AGL-3511) — an org whose rules never do pays no read for it.\n */\nexport async function crmSharingContextFor(\n firestore: Firestore,\n orgId: string,\n rules: readonly CrmSharingRule[],\n object: CrmSharingObject,\n): Promise<CrmSharingContext> {\n if (!sharingRulesAskLeadSourceDirection(rules, object)) return {}\n return { leadSources: await readLeadSourcePicklist(firestore, orgId) }\n}\n\n/*==========================================\n * ONE RECORD, RECOMPUTED.\n *=========================================*/\n\nexport interface RecomputeRecordSharingInput {\n firestore: Firestore\n orgId: string\n object: CrmSharingObject\n id: string\n /** Every rule the org has, in any state. */\n rules: readonly CrmSharingRule[]\n /** Whether `rules` was read just now; a stale list is re-read before it takes a grant away. */\n fresh: boolean\n /** The hand shares' change, for a share or an unshare. */\n manual?: (grants: Record<string, CrmShareGrant>) => Record<string, CrmShareGrant>\n /** What the rules are evaluated against beyond the record — see {@link crmSharingContextFor}. */\n context?: CrmSharingContext\n atMs: number\n}\n\nexport type RecomputeOutcome = 'changed' | 'unchanged' | 'missing'\n\nexport async function recomputeRecordSharing(\n input: RecomputeRecordSharingInput,\n): Promise<RecomputeOutcome> {\n const { firestore, orgId, object, id, atMs } = input\n const ref = firestore.collection('orgs').doc(orgId).collection(object).doc(id)\n return await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return 'missing' as const\n const record = (snapshot.data() ?? {}) as Record<string, unknown>\n let rules = input.rules\n /*\n * A GRANT IS NEVER TAKEN AWAY ON A STALE ANSWER. A rule grant whose rule\n * the cached list does not name is dropped only once a fresh read of the\n * org agrees: another process may have saved that rule seconds ago and\n * applied it to this very record.\n */\n if (!input.fresh) {\n const known = new Set(rules.map((rule) => rule.id))\n const stored = record[CRM_SHARING_FIELD] as { ruleIds?: unknown } | undefined\n const ruleIds = Array.isArray(stored?.ruleIds) ? (stored.ruleIds as unknown[]) : []\n if (ruleIds.some((ruleId) => !known.has(String(ruleId)))) {\n const org = await tx.get(firestore.collection('orgs').doc(orgId))\n rules = readCrmSharingRules(org.data() ?? null)\n }\n }\n // A rule read afresh above may ask a direction the caller's context was not read for.\n const context =\n input.context?.leadSources || rules === input.rules\n ? input.context\n : await crmSharingContextFor(firestore, orgId, rules, object)\n let grants = evaluateRecordGrants(object, record, rules, atMs, context)\n if (input.manual) grants = input.manual(grants)\n const plan = planRecordSharing(record, grants)\n if (!sharingPlanChanges(record, plan)) return 'unchanged' as const\n const next = {\n ...record,\n visibleTo: plan.visibleTo,\n [CRM_WRITE_SCOPE_FIELD]: plan.writeTo ?? undefined,\n [CRM_SHARING_FIELD]: plan.sharing ?? undefined,\n }\n tx.update(ref, {\n visibleTo: plan.visibleTo,\n [CRM_WRITE_SCOPE_FIELD]: plan.writeTo ?? FieldValue.delete(),\n [CRM_SHARING_FIELD]: plan.sharing ?? FieldValue.delete(),\n // The scoped list fields are derived from `visibleTo` (AGL-3321), so a\n // target site's folded search finds the record the moment it can see it.\n ...crmListFieldsPatch(object, next),\n })\n return 'changed' as const\n })\n}\n\n/** Several records at once, a few in flight. */\nasync function recomputeMany(\n input: Omit<RecomputeRecordSharingInput, 'id'>,\n ids: readonly string[],\n): Promise<{ changed: string[]; missing: number }> {\n const queue = [...new Set(ids)]\n const changed: string[] = []\n let missing = 0\n const worker = async () => {\n for (let id = queue.shift(); id !== undefined; id = queue.shift()) {\n const outcome = await recomputeRecordSharing({ ...input, id })\n if (outcome === 'changed') changed.push(id)\n if (outcome === 'missing') missing += 1\n }\n }\n await Promise.all(Array.from({ length: Math.min(8, queue.length) }, worker))\n return { changed, missing }\n}\n\n/**\n * Re-evaluates the org's rules for these records — the one thing a write\n * anywhere owes the sharing. An org with no active rule for the object\n * costs one cached read and nothing else; grants of a rule switched off\n * are taken away by that rule's own removal pass, not here.\n */\nexport async function evaluateCrmSharing(\n firestore: Firestore,\n orgId: string,\n object: CrmSharingObject,\n ids: readonly string[],\n): Promise<{ changed: number; missing: number }> {\n const { rules, fresh } = await crmSharingRulesOf(firestore, orgId)\n if (!activeSharingRules(rules, object).length) return { changed: 0, missing: 0 }\n const context = await crmSharingContextFor(firestore, orgId, rules, object)\n const outcome = await recomputeMany(\n { firestore, orgId, object, rules, fresh, context, atMs: Date.now() },\n ids,\n )\n return { changed: outcome.changed.length, missing: outcome.missing }\n}\n\n/**\n * The core's record-written seam (AGL-3336): every server writer of a lead,\n * a contact, a company or a deal restamps it, and the restamp tells this.\n * Never throws — the write it is told about already landed.\n */\nexport async function crmSharingRecordWritten(event: {\n path: string\n collection: string\n}): Promise<void> {\n if (!isCrmSharingObject(event.collection)) return\n const segments = event.path.split('/')\n if (segments.length !== 4 || segments[0] !== 'orgs' || segments[2] !== event.collection) return\n try {\n await evaluateCrmSharing(\n firebaseAdmin.app().firestore(),\n segments[1],\n event.collection,\n [segments[3]],\n )\n } catch (error) {\n console.error(`[crm] sharing rules could not be evaluated for ${event.path}`, error)\n }\n}\n\n/*==========================================\n * THE AUDIT: a line on the record, a line in the org's feed.\n *=========================================*/\n\nconst LINK_FIELD: Readonly<Record<CrmSharingObject, keyof CrmActivityLink>> = {\n leads: 'leadId',\n contacts: 'contactId',\n companies: 'companyId',\n deals: 'dealId',\n}\n\nconst ORG_TARGET: Readonly<Record<CrmSharingObject, 'lead' | 'contact' | 'company' | 'deal'>> = {\n leads: 'lead',\n contacts: 'contact',\n companies: 'company',\n deals: 'deal',\n}\n\n/**\n * The entry on the record's Activity: who shared it with which sites, or\n * took a share away. Visible to the sites that hold the record and to the\n * sites it names, so both sides of a share read how it came about.\n */\nasync function fileSharingActivity(\n firestore: Firestore,\n input: {\n orgId: string\n object: CrmSharingObject\n id: string\n body: string\n targets: readonly string[]\n by: { uid: string; name: string }\n atMs: number\n },\n): Promise<void> {\n try {\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const record = (await orgRef.collection(input.object).doc(input.id).get()).data() ?? {}\n const held = recordHeldScope(record)\n const visibleTo = [...new Set([...held, ...input.targets])]\n if (!visibleTo.length) return\n const named: CrmActivityLink = { [LINK_FIELD[input.object]]: input.id }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, named))) return\n // The record just read is the deal or the contact the entry rolls up from.\n const link = stampCrmActivityCompany(named, {\n ...(input.object === 'deals' ? { deal: record } : {}),\n ...(input.object === 'contacts' ? { contact: record } : {}),\n })\n const hostId =\n typeof record['hostId'] === 'string' && record['hostId']\n ? record['hostId']\n : (hostIdsFromScope(held)[0] ?? '')\n await orgRef\n .collection(CRM_COLLECTIONS.activities)\n .doc(createResourceUid())\n .create({\n kind: 'note',\n body: input.body,\n atMs: input.atMs,\n byUid: input.by.uid,\n ...(input.by.name ? { byName: input.by.name } : {}),\n ...link,\n hostId,\n visibleTo,\n sourcePluginId: BUNDLE_ID,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n } catch (error) {\n console.error('[crm] the sharing entry could not be written on the record', input.id, error)\n }\n}\n\n/*==========================================\n * THE ORG'S SITES.\n *=========================================*/\n\nexport async function crmSharingSites(firestore: Firestore, orgId: string): Promise<CrmSharingSite[]> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).get()\n return hosts.docs\n .map((doc) => {\n const displayName = String(doc.get('displayName') ?? '').trim()\n const subdomain = String(doc.get('subdomain') ?? '').trim()\n return { id: String(doc.id), name: displayName || subdomain || String(doc.id) }\n })\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\n/*==========================================\n * A RULE, SAVED FROM A REQUEST.\n *=========================================*/\n\nfunction listFrom(raw: unknown, max: number): string[] {\n if (!Array.isArray(raw)) return []\n return [\n ...new Set(\n raw.map((entry) => String(entry ?? '').trim().slice(0, 200)).filter(Boolean),\n ),\n ].slice(0, max)\n}\n\n/**\n * The rule a request describes, judged: an object, a name, sites that are\n * the org's own, targets that are the org's own or all sites. `null` with\n * the reason when it cannot be saved.\n */\nexport function ruleFromRequest(\n raw: unknown,\n context: { hostIds: readonly string[]; existing: CrmSharingRule | null; uid: string; nowMs: number },\n): { rule: CrmSharingRule; error: null } | { rule: null; error: string } {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return { rule: null, error: 'Describe the rule.' }\n }\n const value = raw as Record<string, unknown>\n const object = value['object']\n if (!isCrmSharingObject(object)) {\n return { rule: null, error: 'Choose which records the rule shares.' }\n }\n const name = String(value['name'] ?? '').trim().slice(0, 120)\n if (!name) return { rule: null, error: 'Name the rule.' }\n const own = new Set(context.hostIds)\n const sourceHostIds = listFrom(value['sourceHostIds'], 30)\n if (sourceHostIds.some((id) => !own.has(id))) {\n return { rule: null, error: 'A site the rule names is not one of this organization’s.' }\n }\n const targets = shareTargetsFrom(value['targets'])\n if (!targets) return { rule: null, error: 'Choose the sites to share with, or All sites.' }\n if (hostIdsFromScope(targets).some((id) => !own.has(id))) {\n return { rule: null, error: 'A site the rule shares with is not one of this organization’s.' }\n }\n const access = value['access']\n if (access !== undefined && !isCrmShareAccess(access)) {\n return { rule: null, error: 'Access is read-only, or read and edit.' }\n }\n const rawCriteria = (value['criteria'] ?? {}) as Record<string, unknown>\n const criteria: CrmSharingCriteria = {}\n for (const key of CRM_SHARING_CRITERIA_KEYS) {\n if (!CRM_SHARING_CRITERIA_FOR[object].includes(key)) continue\n const list = listFrom(rawCriteria[key], 20)\n if (list.length) criteria[key] = list\n }\n const existing = context.existing\n const rule = readCrmSharingRule({\n id: existing?.id ?? createResourceUid(),\n name,\n object,\n enabled: value['enabled'] !== false,\n sourceHostIds,\n criteria,\n targets,\n access: (access as CrmShareAccess | undefined) ?? 'read',\n createdByUid: existing?.createdByUid ?? context.uid,\n createdAtMs: existing?.createdAtMs ?? context.nowMs,\n updatedAtMs: context.nowMs,\n })\n if (!rule) return { rule: null, error: 'The rule could not be read.' }\n return { rule, error: null }\n}\n\n/** A rule as the org document stores it — no `undefined` anywhere. */\nfunction storedRule(rule: CrmSharingRule): Record<string, unknown> {\n return JSON.parse(JSON.stringify(rule)) as Record<string, unknown>\n}\n\n/**\n * Writes the org's rule list through `change`, in a transaction over the org\n * document, and answers the list as written.\n */\nasync function writeRules(\n firestore: Firestore,\n orgId: string,\n change: (rules: CrmSharingRule[]) => CrmSharingRule[] | { error: string },\n): Promise<{ rules: CrmSharingRule[]; error: null } | { rules: null; error: string }> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const result = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n const next = change(readCrmSharingRules(snapshot.data() ?? null))\n if ('error' in next) return { rules: null, error: next.error }\n tx.update(orgRef, new FieldPath('crm', 'sharingRules'), next.map(storedRule))\n return { rules: next, error: null }\n })\n forgetCrmSharingRules(orgId)\n return result as { rules: CrmSharingRule[]; error: null } | { rules: null; error: string }\n}\n\n/** Replaces one rule's run, leaving every other rule as it is. */\nasync function writeRun(\n firestore: Firestore,\n orgId: string,\n ruleId: string,\n run: CrmSharingRuleRun,\n options: { dropRule?: boolean } = {},\n): Promise<CrmSharingRule | null> {\n const written = await writeRules(firestore, orgId, (rules) =>\n options.dropRule\n ? rules.filter((rule) => rule.id !== ruleId)\n : rules.map((rule) => (rule.id === ruleId ? { ...rule, run } : rule)),\n )\n return written.rules?.find((rule) => rule.id === ruleId) ?? null\n}\n\n/*==========================================\n * A RULE'S RUN: apply it everywhere, or take it away.\n *=========================================*/\n\nconst RUN_PAGE = 200\n\n/**\n * One budgeted pass of a rule's run, with the progress written on the rule\n * after every page so a reopened settings page shows where it stands and\n * `rule-continue` picks up from the cursor.\n *\n * `apply` walks the object's whole collection by document id — a rule\n * matches on fields no index narrows to (a facet's tags, a site that\n * captured the person) — and writes only the records whose sharing moves.\n * `remove` asks for exactly the records the rule holds a grant on\n * (`sharing.ruleIds`), each of which the recompute then takes it off; a\n * page that makes no progress fails the run rather than looping.\n */\nexport async function advanceSharingRuleRun(\n firestore: Firestore,\n orgId: string,\n ruleId: string,\n deadlineMs: number,\n): Promise<{ rule: CrmSharingRule | null; more: boolean }> {\n const read = await crmSharingRulesOf(firestore, orgId, { fresh: true })\n let rule = read.rules.find((entry) => entry.id === ruleId) ?? null\n if (!rule?.run || rule.run.status !== 'running') return { rule, more: false }\n const records = firestore.collection('orgs').doc(orgId).collection(rule.object)\n let run: CrmSharingRuleRun = { ...rule.run }\n const seen = new Set<string>()\n try {\n while (Date.now() < deadlineMs) {\n const { rules } = await crmSharingRulesOf(firestore, orgId, { fresh: true })\n const context = await crmSharingContextFor(firestore, orgId, rules, rule.object)\n let page: FirebaseFirestore.QuerySnapshot\n if (run.mode === 'apply') {\n let query = records.orderBy(FieldPath.documentId()).limit(RUN_PAGE)\n if (run.cursor) query = query.startAfter(run.cursor)\n page = await query.get()\n } else {\n page = await records.where(CRM_SHARING_RULE_IDS_PATH, 'array-contains', ruleId).limit(RUN_PAGE).get()\n }\n const atMs = Date.now()\n // Only the records whose sharing would move are written.\n const moving = page.docs\n .filter((doc) => {\n const record = (doc.data() ?? {}) as Record<string, unknown>\n const plan = planRecordSharing(\n record,\n evaluateRecordGrants(rule!.object, record, rules, atMs, context),\n )\n return sharingPlanChanges(record, plan)\n })\n .map((doc) => doc.id)\n if (run.mode === 'remove' && page.docs.length && page.docs.every((doc) => seen.has(doc.id))) {\n throw new Error('the rule’s grants did not come off these records')\n }\n for (const doc of page.docs) seen.add(doc.id)\n const outcome = await recomputeMany(\n { firestore, orgId, object: rule.object, rules, fresh: true, context, atMs },\n moving,\n )\n const done = run.mode === 'apply' ? page.size < RUN_PAGE : page.empty\n run = {\n ...run,\n processed: run.processed + page.size,\n changed: run.changed + outcome.changed.length,\n cursor: run.mode === 'apply' ? (page.docs[page.docs.length - 1]?.id ?? run.cursor ?? null) : null,\n ...(done ? { status: 'done' as const, finishedAtMs: Date.now() } : {}),\n }\n rule = await writeRun(firestore, orgId, ruleId, run, {\n dropRule: done && rule.deleting === true,\n })\n if (done || !rule) return { rule, more: false }\n }\n return { rule, more: true }\n } catch (error) {\n console.error('[crm] a sharing rule run failed', orgId, ruleId, error)\n rule = await writeRun(firestore, orgId, ruleId, {\n ...run,\n status: 'failed',\n finishedAtMs: Date.now(),\n error: 'The recompute stopped. Resume it to carry on from where it stopped.',\n })\n return { rule, more: false }\n }\n}\n\n/*==========================================\n * THE ROUTE.\n *=========================================*/\n\n/** How long one request works on a rule before it answers and the page asks again. */\nconst RUN_BUDGET_MS = 20_000\n\n/** Names the permission, never a role (AGL-4047). */\nconst MANAGERS_ONLY = crmSettingsPermissionRefusal()\n\nfunction readIds(raw: unknown): string[] | null {\n if (!Array.isArray(raw)) return null\n const ids = [\n ...new Set(\n raw.map((entry) => String(entry ?? '').trim().slice(0, 256)).filter((id) => id && !id.includes('/')),\n ),\n ].slice(0, CRM_SHARING_IDS_MAX)\n return ids.length ? ids : null\n}\n\n/**\n * `POST /api/crm/sharing` — `{ action, hostId | orgId, … }`.\n *\n * Every action but `evaluate` asks \"Change CRM settings\" over the whole\n * workspace (`authorizeOrgCaller(…, 'crm.settings')`, AGL-4047; owners and\n * admins by default), under a site's hub or the org's. `evaluate` is what a\n * client-direct write owes the rules and is open to whoever may write the\n * CRM. The plan gate is the CRM's own\n * (`crmSuiteRefusal`): sharing is only meaningful across several sites, and\n * the number of sites a workspace may have is already the plan's.\n */\nexport const crmSharingHandler: 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 body = (req.body ?? {}) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const action = String(body['action'] ?? '')\n const firestore = firebaseAdmin.app().firestore()\n try {\n if (action === 'evaluate') {\n const object = body['object']\n const ids = readIds(body['ids'])\n if (!isCrmSharingObject(object) || !ids) {\n res.status(400).json({ error: 'Name the records.' })\n return\n }\n const writer = await authorizeCrmWriter(req, scope, { suiteAct: null })\n if (writer.ok === false) {\n res.status(writer.status).json(writer.body)\n return\n }\n const outcome = await evaluateCrmSharing(firestore, writer.orgId, object, ids)\n const answer: CrmSharingResponse = { ok: true, ...outcome }\n res.status(200).json(answer)\n return\n }\n\n const orgId =\n scope.level === 'org'\n ? scope.orgId\n : ((await getOrgForHost(scope.hostId).catch(() => null))?.orgId ?? '')\n if (!orgId) {\n res.status(404).json({ error: 'This site has no organization, so it has no CRM.' })\n return\n }\n const caller = await authorizeOrgCaller(req, orgId, {\n needs: 'crm.settings',\n refusal: MANAGERS_ONLY,\n })\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n const suite = crmSuiteRefusal(caller.org, 'Sharing records across sites')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const actor = { uid: caller.uid, email: caller.email }\n const byName = caller.name || caller.email || ''\n const nowMs = Date.now()\n\n if (action === 'sites') {\n const answer: CrmSharingResponse = { ok: true, sites: await crmSharingSites(firestore, orgId) }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'share' || action === 'unshare') {\n const object = body['object']\n const ids = readIds(body['ids'])\n if (!isCrmSharingObject(object) || !ids) {\n res.status(400).json({ error: 'Name the records to share.' })\n return\n }\n const targets = shareTargetsFrom(body['targets'])\n if (!targets) {\n res.status(400).json({ error: 'Choose the sites, or All sites.' })\n return\n }\n const sites = await crmSharingSites(firestore, orgId)\n const own = new Set(sites.map((site) => site.id))\n if (hostIdsFromScope(targets).some((id) => !own.has(id))) {\n res.status(400).json({ error: 'A site named is not one of this organization’s.' })\n return\n }\n const access: CrmShareAccess = body['access'] === 'edit' ? 'edit' : 'read'\n const { rules, fresh } = await crmSharingRulesOf(firestore, orgId)\n const context = await crmSharingContextFor(firestore, orgId, rules, object)\n const outcome = await recomputeMany(\n {\n firestore,\n orgId,\n object,\n rules,\n fresh,\n context,\n atMs: nowMs,\n manual: (grants) =>\n action === 'share'\n ? withManualShares(grants, targets, access, { uid: caller.uid, name: byName }, nowMs)\n : withoutManualShares(grants, targets),\n },\n ids,\n )\n const siteName = (id: string) => sites.find((site) => site.id === id)?.name ?? 'a site'\n const named = describeShareTargets(targets, siteName)\n const sentence =\n action === 'share'\n ? `Shared with ${named}${access === 'edit' ? ' (read and edit)' : ' (read-only)'}`\n : `Stopped sharing with ${named}`\n await Promise.all(\n outcome.changed.map((id) =>\n fileSharingActivity(firestore, {\n orgId,\n object,\n id,\n body: sentence,\n targets,\n by: { uid: caller.uid, name: byName },\n atMs: nowMs,\n }),\n ),\n )\n if (outcome.changed.length) {\n const label = CRM_SHARING_OBJECT_LABELS[object]\n await logOrgActivity(\n orgId,\n actor,\n outcome.changed.length === 1\n ? `${sentence}: one ${label.one}`\n : `${sentence}: ${outcome.changed.length} ${label.many.toLowerCase()}`,\n {\n type: ORG_TARGET[object],\n ...(outcome.changed.length === 1 ? { id: outcome.changed[0] } : {}),\n },\n ).catch(() => undefined)\n }\n const answer: CrmSharingResponse = {\n ok: true,\n changed: outcome.changed.length,\n missing: outcome.missing,\n }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'rule-save') {\n const hostIds = await orgHostIds(firestore, orgId)\n const raw = body['rule']\n const ruleId = raw && typeof raw === 'object' ? String((raw as Record<string, unknown>)['id'] ?? '') : ''\n let saved: CrmSharingRule | null = null\n let error: string | null = null\n const written = await writeRules(firestore, orgId, (rules) => {\n const existing = ruleId ? (rules.find((rule) => rule.id === ruleId) ?? null) : null\n if (ruleId && !existing) return { error: 'That rule no longer exists.' }\n if (existing?.deleting) return { error: 'That rule is being deleted.' }\n if (!existing && rules.length >= CRM_SHARING_RULES_MAX) {\n return { error: `A workspace keeps at most ${CRM_SHARING_RULES_MAX} sharing rules.` }\n }\n const judged = ruleFromRequest(raw, { hostIds, existing, uid: caller.uid, nowMs })\n if (!judged.rule) {\n error = judged.error\n return { error: judged.error }\n }\n /*\n * An enabled rule walks every record — it may now match some and not\n * others. A disabled one only has grants to take away, and asks for\n * exactly the records holding them.\n */\n saved = {\n ...judged.rule,\n run: {\n status: 'running',\n mode: judged.rule.enabled ? 'apply' : 'remove',\n processed: 0,\n changed: 0,\n cursor: null,\n startedAtMs: nowMs,\n },\n }\n return existing\n ? rules.map((rule) => (rule.id === existing.id ? saved! : rule))\n : [...rules, saved]\n })\n if (!written.rules || !saved) {\n res.status(400).json({ error: error ?? written.error ?? 'The rule could not be saved.' })\n return\n }\n const rule = saved as CrmSharingRule\n await logOrgActivity(\n orgId,\n actor,\n `${ruleId ? 'Changed' : 'Added'} the sharing rule “${rule.name}”`,\n { type: `${BUNDLE_ID}:sharingRule`, id: rule.id, name: rule.name },\n ).catch(() => undefined)\n const advanced = await advanceSharingRuleRun(firestore, orgId, rule.id, Date.now() + RUN_BUDGET_MS)\n const answer: CrmSharingResponse = { ok: true, rule: advanced.rule, more: advanced.more }\n res.status(200).json(answer)\n return\n }\n\n if (action === 'rule-delete' || action === 'rule-continue') {\n const ruleId = String(body['ruleId'] ?? '').trim()\n if (!ruleId) {\n res.status(400).json({ error: 'Name the rule.' })\n return\n }\n if (action === 'rule-delete') {\n let name = ''\n const written = await writeRules(firestore, orgId, (rules) => {\n const existing = rules.find((rule) => rule.id === ruleId)\n if (!existing) return { error: 'That rule no longer exists.' }\n name = existing.name\n return rules.map((rule) =>\n rule.id === ruleId\n ? {\n ...rule,\n enabled: false,\n deleting: true,\n updatedAtMs: nowMs,\n run: {\n status: 'running' as const,\n mode: 'remove' as const,\n processed: 0,\n changed: 0,\n cursor: null,\n startedAtMs: nowMs,\n },\n }\n : rule,\n )\n })\n if (!written.rules) {\n res.status(404).json({ error: written.error })\n return\n }\n await logOrgActivity(orgId, actor, `Deleted the sharing rule “${name}”`, {\n type: `${BUNDLE_ID}:sharingRule`,\n id: ruleId,\n name,\n }).catch(() => undefined)\n } else {\n // A failed run resumes from its cursor.\n await writeRules(firestore, orgId, (rules) =>\n rules.map((rule) =>\n rule.id === ruleId && rule.run?.status === 'failed'\n ? { ...rule, run: { ...rule.run, status: 'running' as const } }\n : rule,\n ),\n )\n }\n const advanced = await advanceSharingRuleRun(firestore, orgId, ruleId, Date.now() + RUN_BUDGET_MS)\n const answer: CrmSharingResponse = { ok: true, rule: advanced.rule, more: advanced.more }\n res.status(200).json(answer)\n return\n }\n\n res.status(400).json({ error: 'Unknown sharing action.' })\n } catch (error) {\n console.error('[crm] sharing failed', action, error)\n res.status(500).json({ error: 'The sharing could not be saved. Try again.' })\n }\n}\n\n"],"names":["CRM_COLLECTIONS","crmActivityLogHasRoom","crmListFieldsPatch","createResourceUid","hostIdsFromScope","firebaseAdmin","getOrgForHost","logOrgActivity","countCrmActivitiesForRecord","FieldPath","FieldValue","BUNDLE_ID","activeSharingRules","CRM_SHARING_CRITERIA_FOR","CRM_SHARING_CRITERIA_KEYS","CRM_SHARING_FIELD","CRM_SHARING_IDS_MAX","CRM_SHARING_OBJECT_LABELS","CRM_SHARING_RULE_IDS_PATH","CRM_SHARING_RULES_MAX","CRM_WRITE_SCOPE_FIELD","describeShareTargets","evaluateRecordGrants","isCrmShareAccess","isCrmSharingObject","planRecordSharing","readCrmSharingRule","readCrmSharingRules","recordHeldScope","sharingPlanChanges","shareTargetsFrom","sharingRulesAskLeadSourceDirection","withManualShares","withoutManualShares","stampCrmActivityCompany","crmSettingsPermissionRefusal","readLeadSourcePicklist","authorizeOrgCaller","orgHostIds","readCrmRouteScope","crmSuiteRefusal","authorizeCrmWriter","RULES_TTL_MS","rulesCache","Map","forgetCrmSharingRules","orgId","delete","clear","crmSharingRulesOf","firestore","options","snapshot","nowMs","Date","now","cached","get","fresh","atMs","rules","collection","doc","data","set","crmSharingContextFor","object","leadSources","recomputeRecordSharing","input","id","ref","runTransaction","tx","plan","exists","record","known","Set","map","rule","stored","ruleIds","Array","isArray","some","ruleId","has","String","org","context","grants","manual","next","visibleTo","writeTo","undefined","sharing","update","recomputeMany","ids","queue","changed","missing","worker","shift","outcome","push","Promise","all","from","length","Math","min","evaluateCrmSharing","crmSharingRecordWritten","event","segments","path","split","app","error","console","LINK_FIELD","leads","contacts","companies","deals","ORG_TARGET","fileSharingActivity","orgRef","held","targets","named","link","deal","contact","hostId","activities","create","kind","body","byUid","by","uid","name","byName","sourcePluginId","createdAt","serverTimestamp","updatedAt","crmSharingSites","hosts","where","docs","displayName","trim","subdomain","sort","a","b","localeCompare","listFrom","raw","max","entry","slice","filter","Boolean","ruleFromRequest","value","own","hostIds","sourceHostIds","access","rawCriteria","criteria","key","includes","list","existing","enabled","createdByUid","createdAtMs","updatedAtMs","storedRule","JSON","parse","stringify","writeRules","change","result","writeRun","run","written","dropRule","find","RUN_PAGE","advanceSharingRuleRun","deadlineMs","read","status","more","records","seen","page","mode","query","orderBy","documentId","limit","cursor","startAfter","moving","every","Error","add","done","size","empty","processed","finishedAtMs","deleting","RUN_BUDGET_MS","MANAGERS_ONLY","readIds","crmSharingHandler","req","res","method","setHeader","json","scope","action","writer","suiteAct","ok","answer","level","catch","caller","needs","refusal","suite","actor","email","sites","site","siteName","sentence","label","one","many","toLowerCase","type","saved","judged","startedAtMs","advanced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC,GAED,SACEA,eAAe,EACfC,qBAAqB,EAErBC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,SAASC,aAAa,EAAEC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACvF,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC,iBAAiB,EACjBC,mBAAmB,EACnBC,yBAAyB,EACzBC,yBAAyB,EACzBC,qBAAqB,EACrBC,qBAAqB,EAUrBC,oBAAoB,EACpBC,oBAAoB,EACpBC,gBAAgB,EAChBC,kBAAkB,EAClBC,iBAAiB,EACjBC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,EAChBC,kCAAkC,EAClCC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,4BAA4B,QAAQ,8BAA0B;AACvE,SAASC,sBAAsB,QAAQ,4BAAwB;AAC/D,SAASC,kBAAkB,EAAEC,UAAU,EAAEC,iBAAiB,QAAQ,kBAAc;AAChF,SAASC,eAAe,QAAQ,kBAAc;AAC9C,SAASC,kBAAkB,QAAQ,mBAAe;AAIlD;;2CAE2C,GAE3C;;;;CAIC,GACD,MAAMC,eAAe;AACrB,MAAMC,aAAa,IAAIC;AAEvB,8EAA8E,GAC9E,OA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B;gBAAED,IAAI;gBAAM5J,MAAMkL,SAASlL,IAAI;gBAAE0H,MAAMwD,SAASxD,IAAI;YAAC;YACxF0B,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAACM;YACrB;QACF;QAEAT,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAAC;YAAE9G,OAAO;QAA0B;IAC1D,EAAE,OAAOA,OAAO;QACdC,QAAQD,KAAK,CAAC,wBAAwBgH,QAAQhH;QAC9C2G,IAAI3B,MAAM,CAAC,KAAK8B,IAAI,CAAC;YAAE9G,OAAO;QAA6C;IAC7E;AACF,EAAC"}
@@ -25,12 +25,13 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
25
25
  * owner. The listing's ceiling refuses a copy the way the create drawer
26
26
  * refuses a new one.
27
27
  *
28
- * Reached from a site — the host role decides — or from the organization
28
+ * Reached from a site — "Edit site content" decides — or from the organization
29
29
  * hub, where an org-wide seat does. Both scopes land in the same
30
30
  * collection, so the copy is looked up where the source was found.
31
- */ import { DUPLICATE_BUSY_MESSAGE, duplicateDisplayName, uniqueDuplicateName } from "@aglyn/aglyn/app-utils/duplicate-resource";
31
+ */ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
32
+ import { DUPLICATE_BUSY_MESSAGE, duplicateDisplayName, uniqueDuplicateName } from "@aglyn/aglyn/app-utils/duplicate-resource";
32
33
  import { CRM_EMAIL_TEMPLATES_LIMIT, CRM_EMAIL_TEMPLATE_NAME_MAX, normalizeCrmEmailTemplate } from "@aglyn/aglyn/app-utils/crm-email-templates";
33
- import { claimAttempt, createResourceUid, hostRoleCanWrite } from "@aglyn/aglyn/server";
34
+ import { claimAttempt, createResourceUid } from "@aglyn/aglyn/server";
34
35
  import { firebaseAdmin, logResourceDuplicated, resolveOrgIdForHost } from "@aglyn/tenant-data-admin";
35
36
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
36
37
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
@@ -80,15 +81,14 @@ export const crmEmailTemplateDuplicateHandler = async (req, res)=>{
80
81
  // seat is more generous than it is in the one that owns the site.
81
82
  let orgId = scope.orgId;
82
83
  if (scope.level === 'site') {
83
- var _host_get, _ref3;
84
+ var _ref3;
84
85
  const host = await firestore.collection('hosts').doc(scope.hostId).get();
85
86
  if (!host.exists) return res.status(404).json({
86
87
  error: 'Unknown site'
87
88
  });
88
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[decoded.uid];
89
- if (!staff && !hostRoleCanWrite(role)) {
89
+ if (!staff && !holdsSiteKey(host, decoded.uid, 'site.edit')) {
90
90
  return res.status(403).json({
91
- error: 'Editing requires the editor role'
91
+ error: siteKeyRefusal('site.edit')
92
92
  });
93
93
  }
94
94
  orgId = (_ref3 = await resolveOrgIdForHost(scope.hostId)) != null ? _ref3 : '';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/email-template-duplicate.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 * Duplicating a CRM email template (AGL-2936).\n *\n * A template is a letter under a name — subject, body, merge fields — in\n * `crmEmailTemplates` under the organization, scoped to a site or shared\n * across the workspace by the tokens it carries. The copy keeps the letter,\n * the kind and the scope; it is filed under the person copying it, and a\n * personal template stays personal to THEM rather than to the original's\n * owner. The listing's ceiling refuses a copy the way the create drawer\n * refuses a new one.\n *\n * Reached from a site — the host role decides — or from the organization\n * hub, where an org-wide seat does. Both scopes land in the same\n * collection, so the copy is looked up where the source was found.\n */\n\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport {\n CRM_EMAIL_TEMPLATES_LIMIT,\n CRM_EMAIL_TEMPLATE_NAME_MAX,\n normalizeCrmEmailTemplate,\n} from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport {\n claimAttempt,\n createResourceUid,\n hostRoleCanWrite,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n logResourceDuplicated,\n resolveOrgIdForHost,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { readCrmRouteScope } from './org-caller'\n\nexport const CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE = 'crm/email-template-duplicate'\n\nexport const crmEmailTemplateDuplicateHandler: 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 const scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (!scope) return res.status(400).json({ error: 'Missing hostId or orgId' })\n const templateId = String(req.body?.templateId ?? '').trim().slice(0, 64)\n if (!templateId) return res.status(400).json({ error: 'Missing templateId' })\n const requestedName = String(req.body?.name ?? '').trim().slice(0, CRM_EMAIL_TEMPLATE_NAME_MAX)\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\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 res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n if (isRefusedIdToken(error)) return res.status(401).json({ error: 'Unauthenticated' })\n throw error\n }\n const firestore = firebaseAdmin.app().firestore()\n const staff = decoded.staff === true\n\n // WHO MAY COPY: on a site, anyone who may write its content; from the\n // hub, an org-wide seat. The org is resolved from the site rather than\n // taken from the body, so a caller cannot name a workspace where their\n // seat is more generous than it is in the one that owns the site.\n let orgId = scope.orgId\n if (scope.level === 'site') {\n const host = await firestore.collection('hosts').doc(scope.hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const role = (host.get('memberRoles') ?? {})[decoded.uid]\n if (!staff && !hostRoleCanWrite(role)) {\n return res.status(403).json({ error: 'Editing requires the editor role' })\n }\n orgId = (await resolveOrgIdForHost(scope.hostId)) ?? ''\n } else if (!staff) {\n const membership = await resolveOrgPermissions(decoded.uid, { orgId }).catch(\n () => null,\n )\n if (!membership?.orgWide || membership.orgId !== orgId) {\n return res.status(403).json({ error: 'Not a member of this organization' })\n }\n }\n if (!orgId) return res.status(404).json({ error: 'Unknown organization' })\n\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-emailTemplate',\n scopeId: `${orgId}:${templateId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n\n const templates = firestore\n .collection('orgs')\n .doc(orgId)\n .collection(CRM_COLLECTIONS.emailTemplates)\n const id = createResourceUid()\n const outcome = await firestore.runTransaction(async (transaction) => {\n const [source, siblings] = await Promise.all([\n transaction.get(templates.doc(templateId)),\n transaction.get(templates.select('name')),\n ])\n if (!source.exists) {\n return { status: 404 as const, body: { error: 'Unknown template' } }\n }\n if (siblings.size >= CRM_EMAIL_TEMPLATES_LIMIT) {\n return {\n status: 403 as const,\n body: {\n error:\n `This workspace holds ${CRM_EMAIL_TEMPLATES_LIMIT} email templates — ` +\n 'delete one to make room',\n },\n }\n }\n const template = normalizeCrmEmailTemplate(source.data() as Record<string, unknown>)\n const name = uniqueDuplicateName(\n requestedName || duplicateDisplayName(template.name),\n siblings.docs.map((row) => String(row.get('name') ?? '')),\n ).slice(0, CRM_EMAIL_TEMPLATE_NAME_MAX)\n const nowMs = Date.now()\n transaction.create(templates.doc(id), {\n name,\n subject: template.subject,\n body: template.body,\n kind: template.kind,\n visibility: template.visibility,\n ...(template.visibility === 'personal' ? { ownerUid: decoded.uid } : {}),\n createdByUid: decoded.uid,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n hostId: template.hostId,\n visibleTo: [...template.visibleTo],\n createdAt: new Date(nowMs),\n updatedAt: new Date(nowMs),\n })\n return {\n status: 200 as const,\n body: { templateId: id, name },\n sourceName: template.name,\n hostId: template.hostId,\n }\n })\n\n if (outcome.status !== 200) {\n await claim?.release()\n return res.status(outcome.status).json(outcome.body)\n }\n await logResourceDuplicated(\n 'emailTemplate',\n { uid: decoded.uid, email: decoded.email ?? null },\n {\n orgId,\n hostId: outcome.hostId,\n source: { id: templateId, name: outcome.sourceName },\n target: { id, name: outcome.body.name },\n },\n )\n await claim?.record(200, outcome.body)\n return res.status(200).json(outcome.body)\n } catch (error) {\n console.error('[crm] the email template could not be duplicated', error)\n return res.status(500).json({ error: 'The template could not be duplicated.' })\n }\n}\n"],"names":["DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","CRM_EMAIL_TEMPLATES_LIMIT","CRM_EMAIL_TEMPLATE_NAME_MAX","normalizeCrmEmailTemplate","claimAttempt","createResourceUid","hostRoleCanWrite","firebaseAdmin","logResourceDuplicated","resolveOrgIdForHost","isRefusedIdToken","resolveOrgPermissions","CRM_COLLECTIONS","readCrmRouteScope","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","req","res","method","setHeader","status","json","error","scope","body","templateId","String","trim","slice","requestedName","name","attemptKey","authorization","headers","idToken","startsWith","length","undefined","decoded","app","auth","verifyIdToken","firestore","staff","orgId","level","host","collection","doc","hostId","get","exists","role","uid","membership","catch","orgWide","claimed","kind","scopeId","key","busyMessage","replay","claim","templates","emailTemplates","id","outcome","runTransaction","transaction","source","siblings","Promise","all","select","size","template","data","docs","map","row","nowMs","Date","now","create","subject","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","visibleTo","createdAt","updatedAt","sourceName","release","email","target","record","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SACEA,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,yBAAyB,QACpB,6CAA4C;AACnD,SACEC,YAAY,EACZC,iBAAiB,EACjBC,gBAAgB,QAEX,sBAAqB;AAC5B,SACEC,aAAa,EACbC,qBAAqB,EACrBC,mBAAmB,QACd,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,iBAAiB,QAAQ,kBAAc;AAEhD,OAAO,MAAMC,qCAAqC,+BAA8B;AAEhF,OAAO,MAAMC,mCAAqD,OAAOC,KAAKC;4BAY/CD;QALHA,WAEGA,YACHA;IAT1B,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzBD,IAAIE,SAAS,CAAC,SAAS;QACvB,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,QAAQV,kBAAkBG,IAAIQ,IAAI;IACxC,IAAI,CAACD,OAAO,OAAON,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;IAA0B;IAC3E,MAAMG,aAAaC,gBAAOV,YAAAA,IAAIQ,IAAI,qBAARR,UAAUS,UAAU,mBAAI,IAAIE,IAAI,GAAGC,KAAK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BAClCC,WAAW,IAAIV,KAAKD;gBACpBY,WAAW,IAAIX,KAAKD;;YAEtB,OAAO;gBACL7D,QAAQ;gBACRI,MAAM;oBAAEC,YAAYyC;oBAAIpC;gBAAK;gBAC7BgE,YAAYlB,SAAS9C,IAAI;gBACzBmB,QAAQ2B,SAAS3B,MAAM;YACzB;QACF;QAEA,IAAIkB,QAAQ/C,MAAM,KAAK,KAAK;YAC1B,OAAM2C,yBAAAA,MAAOgC,OAAO;YACpB,OAAO9E,IAAIG,MAAM,CAAC+C,QAAQ/C,MAAM,EAAEC,IAAI,CAAC8C,QAAQ3C,IAAI;QACrD;QACA,MAAMhB,sBACJ,iBACA;YAAE6C,KAAKf,QAAQe,GAAG;YAAE2C,KAAK,GAAE1D,iBAAAA,QAAQ0D,KAAK,YAAb1D,iBAAiB;QAAK,GACjD;YACEM;YACAK,QAAQkB,QAAQlB,MAAM;YACtBqB,QAAQ;gBAAEJ,IAAIzC;gBAAYK,MAAMqC,QAAQ2B,UAAU;YAAC;YACnDG,QAAQ;gBAAE/B;gBAAIpC,MAAMqC,QAAQ3C,IAAI,CAACM,IAAI;YAAC;QACxC;QAEF,OAAMiC,yBAAAA,MAAOmC,MAAM,CAAC,KAAK/B,QAAQ3C,IAAI;QACrC,OAAOP,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC8C,QAAQ3C,IAAI;IAC1C,EAAE,OAAOF,OAAO;QACd6E,QAAQ7E,KAAK,CAAC,oDAAoDA;QAClE,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwC;IAC/E;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/email-template-duplicate.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 * Duplicating a CRM email template (AGL-2936).\n *\n * A template is a letter under a name — subject, body, merge fields — in\n * `crmEmailTemplates` under the organization, scoped to a site or shared\n * across the workspace by the tokens it carries. The copy keeps the letter,\n * the kind and the scope; it is filed under the person copying it, and a\n * personal template stays personal to THEM rather than to the original's\n * owner. The listing's ceiling refuses a copy the way the create drawer\n * refuses a new one.\n *\n * Reached from a site — \"Edit site content\" decides — or from the organization\n * hub, where an org-wide seat does. Both scopes land in the same\n * collection, so the copy is looked up where the source was found.\n */\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport {\n CRM_EMAIL_TEMPLATES_LIMIT,\n CRM_EMAIL_TEMPLATE_NAME_MAX,\n normalizeCrmEmailTemplate,\n} from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport {\n claimAttempt,\n createResourceUid,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n logResourceDuplicated,\n resolveOrgIdForHost,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { readCrmRouteScope } from './org-caller'\n\nexport const CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE = 'crm/email-template-duplicate'\n\nexport const crmEmailTemplateDuplicateHandler: 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 const scope = readCrmRouteScope(req.body as Record<string, unknown>)\n if (!scope) return res.status(400).json({ error: 'Missing hostId or orgId' })\n const templateId = String(req.body?.templateId ?? '').trim().slice(0, 64)\n if (!templateId) return res.status(400).json({ error: 'Missing templateId' })\n const requestedName = String(req.body?.name ?? '').trim().slice(0, CRM_EMAIL_TEMPLATE_NAME_MAX)\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\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 res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n if (isRefusedIdToken(error)) return res.status(401).json({ error: 'Unauthenticated' })\n throw error\n }\n const firestore = firebaseAdmin.app().firestore()\n const staff = decoded.staff === true\n\n // WHO MAY COPY: on a site, anyone who may write its content; from the\n // hub, an org-wide seat. The org is resolved from the site rather than\n // taken from the body, so a caller cannot name a workspace where their\n // seat is more generous than it is in the one that owns the site.\n let orgId = scope.orgId\n if (scope.level === 'site') {\n const host = await firestore.collection('hosts').doc(scope.hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n if (!staff && !holdsSiteKey(host, decoded.uid, 'site.edit')) {\n return res.status(403).json({ error: siteKeyRefusal('site.edit') })\n }\n orgId = (await resolveOrgIdForHost(scope.hostId)) ?? ''\n } else if (!staff) {\n const membership = await resolveOrgPermissions(decoded.uid, { orgId }).catch(\n () => null,\n )\n if (!membership?.orgWide || membership.orgId !== orgId) {\n return res.status(403).json({ error: 'Not a member of this organization' })\n }\n }\n if (!orgId) return res.status(404).json({ error: 'Unknown organization' })\n\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-emailTemplate',\n scopeId: `${orgId}:${templateId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n\n const templates = firestore\n .collection('orgs')\n .doc(orgId)\n .collection(CRM_COLLECTIONS.emailTemplates)\n const id = createResourceUid()\n const outcome = await firestore.runTransaction(async (transaction) => {\n const [source, siblings] = await Promise.all([\n transaction.get(templates.doc(templateId)),\n transaction.get(templates.select('name')),\n ])\n if (!source.exists) {\n return { status: 404 as const, body: { error: 'Unknown template' } }\n }\n if (siblings.size >= CRM_EMAIL_TEMPLATES_LIMIT) {\n return {\n status: 403 as const,\n body: {\n error:\n `This workspace holds ${CRM_EMAIL_TEMPLATES_LIMIT} email templates — ` +\n 'delete one to make room',\n },\n }\n }\n const template = normalizeCrmEmailTemplate(source.data() as Record<string, unknown>)\n const name = uniqueDuplicateName(\n requestedName || duplicateDisplayName(template.name),\n siblings.docs.map((row) => String(row.get('name') ?? '')),\n ).slice(0, CRM_EMAIL_TEMPLATE_NAME_MAX)\n const nowMs = Date.now()\n transaction.create(templates.doc(id), {\n name,\n subject: template.subject,\n body: template.body,\n kind: template.kind,\n visibility: template.visibility,\n ...(template.visibility === 'personal' ? { ownerUid: decoded.uid } : {}),\n createdByUid: decoded.uid,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n hostId: template.hostId,\n visibleTo: [...template.visibleTo],\n createdAt: new Date(nowMs),\n updatedAt: new Date(nowMs),\n })\n return {\n status: 200 as const,\n body: { templateId: id, name },\n sourceName: template.name,\n hostId: template.hostId,\n }\n })\n\n if (outcome.status !== 200) {\n await claim?.release()\n return res.status(outcome.status).json(outcome.body)\n }\n await logResourceDuplicated(\n 'emailTemplate',\n { uid: decoded.uid, email: decoded.email ?? null },\n {\n orgId,\n hostId: outcome.hostId,\n source: { id: templateId, name: outcome.sourceName },\n target: { id, name: outcome.body.name },\n },\n )\n await claim?.record(200, outcome.body)\n return res.status(200).json(outcome.body)\n } catch (error) {\n console.error('[crm] the email template could not be duplicated', error)\n return res.status(500).json({ error: 'The template could not be duplicated.' })\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","CRM_EMAIL_TEMPLATES_LIMIT","CRM_EMAIL_TEMPLATE_NAME_MAX","normalizeCrmEmailTemplate","claimAttempt","createResourceUid","firebaseAdmin","logResourceDuplicated","resolveOrgIdForHost","isRefusedIdToken","resolveOrgPermissions","CRM_COLLECTIONS","readCrmRouteScope","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","req","res","method","setHeader","status","json","error","scope","body","templateId","String","trim","slice","requestedName","name","attemptKey","authorization","headers","idToken","startsWith","length","undefined","decoded","app","auth","verifyIdToken","firestore","staff","orgId","level","host","collection","doc","hostId","get","exists","uid","membership","catch","orgWide","claimed","kind","scopeId","key","busyMessage","replay","claim","templates","emailTemplates","id","outcome","runTransaction","transaction","source","siblings","Promise","all","select","size","template","data","docs","map","row","nowMs","Date","now","create","subject","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","visibleTo","createdAt","updatedAt","sourceName","release","email","target","record","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,yBAAyB,QACpB,6CAA4C;AACnD,SACEC,YAAY,EACZC,iBAAiB,QAEZ,sBAAqB;AAC5B,SACEC,aAAa,EACbC,qBAAqB,EACrBC,mBAAmB,QACd,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,iBAA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,CAAC,KAAKC,IAAI,CAAC6C,QAAQ1C,IAAI;IAC1C,EAAE,OAAOF,OAAO;QACd4E,QAAQ5E,KAAK,CAAC,oDAAoDA;QAClE,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwC;IAC/E;AACF,EAAC"}
@@ -38,12 +38,13 @@ import { type PluginApiHandler } from '@aglyn/aglyn/server';
38
38
  * Asking takes what opening the CRM takes: `data.manage` on the site's
39
39
  * org, for a member who reaches the site — the sender's own gate in
40
40
  * `email-send.ts`, restated — or, at the organization level, org-wide
41
- * reach with the same permission. Rotating is a workspace OWNER or ADMIN's
42
- * act, because the old address stops filing the moment the new token is
43
- * written and every mailbox rule that carried it goes quiet: the same bar
44
- * every CRM setting has, and the erasure route's. Staff are admitted to
45
- * read as they are on every CRM route, and refused the rotation as the
46
- * erasure route refuses them — it is the workspace's address to retire.
41
+ * reach with the same permission. Rotating asks "Change CRM settings"
42
+ * (`crm.settings`, AGL-4047) over the whole workspace, because the old
43
+ * address stops filing the moment the new token is written and every
44
+ * mailbox rule that carried it goes quiet: the same key every CRM setting
45
+ * asks, on for owners and admins by default. Staff are admitted to read as
46
+ * they are on every CRM route, and refused the rotation as the erasure
47
+ * route refuses them — it is the workspace's address to retire.
47
48
  */
48
49
  export declare const CRM_INBOUND_ADDRESS_ROUTE: "crm/inbound-address";
49
50
  /** What a successful call answers with. */
@@ -56,6 +57,7 @@ export interface CrmInboundAddressResponse {
56
57
  /** True when this call replaced the token. */
57
58
  rotated: boolean;
58
59
  }
59
- export declare const CRM_INBOUND_ROTATE_REFUSAL = "Rotating the capture address requires a workspace owner or admin.";
60
+ /** Names the permission, never a role (AGL-4047). */
61
+ export declare const CRM_INBOUND_ROTATE_REFUSAL: string;
60
62
  export declare const crmInboundAddressHandler: PluginApiHandler;
61
63
  export default crmInboundAddressHandler;
@@ -14,11 +14,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { canManageOrg, inboundMailDomain, isOrgWideMember } from "@aglyn/aglyn/server";
17
+ */ import { inboundMailDomain, isOrgWideMember } from "@aglyn/aglyn/server";
18
18
  import { firebaseAdmin, getOrgForHost, logOrgActivity, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin";
19
19
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
20
20
  import { CRM_API_ROUTES } from "../constants/api-routes.js";
21
21
  import { crmInboundAddress } from "../model/crm-inbound.js";
22
+ import { crmSettingsPermissionRefusal } from "../model/crm-permissions.js";
22
23
  import { ensureCrmInboundToken } from "./crm-inbound-email.js";
23
24
  import { authorizeOrgCaller, readCrmRouteScope } from "./org-caller.js";
24
25
  import { crmSuiteRefusal } from "./suite-gate.js";
@@ -45,14 +46,15 @@ import { crmSuiteRefusal } from "./suite-gate.js";
45
46
  * Asking takes what opening the CRM takes: `data.manage` on the site's
46
47
  * org, for a member who reaches the site — the sender's own gate in
47
48
  * `email-send.ts`, restated — or, at the organization level, org-wide
48
- * reach with the same permission. Rotating is a workspace OWNER or ADMIN's
49
- * act, because the old address stops filing the moment the new token is
50
- * written and every mailbox rule that carried it goes quiet: the same bar
51
- * every CRM setting has, and the erasure route's. Staff are admitted to
52
- * read as they are on every CRM route, and refused the rotation as the
53
- * erasure route refuses them — it is the workspace's address to retire.
49
+ * reach with the same permission. Rotating asks "Change CRM settings"
50
+ * (`crm.settings`, AGL-4047) over the whole workspace, because the old
51
+ * address stops filing the moment the new token is written and every
52
+ * mailbox rule that carried it goes quiet: the same key every CRM setting
53
+ * asks, on for owners and admins by default. Staff are admitted to read as
54
+ * they are on every CRM route, and refused the rotation as the erasure
55
+ * route refuses them — it is the workspace's address to retire.
54
56
  */ export const CRM_INBOUND_ADDRESS_ROUTE = CRM_API_ROUTES.inboundAddress;
55
- export const CRM_INBOUND_ROTATE_REFUSAL = 'Rotating the capture address requires a workspace owner or admin.';
57
+ /** Names the permission, never a role (AGL-4047). */ export const CRM_INBOUND_ROTATE_REFUSAL = crmSettingsPermissionRefusal();
56
58
  const refuse = (status, error)=>({
57
59
  ok: false,
58
60
  status,
@@ -61,9 +63,10 @@ const refuse = (status, error)=>({
61
63
  /**
62
64
  * The site variant's caller: a verified token, then `data.manage` on the
63
65
  * site's org for a member who reaches the site, staff passing as they do
64
- * on every CRM route. Rotation needs the org role itself.
65
- */ async function authorizeSiteCaller(req, hostId) {
66
- var _req_headers_authorization, _ref, _decoded_email, _ref1;
66
+ * on every CRM route. Rotation needs "Change CRM settings" over the whole
67
+ * workspace, asked only when the caller asks to rotate.
68
+ */ async function authorizeSiteCaller(req, hostId, rotate) {
69
+ var _req_headers_authorization, _ref, _decoded_email;
67
70
  const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
68
71
  const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
69
72
  if (!idToken) return refuse(401, 'Unauthenticated');
@@ -96,12 +99,12 @@ const refuse = (status, error)=>({
96
99
  email: (_decoded_email = decoded.email) != null ? _decoded_email : null,
97
100
  orgId,
98
101
  org: resolved.org,
99
- canRotate: canManageOrg((_ref1 = member == null ? void 0 : member.role) != null ? _ref1 : null)
102
+ canRotate: rotate && member !== null && isOrgWideMember(member) && await memberHasOrgPermission(orgId, member, 'crm.settings')
100
103
  };
101
104
  }
102
105
  /** The organization variant's caller, by the org the body names (AGL-2634). */ async function authorizeOrgLevelCaller(req, orgId, rotate) {
103
106
  const caller = await authorizeOrgCaller(req, orgId, {
104
- needs: rotate ? 'manage-org' : 'data.manage',
107
+ needs: rotate ? 'crm.settings' : 'data.manage',
105
108
  refusal: rotate ? CRM_INBOUND_ROTATE_REFUSAL : 'Reading the capture address at the organization level requires the ' + 'data.manage permission across the whole workspace'
106
109
  });
107
110
  if (caller.ok === false) return refuse(caller.status, caller.error);
@@ -111,7 +114,7 @@ const refuse = (status, error)=>({
111
114
  email: caller.email,
112
115
  orgId,
113
116
  org: caller.org,
114
- // `manage-org` admitted them when they asked to rotate; a reader who
117
+ // `crm.settings` admitted them when they asked to rotate; a reader who
115
118
  // did not ask is not told whether they could.
116
119
  canRotate: rotate
117
120
  };
@@ -135,7 +138,7 @@ export const crmInboundAddressHandler = async (req, res)=>{
135
138
  }
136
139
  const rotate = body['rotate'] === true;
137
140
  try {
138
- const caller = scope.level === 'org' ? await authorizeOrgLevelCaller(req, scope.orgId, rotate) : await authorizeSiteCaller(req, scope.hostId);
141
+ const caller = scope.level === 'org' ? await authorizeOrgLevelCaller(req, scope.orgId, rotate) : await authorizeSiteCaller(req, scope.hostId, rotate);
139
142
  if (caller.ok === false) {
140
143
  res.status(caller.status).json({
141
144
  error: caller.error
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/inbound-address.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 canManageOrg,\n inboundMailDomain,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\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 { CRM_API_ROUTES } from '../constants/api-routes'\nimport { crmInboundAddress } from '../model/crm-inbound'\nimport { ensureCrmInboundToken } from './crm-inbound-email'\nimport { authorizeOrgCaller, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/**\n * `POST /api/crm/inbound-address` — the workspace's email capture address\n * (AGL-2657).\n *\n * Body: `{ hostId }` under a site, `{ orgId, hostId? }` at the organization\n * level, and `rotate: true` to replace the token. Answers\n * `{ ok: true, address, createdAtMs, rotatedAtMs?, rotated }`.\n *\n * ## Why a route and not a read of the org document\n *\n * The token is on the org document, which every member may read, and the\n * address is the token in a fixed shape — but the shape's domain is the\n * deployment's, `CRM_INBOUND_DOMAIN`, which a browser does not know, and\n * the token does not exist until somebody asks for the address. So the\n * first ask mints it, inside a transaction, and every ask answers the\n * whole address. The org document is the read side for nothing but the\n * rules, which deny the key to every client.\n *\n * ## Who may ask, and who may rotate\n *\n * Asking takes what opening the CRM takes: `data.manage` on the site's\n * org, for a member who reaches the site — the sender's own gate in\n * `email-send.ts`, restated — or, at the organization level, org-wide\n * reach with the same permission. Rotating is a workspace OWNER or ADMIN's\n * act, because the old address stops filing the moment the new token is\n * written and every mailbox rule that carried it goes quiet: the same bar\n * every CRM setting has, and the erasure route's. Staff are admitted to\n * read as they are on every CRM route, and refused the rotation as the\n * erasure route refuses them — it is the workspace's address to retire.\n */\n\nexport const CRM_INBOUND_ADDRESS_ROUTE = CRM_API_ROUTES.inboundAddress\n\n/** What a successful call answers with. */\nexport interface CrmInboundAddressResponse {\n ok: true\n /** `crm+<token>@<capture domain>`. */\n address: string\n createdAtMs: number\n rotatedAtMs?: number\n /** True when this call replaced the token. */\n rotated: boolean\n}\n\nexport const CRM_INBOUND_ROTATE_REFUSAL =\n 'Rotating the capture address requires a workspace owner or admin.'\n\ntype Refusal = { ok: false; status: number; error: string }\n\ninterface Caller {\n ok: true\n uid: string\n email: string | null\n orgId: string\n /** The org document, for the plan the address belongs to. */\n org: unknown\n /** Whether this caller may replace the token. */\n canRotate: boolean\n}\n\nconst refuse = (status: number, error: string): Refusal => ({ ok: false, status, error })\n\n/**\n * The site variant's caller: a verified token, then `data.manage` on the\n * site's org for a member who reaches the site, staff passing as they do\n * on every CRM route. Rotation needs the org role itself.\n */\nasync function authorizeSiteCaller(\n req: PluginApiRequest,\n hostId: string,\n): Promise<Caller | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return refuse(401, 'Unauthenticated')\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\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 refuse(401, 'Unauthenticated')\n console.error('[crm] inbound-address could not verify the caller', error)\n return refuse(500, 'The sign-in could not be checked. Try again.')\n }\n const resolved = await getOrgForHost(hostId).catch(() => null)\n if (!resolved) return refuse(404, 'Unknown site')\n const { orgId } = resolved\n const membership = await resolveOrgMembership(decoded.uid, orgId).catch(() => null)\n const member = (membership?.member ?? null) as Partial<AglynOrgMember> | null\n if (decoded.staff !== true) {\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member && reaches && (await memberHasOrgPermission(orgId, member, 'data.manage'))\n if (!allowed) {\n return refuse(\n 403,\n 'Reading the capture address requires the data.manage permission on this site',\n )\n }\n }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n orgId,\n org: resolved.org,\n canRotate: canManageOrg(member?.role ?? null),\n }\n}\n\n/** The organization variant's caller, by the org the body names (AGL-2634). */\nasync function authorizeOrgLevelCaller(\n req: PluginApiRequest,\n orgId: string,\n rotate: boolean,\n): Promise<Caller | Refusal> {\n const caller = await authorizeOrgCaller(req, orgId, {\n needs: rotate ? 'manage-org' : 'data.manage',\n refusal: rotate\n ? CRM_INBOUND_ROTATE_REFUSAL\n : 'Reading the capture address at the organization level requires the ' +\n 'data.manage permission across the whole workspace',\n })\n if (caller.ok === false) return refuse(caller.status, caller.error)\n return {\n ok: true,\n uid: caller.uid,\n email: caller.email,\n orgId,\n org: caller.org,\n // `manage-org` admitted them when they asked to rotate; a reader who\n // did not ask is not told whether they could.\n canRotate: rotate,\n }\n}\n\nexport const crmInboundAddressHandler: 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 body = (\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n ) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const rotate = body['rotate'] === true\n try {\n const caller =\n scope.level === 'org'\n ? await authorizeOrgLevelCaller(req, scope.orgId, rotate)\n : await authorizeSiteCaller(req, scope.hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n if (rotate && !caller.canRotate) {\n res.status(403).json({ error: CRM_INBOUND_ROTATE_REFUSAL })\n return\n }\n // The first ask mints the token, so reading the address is a write on\n // a plan without the suite; the webhook refuses such a plan's mail too.\n const suite = crmSuiteRefusal(caller.org, 'The email capture address')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const firestore = firebaseAdmin.app().firestore()\n const result = await ensureCrmInboundToken(firestore, caller.orgId, { rotate })\n if (result.rotated) {\n // The old address went quiet with this write; the feed says who did it.\n await logOrgActivity(\n caller.orgId,\n { uid: caller.uid, email: caller.email },\n 'Rotated the email capture address',\n { type: 'org' },\n )\n }\n const answer: CrmInboundAddressResponse = {\n ok: true,\n address: crmInboundAddress(result.token, inboundMailDomain()),\n createdAtMs: result.createdAtMs,\n ...(typeof result.rotatedAtMs === 'number' ? { rotatedAtMs: result.rotatedAtMs } : {}),\n rotated: result.rotated,\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] inbound-address failed', scope, error)\n res.status(500).json({ error: 'The capture address could not be read.' })\n }\n}\n\nexport default crmInboundAddressHandler\n"],"names":["canManageOrg","inboundMailDomain","isOrgWideMember","firebaseAdmin","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","CRM_API_ROUTES","crmInboundAddress","ensureCrmInboundToken","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","CRM_INBOUND_ADDRESS_ROUTE","inboundAddress","CRM_INBOUND_ROTATE_REFUSAL","refuse","status","error","ok","authorizeSiteCaller","req","hostId","decoded","authorization","String","headers","idToken","startsWith","slice","length","undefined","app","auth","verifyIdToken","console","resolved","catch","orgId","membership","uid","member","staff","reaches","Boolean","hostAccess","allowed","email","org","canRotate","role","authorizeOrgLevelCaller","rotate","caller","needs","refusal","crmInboundAddressHandler","res","method","setHeader","json","body","JSON","parse","scope","level","suite","firestore","result","rotated","type","answer","address","token","createdAtMs","rotatedAtMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,YAAY,EACZC,iBAAiB,EACjBC,eAAe,QAGV,sBAAqB;AAC5B,SACEC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,cAAc,QAAQ,6BAAyB;AACxD,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,kBAAc;AACpE,SAASC,eAAe,QAAQ,kBAAc;AAE9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED,OAAO,MAAMC,4BAA4BN,eAAeO,cAAc,CAAA;AAatE,OAAO,MAAMC,6BACX,oEAAmE;AAerE,MAAMC,SAAS,CAACC,QAAgBC,QAA4B,CAAA;QAAEC,IAAI;QAAOF;QAAQC;IAAM,CAAA;AAEvF;;;;CAIC,GACD,eAAeE,oBACbC,GAAqB,EACrBC,MAAc;QAEeD,kCAmCpBE;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],"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 inboundMailDomain,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\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 { CRM_API_ROUTES } from '../constants/api-routes'\nimport { crmInboundAddress } from '../model/crm-inbound'\nimport { crmSettingsPermissionRefusal } from '../model/crm-permissions'\nimport { ensureCrmInboundToken } from './crm-inbound-email'\nimport { authorizeOrgCaller, readCrmRouteScope } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/**\n * `POST /api/crm/inbound-address` — the workspace's email capture address\n * (AGL-2657).\n *\n * Body: `{ hostId }` under a site, `{ orgId, hostId? }` at the organization\n * level, and `rotate: true` to replace the token. Answers\n * `{ ok: true, address, createdAtMs, rotatedAtMs?, rotated }`.\n *\n * ## Why a route and not a read of the org document\n *\n * The token is on the org document, which every member may read, and the\n * address is the token in a fixed shape — but the shape's domain is the\n * deployment's, `CRM_INBOUND_DOMAIN`, which a browser does not know, and\n * the token does not exist until somebody asks for the address. So the\n * first ask mints it, inside a transaction, and every ask answers the\n * whole address. The org document is the read side for nothing but the\n * rules, which deny the key to every client.\n *\n * ## Who may ask, and who may rotate\n *\n * Asking takes what opening the CRM takes: `data.manage` on the site's\n * org, for a member who reaches the site — the sender's own gate in\n * `email-send.ts`, restated — or, at the organization level, org-wide\n * reach with the same permission. Rotating asks \"Change CRM settings\"\n * (`crm.settings`, AGL-4047) over the whole workspace, because the old\n * address stops filing the moment the new token is written and every\n * mailbox rule that carried it goes quiet: the same key every CRM setting\n * asks, on for owners and admins by default. Staff are admitted to read as\n * they are on every CRM route, and refused the rotation as the erasure\n * route refuses them — it is the workspace's address to retire.\n */\n\nexport const CRM_INBOUND_ADDRESS_ROUTE = CRM_API_ROUTES.inboundAddress\n\n/** What a successful call answers with. */\nexport interface CrmInboundAddressResponse {\n ok: true\n /** `crm+<token>@<capture domain>`. */\n address: string\n createdAtMs: number\n rotatedAtMs?: number\n /** True when this call replaced the token. */\n rotated: boolean\n}\n\n/** Names the permission, never a role (AGL-4047). */\nexport const CRM_INBOUND_ROTATE_REFUSAL = crmSettingsPermissionRefusal()\n\ntype Refusal = { ok: false; status: number; error: string }\n\ninterface Caller {\n ok: true\n uid: string\n email: string | null\n orgId: string\n /** The org document, for the plan the address belongs to. */\n org: unknown\n /** Whether this caller may replace the token. */\n canRotate: boolean\n}\n\nconst refuse = (status: number, error: string): Refusal => ({ ok: false, status, error })\n\n/**\n * The site variant's caller: a verified token, then `data.manage` on the\n * site's org for a member who reaches the site, staff passing as they do\n * on every CRM route. Rotation needs \"Change CRM settings\" over the whole\n * workspace, asked only when the caller asks to rotate.\n */\nasync function authorizeSiteCaller(\n req: PluginApiRequest,\n hostId: string,\n rotate: boolean,\n): Promise<Caller | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return refuse(401, 'Unauthenticated')\n let decoded: { uid: string; email?: string; staff?: unknown }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\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 refuse(401, 'Unauthenticated')\n console.error('[crm] inbound-address could not verify the caller', error)\n return refuse(500, 'The sign-in could not be checked. Try again.')\n }\n const resolved = await getOrgForHost(hostId).catch(() => null)\n if (!resolved) return refuse(404, 'Unknown site')\n const { orgId } = resolved\n const membership = await resolveOrgMembership(decoded.uid, orgId).catch(() => null)\n const member = (membership?.member ?? null) as Partial<AglynOrgMember> | null\n if (decoded.staff !== true) {\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member && reaches && (await memberHasOrgPermission(orgId, member, 'data.manage'))\n if (!allowed) {\n return refuse(\n 403,\n 'Reading the capture address requires the data.manage permission on this site',\n )\n }\n }\n return {\n ok: true,\n uid: decoded.uid,\n email: decoded.email ?? null,\n orgId,\n org: resolved.org,\n canRotate:\n rotate &&\n member !== null &&\n isOrgWideMember(member) &&\n (await memberHasOrgPermission(orgId, member, 'crm.settings')),\n }\n}\n\n/** The organization variant's caller, by the org the body names (AGL-2634). */\nasync function authorizeOrgLevelCaller(\n req: PluginApiRequest,\n orgId: string,\n rotate: boolean,\n): Promise<Caller | Refusal> {\n const caller = await authorizeOrgCaller(req, orgId, {\n needs: rotate ? 'crm.settings' : 'data.manage',\n refusal: rotate\n ? CRM_INBOUND_ROTATE_REFUSAL\n : 'Reading the capture address at the organization level requires the ' +\n 'data.manage permission across the whole workspace',\n })\n if (caller.ok === false) return refuse(caller.status, caller.error)\n return {\n ok: true,\n uid: caller.uid,\n email: caller.email,\n orgId,\n org: caller.org,\n // `crm.settings` admitted them when they asked to rotate; a reader who\n // did not ask is not told whether they could.\n canRotate: rotate,\n }\n}\n\nexport const crmInboundAddressHandler: 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 body = (\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n ) as Record<string, unknown>\n const scope = readCrmRouteScope(body)\n if (!scope) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const rotate = body['rotate'] === true\n try {\n const caller =\n scope.level === 'org'\n ? await authorizeOrgLevelCaller(req, scope.orgId, rotate)\n : await authorizeSiteCaller(req, scope.hostId, rotate)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n if (rotate && !caller.canRotate) {\n res.status(403).json({ error: CRM_INBOUND_ROTATE_REFUSAL })\n return\n }\n // The first ask mints the token, so reading the address is a write on\n // a plan without the suite; the webhook refuses such a plan's mail too.\n const suite = crmSuiteRefusal(caller.org, 'The email capture address')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const firestore = firebaseAdmin.app().firestore()\n const result = await ensureCrmInboundToken(firestore, caller.orgId, { rotate })\n if (result.rotated) {\n // The old address went quiet with this write; the feed says who did it.\n await logOrgActivity(\n caller.orgId,\n { uid: caller.uid, email: caller.email },\n 'Rotated the email capture address',\n { type: 'org' },\n )\n }\n const answer: CrmInboundAddressResponse = {\n ok: true,\n address: crmInboundAddress(result.token, inboundMailDomain()),\n createdAtMs: result.createdAtMs,\n ...(typeof result.rotatedAtMs === 'number' ? { rotatedAtMs: result.rotatedAtMs } : {}),\n rotated: result.rotated,\n }\n res.status(200).json(answer)\n } catch (error) {\n console.error('[crm] inbound-address failed', scope, error)\n res.status(500).json({ error: 'The capture address could not be read.' })\n }\n}\n\nexport default crmInboundAddressHandler\n"],"names":["inboundMailDomain","isOrgWideMember","firebaseAdmin","getOrgForHost","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","isRefusedIdToken","CRM_API_ROUTES","crmInboundAddress","crmSettingsPermissionRefusal","ensureCrmInboundToken","authorizeOrgCaller","readCrmRouteScope","crmSuiteRefusal","CRM_INBOUND_ADDRESS_ROUTE","inboundAddress","CRM_INBOUND_ROTATE_REFUSAL","refuse","status","error","ok","authorizeSiteCaller","req","hostId","rotate","decoded","authorization","String","headers","idToken","startsWith","slice","length","undefined","app","auth","verifyIdToken","console","resolved","catch","orgId","membership","uid","member","staff","reaches","Boolean","hostAccess","allowed","email","org","canRotate","authorizeOrgLevelCaller","caller","needs","refusal","crmInboundAddressHandler","res","method","setHeader","json","body","JSON","parse","scope","level","suite","firestore","result","rotated","type","answer","address","token","createdAtMs","rotatedAtMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,iBAAiB,EACjBC,eAAe,QAGV,sBAAqB;AAC5B,SACEC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,cAAc,QAAQ,6BAAyB;AACxD,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,4BAA4B,QAAQ,8BAA0B;AACvE,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,kBAAkB,EAAEC,iBAAiB,QAAQ,kBAAc;AACpE,SAASC,eAAe,QAAQ,kBAAc;AAE9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,OAAO,MAAMC,4BAA4BP,eAAeQ,cAAc,CAAA;AAatE,mDAAmD,GACnD,OAAO,MAAMC,6BAA6BP,+BAA8B;AAexE,MAAMQ,SAAS,CAACC,QAAgBC,QAA4B,CAAA;QAAEC,IAAI;QAAOF;QAAQC;IAAM,CAAA;AAEvF;;;;;CAKC,GACD,eAAeE,oBACbC,GAAqB,EACrBC,MAAc,EACdC,MAAe;QAEcF,kCAmCpBG;IAnCT,MAAMC,gBAAgBC,QAAOL,6BAAAA,IAAIM,OAAO,CAACF,aAAa,YAAzBJ,6BAA6B;IAC1D,MAAMO,UAAUH,cAAcI,UAAU,CAAC,aACrCJ,cAAcK,KAAK,CAAC,UAAUC,MAAM,IACpCC;IACJ,IAAI,CAACJ,SAAS,OAAOZ,OAAO,KAAK;IACjC,IAAIQ;IACJ,IAAI;QACFA,UAAU,MAAMxB,cAAciC,GAAG,GAAGC,IAAI,GAAGC,aAAa,CAACP;IAC3D,EAAE,OAAOV,OAAO;Q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