@aglyn/plugins-workflows 1.0.0-beta.199 → 1.0.0-beta.201
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 +12 -12
- package/src/lib/components/host-actions-card.component.js +2 -1
- package/src/lib/components/host-actions-card.component.js.map +1 -1
- package/src/lib/components/host-run-history-card.component.d.ts +7 -4
- package/src/lib/components/host-run-history-card.component.js +86 -163
- package/src/lib/components/host-run-history-card.component.js.map +1 -1
- package/src/lib/components/host-workflows-card.component.js +2 -1
- package/src/lib/components/host-workflows-card.component.js.map +1 -1
- package/src/lib/components/site-org-automations-panel.component.js +2 -1
- package/src/lib/components/site-org-automations-panel.component.js.map +1 -1
- package/src/lib/engine/crm-action-steps.js +8 -3
- package/src/lib/engine/crm-action-steps.js.map +1 -1
- package/src/lib/engine/run-event-actions.js +95 -24
- package/src/lib/engine/run-event-actions.js.map +1 -1
- package/src/lib/engine/run-event-workflows.js +18 -8
- package/src/lib/engine/run-event-workflows.js.map +1 -1
- package/src/lib/engine/site-suspension.d.ts +45 -0
- package/src/lib/engine/site-suspension.js +54 -0
- package/src/lib/engine/site-suspension.js.map +1 -0
- package/src/lib/model/run-history.d.ts +79 -0
- package/src/lib/model/run-history.js +180 -0
- package/src/lib/model/run-history.js.map +1 -0
- package/src/lib/server.js +26 -4
- package/src/lib/server.js.map +1 -1
|
@@ -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,EACnBC,2BAA2B,EAC3BC,aAAa,EACbC,iBAAiB,EACjBC,mBAAmB,EACnBC,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,EACdC,OAAyB;QAGAA,oBAQsBC;IAT/C,MAAM,EAAEC,KAAKC,WAAW,EAAE,GAAG,MAAMb,oBAAoBS,QAAQ;IAC/D,MAAMK,Y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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,EACdC,OAAyB;QAGAA,oBAQsBC;IAT/C,MAAM,EAAEC,KAAKC,WAAW,EAAE,GAAG,MAAMd,oBAAoBU,QAAQ;IAC/D,MAAMK,YAAYC,QAAOL,qBAAAA,OAAO,CAAC,YAAY,YAApBA,qBAAwB,IAAIM,IAAI;IACzD,IAAIF,WAAW;QACb,MAAMG,MAAM,MAAMJ,YAAYI,GAAG,CAACH,WAAWI,GAAG;QAChD,IAAID,IAAIE,MAAM,IAAIzB,cAAcuB,IAAIC,GAAG,CAAC,cAAcT,SAAS;gBACpBQ;YAAzC,OAAO;gBAAEG,IAAIH,IAAIG,EAAE;gBAAER,KAAKK,IAAIL,GAAG;gBAAES,IAAI,GAAEJ,YAAAA,IAAII,IAAI,cAARJ,YAAc,CAAC;Y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AgDoF,SAASpG,GAAG,CAACQ,EAAE,EAAEQ;IACjF;AACF"}
|
|
@@ -18,12 +18,18 @@ 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";
|
|
26
|
+
// The leaf again, for the phishing screen's hold (AGL-3356): the control
|
|
27
|
+
// that stops a send must be the real one under a spec that mocks the barrel.
|
|
28
|
+
import { screenOutboundSend } from "@aglyn/tenant-data-admin/server/outbound-send-review";
|
|
25
29
|
import { createHmac } from "crypto";
|
|
26
30
|
import { FieldValue } from "firebase-admin/firestore";
|
|
31
|
+
import { runSummaryFields } from "../model/run-history.js";
|
|
32
|
+
import { eventRunSuspension } from "./site-suspension.js";
|
|
27
33
|
import { advanceFlowEnrollment, claimFlowEnrollment, deferFlowEnrollment, endFlowEnrollment, enrollInFlow, findFlowEnrollmentsAwaiting, sweepDueFlowEnrollments } from "./flow-enrollments.js";
|
|
28
34
|
import { logCrmEmailActivity, prepareCrmEmailActivity, runCrmActionStep } from "./crm-action-steps.js";
|
|
29
35
|
import { resolveDatasetDoc } from "@aglyn/tenant-runtime/resolve-dataset";
|
|
@@ -436,8 +442,18 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
436
442
|
values: merged
|
|
437
443
|
}, datasetIntegrityUpdate(updateModel, merged, FieldValue.delete()), {
|
|
438
444
|
updatedAt: FieldValue.serverTimestamp()
|
|
439
|
-
}),
|
|
440
|
-
|
|
445
|
+
}), // `mergeFields`, not `merge: true`: a merge would fold the new
|
|
446
|
+
// `filterValues` map into the stored one key by key, and a value
|
|
447
|
+
// cleared here would go on answering its old equality. Each named
|
|
448
|
+
// field is replaced whole; `merged` already holds every value.
|
|
449
|
+
{
|
|
450
|
+
mergeFields: [
|
|
451
|
+
'values',
|
|
452
|
+
'referencedIds',
|
|
453
|
+
'filterKeys',
|
|
454
|
+
'filterValues',
|
|
455
|
+
'updatedAt'
|
|
456
|
+
]
|
|
441
457
|
});
|
|
442
458
|
} else {
|
|
443
459
|
// The APPEND leg of update-or-append, and the only one of the two
|
|
@@ -465,7 +481,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
465
481
|
link: `/${hostId}`
|
|
466
482
|
}));
|
|
467
483
|
} else if (step.type === 'sendEmail') {
|
|
468
|
-
var _payload_, _hostPublicOrigin, _step_topicId, _step_subject, _step_body, _env_org;
|
|
484
|
+
var _payload_, _ref4, _hostPublicOrigin, _step_topicId, _step_subject, _step_body, _ref5, _run_orgId, _env_org, _env_org1, _screened_releasedReviewId;
|
|
469
485
|
var _step_toField, _this;
|
|
470
486
|
const to = String((_payload_ = payload[((_step_toField = step.toField) == null ? void 0 : _step_toField.trim()) || 'email']) != null ? _payload_ : '').trim();
|
|
471
487
|
if (!isEmailConfigured()) return failed('email is not configured');
|
|
@@ -476,7 +492,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
476
492
|
// than carried on the run env because most action runs send no email
|
|
477
493
|
// at all, and a document read every workflow pays for is a read on
|
|
478
494
|
// the hot path for a link nine runs in ten never need.
|
|
479
|
-
const
|
|
495
|
+
const hostData = (_ref4 = (_this = await hostRef.get().catch(()=>null)) == null ? void 0 : _this.data()) != null ? _ref4 : null;
|
|
496
|
+
const siteBase = (_hostPublicOrigin = hostPublicOrigin(hostData)) != null ? _hostPublicOrigin : '';
|
|
480
497
|
/*
|
|
481
498
|
* MARKETING. The subject and body are merchant-authored and the
|
|
482
499
|
* recipient comes out of the event payload — which, for the collect
|
|
@@ -543,7 +560,40 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
543
560
|
}
|
|
544
561
|
const emailSubject = String((_step_subject = step.subject) != null ? _step_subject : '').slice(0, 200);
|
|
545
562
|
const emailText = String((_step_body = step.body) != null ? _step_body : '').slice(0, 5000);
|
|
546
|
-
|
|
563
|
+
/*
|
|
564
|
+
* THE PHISHING SCREEN, for a workspace in its first fortnight
|
|
565
|
+
* (AGL-3356). The incident's second message was exactly this step: a
|
|
566
|
+
* `contactCreated` workflow mailing "Poshmark Order … has finally
|
|
567
|
+
* sold" with a link to a Poshmark lookalike, once per imported contact.
|
|
568
|
+
*
|
|
569
|
+
* A hold files one review row per (automation, content) in the abuse
|
|
570
|
+
* queue and stops the message. After a wait the step DEFERS, so the
|
|
571
|
+
* enrollment sends the same step once staff release it; an immediate
|
|
572
|
+
* step has no later beat to come back on, so this run records the hold
|
|
573
|
+
* as its failure and the automation sends again from its next event
|
|
574
|
+
* once released. See `outbound-send-review.ts`.
|
|
575
|
+
*/ const screened = await screenOutboundSend({
|
|
576
|
+
kind: run.kind,
|
|
577
|
+
path: run.kind === 'orgAutomation' ? `orgs/${(_ref5 = (_run_orgId = run.orgId) != null ? _run_orgId : env.orgId) != null ? _ref5 : ''}/automations/${run.id}` : `hosts/${hostId}/${run.kind === 'workflow' ? 'workflows' : 'actions'}/${run.id}`,
|
|
578
|
+
hostId,
|
|
579
|
+
orgId: env.orgId,
|
|
580
|
+
org: (_env_org = env.org) != null ? _env_org : null,
|
|
581
|
+
host: hostData,
|
|
582
|
+
subject: emailSubject,
|
|
583
|
+
bodies: [
|
|
584
|
+
emailText
|
|
585
|
+
]
|
|
586
|
+
});
|
|
587
|
+
if (screened.outcome === 'rejected') {
|
|
588
|
+
return failed(`this email was rejected by staff review (${screened.reference})`);
|
|
589
|
+
}
|
|
590
|
+
if (screened.outcome === 'held') {
|
|
591
|
+
if (enrollmentRef) return {
|
|
592
|
+
kind: 'deferred'
|
|
593
|
+
};
|
|
594
|
+
return failed('this email is held for staff review because it may impersonate ' + `another business (${screened.reference})`);
|
|
595
|
+
}
|
|
596
|
+
const consentGroup = consentGroupForHost((_env_org1 = env.org) != null ? _env_org1 : null, hostId);
|
|
547
597
|
/*
|
|
548
598
|
* THE TIMELINE ENTRY (AGL-2615). A message addressed to the contact
|
|
549
599
|
* the event is about is logged on that contact's timeline as an
|
|
@@ -567,7 +617,10 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
567
617
|
tags: emailActivity.tags
|
|
568
618
|
} : {}, {
|
|
569
619
|
audience: 'tenant',
|
|
570
|
-
context: enrollmentRef ? 'flow step' : 'event action'
|
|
620
|
+
context: enrollmentRef ? 'flow step' : 'event action',
|
|
621
|
+
// A step staff released above carries its release to the send
|
|
622
|
+
// seam's screen, which would otherwise hold the same signals again.
|
|
623
|
+
releasedReviewId: screened.outcome === 'send' ? (_screened_releasedReviewId = screened.releasedReviewId) != null ? _screened_releasedReviewId : null : null
|
|
571
624
|
}, enrollmentRef ? {
|
|
572
625
|
priority: 'bulk'
|
|
573
626
|
} : {}, {
|
|
@@ -603,7 +656,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
603
656
|
// a frequency ceiling are the controls working, and a merchant
|
|
604
657
|
// reading the run's alerts has a different thing to do about each.
|
|
605
658
|
const refusal = sendFailureReason(result);
|
|
606
|
-
const sendError = refusal ? refusal === 'suppressed' ? 'the recipient is unsubscribed or suppressed' : refusal === 'frequency-capped' ? 'the recipient has already had today’s limit of email ' + 'from this site' : 'email delivery failed' : null;
|
|
659
|
+
const sendError = refusal ? refusal === 'suppressed' ? 'the recipient is unsubscribed or suppressed' : refusal === 'frequency-capped' ? 'the recipient has already had today’s limit of email ' + 'from this site' : refusal === 'held-for-review' ? 'this email is held for staff review because it may ' + 'impersonate another business' : 'email delivery failed' : null;
|
|
607
660
|
// Cost meter (AGL-1438). A workflow notification is transactional:
|
|
608
661
|
// counted, never capped. `sent` is false when Resend refused or the
|
|
609
662
|
// environment is unconfigured, and an email that never left is not a
|
|
@@ -624,7 +677,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
624
677
|
}
|
|
625
678
|
if (sendError) return failed(sendError);
|
|
626
679
|
} else if (step.type === 'enrollList') {
|
|
627
|
-
var _payload_email1,
|
|
680
|
+
var _payload_email1, _ref6;
|
|
628
681
|
var _step_listId, _step_listName;
|
|
629
682
|
const orgId = await resolveOrgIdForHost(hostId);
|
|
630
683
|
const email = String((_payload_email1 = payload.email) != null ? _payload_email1 : '').trim().toLowerCase();
|
|
@@ -632,7 +685,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
632
685
|
return failed('no email to enroll');
|
|
633
686
|
}
|
|
634
687
|
const listsRef = firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('lists');
|
|
635
|
-
const listDoc = ((_step_listId = step.listId) == null ? void 0 : _step_listId.trim()) ? await listsRef.doc(step.listId.trim()).get() : (await listsRef.where('name', '==', (
|
|
688
|
+
const listDoc = ((_step_listId = step.listId) == null ? void 0 : _step_listId.trim()) ? await listsRef.doc(step.listId.trim()).get() : (await listsRef.where('name', '==', (_ref6 = (_step_listName = step.listName) == null ? void 0 : _step_listName.trim()) != null ? _ref6 : '').limit(1).get()).docs[0];
|
|
636
689
|
if (!(listDoc == null ? void 0 : listDoc.exists)) {
|
|
637
690
|
return failed(`unknown list "${step.listName || step.listId}"`);
|
|
638
691
|
}
|
|
@@ -647,7 +700,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
647
700
|
source: `${run.kind}:${run.id}`
|
|
648
701
|
});
|
|
649
702
|
} else if (step.type === 'assignCampaign') {
|
|
650
|
-
var _payload_email2, _env_orgId,
|
|
703
|
+
var _payload_email2, _env_orgId, _ref7, _ref8;
|
|
651
704
|
var _step_campaignId, _step_campaignName;
|
|
652
705
|
const email = String((_payload_email2 = payload.email) != null ? _payload_email2 : '').trim().toLowerCase();
|
|
653
706
|
if (!email || !email.includes('@')) {
|
|
@@ -691,8 +744,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
691
744
|
if (!campaignOrgId) return failed(`unknown campaign "${campaignLabel}"`);
|
|
692
745
|
const campaignsRef = firebaseAdmin.app().firestore().collection('orgs').doc(campaignOrgId).collection('emailCampaigns');
|
|
693
746
|
const usable = (doc)=>Boolean((doc == null ? void 0 : doc.exists) && !doc.get('deletedAt') && visibleToHost(doc.get('visibleTo'), hostId));
|
|
694
|
-
const namedId = (
|
|
695
|
-
const campaignDoc = namedId ? await campaignsRef.doc(namedId).get() : (await campaignsRef.where('name', '==', (
|
|
747
|
+
const namedId = (_ref7 = (_step_campaignId = step.campaignId) == null ? void 0 : _step_campaignId.trim()) != null ? _ref7 : '';
|
|
748
|
+
const campaignDoc = namedId ? await campaignsRef.doc(namedId).get() : (await campaignsRef.where('name', '==', (_ref8 = (_step_campaignName = step.campaignName) == null ? void 0 : _step_campaignName.trim()) != null ? _ref8 : '').limit(10).get()).docs.find(usable);
|
|
696
749
|
if (!(campaignDoc == null ? void 0 : campaignDoc.exists)) {
|
|
697
750
|
return failed(`unknown campaign "${campaignLabel}"`);
|
|
698
751
|
}
|
|
@@ -833,7 +886,7 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
833
886
|
*/ if (ending === 'deferred') return ending;
|
|
834
887
|
const noun = orgRun ? 'Org automation' : 'Action';
|
|
835
888
|
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({
|
|
889
|
+
await hostRef.collection('activity').add(_extends({
|
|
837
890
|
actorId: null,
|
|
838
891
|
actorEmail: null,
|
|
839
892
|
// The prose line stays exactly as it was: `activityPrimaryText` and
|
|
@@ -843,8 +896,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
843
896
|
// The structured half (AGL-2171) — the two columns the advertised
|
|
844
897
|
// run-history table could not otherwise fill.
|
|
845
898
|
result: stepErrors.length ? 'failed' : 'succeeded',
|
|
846
|
-
trigger: event
|
|
847
|
-
|
|
899
|
+
trigger: event
|
|
900
|
+
}, runSummaryFields((outcomes.length ? outcomes.join(' · ') : 'Ran').slice(0, 300)), {
|
|
848
901
|
target: {
|
|
849
902
|
// An org automation's run is filed under its own type, so the site's
|
|
850
903
|
// run history can tell it from a site action sharing the feed.
|
|
@@ -852,8 +905,14 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
852
905
|
id: actionId,
|
|
853
906
|
name: (_action_name2 = action.name) != null ? _action_name2 : ''
|
|
854
907
|
},
|
|
908
|
+
// The site log's search finds a run by its action's name (AGL-3321).
|
|
909
|
+
searchTokens: activitySearchTokens({
|
|
910
|
+
target: {
|
|
911
|
+
name: action.name
|
|
912
|
+
}
|
|
913
|
+
}),
|
|
855
914
|
createdAt: FieldValue.serverTimestamp()
|
|
856
|
-
}).catch(()=>undefined);
|
|
915
|
+
})).catch(()=>undefined);
|
|
857
916
|
return ending;
|
|
858
917
|
}
|
|
859
918
|
/**
|
|
@@ -1070,20 +1129,25 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
1070
1129
|
return String((_ref = condition == null ? void 0 : condition.field) != null ? _ref : '').trim();
|
|
1071
1130
|
}).filter(Boolean);
|
|
1072
1131
|
const reason = named.length ? `Condition on ${named.slice(0, 3).join(', ')} not met` : 'Trigger condition not met';
|
|
1073
|
-
await hostRef.collection('activity').add({
|
|
1132
|
+
await hostRef.collection('activity').add(_extends({
|
|
1074
1133
|
actorId: null,
|
|
1075
1134
|
actorEmail: null,
|
|
1076
1135
|
action: `${kind === 'orgAutomation' ? 'Org automation' : 'Action'} skipped on ${event}`,
|
|
1077
1136
|
result: 'skipped',
|
|
1078
|
-
trigger: event
|
|
1079
|
-
|
|
1137
|
+
trigger: event
|
|
1138
|
+
}, runSummaryFields(reason.slice(0, 300)), {
|
|
1080
1139
|
target: {
|
|
1081
1140
|
type: kind === 'orgAutomation' ? ORG_AUTOMATION_RUN_TARGET : 'workflow',
|
|
1082
1141
|
id: actionId,
|
|
1083
1142
|
name: (_action_name = action.name) != null ? _action_name : ''
|
|
1084
1143
|
},
|
|
1144
|
+
searchTokens: activitySearchTokens({
|
|
1145
|
+
target: {
|
|
1146
|
+
name: action.name
|
|
1147
|
+
}
|
|
1148
|
+
}),
|
|
1085
1149
|
createdAt: FieldValue.serverTimestamp()
|
|
1086
|
-
}).catch(()=>undefined);
|
|
1150
|
+
})).catch(()=>undefined);
|
|
1087
1151
|
}
|
|
1088
1152
|
/**
|
|
1089
1153
|
* Event-triggered action runner (AGL-148): loads enabled actions whose
|
|
@@ -1143,6 +1207,8 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
1143
1207
|
// Plan-less orgs resolve as free (AGL-247) — gates always run. Held for
|
|
1144
1208
|
// the rest of the run so the dataset caps below cost no second read.
|
|
1145
1209
|
const owner = await getOrgForHost(hostId);
|
|
1210
|
+
// A suspended site runs nothing (AGL-3356): see `eventRunSuspension`.
|
|
1211
|
+
if (await eventRunSuspension(hostRef, owner == null ? void 0 : owner.org)) return alerts;
|
|
1146
1212
|
{
|
|
1147
1213
|
var _counterSnapshot_get, _ref2;
|
|
1148
1214
|
const org = owner == null ? void 0 : owner.org;
|
|
@@ -1351,20 +1417,25 @@ async function datasetAppendRefusal(env, datasetRef) {
|
|
|
1351
1417
|
var _enrollment_actionName;
|
|
1352
1418
|
const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(enrollment.hostId);
|
|
1353
1419
|
await endFlowEnrollment(ref);
|
|
1354
|
-
await hostRef.collection('activity').add({
|
|
1420
|
+
await hostRef.collection('activity').add(_extends({
|
|
1355
1421
|
actorId: null,
|
|
1356
1422
|
actorEmail: null,
|
|
1357
1423
|
action: `Flow stopped mid-wait: ${reason}`.slice(0, 300),
|
|
1358
1424
|
result: 'skipped',
|
|
1359
|
-
trigger: enrollment.event
|
|
1360
|
-
|
|
1425
|
+
trigger: enrollment.event
|
|
1426
|
+
}, runSummaryFields(reason.slice(0, 300)), {
|
|
1361
1427
|
target: {
|
|
1362
1428
|
type: enrollment.automation === 'org' ? ORG_AUTOMATION_RUN_TARGET : 'workflow',
|
|
1363
1429
|
id: enrollment.actionId,
|
|
1364
1430
|
name: (_enrollment_actionName = enrollment.actionName) != null ? _enrollment_actionName : ''
|
|
1365
1431
|
},
|
|
1432
|
+
searchTokens: activitySearchTokens({
|
|
1433
|
+
target: {
|
|
1434
|
+
name: enrollment.actionName
|
|
1435
|
+
}
|
|
1436
|
+
}),
|
|
1366
1437
|
createdAt: FieldValue.serverTimestamp()
|
|
1367
|
-
}).catch(()=>undefined);
|
|
1438
|
+
})).catch(()=>undefined);
|
|
1368
1439
|
return 'stopped';
|
|
1369
1440
|
}
|
|
1370
1441
|
/**
|