@aglyn/plugins-workflows 1.0.0-beta.199 → 1.0.0-beta.200

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/engine/crm-action-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 CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActionStep,\n type CrmActivity,\n type CrmActivityLink,\n type CrmTask,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskReminderAfterEdit,\n normalizeContactEmail,\n parseCrmMemberRef,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n newCrmActivityRef,\n orgDataQueryForHost,\n recomputeCrmNextTaskAt,\n writeCrmEmailActivity,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: this library's specs substitute the barrel\n// wholesale, and 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 leaves, not the runtime barrel, for the reason `run-event-actions.ts`\n// gives: the specs substitute each one.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n} from '@aglyn/tenant-runtime/assign-contact-owner'\nimport type { HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners'\n\n/**\n * The CRM steps of an action run (AGL-2605): what `setContactStage`,\n * `addContactTag`, `assignContactOwner`, `createCrmTask` and\n * `logCrmActivity` actually write.\n *\n * Split out of `run-event-actions.ts` because the five share one shape the\n * other server steps do not: each begins by finding THE PERSON the event is\n * about, and each writes either inside the site's facet on that person or a\n * record stamped with the site's scope. One resolver and one scope\n * 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\n * lookups are scoped to what THIS site may see: a document the id names\n * but the site cannot read is treated as absent, exactly as the scoped\n * query would have treated it, so an event replayed against the wrong site\n * 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\n * fire?\" is answered for every other step. Silence here would make a\n * mis-wired trigger (a form with no email field) indistinguishable from a\n * working one.\n */\n\nexport interface 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\nexport interface CrmStepOutcome {\n /** The reason nothing was written, when nothing was. */\n error?: string\n /** The one fact worth carrying into the run summary. */\n detail?: string\n /**\n * An event this step's write earned, for the CALLER to fan out under its\n * own depth guard. Not emitted from here: a stage set by an automation is\n * itself a stage change, and the action listening for it must run — but\n * through the same nesting cap a `customEvent` chain has, or an action\n * that sets the stage it listens for would run until the meter ran dry.\n */\n emit?: { event: 'contactStageChanged'; payload: HostEventPayload }\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 contact an event payload names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote\n * and a lookup by id is a read, not a query. The address second, through\n * the org's address index narrowed to this site (AGL-2633), for every\n * event that predates the CRM and knows only who filled in the form — so\n * an address a merge folded into another record still reaches the person\n * who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n payload: HostEventPayload,\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(payload['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, payload['email'], { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : 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\n * the 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\n * the 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\n * stranger's uid in one is a task nobody on the team can find. An address\n * is matched on the roster's own `email` field, and two production paths\n * create a member document WITHOUT one (a host-access re-grant, and an add\n * whose auth record carried none) — such a member is named by uid, which\n * is the reason the editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup\n * by 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\n * stored 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 =\n 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())\n .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. Never throws for a\n * missing person, an unknown owner or a site with no org — those are\n * answered as `error` so the run records them; a Firestore failure\n * propagates to the executor's catch like every other step's would.\n */\nexport async function runCrmActionStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmActionStep,\n payload: HostEventPayload,\n nowMs = Date.now(),\n): Promise<CrmStepOutcome> {\n const { hostId } = env\n const contact = await resolveEventContact(hostId, payload)\n if (!contact) {\n const named = String(payload['contactId'] ?? payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\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\n * a 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\n * for a non-event, and the absent emit is what stops an action that\n * sets the stage it listens for from re-running on its own write —\n * the depth guard 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 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 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\n * moves the round-robin pointer inside the transaction that writes the\n * owner, mirrors the owner onto the site's lead, and tells the new\n * owner. A member named on the step is still resolved here — by\n * address against the roster, as before — and handed over by uid; the\n * helper checks the roster document again, which is one read and the\n * 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:\n step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of\n // their own beside the contact, stamped with the scope a contact\n // captured on this site would carry — `crmScopeTokens` is the create\n // path's own expression, so a record an automation made is visible to\n // exactly the sites a record a person made would be.\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(env.orgId)\n const visibleTo = crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n )\n const links = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\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,\n * else nobody. A follow-up task belongs to whoever holds the\n * relationship, and an automation that had to name one person for\n * every contact it touches would assign the whole list to one rep. A\n * named assignee who cannot be resolved is an error rather than a\n * fallback to the owner: the author 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 task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\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 await orgRef.collection(CRM_COLLECTIONS.tasks).add(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((error: unknown) => {\n console.error('[workflow] next activity could not be recomputed', env.orgId, error)\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\n * exists for: a flow that logs on every page view fills one person's\n * log in an afternoon. Refused into the run history as an error, the\n * way an unresolvable assignee is, so the merchant reads why the flow\n * stopped 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 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).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * The activity row a `sendEmail` step's message will be logged as, prepared\n * BEFORE the send (AGL-2615): the minted reference whose id rides the\n * message as a tag, the links it files under, and the scope it is stamped\n * with. `null` when the message earns no row.\n */\nexport interface PreparedCrmEmailActivity {\n ref: FirebaseFirestore.DocumentReference\n /** The provider tags the delivery webhook finds the row by. */\n tags: { name: string; value: string }[]\n link: CrmActivityLink\n visibleTo: string[]\n}\n\n/**\n * Whether — and where — an automation's email lands on a timeline.\n *\n * A `sendEmail` step is not a CRM step: it mails whatever address the event\n * carries, to a person who may be nobody the CRM knows. It earns a row on\n * exactly one condition, that the message is ADDRESSED TO THE CONTACT the\n * event is about — the person `resolveEventContact` finds, at the address\n * the row holds. A welcome sequence to a new contact is that; an internal\n * alert routed to a merchant's own address through `toField` is not, and a\n * 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\n * id first: the webhook has nothing but the tags on the message to find\n * the row with. Nothing is written here. A record at the activity ceiling\n * earns no row — the message still goes, because the ceiling bounds the\n * log and not the mail — and neither does a site with no org to hold one.\n *\n * **Never throws.** The row is bookkeeping beside a send, and a lookup that\n * fails must not become a message that never left — the posture every\n * meter beside `sendEmail` takes. A failure here is logged and the message\n * goes out untagged.\n */\nexport async function prepareCrmEmailActivity(\n env: CrmStepEnv,\n to: string,\n payload: HostEventPayload,\n): Promise<PreparedCrmEmailActivity | null> {\n if (!env.orgId) return null\n const address = normalizeContactEmail(to)\n if (!address) return null\n try {\n const contact = await resolveEventContact(env.hostId, payload)\n if (!contact || normalizeContactEmail(contact.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(env.hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const link: CrmActivityLink = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\n }\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(env.orgId)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, env.orgId)\n return {\n ref,\n tags: crmEmailDeliveryTags({\n orgId: env.orgId,\n hostId: env.hostId,\n activityId: ref.id,\n }),\n link,\n visibleTo: crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n ),\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', env.hostId, error)\n return null\n }\n}\n\n/**\n * Writes the prepared row, once the provider has accepted the message.\n *\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the automation 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 step.\n */\nexport async function logCrmEmailActivity(\n env: CrmStepEnv,\n prepared: PreparedCrmEmailActivity,\n message: { subject: string; body: string; to: string },\n actionId: string,\n nowMs = Date.now(),\n): Promise<void> {\n try {\n await writeCrmEmailActivity(\n prepared.ref,\n buildCrmEmailActivity({\n subject: message.subject,\n body: message.body,\n to: normalizeContactEmail(message.to) ?? message.to,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n link: prepared.link,\n hostId: env.hostId,\n visibleTo: prepared.visibleTo,\n }),\n )\n } catch (error) {\n console.error('[crm] automation email activity write failed', prepared.ref.id, error)\n }\n}\n"],"names":["buildCrmEmailActivity","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmEmailDeliveryTags","crmScopeTokens","crmTaskReminderAfterEdit","normalizeContactEmail","parseCrmMemberRef","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","newCrmActivityRef","orgDataQueryForHost","recomputeCrmNextTaskAt","writeCrmEmailActivity","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","DAY_MS","resolveEventContact","hostId","payload","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","resolveMemberUid","orgId","named","role","uid","email","error","members","app","firestore","collection","kind","member","detail","byField","where","limit","docs","runCrmActionStep","env","actionId","step","nowMs","Date","now","contact","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","org","links","companyId","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","task","priority","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","activity","atMs","byUid","activities","prepareCrmEmailActivity","to","address","link","tags","activityId","logCrmEmailActivity","prepared","message","subject"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,eAAe,EACfC,qBAAqB,EAKrBC,oBAAoB,EACpBC,cAAc,EACdC,wBAAwB,EACxBC,qBAAqB,EACrBC,iBAAiB,EACjBC,gBAAgB,EAChBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,E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YAAPlC,WAAW,MACZO;QAEJ;IACF,EAAE,OAAOpB,OAAO;QACdsE,QAAQtE,KAAK,CAAC,yDAAyDa,IAAIhC,MAAM,EAAEmB;QACnF,OAAO;IACT;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAemF,oBACpBtE,GAAe,EACfuE,QAAkC,EAClCC,OAAsD,EACtDvE,QAAgB,EAChBE,QAAQC,KAAKC,GAAG,EAAE;IAElB,IAAI;YAMMtD;QALR,MAAMU,sBACJ8G,SAASpG,GAAG,EACZ9B,sBAAsB;YACpBoI,SAASD,QAAQC,OAAO;YACxBf,MAAMc,QAAQd,IAAI;YAClBO,EAAE,GAAElH,yBAAAA,sBAAsByH,QAAQP,EAAE,aAAhClH,yBAAqCyH,QAAQP,EAAE;YACnDJ,MAAM1D;YACN2D,OAAO;YACPV,gBAAgBnD;YAChBkE,MAAMI,SAASJ,IAAI;YACnBnG,QAAQgC,IAAIhC,MAAM;YAClBiE,WAAWsC,SAAStC,SAAS;QAC/B;IAEJ,EAAE,OAAO9C,OAAO;QACdsE,QAAQtE,KAAK,CAAC,gDAAgDoF,SAASpG,GAAG,CAACQ,EAAE,EAAEQ;IACjF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/engine/crm-action-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 CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActionStep,\n type CrmActivity,\n type CrmActivityLink,\n type CrmTask,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskListFields,\n crmTaskReminderAfterEdit,\n normalizeContactEmail,\n parseCrmMemberRef,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n newCrmActivityRef,\n orgDataQueryForHost,\n recomputeCrmNextTaskAt,\n restampCrmListFieldsAt,\n writeCrmEmailActivity,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: this library's specs substitute the barrel\n// wholesale, and 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 leaves, not the runtime barrel, for the reason `run-event-actions.ts`\n// gives: the specs substitute each one.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n} from '@aglyn/tenant-runtime/assign-contact-owner'\nimport type { HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners'\n\n/**\n * The CRM steps of an action run (AGL-2605): what `setContactStage`,\n * `addContactTag`, `assignContactOwner`, `createCrmTask` and\n * `logCrmActivity` actually write.\n *\n * Split out of `run-event-actions.ts` because the five share one shape the\n * other server steps do not: each begins by finding THE PERSON the event is\n * about, and each writes either inside the site's facet on that person or a\n * record stamped with the site's scope. One resolver and one scope\n * 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\n * lookups are scoped to what THIS site may see: a document the id names\n * but the site cannot read is treated as absent, exactly as the scoped\n * query would have treated it, so an event replayed against the wrong site\n * 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\n * fire?\" is answered for every other step. Silence here would make a\n * mis-wired trigger (a form with no email field) indistinguishable from a\n * working one.\n */\n\nexport interface 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\nexport interface CrmStepOutcome {\n /** The reason nothing was written, when nothing was. */\n error?: string\n /** The one fact worth carrying into the run summary. */\n detail?: string\n /**\n * An event this step's write earned, for the CALLER to fan out under its\n * own depth guard. Not emitted from here: a stage set by an automation is\n * itself a stage change, and the action listening for it must run — but\n * through the same nesting cap a `customEvent` chain has, or an action\n * that sets the stage it listens for would run until the meter ran dry.\n */\n emit?: { event: 'contactStageChanged'; payload: HostEventPayload }\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 contact an event payload names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote\n * and a lookup by id is a read, not a query. The address second, through\n * the org's address index narrowed to this site (AGL-2633), for every\n * event that predates the CRM and knows only who filled in the form — so\n * an address a merge folded into another record still reaches the person\n * who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n payload: HostEventPayload,\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(payload['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, payload['email'], { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : 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\n * the 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\n * the 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\n * stranger's uid in one is a task nobody on the team can find. An address\n * is matched on the roster's own `email` field, and two production paths\n * create a member document WITHOUT one (a host-access re-grant, and an add\n * whose auth record carried none) — such a member is named by uid, which\n * is the reason the editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup\n * by 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\n * stored 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 =\n 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())\n .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. Never throws for a\n * missing person, an unknown owner or a site with no org — those are\n * answered as `error` so the run records them; a Firestore failure\n * propagates to the executor's catch like every other step's would.\n */\nexport async function runCrmActionStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmActionStep,\n payload: HostEventPayload,\n nowMs = Date.now(),\n): Promise<CrmStepOutcome> {\n const { hostId } = env\n const contact = await resolveEventContact(hostId, payload)\n if (!contact) {\n const named = String(payload['contactId'] ?? payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\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\n * a 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\n * for a non-event, and the absent emit is what stops an action that\n * sets the stage it listens for from re-running on its own write —\n * the depth guard 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 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\n * moves the round-robin pointer inside the transaction that writes the\n * owner, mirrors the owner onto the site's lead, and tells the new\n * owner. A member named on the step is still resolved here — by\n * address against the roster, as before — and handed over by uid; the\n * helper checks the roster document again, which is one read and the\n * 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:\n step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of\n // their own beside the contact, stamped with the scope a contact\n // captured on this site would carry — `crmScopeTokens` is the create\n // path's own expression, so a record an automation made is visible to\n // exactly the sites a record a person made would be.\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(env.orgId)\n const visibleTo = crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n )\n const links = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\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,\n * else nobody. A follow-up task belongs to whoever holds the\n * relationship, and an automation that had to name one person for\n * every contact it touches would assign the whole list to one rep. A\n * named assignee who cannot be resolved is an error rather than a\n * fallback to the owner: the author 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 task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\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((error: unknown) => {\n console.error('[workflow] next activity could not be recomputed', env.orgId, error)\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\n * exists for: a flow that logs on every page view fills one person's\n * log in an afternoon. Refused into the run history as an error, the\n * way an unresolvable assignee is, so the merchant reads why the flow\n * stopped 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 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).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * The activity row a `sendEmail` step's message will be logged as, prepared\n * BEFORE the send (AGL-2615): the minted reference whose id rides the\n * message as a tag, the links it files under, and the scope it is stamped\n * with. `null` when the message earns no row.\n */\nexport interface PreparedCrmEmailActivity {\n ref: FirebaseFirestore.DocumentReference\n /** The provider tags the delivery webhook finds the row by. */\n tags: { name: string; value: string }[]\n link: CrmActivityLink\n visibleTo: string[]\n}\n\n/**\n * Whether — and where — an automation's email lands on a timeline.\n *\n * A `sendEmail` step is not a CRM step: it mails whatever address the event\n * carries, to a person who may be nobody the CRM knows. It earns a row on\n * exactly one condition, that the message is ADDRESSED TO THE CONTACT the\n * event is about — the person `resolveEventContact` finds, at the address\n * the row holds. A welcome sequence to a new contact is that; an internal\n * alert routed to a merchant's own address through `toField` is not, and a\n * 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\n * id first: the webhook has nothing but the tags on the message to find\n * the row with. Nothing is written here. A record at the activity ceiling\n * earns no row — the message still goes, because the ceiling bounds the\n * log and not the mail — and neither does a site with no org to hold one.\n *\n * **Never throws.** The row is bookkeeping beside a send, and a lookup that\n * fails must not become a message that never left — the posture every\n * meter beside `sendEmail` takes. A failure here is logged and the message\n * goes out untagged.\n */\nexport async function prepareCrmEmailActivity(\n env: CrmStepEnv,\n to: string,\n payload: HostEventPayload,\n): Promise<PreparedCrmEmailActivity | null> {\n if (!env.orgId) return null\n const address = normalizeContactEmail(to)\n if (!address) return null\n try {\n const contact = await resolveEventContact(env.hostId, payload)\n if (!contact || normalizeContactEmail(contact.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(env.hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const link: CrmActivityLink = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\n }\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(env.orgId)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, env.orgId)\n return {\n ref,\n tags: crmEmailDeliveryTags({\n orgId: env.orgId,\n hostId: env.hostId,\n activityId: ref.id,\n }),\n link,\n visibleTo: crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n ),\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', env.hostId, error)\n return null\n }\n}\n\n/**\n * Writes the prepared row, once the provider has accepted the message.\n *\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the automation 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 step.\n */\nexport async function logCrmEmailActivity(\n env: CrmStepEnv,\n prepared: PreparedCrmEmailActivity,\n message: { subject: string; body: string; to: string },\n actionId: string,\n nowMs = Date.now(),\n): Promise<void> {\n try {\n await writeCrmEmailActivity(\n prepared.ref,\n buildCrmEmailActivity({\n subject: message.subject,\n body: message.body,\n to: normalizeContactEmail(message.to) ?? message.to,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n link: prepared.link,\n hostId: env.hostId,\n visibleTo: prepared.visibleTo,\n }),\n )\n } catch (error) {\n console.error('[crm] automation email activity write failed', prepared.ref.id, error)\n }\n}\n"],"names":["buildCrmEmailActivity","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmEmailDeliveryTags","crmScopeTokens","crmTaskListFields","crmTaskReminderAfterEdit","normalizeContactEmail","parseCrmMemberRef","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","newCrmActivityRef","orgDataQueryForHost","recomputeCrmNextTaskAt","restampCrmListFieldsAt","writeCrmEmailActivity","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","DAY_MS","resolveEventContact","hostId","payload","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","resolveMemberUid","orgId","named","role","uid","email","error","members","app","firestore","collection","kind","member","detail","byField","where","limit","docs","runCrmActionStep","env","actionId","step","nowMs","Date","now","contact","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","org","links","companyId","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","task","priority","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","activity","atMs","byUid","activities","prepareCrmEmailActivity","to","address","link","tags","activityId","logCrmEmailActivity","prepared","message","subject"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,eAAe,EACfC,qBAAqB,EAKrBC,oBAAoB,EACpBC,cAAc,EACdC,iBAAiB,EACjBC,wBAAwB,EACxBC,qBAAqB,EACrBC,iBAAiB,EACjBC,gBAAgB,EAChBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,aAAa,EACbC,iBAAiB,EACjBC,mBAAmB,EACnBC,sBAAsB,EACtBC,sBAAsB,EACtBC,qBAAqB,QAChB,2BAA0B;AACjC,uEAAuE;AACvE,wEAAwE;AACxE,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,4EAA4E;AAC5E,wCAAwC;AACxC,SACEC,yBAAyB,EACzBC,oBAAoB,QACf,6CAA4C;AAuDnD,MAAMC,SAAS,KAAK,KAAK,KAAK;AAQ9B;;;;;;;;;CASC,GACD,eAAeC,oBACbC,MAAc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ClCC,OAAsD,EACtDvE,QAAgB,EAChBE,QAAQC,KAAKC,GAAG,EAAE;IAElB,IAAI;YAMMvD;QALR,MAAMW,sBACJ8G,SAASpG,GAAG,EACZhC,sBAAsB;YACpBsI,SAASD,QAAQC,OAAO;YACxBf,MAAMc,QAAQd,IAAI;YAClBO,EAAE,GAAEnH,yBAAAA,sBAAsB0H,QAAQP,EAAE,aAAhCnH,yBAAqC0H,QAAQP,EAAE;YACnDJ,MAAM1D;YACN2D,OAAO;YACPV,gBAAgBnD;YAChBkE,MAAMI,SAASJ,IAAI;YACnBnG,QAAQgC,IAAIhC,MAAM;YAClBiE,WAAWsC,SAAStC,SAAS;QAC/B;IAEJ,EAAE,OAAO9C,OAAO;QACdsE,QAAQtE,KAAK,CAAC,gDAAgDoF,SAASpG,GAAG,CAACQ,EAAE,EAAEQ;IACjF;AACF"}
@@ -18,12 +18,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { isDeferrableSendResult, isEmailConfigured, sendEmail, sendFailureReason } from "@aglyn/shared-util-email";
19
19
  import { dataStorageRefusal, enrollListMember, firebaseAdmin, flowEmailRefusal, getOrgForHost, hostSendingIdentity, meterHostEmail, notifyHostManagers, consentGroupForSite, orgDataCollectionForHost, orgDataQueryForHost, resolveOrgIdForHost } from "@aglyn/tenant-data-admin";
20
20
  import { announceDatasetRecordChange } from "@aglyn/tenant-data-admin/server/dataset-live-pages";
21
+ import { activitySearchTokens } from "@aglyn/aglyn/app-utils/activity-search";
21
22
  import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
22
23
  // The leaf, not the barrel: this library's specs substitute the barrel
23
24
  // wholesale, and the lookup must reach the real index logic under them.
24
25
  import { findContactByEmail } from "@aglyn/tenant-data-admin/server/contact-email-index";
25
26
  import { createHmac } from "crypto";
26
27
  import { FieldValue } from "firebase-admin/firestore";
28
+ import { runSummaryFields } from "../model/run-history.js";
27
29
  import { advanceFlowEnrollment, claimFlowEnrollment, deferFlowEnrollment, endFlowEnrollment, enrollInFlow, findFlowEnrollmentsAwaiting, sweepDueFlowEnrollments } from "./flow-enrollments.js";
28
30
  import { logCrmEmailActivity, prepareCrmEmailActivity, runCrmActionStep } from "./crm-action-steps.js";
29
31
  import { resolveDatasetDoc } from "@aglyn/tenant-runtime/resolve-dataset";
@@ -436,8 +438,18 @@ async function datasetAppendRefusal(env, datasetRef) {
436
438
  values: merged
437
439
  }, datasetIntegrityUpdate(updateModel, merged, FieldValue.delete()), {
438
440
  updatedAt: FieldValue.serverTimestamp()
439
- }), {
440
- merge: true
441
+ }), // `mergeFields`, not `merge: true`: a merge would fold the new
442
+ // `filterValues` map into the stored one key by key, and a value
443
+ // cleared here would go on answering its old equality. Each named
444
+ // field is replaced whole; `merged` already holds every value.
445
+ {
446
+ mergeFields: [
447
+ 'values',
448
+ 'referencedIds',
449
+ 'filterKeys',
450
+ 'filterValues',
451
+ 'updatedAt'
452
+ ]
441
453
  });
442
454
  } else {
443
455
  // The APPEND leg of update-or-append, and the only one of the two
@@ -833,7 +845,7 @@ async function datasetAppendRefusal(env, datasetRef) {
833
845
  */ if (ending === 'deferred') return ending;
834
846
  const noun = orgRun ? 'Org automation' : 'Action';
835
847
  const summary = stepErrors.length ? `${noun} ran on ${event} with errors: ${stepErrors.join('; ')}`.slice(0, 300) : ending === 'waiting' ? `${noun} is waiting, on ${event}` : `${noun} ran on ${event}`;
836
- await hostRef.collection('activity').add({
848
+ await hostRef.collection('activity').add(_extends({
837
849
  actorId: null,
838
850
  actorEmail: null,
839
851
  // The prose line stays exactly as it was: `activityPrimaryText` and
@@ -843,8 +855,8 @@ async function datasetAppendRefusal(env, datasetRef) {
843
855
  // The structured half (AGL-2171) — the two columns the advertised
844
856
  // run-history table could not otherwise fill.
845
857
  result: stepErrors.length ? 'failed' : 'succeeded',
846
- trigger: event,
847
- summary: (outcomes.length ? outcomes.join(' · ') : 'Ran').slice(0, 300),
858
+ trigger: event
859
+ }, runSummaryFields((outcomes.length ? outcomes.join(' · ') : 'Ran').slice(0, 300)), {
848
860
  target: {
849
861
  // An org automation's run is filed under its own type, so the site's
850
862
  // run history can tell it from a site action sharing the feed.
@@ -852,8 +864,14 @@ async function datasetAppendRefusal(env, datasetRef) {
852
864
  id: actionId,
853
865
  name: (_action_name2 = action.name) != null ? _action_name2 : ''
854
866
  },
867
+ // The site log's search finds a run by its action's name (AGL-3321).
868
+ searchTokens: activitySearchTokens({
869
+ target: {
870
+ name: action.name
871
+ }
872
+ }),
855
873
  createdAt: FieldValue.serverTimestamp()
856
- }).catch(()=>undefined);
874
+ })).catch(()=>undefined);
857
875
  return ending;
858
876
  }
859
877
  /**
@@ -1070,20 +1088,25 @@ async function datasetAppendRefusal(env, datasetRef) {
1070
1088
  return String((_ref = condition == null ? void 0 : condition.field) != null ? _ref : '').trim();
1071
1089
  }).filter(Boolean);
1072
1090
  const reason = named.length ? `Condition on ${named.slice(0, 3).join(', ')} not met` : 'Trigger condition not met';
1073
- await hostRef.collection('activity').add({
1091
+ await hostRef.collection('activity').add(_extends({
1074
1092
  actorId: null,
1075
1093
  actorEmail: null,
1076
1094
  action: `${kind === 'orgAutomation' ? 'Org automation' : 'Action'} skipped on ${event}`,
1077
1095
  result: 'skipped',
1078
- trigger: event,
1079
- summary: reason.slice(0, 300),
1096
+ trigger: event
1097
+ }, runSummaryFields(reason.slice(0, 300)), {
1080
1098
  target: {
1081
1099
  type: kind === 'orgAutomation' ? ORG_AUTOMATION_RUN_TARGET : 'workflow',
1082
1100
  id: actionId,
1083
1101
  name: (_action_name = action.name) != null ? _action_name : ''
1084
1102
  },
1103
+ searchTokens: activitySearchTokens({
1104
+ target: {
1105
+ name: action.name
1106
+ }
1107
+ }),
1085
1108
  createdAt: FieldValue.serverTimestamp()
1086
- }).catch(()=>undefined);
1109
+ })).catch(()=>undefined);
1087
1110
  }
1088
1111
  /**
1089
1112
  * Event-triggered action runner (AGL-148): loads enabled actions whose
@@ -1351,20 +1374,25 @@ async function datasetAppendRefusal(env, datasetRef) {
1351
1374
  var _enrollment_actionName;
1352
1375
  const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(enrollment.hostId);
1353
1376
  await endFlowEnrollment(ref);
1354
- await hostRef.collection('activity').add({
1377
+ await hostRef.collection('activity').add(_extends({
1355
1378
  actorId: null,
1356
1379
  actorEmail: null,
1357
1380
  action: `Flow stopped mid-wait: ${reason}`.slice(0, 300),
1358
1381
  result: 'skipped',
1359
- trigger: enrollment.event,
1360
- summary: reason.slice(0, 300),
1382
+ trigger: enrollment.event
1383
+ }, runSummaryFields(reason.slice(0, 300)), {
1361
1384
  target: {
1362
1385
  type: enrollment.automation === 'org' ? ORG_AUTOMATION_RUN_TARGET : 'workflow',
1363
1386
  id: enrollment.actionId,
1364
1387
  name: (_enrollment_actionName = enrollment.actionName) != null ? _enrollment_actionName : ''
1365
1388
  },
1389
+ searchTokens: activitySearchTokens({
1390
+ target: {
1391
+ name: enrollment.actionName
1392
+ }
1393
+ }),
1366
1394
  createdAt: FieldValue.serverTimestamp()
1367
- }).catch(()=>undefined);
1395
+ })).catch(()=>undefined);
1368
1396
  return 'stopped';
1369
1397
  }
1370
1398
  /**