@aglyn/plugins-crm 1.18.0 → 1.20.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.
- package/package.json +14 -14
- package/src/lib/components/log-activity-dialog.d.ts +2 -0
- package/src/lib/components/log-activity-dialog.js +11 -2
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/record-sharing-card.js +8 -7
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +10 -3
- package/src/lib/components/settings-section.js +286 -35
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/share-records-dialog.d.ts +17 -3
- package/src/lib/components/share-records-dialog.js +59 -45
- package/src/lib/components/share-records-dialog.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
- package/src/lib/components/sharing-rule-drawer.js +51 -40
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/declarations.server.js +10 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -2
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
- package/src/lib/hooks/use-crm-sharing.js +20 -0
- package/src/lib/hooks/use-crm-sharing.js.map +1 -1
- package/src/lib/model/crm-sharing-api.d.ts +5 -2
- package/src/lib/model/crm-sharing-api.js +3 -0
- package/src/lib/model/crm-sharing-api.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +153 -5
- package/src/lib/model/crm-sharing.js +243 -20
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/add-contact-by-hand.js +11 -4
- package/src/lib/server/add-contact-by-hand.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +2 -2
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +2 -2
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +2 -2
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
- package/src/lib/server/api-v1/crm-shared.js +12 -1
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +2 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/associate-company-by-domain.d.ts +1 -1
- package/src/lib/server/associate-company-by-domain.js +4 -4
- package/src/lib/server/associate-company-by-domain.js.map +1 -1
- package/src/lib/server/automation-steps.js +24 -12
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -3
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -4
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/crm-default-sharing.d.ts +86 -0
- package/src/lib/server/crm-default-sharing.js +409 -0
- package/src/lib/server/crm-default-sharing.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +2 -2
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing-runs.d.ts +71 -0
- package/src/lib/server/crm-sharing-runs.js +221 -0
- package/src/lib/server/crm-sharing-runs.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +24 -1
- package/src/lib/server/crm-sharing.js +183 -31
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +5 -2
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +2 -1
- package/src/lib/server/record-timeline.js +11 -6
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +10 -6
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server.js +23 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/common.d.ts +5 -1
- package/src/lib/transfer/common.js +8 -5
- package/src/lib/transfer/common.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/automation-steps.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 buildCrmEmailActivity,\n checkEntitlement,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActivity,\n type CrmActivityDirection,\n crmActivityDirection,\n type CrmActivityLink,\n type CrmTask,\n type CrmTaskPriority,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskLabelsForNew,\n crmTaskListFields,\n normalizeContactEmail,\n parseCrmMemberRef,\n personKey,\n planLabelGrantingFeature,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport type {\n PluginRecordEmailPrepareRequest,\n PluginRecordPreparedEmail,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport type {\n ServerStepAnswer,\n ServerStepRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n orgDataQueryForHost,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: the specs substitute the barrel wholesale, and\n// the lookup must reach the real index logic under them.\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { FieldValue } from 'firebase-admin/firestore'\n// The leaf, not the runtime barrel: the specs substitute it.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n reassignLeadOwner,\n} from './assign-contact-owner'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { InteractionStepGuard } from '@aglyn/aglyn/app-utils/site-interactions'\nimport type { ContactLifecycleStage, CrmActivityKind, CrmTaskKind } from '@aglyn/aglyn/app-utils/crm-kinds'\nimport type { CRM_STEP_TYPES } from '../constants/bundle-common'\nimport { readCrmTaskPicklists } from './read-picklist'\nimport { CRM_SUITE_FEATURE } from './suite-gate'\nimport { crmTaskReminderAfterEdit } from '../model/crm-task-reminders'\nimport { recomputeCrmNextTaskAt } from './crm-next-activity'\nimport { newCrmActivityRef, writeCrmEmailActivity } from './crm-email-activity'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\n\n/**\n * THE AUTOMATION STEPS THAT WRITE THE CRM (AGL-2605), run for the automation\n * engine through the platform's server-step seam (`plugin-server-steps`,\n * AGL-3080): `setContactStage`, `addContactTag`, `assignContactOwner`,\n * `createCrmTask` and `logCrmActivity`.\n *\n * The engine keeps the step's guard, the run's order, its history and the\n * nesting cap; this answers what the step did. A refusal is ANSWERED as\n * `error`, never thrown, and its words are the line the run history carries —\n * the same words the engine wrote when these steps were its own.\n *\n * The five share one shape no other step has: each begins by finding THE\n * PERSON the event is about, and each writes either inside the site's facet on\n * that person or a record stamped with the site's scope. One resolver and one\n * scope expression, used five times, rather than five copies drifting apart.\n *\n * ## The person is the event's, never the step's\n *\n * A step carries no contact reference. The contact is whoever the event\n * names — by `contactId` when the emitting door knew the document, and by\n * `email` otherwise, which is what every pre-CRM event carries. Both lookups\n * are scoped to what THIS site may see: a document the id names but the site\n * cannot read is treated as absent, exactly as the scoped query would have\n * treated it, so an event replayed against the wrong site reaches nobody.\n *\n * ## A missing person is a reported no-op\n *\n * Nothing is written and the step's error names the reason, which lands in\n * the run summary beside the trigger — the same place \"why didn't it fire?\"\n * is answered for every other step. Silence here would make a mis-wired\n * trigger (a form with no email field) indistinguishable from a working one.\n *\n * ## The plan gate is the CRM's\n *\n * Every step is refused on a workspace whose plan does not carry the CRM,\n * into the run history with the tier that carries it, so a Free workspace\n * whose flow names a CRM step reads why the step did nothing rather than a\n * log that says it ran. The org document is the one the run's gate already\n * read, handed over with the step, so the check costs no read.\n *\n * The same module answers the record timeline's `prepareEmail` (AGL-2615): an\n * automation's email addressed to the contact the event is about is filed on\n * that contact's timeline — see {@link prepareCrmRecordEmail}.\n */\n\n/** One of the steps this module runs. */\nexport type CrmStepType = (typeof CRM_STEP_TYPES)[number]\n\n/**\n * A CRM step, as it is stored: the CRM's own shapes of the steps it runs. The\n * automation editor writes them and checks them; `apps/console/specs/\n * crm-automation-steps.spec.ts` runs what it writes through this module.\n */\nexport type CrmAutomationStep = (\n | { type: 'setContactStage'; lifecycleStage: ContactLifecycleStage }\n | { type: 'addContactTag'; tag: string }\n | { type: 'assignContactOwner'; ownerUid?: string; ownerEmail?: string; roundRobin?: boolean }\n | {\n type: 'createCrmTask'\n title: string\n kind: CrmTaskKind\n /** `normal` when absent — the steps written before priorities were (AGL-3517). */\n priority?: CrmTaskPriority\n dueInDays: number\n assigneeUid?: string\n assigneeEmail?: string\n }\n | {\n type: 'logCrmActivity'\n kind: CrmActivityKind\n body: string\n /** Which way a call or an email went (AGL-3517). */\n direction?: CrmActivityDirection\n }\n) & { when?: InteractionStepGuard | null } & { type: CrmStepType }\n\n/** The site, the plan and the org a step or an email is answered for. */\ninterface CrmStepEnv {\n hostId: string\n /** The owning org's billing doc, already read by the run's gate. */\n org: unknown\n orgId: string | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\ninterface ResolvedContact {\n id: string\n ref: FirebaseFirestore.DocumentReference\n data: Record<string, unknown>\n}\n\n/**\n * The person a CRM step acts on: a contact, or — when the workspace holds\n * none for them — the LEAD the site filed (AGL-3458).\n *\n * A lead-routed form files a lead and no contact (AGL-3232), and announces it\n * with the `lead` event. An automation welcoming that person — assign an\n * owner, book a call, tag them — has only the lead to act on, so each step\n * that has a lead's equivalent writes it there: the lead's own `ownerUid`,\n * its own `tags`, a task or an activity filed under `leadId`. A stage is a\n * contact's alone, and a step setting one on a lead says so.\n */\ntype ResolvedPerson =\n | ({ kind: 'contact' } & ResolvedContact)\n | ({ kind: 'lead' } & ResolvedContact)\n\n/**\n * The contact an event names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote and\n * a lookup by id is a read, not a query. The address second, through the\n * org's address index narrowed to this site (AGL-2633), for every event that\n * predates the CRM and knows only who filled in the form — so an address a\n * merge folded into another record still reaches the person who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n named: { contactId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(named.contactId ?? '').trim()\n if (contactId) {\n const doc = await contactsRef.doc(contactId).get()\n if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n }\n }\n const hit = await findContactByEmail(contactsRef, named.email, { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : null\n}\n\n/**\n * The lead an event names, as this site may see it: by `leadId` — the `lead`\n * event carries it, and it is the person's key — else by the key of the\n * `email`. A row this site cannot see is absent, exactly as a contact's is.\n */\nasync function resolveEventLead(\n hostId: string,\n named: { leadId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const key = String(named.leadId ?? '').trim() || personKey(named.email) || ''\n if (!key) return null\n const { ref: leadsRef } = await orgDataQueryForHost(hostId, 'leads')\n const doc = await leadsRef.doc(key).get()\n if (!doc.exists || !visibleToHost(doc.get('visibleTo'), hostId)) return null\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n}\n\n/** The contact the event names, else its lead — see {@link ResolvedPerson}. */\nasync function resolveEventPerson(\n hostId: string,\n named: { contactId?: unknown; leadId?: unknown; email?: unknown },\n): Promise<ResolvedPerson | null> {\n const contact = await resolveEventContact(hostId, named)\n if (contact) return { kind: 'contact', ...contact }\n const lead = await resolveEventLead(hostId, named)\n return lead ? { kind: 'lead', ...lead } : null\n}\n\n/**\n * The uid a step names for somebody on the team — an owner, an assignee —\n * resolved against the org's roster, whichever way the step named them.\n *\n * A step names a member by uid when a picker wrote it and by address when a\n * person typed it, and the editor's one text field accepts either — so both\n * fields are read through `parseCrmMemberRef`, and an address typed into the\n * uid slot or a uid typed into the address slot still names the person.\n *\n * Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by the\n * uid, so a uid costs one document read and must exist: `ownerUid` and\n * `assigneeUid` are fields every reader resolves as a member, and a stranger's\n * uid in one is a task nobody on the team can find. An address is matched on\n * the roster's own `email` field, and two production paths create a member\n * document WITHOUT one (a host-access re-grant, and an add whose auth record\n * carried none) — such a member is named by uid, which is the reason the\n * editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup by\n * address would resolve people who are not on this organization at all\n * (AGL-1122). A reference that resolves neither way is an error, not a stored\n * string.\n */\nasync function resolveMemberUid(\n orgId: string | null,\n named: { uid?: string; email?: string },\n role: 'owner' | 'assignee',\n): Promise<{ uid: string; detail: string } | { error: string }> {\n const ref = parseCrmMemberRef(named.uid) ?? parseCrmMemberRef(named.email)\n if (!ref) return { error: `no ${role} named on the step` }\n if (!orgId) return { error: 'this site has no organization' }\n const members = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n if (ref.kind === 'uid') {\n const member = await members.doc(ref.uid).get()\n if (member.exists) return { uid: ref.uid, detail: ref.uid }\n return { error: `no team member with the id ${ref.uid}` }\n }\n const byField = (await members.where('email', '==', ref.email).limit(1).get()).docs[0]\n if (byField) return { uid: byField.id, detail: ref.email }\n return { error: `no team member with the address ${ref.email}` }\n}\n\n/**\n * Runs one CRM step for the person the event names: the executor the CRM\n * registers on the server-step seam for every type in `CRM_STEP_TYPES`.\n *\n * Never throws for a plan without the CRM, a missing person, an unknown owner\n * or a site with no org — those are answered as `error` so the run records\n * them; a Firestore failure propagates, and the engine records it the same\n * way.\n */\nexport async function runCrmAutomationStep(\n request: ServerStepRequest,\n nowMs = Date.now(),\n): Promise<ServerStepAnswer> {\n if (!checkEntitlement(request.org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return { error: `CRM steps require the ${planLabelGrantingFeature(CRM_SUITE_FEATURE)} plan` }\n }\n const env: CrmStepEnv = { hostId: request.hostId, org: request.org, orgId: request.orgId }\n const step = request.step as unknown as CrmAutomationStep\n const actionId = request.run.id\n const { hostId } = env\n const person = await resolveEventPerson(hostId, request.payload)\n if (!person) {\n const named = String(request.payload['contactId'] ?? request.payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact or lead this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\n if (person.kind === 'lead') return runLeadStep(env, actionId, step, person, nowMs)\n const contact = person\n /*\n * THE HOLDER whose facet the write addresses — the site's consent group,\n * which is the site alone unless the org declared the site one of a set\n * that presents as one sender. Same resolution the capture doors use, so a\n * stage set here lands in the facet the console reads.\n */\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const email = String(contact.data['email'] ?? '')\n\n if (step.type === 'setContactStage') {\n const previous = facet.lifecycleStage ?? ''\n const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage]\n /*\n * A stage set to what it already is changes nothing and ANNOUNCES\n * nothing. The write is skipped so the row's `updatedAt` does not move for\n * a non-event, and the absent emit is what stops an action that sets the\n * stage it listens for from re-running on its own write — the engine's\n * nesting cap bounds that chain, this ends it at once.\n */\n if (previous === step.lifecycleStage) {\n return { detail: `${label} (already)` }\n }\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n /*\n * A stage set by an automation IS a stage change, and the action\n * listening for it must run — but through the engine's nesting cap, so\n * the event is answered back for the engine to raise, never raised here.\n */\n return {\n detail: label,\n emit: {\n event: 'contactStageChanged',\n payload: {\n contactId: contact.id,\n email,\n lifecycleStage: step.lifecycleStage,\n previousStage: previous,\n },\n },\n }\n }\n\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n // `arrayUnion`, so the tag a merchant already applied by hand is not\n // duplicated and the tags beside it are kept.\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n return { detail: tag }\n }\n\n if (step.type === 'assignContactOwner') {\n /*\n * Through the one server assignment (AGL-2618), in both of the step's\n * modes, rather than a facet write of its own: the helper is what moves\n * the round-robin pointer inside the transaction that writes the owner,\n * mirrors the owner onto the site's lead, and tells the new owner. A\n * member named on the step is still resolved here — by address against\n * the roster, as before — and handed over by uid; the helper checks the\n * roster document again, which is one read and the same answer.\n */\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignContactOwner({\n hostId,\n contactId: contact.id,\n email,\n assign,\n })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') {\n return { detail: `${named} (already)` }\n }\n return {\n detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of their\n // own beside the contact, stamped with the scope a contact captured on this\n // site would carry — `crmScopeTokens` is the create path's own expression,\n // so a record an automation made is visible to exactly the sites a record a\n // person made would be.\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const visibleTo = crmScopeTokens((env.org ?? null) as Record<string, unknown> | null, group)\n const links = stampCrmActivityCompany(\n { contactId: contact.id },\n { contact: contact.data, groupId: group.groupId },\n )\n\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n /*\n * The assignee the step names, else the person who OWNS the contact, else\n * nobody. A follow-up task belongs to whoever holds the relationship, and\n * an automation that had to name one person for every contact it touches\n * would assign the whole list to one rep. A named assignee who cannot be\n * resolved is an error rather than a fallback to the owner: the author\n * named somebody on purpose.\n */\n let assignee = facet.ownerUid ?? ''\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const priority: CrmTaskPriority =\n step.priority === 'high' || step.priority === 'low' ? step.priority : 'normal'\n // The org's labels for the meanings the step names (AGL-3517).\n const labels = crmTaskLabelsForNew(\n await readCrmTaskPicklists(firebaseAdmin.app().firestore(), env.orgId),\n { kind: step.kind, priority },\n )\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority,\n status: 'open',\n ...labels,\n dueAtMs,\n // The reminder a person's task gets (AGL-2659): the due time.\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n // What the Tasks list searches by (AGL-3321), beside the task.\n await orgRef.collection(CRM_COLLECTIONS.tasks).add({ ...task, ...crmTaskListFields(task) })\n // The contact and company the task names carry `nextTaskAtMs` (AGL-2661);\n // a figure that could not move is the Fields section's recompute's.\n await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [links]).catch(\n (error: unknown) => {\n console.error('[crm] next activity could not be recomputed', env.orgId, error)\n },\n )\n return { detail: title.slice(0, 60) }\n }\n\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n /*\n * The per-record ceiling (AGL-2611), and this step is the writer it exists\n * for: a flow that logs on every page view fills one person's log in an\n * afternoon. Refused into the run history as an error, the way an\n * unresolvable assignee is, so the merchant reads why the flow stopped\n * writing rather than finding a log that silently stopped.\n */\n const logged = await countCrmActivitiesForRecord(orgRef, links)\n if (!crmActivityLogHasRoom(logged)) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const direction = crmActivityDirection(step.kind, step.direction)\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n ...(direction ? { direction } : {}),\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * A CRM step on a LEAD (AGL-3458) — the person is not a contact yet, so each\n * step writes the lead's equivalent of what it writes on a contact. See\n * {@link ResolvedPerson}.\n */\nasync function runLeadStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmAutomationStep,\n lead: ResolvedContact,\n nowMs: number,\n): Promise<ServerStepAnswer> {\n const { hostId } = env\n if (step.type === 'setContactStage') {\n return {\n error:\n 'the event names a lead, and a lead has no lifecycle stage until it is ' +\n 'converted to a contact',\n }\n }\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n await lead.ref.update({\n tags: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // A lead's tags are what the Leads list searches (AGL-3321).\n await restampCrmListFieldsAt(lead.ref, 'leads')\n return { detail: `${tag} (lead)` }\n }\n if (step.type === 'assignContactOwner') {\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignLeadOwner({ hostId, leadId: lead.id, assign })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') return { detail: `${named} (already, lead)` }\n return {\n detail:\n step.roundRobin === true\n ? `round robin → ${verdict.ownerUid} (lead)`\n : `${named} (lead)`,\n }\n }\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const group = await consentGroupForSite(hostId)\n const visibleTo = crmScopeTokens((env.org ?? null) as Record<string, unknown> | null, group)\n // Filed under the lead, as a sequence's call step files one (AGL-3233); a\n // conversion stamps the contact beside it, and the task follows the person.\n const links = { leadId: lead.id }\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n // The named assignee, else whoever owns the lead NOW — an owner step\n // earlier in this same run wrote the lead after it was resolved, so it\n // is read again — else nobody.\n let assignee: string\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n } else {\n const fresh = await lead.ref.get()\n assignee = String((fresh.data() ?? lead.data)['ownerUid'] ?? '')\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\n dueAtMs,\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef\n .collection(CRM_COLLECTIONS.tasks)\n .doc(createResourceUid())\n .set({ ...task, ...crmTaskListFields(task) })\n return { detail: `${title.slice(0, 60)} (lead)` }\n }\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, links))) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).doc(createResourceUid()).set(activity)\n return { detail: `${step.kind} (lead)` }\n }\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * Whether — and where — an email a plugin is about to send lands on a\n * timeline: the CRM's answer to the record timeline's `prepareEmail`.\n *\n * An automation's `sendEmail` step is not a CRM step: it mails whatever\n * address the event carries, to a person who may be nobody the CRM knows. It\n * earns a row on exactly one condition, that the message is ADDRESSED TO THE\n * PERSON the sender means — a contact, else the lead a lead-routed form filed\n * (AGL-3458), whose row lands on the lead's timeline — the person the request's link finds, at the\n * address the row holds. A welcome sequence to a new contact is that; an\n * internal alert routed to a merchant's own address through `toField` is not,\n * and a row for it would put the merchant's inbox on a customer's history.\n *\n * Prepared ahead of the send, for the reason the console route mints its id\n * first: the delivery webhook has nothing but the tags on the message to find\n * the row with. Nothing is written until `file` is called, once the provider\n * accepted the message. A workspace whose plan does not carry the CRM, a\n * record at the activity ceiling and a site with no org earn no row — the\n * message still goes, because the ceiling bounds the log and not the mail.\n *\n * **Never throws**, and neither does `file`. The row is bookkeeping beside a\n * send, and a lookup that fails must not become a message that never left —\n * the posture every meter beside a send takes. A failure is logged and the\n * message goes out untagged.\n */\nexport async function prepareCrmRecordEmail(\n request: PluginRecordEmailPrepareRequest,\n): Promise<PluginRecordPreparedEmail | null> {\n const orgId = String(request.orgId ?? '').trim()\n const hostId = String(request.hostId ?? '').trim()\n if (!orgId || !hostId) return null\n const address = normalizeContactEmail(request.to)\n if (!address) return null\n try {\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n // The org the caller already read, or the one read here once.\n const org =\n request.org !== undefined ? request.org : ((await orgRef.get()).data() ?? null)\n if (!checkEntitlement(org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return null\n }\n const person = await resolveEventPerson(hostId, request.link)\n if (!person || normalizeContactEmail(person.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(hostId)\n const link: CrmActivityLink =\n person.kind === 'lead'\n ? { leadId: person.id }\n : stampCrmActivityCompany(\n { contactId: person.id },\n { contact: person.data, groupId: group.groupId },\n )\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, orgId)\n const visibleTo = crmScopeTokens((org ?? null) as Record<string, unknown> | null, group)\n return {\n tags: crmEmailDeliveryTags({ orgId, hostId, activityId: ref.id }),\n /*\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the sender's id as its source and nobody as its\n * author. Never throws: the message has left, and a row that could not\n * be written is a gap on the timeline rather than a failed send.\n */\n async file(sent) {\n try {\n await writeCrmEmailActivity(\n ref,\n buildCrmEmailActivity({\n subject: sent.subject,\n body: sent.body,\n to: normalizeContactEmail(sent.to) ?? sent.to,\n atMs: sent.atMs ?? Date.now(),\n byUid: '',\n sourceActionId: sent.sourceRef,\n link,\n hostId,\n visibleTo,\n }),\n )\n } catch (error) {\n console.error('[crm] automation email activity write failed', ref.id, error)\n }\n },\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', hostId, error)\n return null\n }\n}\n"],"names":["buildCrmEmailActivity","checkEntitlement","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmActivityDirection","crmEmailDeliveryTags","crmScopeTokens","crmTaskLabelsForNew","crmTaskListFields","normalizeContactEmail","parseCrmMemberRef","personKey","planLabelGrantingFeature","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","orgDataQueryForHost","restampCrmListFieldsAt","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","reassignLeadOwner","createResourceUid","readCrmTaskPicklists","CRM_SUITE_FEATURE","crmTaskReminderAfterEdit","recomputeCrmNextTaskAt","newCrmActivityRef","writeCrmEmailActivity","stampCrmActivityCompany","DAY_MS","resolveEventContact","hostId","named","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","email","resolveEventLead","key","leadId","leadsRef","resolveEventPerson","contact","kind","lead","resolveMemberUid","orgId","role","uid","error","members","app","firestore","collection","member","detail","byField","where","limit","docs","runCrmAutomationStep","request","nowMs","Date","now","env","org","step","actionId","run","person","payload","runLeadStep","group","facet","groupId","type","previous","lifecycleStage","label","update","updatedAt","serverTimestamp","emit","event","previousStage","tag","slice","arrayUnion","assign","roundRobin","owner","ownerUid","ownerEmail","memberUid","verdict","outcome","reason","orgRef","visibleTo","links","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","priority","labels","task","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","direction","activity","atMs","byUid","activities","tags","fresh","set","prepareCrmRecordEmail","address","to","undefined","link","activityId","file","sent","subject","sourceRef"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,eAAe,EACfC,qBAAqB,EAGrBC,oBAAoB,EAIpBC,oBAAoB,EACpBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,qBAAqB,EACrBC,iBAAiB,EACjBC,SAAS,EACTC,wBAAwB,EACxBC,gBAAgB,EAChBC,aAAa,QACR,sBAAqB;AAS5B,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,aAAa,EACbC,mBAAmB,EACnBC,sBAAsB,QACjB,2BAA0B;AACjC,2EAA2E;AAC3E,yDAAyD;AACzD,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,6DAA6D;AAC7D,SACEC,yBAAyB,EACzBC,oBAAoB,EACpBC,iBAAiB,QACZ,4BAAwB;AAC/B,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,wBAAwB,QAAQ,iCAA6B;AACtE,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,qBAAqB,QAA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BAAQmH,YAAYhH,IAAIQ,EAAE;YAAC;YAC/D;;;;;OAKC,GACD,MAAMyG,MAAKC,IAAI;gBACb,IAAI;wBAMM/I,wBACE+I;oBANV,MAAMzH,sBACJO,KACA1C,sBAAsB;wBACpB6J,SAASD,KAAKC,OAAO;wBACrBlB,MAAMiB,KAAKjB,IAAI;wBACfY,EAAE,GAAE1I,yBAAAA,sBAAsB+I,KAAKL,EAAE,aAA7B1I,yBAAkC+I,KAAKL,EAAE;wBAC7CR,IAAI,GAAEa,aAAAA,KAAKb,IAAI,YAATa,aAAa7E,KAAKC,GAAG;wBAC3BgE,OAAO;wBACPX,gBAAgBuB,KAAKE,SAAS;wBAC9BL;wBACAlH;wBACA4E;oBACF;gBAEJ,EAAE,OAAOlD,OAAO;oBACdyE,QAAQzE,KAAK,CAAC,gDAAgDvB,IAAIQ,EAAE,EAAEe;gBACxE;YACF;QACF;IACF,EAAE,OAAOA,OAAO;QACdyE,QAAQzE,KAAK,CAAC,yDAAyD1B,QAAQ0B;QAC/E,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/automation-steps.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 buildCrmEmailActivity,\n checkEntitlement,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActivity,\n type CrmActivityDirection,\n crmActivityDirection,\n type CrmActivityLink,\n type CrmTask,\n type CrmTaskPriority,\n crmEmailDeliveryTags,\n crmScopeFields,\n crmTaskLabelsForNew,\n crmTaskListFields,\n normalizeContactEmail,\n parseCrmMemberRef,\n personKey,\n planLabelGrantingFeature,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport type {\n PluginRecordEmailPrepareRequest,\n PluginRecordPreparedEmail,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport type {\n ServerStepAnswer,\n ServerStepRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-server-steps'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n orgDataQueryForHost,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: the specs substitute the barrel wholesale, and\n// the lookup must reach the real index logic under them.\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { FieldValue } from 'firebase-admin/firestore'\n// The leaf, not the runtime barrel: the specs substitute it.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n reassignLeadOwner,\n} from './assign-contact-owner'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { InteractionStepGuard } from '@aglyn/aglyn/app-utils/site-interactions'\nimport type { ContactLifecycleStage, CrmActivityKind, CrmTaskKind } from '@aglyn/aglyn/app-utils/crm-kinds'\nimport type { CRM_STEP_TYPES } from '../constants/bundle-common'\nimport { readCrmTaskPicklists } from './read-picklist'\nimport { CRM_SUITE_FEATURE } from './suite-gate'\nimport { crmTaskReminderAfterEdit } from '../model/crm-task-reminders'\nimport { recomputeCrmNextTaskAt } from './crm-next-activity'\nimport { newCrmActivityRef, writeCrmEmailActivity } from './crm-email-activity'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\n\n/**\n * THE AUTOMATION STEPS THAT WRITE THE CRM (AGL-2605), run for the automation\n * engine through the platform's server-step seam (`plugin-server-steps`,\n * AGL-3080): `setContactStage`, `addContactTag`, `assignContactOwner`,\n * `createCrmTask` and `logCrmActivity`.\n *\n * The engine keeps the step's guard, the run's order, its history and the\n * nesting cap; this answers what the step did. A refusal is ANSWERED as\n * `error`, never thrown, and its words are the line the run history carries —\n * the same words the engine wrote when these steps were its own.\n *\n * The five share one shape no other step has: each begins by finding THE\n * PERSON the event is about, and each writes either inside the site's facet on\n * that person or a record stamped with the site's scope. One resolver and one\n * scope expression, used five times, rather than five copies drifting apart.\n *\n * ## The person is the event's, never the step's\n *\n * A step carries no contact reference. The contact is whoever the event\n * names — by `contactId` when the emitting door knew the document, and by\n * `email` otherwise, which is what every pre-CRM event carries. Both lookups\n * are scoped to what THIS site may see: a document the id names but the site\n * cannot read is treated as absent, exactly as the scoped query would have\n * treated it, so an event replayed against the wrong site reaches nobody.\n *\n * ## A missing person is a reported no-op\n *\n * Nothing is written and the step's error names the reason, which lands in\n * the run summary beside the trigger — the same place \"why didn't it fire?\"\n * is answered for every other step. Silence here would make a mis-wired\n * trigger (a form with no email field) indistinguishable from a working one.\n *\n * ## The plan gate is the CRM's\n *\n * Every step is refused on a workspace whose plan does not carry the CRM,\n * into the run history with the tier that carries it, so a Free workspace\n * whose flow names a CRM step reads why the step did nothing rather than a\n * log that says it ran. The org document is the one the run's gate already\n * read, handed over with the step, so the check costs no read.\n *\n * The same module answers the record timeline's `prepareEmail` (AGL-2615): an\n * automation's email addressed to the contact the event is about is filed on\n * that contact's timeline — see {@link prepareCrmRecordEmail}.\n */\n\n/** One of the steps this module runs. */\nexport type CrmStepType = (typeof CRM_STEP_TYPES)[number]\n\n/**\n * A CRM step, as it is stored: the CRM's own shapes of the steps it runs. The\n * automation editor writes them and checks them; `apps/console/specs/\n * crm-automation-steps.spec.ts` runs what it writes through this module.\n */\nexport type CrmAutomationStep = (\n | { type: 'setContactStage'; lifecycleStage: ContactLifecycleStage }\n | { type: 'addContactTag'; tag: string }\n | { type: 'assignContactOwner'; ownerUid?: string; ownerEmail?: string; roundRobin?: boolean }\n | {\n type: 'createCrmTask'\n title: string\n kind: CrmTaskKind\n /** `normal` when absent — the steps written before priorities were (AGL-3517). */\n priority?: CrmTaskPriority\n dueInDays: number\n assigneeUid?: string\n assigneeEmail?: string\n }\n | {\n type: 'logCrmActivity'\n kind: CrmActivityKind\n body: string\n /** Which way a call or an email went (AGL-3517). */\n direction?: CrmActivityDirection\n }\n) & { when?: InteractionStepGuard | null } & { type: CrmStepType }\n\n/** The site, the plan and the org a step or an email is answered for. */\ninterface CrmStepEnv {\n hostId: string\n /** The owning org's billing doc, already read by the run's gate. */\n org: unknown\n orgId: string | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\ninterface ResolvedContact {\n id: string\n ref: FirebaseFirestore.DocumentReference\n data: Record<string, unknown>\n}\n\n/**\n * The person a CRM step acts on: a contact, or — when the workspace holds\n * none for them — the LEAD the site filed (AGL-3458).\n *\n * A lead-routed form files a lead and no contact (AGL-3232), and announces it\n * with the `lead` event. An automation welcoming that person — assign an\n * owner, book a call, tag them — has only the lead to act on, so each step\n * that has a lead's equivalent writes it there: the lead's own `ownerUid`,\n * its own `tags`, a task or an activity filed under `leadId`. A stage is a\n * contact's alone, and a step setting one on a lead says so.\n */\ntype ResolvedPerson =\n | ({ kind: 'contact' } & ResolvedContact)\n | ({ kind: 'lead' } & ResolvedContact)\n\n/**\n * The contact an event names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote and\n * a lookup by id is a read, not a query. The address second, through the\n * org's address index narrowed to this site (AGL-2633), for every event that\n * predates the CRM and knows only who filled in the form — so an address a\n * merge folded into another record still reaches the person who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n named: { contactId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(named.contactId ?? '').trim()\n if (contactId) {\n const doc = await contactsRef.doc(contactId).get()\n if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n }\n }\n const hit = await findContactByEmail(contactsRef, named.email, { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : null\n}\n\n/**\n * The lead an event names, as this site may see it: by `leadId` — the `lead`\n * event carries it, and it is the person's key — else by the key of the\n * `email`. A row this site cannot see is absent, exactly as a contact's is.\n */\nasync function resolveEventLead(\n hostId: string,\n named: { leadId?: unknown; email?: unknown },\n): Promise<ResolvedContact | null> {\n const key = String(named.leadId ?? '').trim() || personKey(named.email) || ''\n if (!key) return null\n const { ref: leadsRef } = await orgDataQueryForHost(hostId, 'leads')\n const doc = await leadsRef.doc(key).get()\n if (!doc.exists || !visibleToHost(doc.get('visibleTo'), hostId)) return null\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n}\n\n/** The contact the event names, else its lead — see {@link ResolvedPerson}. */\nasync function resolveEventPerson(\n hostId: string,\n named: { contactId?: unknown; leadId?: unknown; email?: unknown },\n): Promise<ResolvedPerson | null> {\n const contact = await resolveEventContact(hostId, named)\n if (contact) return { kind: 'contact', ...contact }\n const lead = await resolveEventLead(hostId, named)\n return lead ? { kind: 'lead', ...lead } : null\n}\n\n/**\n * The uid a step names for somebody on the team — an owner, an assignee —\n * resolved against the org's roster, whichever way the step named them.\n *\n * A step names a member by uid when a picker wrote it and by address when a\n * person typed it, and the editor's one text field accepts either — so both\n * fields are read through `parseCrmMemberRef`, and an address typed into the\n * uid slot or a uid typed into the address slot still names the person.\n *\n * Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by the\n * uid, so a uid costs one document read and must exist: `ownerUid` and\n * `assigneeUid` are fields every reader resolves as a member, and a stranger's\n * uid in one is a task nobody on the team can find. An address is matched on\n * the roster's own `email` field, and two production paths create a member\n * document WITHOUT one (a host-access re-grant, and an add whose auth record\n * carried none) — such a member is named by uid, which is the reason the\n * editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup by\n * address would resolve people who are not on this organization at all\n * (AGL-1122). A reference that resolves neither way is an error, not a stored\n * string.\n */\nasync function resolveMemberUid(\n orgId: string | null,\n named: { uid?: string; email?: string },\n role: 'owner' | 'assignee',\n): Promise<{ uid: string; detail: string } | { error: string }> {\n const ref = parseCrmMemberRef(named.uid) ?? parseCrmMemberRef(named.email)\n if (!ref) return { error: `no ${role} named on the step` }\n if (!orgId) return { error: 'this site has no organization' }\n const members = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n if (ref.kind === 'uid') {\n const member = await members.doc(ref.uid).get()\n if (member.exists) return { uid: ref.uid, detail: ref.uid }\n return { error: `no team member with the id ${ref.uid}` }\n }\n const byField = (await members.where('email', '==', ref.email).limit(1).get()).docs[0]\n if (byField) return { uid: byField.id, detail: ref.email }\n return { error: `no team member with the address ${ref.email}` }\n}\n\n/**\n * Runs one CRM step for the person the event names: the executor the CRM\n * registers on the server-step seam for every type in `CRM_STEP_TYPES`.\n *\n * Never throws for a plan without the CRM, a missing person, an unknown owner\n * or a site with no org — those are answered as `error` so the run records\n * them; a Firestore failure propagates, and the engine records it the same\n * way.\n */\nexport async function runCrmAutomationStep(\n request: ServerStepRequest,\n nowMs = Date.now(),\n): Promise<ServerStepAnswer> {\n if (!checkEntitlement(request.org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return { error: `CRM steps require the ${planLabelGrantingFeature(CRM_SUITE_FEATURE)} plan` }\n }\n const env: CrmStepEnv = { hostId: request.hostId, org: request.org, orgId: request.orgId }\n const step = request.step as unknown as CrmAutomationStep\n const actionId = request.run.id\n const { hostId } = env\n const person = await resolveEventPerson(hostId, request.payload)\n if (!person) {\n const named = String(request.payload['contactId'] ?? request.payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact or lead this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\n if (person.kind === 'lead') return runLeadStep(env, actionId, step, person, nowMs)\n const contact = person\n /*\n * THE HOLDER whose facet the write addresses — the site's consent group,\n * which is the site alone unless the org declared the site one of a set\n * that presents as one sender. Same resolution the capture doors use, so a\n * stage set here lands in the facet the console reads.\n */\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const email = String(contact.data['email'] ?? '')\n\n if (step.type === 'setContactStage') {\n const previous = facet.lifecycleStage ?? ''\n const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage]\n /*\n * A stage set to what it already is changes nothing and ANNOUNCES\n * nothing. The write is skipped so the row's `updatedAt` does not move for\n * a non-event, and the absent emit is what stops an action that sets the\n * stage it listens for from re-running on its own write — the engine's\n * nesting cap bounds that chain, this ends it at once.\n */\n if (previous === step.lifecycleStage) {\n return { detail: `${label} (already)` }\n }\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n /*\n * A stage set by an automation IS a stage change, and the action\n * listening for it must run — but through the engine's nesting cap, so\n * the event is answered back for the engine to raise, never raised here.\n */\n return {\n detail: label,\n emit: {\n event: 'contactStageChanged',\n payload: {\n contactId: contact.id,\n email,\n lifecycleStage: step.lifecycleStage,\n previousStage: previous,\n },\n },\n }\n }\n\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n // `arrayUnion`, so the tag a merchant already applied by hand is not\n // duplicated and the tags beside it are kept.\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\n return { detail: tag }\n }\n\n if (step.type === 'assignContactOwner') {\n /*\n * Through the one server assignment (AGL-2618), in both of the step's\n * modes, rather than a facet write of its own: the helper is what moves\n * the round-robin pointer inside the transaction that writes the owner,\n * mirrors the owner onto the site's lead, and tells the new owner. A\n * member named on the step is still resolved here — by address against\n * the roster, as before — and handed over by uid; the helper checks the\n * roster document again, which is one read and the same answer.\n */\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignContactOwner({\n hostId,\n contactId: contact.id,\n email,\n assign,\n })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') {\n return { detail: `${named} (already)` }\n }\n return {\n detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of their\n // own beside the contact, stamped with the scope a contact captured on this\n // site would carry — `crmScopeFields` is the create path's own expression,\n // so a record an automation made is visible to exactly the sites a record a\n // person made would be, with the marker under \"All sites except…\" (AGL-4047).\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const { visibleTo, ...marker } = crmScopeFields(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n )\n const links = stampCrmActivityCompany(\n { contactId: contact.id },\n { contact: contact.data, groupId: group.groupId },\n )\n\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n /*\n * The assignee the step names, else the person who OWNS the contact, else\n * nobody. A follow-up task belongs to whoever holds the relationship, and\n * an automation that had to name one person for every contact it touches\n * would assign the whole list to one rep. A named assignee who cannot be\n * resolved is an error rather than a fallback to the owner: the author\n * named somebody on purpose.\n */\n let assignee = facet.ownerUid ?? ''\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const priority: CrmTaskPriority =\n step.priority === 'high' || step.priority === 'low' ? step.priority : 'normal'\n // The org's labels for the meanings the step names (AGL-3517).\n const labels = crmTaskLabelsForNew(\n await readCrmTaskPicklists(firebaseAdmin.app().firestore(), env.orgId),\n { kind: step.kind, priority },\n )\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority,\n status: 'open',\n ...labels,\n dueAtMs,\n // The reminder a person's task gets (AGL-2659): the due time.\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n ...marker,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n // What the Tasks list searches by (AGL-3321), beside the task.\n await orgRef.collection(CRM_COLLECTIONS.tasks).add({ ...task, ...crmTaskListFields(task) })\n // The contact and company the task names carry `nextTaskAtMs` (AGL-2661);\n // a figure that could not move is the Fields section's recompute's.\n await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [links]).catch(\n (error: unknown) => {\n console.error('[crm] next activity could not be recomputed', env.orgId, error)\n },\n )\n return { detail: title.slice(0, 60) }\n }\n\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n /*\n * The per-record ceiling (AGL-2611), and this step is the writer it exists\n * for: a flow that logs on every page view fills one person's log in an\n * afternoon. Refused into the run history as an error, the way an\n * unresolvable assignee is, so the merchant reads why the flow stopped\n * writing rather than finding a log that silently stopped.\n */\n const logged = await countCrmActivitiesForRecord(orgRef, links)\n if (!crmActivityLogHasRoom(logged)) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const direction = crmActivityDirection(step.kind, step.direction)\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n ...(direction ? { direction } : {}),\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n ...marker,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * A CRM step on a LEAD (AGL-3458) — the person is not a contact yet, so each\n * step writes the lead's equivalent of what it writes on a contact. See\n * {@link ResolvedPerson}.\n */\nasync function runLeadStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmAutomationStep,\n lead: ResolvedContact,\n nowMs: number,\n): Promise<ServerStepAnswer> {\n const { hostId } = env\n if (step.type === 'setContactStage') {\n return {\n error:\n 'the event names a lead, and a lead has no lifecycle stage until it is ' +\n 'converted to a contact',\n }\n }\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n await lead.ref.update({\n tags: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // A lead's tags are what the Leads list searches (AGL-3321).\n await restampCrmListFieldsAt(lead.ref, 'leads')\n return { detail: `${tag} (lead)` }\n }\n if (step.type === 'assignContactOwner') {\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignLeadOwner({ hostId, leadId: lead.id, assign })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') return { detail: `${named} (already, lead)` }\n return {\n detail:\n step.roundRobin === true\n ? `round robin → ${verdict.ownerUid} (lead)`\n : `${named} (lead)`,\n }\n }\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId)\n const group = await consentGroupForSite(hostId)\n // With the marker under \"All sites except…\" (AGL-4047), as on a contact.\n const { visibleTo, ...marker } = crmScopeFields(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n )\n // Filed under the lead, as a sequence's call step files one (AGL-3233); a\n // conversion stamps the contact beside it, and the task follows the person.\n const links = { leadId: lead.id }\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n // The named assignee, else whoever owns the lead NOW — an owner step\n // earlier in this same run wrote the lead after it was resolved, so it\n // is read again — else nobody.\n let assignee: string\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n } else {\n const fresh = await lead.ref.get()\n assignee = String((fresh.data() ?? lead.data)['ownerUid'] ?? '')\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\n dueAtMs,\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n ...marker,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef\n .collection(CRM_COLLECTIONS.tasks)\n .doc(createResourceUid())\n .set({ ...task, ...crmTaskListFields(task) })\n return { detail: `${title.slice(0, 60)} (lead)` }\n }\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, links))) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n ...marker,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).doc(createResourceUid()).set(activity)\n return { detail: `${step.kind} (lead)` }\n }\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * Whether — and where — an email a plugin is about to send lands on a\n * timeline: the CRM's answer to the record timeline's `prepareEmail`.\n *\n * An automation's `sendEmail` step is not a CRM step: it mails whatever\n * address the event carries, to a person who may be nobody the CRM knows. It\n * earns a row on exactly one condition, that the message is ADDRESSED TO THE\n * PERSON the sender means — a contact, else the lead a lead-routed form filed\n * (AGL-3458), whose row lands on the lead's timeline — the person the request's link finds, at the\n * address the row holds. A welcome sequence to a new contact is that; an\n * internal alert routed to a merchant's own address through `toField` is not,\n * and a row for it would put the merchant's inbox on a customer's history.\n *\n * Prepared ahead of the send, for the reason the console route mints its id\n * first: the delivery webhook has nothing but the tags on the message to find\n * the row with. Nothing is written until `file` is called, once the provider\n * accepted the message. A workspace whose plan does not carry the CRM, a\n * record at the activity ceiling and a site with no org earn no row — the\n * message still goes, because the ceiling bounds the log and not the mail.\n *\n * **Never throws**, and neither does `file`. The row is bookkeeping beside a\n * send, and a lookup that fails must not become a message that never left —\n * the posture every meter beside a send takes. A failure is logged and the\n * message goes out untagged.\n */\nexport async function prepareCrmRecordEmail(\n request: PluginRecordEmailPrepareRequest,\n): Promise<PluginRecordPreparedEmail | null> {\n const orgId = String(request.orgId ?? '').trim()\n const hostId = String(request.hostId ?? '').trim()\n if (!orgId || !hostId) return null\n const address = normalizeContactEmail(request.to)\n if (!address) return null\n try {\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n // The org the caller already read, or the one read here once.\n const org =\n request.org !== undefined ? request.org : ((await orgRef.get()).data() ?? null)\n if (!checkEntitlement(org as Parameters<typeof checkEntitlement>[0], CRM_SUITE_FEATURE)) {\n return null\n }\n const person = await resolveEventPerson(hostId, request.link)\n if (!person || normalizeContactEmail(person.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(hostId)\n const link: CrmActivityLink =\n person.kind === 'lead'\n ? { leadId: person.id }\n : stampCrmActivityCompany(\n { contactId: person.id },\n { contact: person.data, groupId: group.groupId },\n )\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, orgId)\n const { visibleTo, ...marker } = crmScopeFields(\n (org ?? null) as Record<string, unknown> | null,\n group,\n )\n return {\n tags: crmEmailDeliveryTags({ orgId, hostId, activityId: ref.id }),\n /*\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the sender's id as its source and nobody as its\n * author. Never throws: the message has left, and a row that could not\n * be written is a gap on the timeline rather than a failed send.\n */\n async file(sent) {\n try {\n await writeCrmEmailActivity(ref, {\n ...buildCrmEmailActivity({\n subject: sent.subject,\n body: sent.body,\n to: normalizeContactEmail(sent.to) ?? sent.to,\n atMs: sent.atMs ?? Date.now(),\n byUid: '',\n sourceActionId: sent.sourceRef,\n link,\n hostId,\n visibleTo,\n }),\n // Under \"All sites except…\", the marker a site added later joins by (AGL-4047).\n ...marker,\n })\n } catch (error) {\n console.error('[crm] automation email activity write failed', ref.id, error)\n }\n },\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', hostId, error)\n return null\n }\n}\n"],"names":["buildCrmEmailActivity","checkEntitlement","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmActivityDirection","crmEmailDeliveryTags","crmScopeFields","crmTaskLabelsForNew","crmTaskListFields","normalizeContactEmail","parseCrmMemberRef","personKey","planLabelGrantingFeature","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","orgDataQueryForHost","restampCrmListFieldsAt","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","reassignLeadOwner","createResourceUid","readCrmTaskPicklists","CRM_SUITE_FEATURE","crmTaskReminderAfterEdit","recomputeCrmNextTaskAt","newCrmActivityRef","writeCrmEmailActivity","stampCrmActivityCompany","DAY_MS","resolveEventContact","hostId","named","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","email","resolveEventLead","key","leadId","leadsRef","resolveEventPerson","contact","kind","lead","resolveMemberUid","orgId","role","uid","error","members","app","firestore","collection","member","detail","byField","where","limit","docs","runCrmAutomationStep","request","nowMs","Date","now","env","org","step","actionId","run","person","payload","runLeadStep","group","facet","groupId","type","previous","lifecycleStage","label","update","updatedAt","serverTimestamp","emit","event","previousStage","tag","slice","arrayUnion","assign","roundRobin","owner","ownerUid","ownerEmail","memberUid","verdict","outcome","reason","orgRef","visibleTo","marker","links","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","priority","labels","task","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","direction","activity","atMs","byUid","activities","tags","fresh","set","prepareCrmRecordEmail","address","to","undefined","link","activityId","file","sent","subject","sourceRef"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,gBAAgB,EAChBC,8B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,KAAKL,EAAE,aAA7B3I,yBAAkCgJ,KAAKL,EAAE;wBAC7CR,IAAI,GAAEa,aAAAA,KAAKb,IAAI,YAATa,aAAa9E,KAAKC,GAAG;wBAC3BiE,OAAO;wBACPX,gBAAgBuB,KAAKE,SAAS;wBAC9BL;wBACAnH;wBACA4E;oBACF,IAEGC;gBAEP,EAAE,OAAOnD,OAAO;oBACd0E,QAAQ1E,KAAK,CAAC,gDAAgDvB,IAAIQ,EAAE,EAAEe;gBACxE;YACF;QACF;IACF,EAAE,OAAOA,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,yDAAyD1B,QAAQ0B;QAC/E,OAAO;IACT;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
2
3
|
/**
|
|
3
4
|
* @license
|
|
4
5
|
* Copyright 2026 Aglyn LLC
|
|
@@ -16,7 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
17
|
* limitations under the License.
|
|
17
18
|
*/ import { consentGroupForHost } from "@aglyn/aglyn/app-utils/consent-groups";
|
|
18
19
|
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
19
|
-
import { CRM_COLLECTIONS, crmActivityLogHasRoom,
|
|
20
|
+
import { CRM_COLLECTIONS, crmActivityLogHasRoom, crmScopeFields } from "@aglyn/aglyn/app-utils/crm";
|
|
20
21
|
import { countCrmActivitiesForRecord } from "@aglyn/tenant-data-admin/server/crm-records";
|
|
21
22
|
import { readOrgContainers } from "@aglyn/tenant-data-admin/server/org-containers";
|
|
22
23
|
import { createHash } from "crypto";
|
|
@@ -51,7 +52,10 @@ import { crmActivityLinkWithCompany } from "./crm-activity-company.js";
|
|
|
51
52
|
const orgRef = firestore.collection('orgs').doc(input.orgId);
|
|
52
53
|
const org = (_ref = (_input_org = input.org) != null ? _input_org : (await orgRef.get()).data()) != null ? _ref : null;
|
|
53
54
|
const group = consentGroupForHost(org, input.hostId);
|
|
54
|
-
|
|
55
|
+
// With the marker under "All sites except…" (AGL-4047).
|
|
56
|
+
const _crmScopeFields = crmScopeFields(org, group), { visibleTo } = _crmScopeFields, marker = _object_without_properties_loose(_crmScopeFields, [
|
|
57
|
+
"visibleTo"
|
|
58
|
+
]);
|
|
55
59
|
if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, input.link))) {
|
|
56
60
|
console.warn('[crm] the filing was not written on the timeline: the record’s log is full', input.link);
|
|
57
61
|
return 0;
|
|
@@ -72,7 +76,7 @@ import { crmActivityLinkWithCompany } from "./crm-activity-company.js";
|
|
|
72
76
|
atMs: input.atMs,
|
|
73
77
|
byUid: input.byUid,
|
|
74
78
|
byName: (_input_byName = input.byName) != null ? _input_byName : null
|
|
75
|
-
}), {
|
|
79
|
+
}), marker, {
|
|
76
80
|
createdAt: FieldValue.serverTimestamp(),
|
|
77
81
|
updatedAt: FieldValue.serverTimestamp()
|
|
78
82
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/campaign-filing-activity.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n crmScopeTokens,\n type CrmActivityLink,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { createHash } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n buildCampaignFilingActivity,\n type CampaignFilingAction,\n type CampaignFilingRef,\n} from '../model/campaign-filing-activity'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\n\n/**\n * FILES A FILING ON THE RECORD'S TIMELINE (AGL-3274), from the server.\n *\n * The two doors that file a lead under a campaign on the server — the\n * `leads-create` route behind the New lead drawer, and the conversion's\n * carry of a lead's campaigns onto the contact — write the entry through\n * this, with the scope a record made on the site carries and the CRM's\n * own id as the filing plugin, exactly as the console's hook writes one.\n *\n * ## Once, when the caller says so\n *\n * A member's act is an act each time, and the route's entries are named\n * by `createResourceUid()`, the id every console resource carries. The\n * conversion carry runs from a seam every converting\n * door reaches, and a door that runs twice must not file twice — so a\n * caller that hands in a `dedupeKey` gets a keyed `create()`, and the\n * second run finds its own entry and writes nothing. The key is hashed\n * under the CRM's id the way the timeline seam hashes a plugin's, so no\n * caller's raw key becomes a document id.\n *\n * ## Never throws\n *\n * The membership has landed by the time this runs; an entry that could\n * not be filed is logged, and the record's page shows the campaigns from\n * the document either way. A record at its activity ceiling is refused\n * before anything is written, in the same breath.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CampaignFilingActivitiesInput {\n orgId: string\n /**\n * The organization document, when the caller already holds it — the\n * scope tokens read `defaultResourceScope` and the consent groups off\n * it. Read here otherwise.\n */\n org?: Record<string, unknown> | null\n /** The site the entry carries as provenance. */\n hostId: string\n link: CrmActivityLink\n action: CampaignFilingAction\n campaigns: readonly CampaignFilingRef[]\n atMs: number\n /** The member who did it, or `''` for the conversion. */\n byUid: string\n byName?: string | null\n /**\n * A key that files each campaign's entry once across runs — the carry's\n * — or nothing for a member's act, which is new each time.\n */\n dedupeKey?: string | null\n}\n\n/** The document id a keyed entry files under: the CRM's namespace, never a raw key. */\nexport function campaignFilingActivityId(key: string): string {\n return `plg_${createHash('sha256').update(`${BUNDLE_ID}:${key}`).digest('hex').slice(0, 28)}`\n}\n\n/** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */\nconst ALREADY_EXISTS = 6\n\n/**\n * The names of an org's campaigns — the `campaign` container kind — by id,\n * for the entries that name them. A container that is gone answers its id,\n * so the entry still says which.\n */\nexport async function orgCampaignRefs(\n firestore: Firestore,\n orgId: string,\n campaignIds: readonly string[],\n): Promise<CampaignFilingRef[]> {\n if (!campaignIds.length) return []\n if (!orgId) return campaignIds.map((id) => ({ id, name: id }))\n const found = await readOrgContainers(firestore, 'campaign', orgId, campaignIds)\n return found.map((container) => ({ id: container.id, name: container.name || container.id }))\n}\n\n/** Files one entry per campaign; answers how many were written. */\nexport async function fileCampaignFilingActivities(\n firestore: Firestore,\n input: CampaignFilingActivitiesInput,\n): Promise<number> {\n if (!input.campaigns.length) return 0\n try {\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const org =\n input.org ?? ((await orgRef.get()).data() as Record<string, unknown> | undefined) ?? null\n const group = consentGroupForHost(org, input.hostId)\n const visibleTo = crmScopeTokens(org, group)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, input.link))) {\n console.warn('[crm] the filing was not written on the timeline: the record’s log is full', input.link)\n return 0\n }\n const link = await crmActivityLinkWithCompany(orgRef, input.link, { groupId: group.groupId })\n const activities = orgRef.collection(CRM_COLLECTIONS.activities)\n let written = 0\n for (const campaign of input.campaigns) {\n const entry = {\n ...buildCampaignFilingActivity({\n action: input.action,\n campaign,\n link,\n hostId: input.hostId,\n visibleTo,\n atMs: input.atMs,\n byUid: input.byUid,\n byName: input.byName ?? null,\n }),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n if (input.dedupeKey) {\n try {\n await activities.doc(campaignFilingActivityId(`${input.dedupeKey}:${campaign.id}`)).create(entry)\n written += 1\n } catch (error) {\n if ((error as { code?: unknown })?.code !== ALREADY_EXISTS) throw error\n }\n } else {\n // A member's act, new each time, named by the platform's own id.\n await activities.doc(createResourceUid()).create(entry)\n written += 1\n }\n }\n return written\n } catch (error) {\n console.error('[crm] the filing could not be written on the timeline', input.link, error)\n return 0\n }\n}\n"],"names":["consentGroupForHost","createResourceUid","CRM_COLLECTIONS","crmActivityLogHasRoom","crmScopeTokens","countCrmActivitiesForRecord","readOrgContainers","createHash","FieldValue","BUNDLE_ID","buildCampaignFilingActivity","crmActivityLinkWithCompany","campaignFilingActivityId","key","update","digest","slice","ALREADY_EXISTS","orgCampaignRefs","firestore","orgId","campaignIds","length","map","id","name","found","container","fileCampaignFilingActivities","input","campaigns","orgRef","collection","doc","org","get","data","group","hostId","visibleTo","link","console","warn","groupId","activities","written","campaign","entry","action","atMs","byUid","byName","createdAt","serverTimestamp","updatedAt","dedupeKey","create","error","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,eAAe,EACfC,qBAAqB,EACrBC,cAAc,QAET,6BAA4B;AACnC,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,2BAA2B,QAGtB,uCAAmC;AAC1C,SAASC,0BAA0B,QAAQ,4BAAwB;AAwDnE,qFAAqF,GACrF,OAAO,SAASC,yBAAyBC,GAAW;IAClD,OAAO,CAAC,IAAI,EAAEN,WAAW,UAAUO,MAAM,CAAC,GAAGL,UAAU,CAAC,EAAEI,KAAK,EAAEE,MAAM,CAAC,OAAOC,KAAK,CAAC,GAAG,KAAK;AAC/F;AAEA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C,YAAYjB,MAAMC,SAAS,CAAE;gBAU1BD;YATZ,MAAMkB,QAAQ,aACTrC,4BAA4B;gBAC7BsC,QAAQnB,MAAMmB,MAAM;gBACpBF;gBACAN;gBACAF,QAAQT,MAAMS,MAAM;gBACpBC;gBACAU,MAAMpB,MAAMoB,IAAI;gBAChBC,OAAOrB,MAAMqB,KAAK;gBAClBC,MAAM,GAAEtB,gBAAAA,MAAMsB,MAAM,YAAZtB,gBAAgB;YAC1B;gBACAuB,WAAW5C,WAAW6C,eAAe;gBACrCC,WAAW9C,WAAW6C,eAAe;;YAEvC,IAAIxB,MAAM0B,SAAS,EAAE;gBACnB,IAAI;oBACF,MAAMX,WAAWX,GAAG,CAACrB,yBAAyB,GAAGiB,MAAM0B,SAAS,CAAC,CAAC,EAAET,SAAStB,EAAE,EAAE,GAAGgC,MAAM,CAACT;oBAC3FF,WAAW;gBACb,EAAE,OAAOY,OAAO;oBACd,IAAI,CAACA,yBAAD,AAACA,MAA8BC,IAAI,MAAKzC,gBAAgB,MAAMwC;gBACpE;YACF,OAAO;gBACL,iEAAiE;gBACjE,MAAMb,WAAWX,GAAG,CAAChC,qBAAqBuD,MAAM,CAACT;gBACjDF,WAAW;YACb;QACF;QACA,OAAOA;IACT,EAAE,OAAOY,OAAO;QACdhB,QAAQgB,KAAK,CAAC,yDAAyD5B,MAAMW,IAAI,EAAEiB;QACnF,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/campaign-filing-activity.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n crmScopeFields,\n type CrmActivityLink,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { createHash } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n buildCampaignFilingActivity,\n type CampaignFilingAction,\n type CampaignFilingRef,\n} from '../model/campaign-filing-activity'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\n\n/**\n * FILES A FILING ON THE RECORD'S TIMELINE (AGL-3274), from the server.\n *\n * The two doors that file a lead under a campaign on the server — the\n * `leads-create` route behind the New lead drawer, and the conversion's\n * carry of a lead's campaigns onto the contact — write the entry through\n * this, with the scope a record made on the site carries and the CRM's\n * own id as the filing plugin, exactly as the console's hook writes one.\n *\n * ## Once, when the caller says so\n *\n * A member's act is an act each time, and the route's entries are named\n * by `createResourceUid()`, the id every console resource carries. The\n * conversion carry runs from a seam every converting\n * door reaches, and a door that runs twice must not file twice — so a\n * caller that hands in a `dedupeKey` gets a keyed `create()`, and the\n * second run finds its own entry and writes nothing. The key is hashed\n * under the CRM's id the way the timeline seam hashes a plugin's, so no\n * caller's raw key becomes a document id.\n *\n * ## Never throws\n *\n * The membership has landed by the time this runs; an entry that could\n * not be filed is logged, and the record's page shows the campaigns from\n * the document either way. A record at its activity ceiling is refused\n * before anything is written, in the same breath.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CampaignFilingActivitiesInput {\n orgId: string\n /**\n * The organization document, when the caller already holds it — the\n * scope tokens read `defaultResourceScope` and the consent groups off\n * it. Read here otherwise.\n */\n org?: Record<string, unknown> | null\n /** The site the entry carries as provenance. */\n hostId: string\n link: CrmActivityLink\n action: CampaignFilingAction\n campaigns: readonly CampaignFilingRef[]\n atMs: number\n /** The member who did it, or `''` for the conversion. */\n byUid: string\n byName?: string | null\n /**\n * A key that files each campaign's entry once across runs — the carry's\n * — or nothing for a member's act, which is new each time.\n */\n dedupeKey?: string | null\n}\n\n/** The document id a keyed entry files under: the CRM's namespace, never a raw key. */\nexport function campaignFilingActivityId(key: string): string {\n return `plg_${createHash('sha256').update(`${BUNDLE_ID}:${key}`).digest('hex').slice(0, 28)}`\n}\n\n/** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */\nconst ALREADY_EXISTS = 6\n\n/**\n * The names of an org's campaigns — the `campaign` container kind — by id,\n * for the entries that name them. A container that is gone answers its id,\n * so the entry still says which.\n */\nexport async function orgCampaignRefs(\n firestore: Firestore,\n orgId: string,\n campaignIds: readonly string[],\n): Promise<CampaignFilingRef[]> {\n if (!campaignIds.length) return []\n if (!orgId) return campaignIds.map((id) => ({ id, name: id }))\n const found = await readOrgContainers(firestore, 'campaign', orgId, campaignIds)\n return found.map((container) => ({ id: container.id, name: container.name || container.id }))\n}\n\n/** Files one entry per campaign; answers how many were written. */\nexport async function fileCampaignFilingActivities(\n firestore: Firestore,\n input: CampaignFilingActivitiesInput,\n): Promise<number> {\n if (!input.campaigns.length) return 0\n try {\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const org =\n input.org ?? ((await orgRef.get()).data() as Record<string, unknown> | undefined) ?? null\n const group = consentGroupForHost(org, input.hostId)\n // With the marker under \"All sites except…\" (AGL-4047).\n const { visibleTo, ...marker } = crmScopeFields(org, group)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, input.link))) {\n console.warn('[crm] the filing was not written on the timeline: the record’s log is full', input.link)\n return 0\n }\n const link = await crmActivityLinkWithCompany(orgRef, input.link, { groupId: group.groupId })\n const activities = orgRef.collection(CRM_COLLECTIONS.activities)\n let written = 0\n for (const campaign of input.campaigns) {\n const entry = {\n ...buildCampaignFilingActivity({\n action: input.action,\n campaign,\n link,\n hostId: input.hostId,\n visibleTo,\n atMs: input.atMs,\n byUid: input.byUid,\n byName: input.byName ?? null,\n }),\n ...marker,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n if (input.dedupeKey) {\n try {\n await activities.doc(campaignFilingActivityId(`${input.dedupeKey}:${campaign.id}`)).create(entry)\n written += 1\n } catch (error) {\n if ((error as { code?: unknown })?.code !== ALREADY_EXISTS) throw error\n }\n } else {\n // A member's act, new each time, named by the platform's own id.\n await activities.doc(createResourceUid()).create(entry)\n written += 1\n }\n }\n return written\n } catch (error) {\n console.error('[crm] the filing could not be written on the timeline', input.link, error)\n return 0\n }\n}\n"],"names":["consentGroupForHost","createResourceUid","CRM_COLLECTIONS","crmActivityLogHasRoom","crmScopeFields","countCrmActivitiesForRecord","readOrgContainers","createHash","FieldValue","BUNDLE_ID","buildCampaignFilingActivity","crmActivityLinkWithCompany","campaignFilingActivityId","key","update","digest","slice","ALREADY_EXISTS","orgCampaignRefs","firestore","orgId","campaignIds","length","map","id","name","found","container","fileCampaignFilingActivities","input","campaigns","orgRef","collection","doc","org","get","data","group","hostId","visibleTo","marker","link","console","warn","groupId","activities","written","campaign","entry","action","atMs","byUid","byName","createdAt","serverTimestamp","updatedAt","dedupeKey","create","error","code"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,eAAe,EACfC,qBAAqB,EACrBC,cAAc,QAET,6BAA4B;AACnC,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,2BAA2B,QAGtB,uCA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1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
2
3
|
/**
|
|
3
4
|
* @license
|
|
4
5
|
* Copyright 2026 Aglyn LLC
|
|
@@ -92,7 +93,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
92
93
|
* account of the business, and the account record may know better. The
|
|
93
94
|
* deal's Primary Campaign Source is the lead's most recent campaign — see
|
|
94
95
|
* {@link leadLatestCampaignId}.
|
|
95
|
-
*/ import { consentGroupDisclosureKey, consentGroupScope, CRM_COLLECTIONS, CRM_LEAD_STATUS_PICKLIST, crmLeadStatusLabelFor, CRM_COMPANY_PICKLIST_FIELDS, crmPicklistDefaultLabel, judgeCrmCompanyPicklists, readCrmCompanyAccountFields,
|
|
96
|
+
*/ import { consentGroupDisclosureKey, consentGroupScope, CRM_COLLECTIONS, CRM_LEAD_STATUS_PICKLIST, crmLeadStatusLabelFor, CRM_COMPANY_PICKLIST_FIELDS, crmPicklistDefaultLabel, judgeCrmCompanyPicklists, readCrmCompanyAccountFields, crmScopeFields, dealStageForecastCategory, DEFAULT_DEAL_STAGES, grantedUnderConsentGroup, nameSearchFields, contactFacetPath, normalizeContactEmail, ORG_SCOPE_TOKEN, readContactFacet, crmNewRecordListFields, readMarketingBasis, soloConsentGroup } from "@aglyn/aglyn/server";
|
|
96
97
|
import { consentGroupForSite, crmRecordsQuotaForOrg, findContactByEmail, logHostActivity, orgDataCollectionForHost, restampCrmListFieldsAt, writeContactCompanyLink } from "@aglyn/tenant-data-admin";
|
|
97
98
|
import { FieldPath, FieldValue } from "firebase-admin/firestore";
|
|
98
99
|
import { assignOwnerForCapture, notifyRecordAssigned } from "./assign-contact-owner.js";
|
|
@@ -247,7 +248,13 @@ import { readContainerIds } from "@aglyn/aglyn/app-utils/container-membership";
|
|
|
247
248
|
reason: 'no-email'
|
|
248
249
|
};
|
|
249
250
|
const group = await consentGroupForSite(hostId, org);
|
|
250
|
-
|
|
251
|
+
/*
|
|
252
|
+
* The company and the deal carry the marker under "All sites except…"
|
|
253
|
+
* (AGL-4047), so a site added later joins them; a pipeline seeded here is
|
|
254
|
+
* stamped only, as the sweep does not keep pipelines.
|
|
255
|
+
*/ const _crmScopeFields = crmScopeFields(org, group), { visibleTo } = _crmScopeFields, marker = _object_without_properties_loose(_crmScopeFields, [
|
|
256
|
+
"visibleTo"
|
|
257
|
+
]);
|
|
251
258
|
/*
|
|
252
259
|
* What the CALLER may read, for the company-by-domain reuse below: their
|
|
253
260
|
* group's own tokens plus `org`, exactly the set the console's listeners
|
|
@@ -474,7 +481,8 @@ import { readContainerIds } from "@aglyn/aglyn/app-utils/container-membership";
|
|
|
474
481
|
} : {}, ownerUid ? {
|
|
475
482
|
ownerUid
|
|
476
483
|
} : {}, {
|
|
477
|
-
visibleTo
|
|
484
|
+
visibleTo
|
|
485
|
+
}, marker, {
|
|
478
486
|
hostId,
|
|
479
487
|
createdByUid: actor.uid,
|
|
480
488
|
createdAt: FieldValue.serverTimestamp(),
|
|
@@ -604,7 +612,8 @@ import { readContainerIds } from "@aglyn/aglyn/app-utils/container-membership";
|
|
|
604
612
|
}, companyId ? {
|
|
605
613
|
companyId
|
|
606
614
|
} : {}, {
|
|
607
|
-
visibleTo
|
|
615
|
+
visibleTo
|
|
616
|
+
}, marker, {
|
|
608
617
|
hostId,
|
|
609
618
|
createdByUid: actor.uid,
|
|
610
619
|
createdAt: FieldValue.serverTimestamp(),
|