@aglyn/plugins-outreach 1.0.0-beta.221 → 1.0.0-beta.222
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/do-not-contact-domains.d.ts +6 -2
- package/src/lib/components/do-not-contact-domains.js +73 -11
- package/src/lib/components/do-not-contact-domains.js.map +1 -1
- package/src/lib/components/enrollments-table.d.ts +6 -0
- package/src/lib/components/enrollments-table.js +77 -4
- package/src/lib/components/enrollments-table.js.map +1 -1
- package/src/lib/components/sequence-detail.js +3 -1
- package/src/lib/components/sequence-detail.js.map +1 -1
- package/src/lib/components/sequence-report-card.js +7 -3
- package/src/lib/components/sequence-report-card.js.map +1 -1
- package/src/lib/components/use-outreach-crm.d.ts +18 -15
- package/src/lib/components/use-outreach-crm.js +118 -87
- package/src/lib/components/use-outreach-crm.js.map +1 -1
- package/src/lib/components/use-outreach-data.d.ts +2 -2
- package/src/lib/components/use-outreach-data.js.map +1 -1
- package/src/lib/constants/transfer-resources.d.ts +33 -0
- package/src/lib/constants/transfer-resources.js +38 -0
- package/src/lib/constants/transfer-resources.js.map +1 -0
- package/src/lib/declarations.console-server.d.ts +7 -1
- package/src/lib/declarations.console-server.js +66 -1
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/engine/click-tracking.js +1 -1
- package/src/lib/engine/click-tracking.js.map +1 -1
- package/src/lib/engine/ip-range.d.ts +26 -0
- package/src/lib/engine/ip-range.js +78 -0
- package/src/lib/engine/ip-range.js.map +1 -0
- package/src/lib/engine/open-source.d.ts +24 -0
- package/src/lib/engine/open-source.js +130 -0
- package/src/lib/engine/open-source.js.map +1 -0
- package/src/lib/engine/open-tracking.d.ts +15 -2
- package/src/lib/engine/open-tracking.js +59 -16
- package/src/lib/engine/open-tracking.js.map +1 -1
- package/src/lib/engine/outreach-access.d.ts +47 -0
- package/src/lib/engine/outreach-access.js +56 -0
- package/src/lib/engine/outreach-access.js.map +1 -0
- package/src/lib/enrollment/enroll-people.d.ts +10 -10
- package/src/lib/enrollment/enroll-people.js +30 -25
- package/src/lib/enrollment/enroll-people.js.map +1 -1
- package/src/lib/enrollment/gate-lookups.js +30 -15
- package/src/lib/enrollment/gate-lookups.js.map +1 -1
- package/src/lib/enrollment/message-templates.d.ts +24 -0
- package/src/lib/enrollment/message-templates.js +35 -0
- package/src/lib/enrollment/message-templates.js.map +1 -0
- package/src/lib/model/enrollment-engagement.d.ts +16 -0
- package/src/lib/model/enrollment-engagement.js +16 -0
- package/src/lib/model/enrollment-engagement.js.map +1 -1
- package/src/lib/model/enrollment-history.d.ts +8 -1
- package/src/lib/model/enrollment-history.js +17 -5
- package/src/lib/model/enrollment-history.js.map +1 -1
- package/src/lib/model/enrollment-timeline.d.ts +3 -0
- package/src/lib/model/enrollment-timeline.js +15 -4
- package/src/lib/model/enrollment-timeline.js.map +1 -1
- package/src/lib/model/outreach.types.d.ts +12 -3
- package/src/lib/model/outreach.types.js +12 -1
- package/src/lib/model/outreach.types.js.map +1 -1
- package/src/lib/model/sequence-report.d.ts +14 -7
- package/src/lib/model/sequence-report.js +12 -8
- package/src/lib/model/sequence-report.js.map +1 -1
- package/src/lib/plugin.js +18 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/routes/curate-routes.js +4 -6
- package/src/lib/routes/curate-routes.js.map +1 -1
- package/src/lib/routes/enroll-routes.d.ts +0 -12
- package/src/lib/routes/enroll-routes.js +52 -92
- package/src/lib/routes/enroll-routes.js.map +1 -1
- package/src/lib/routes/platform-deps.d.ts +4 -16
- package/src/lib/routes/platform-deps.js +5 -25
- package/src/lib/routes/platform-deps.js.map +1 -1
- package/src/lib/routes/preview-routes.js +25 -13
- package/src/lib/routes/preview-routes.js.map +1 -1
- package/src/lib/routes/register-routes.js +7 -5
- package/src/lib/routes/register-routes.js.map +1 -1
- package/src/lib/routes/route-gate.js +6 -17
- package/src/lib/routes/route-gate.js.map +1 -1
- package/src/lib/routes/sequence-routes.d.ts +46 -0
- package/src/lib/routes/sequence-routes.js +155 -63
- package/src/lib/routes/sequence-routes.js.map +1 -1
- package/src/lib/runtime/click-events.js +8 -8
- package/src/lib/runtime/click-events.js.map +1 -1
- package/src/lib/runtime/click-route.js +5 -2
- package/src/lib/runtime/click-route.js.map +1 -1
- package/src/lib/runtime/lead-records.d.ts +18 -10
- package/src/lib/runtime/lead-records.js +14 -60
- package/src/lib/runtime/lead-records.js.map +1 -1
- package/src/lib/runtime/open-events.d.ts +8 -0
- package/src/lib/runtime/open-events.js +10 -3
- package/src/lib/runtime/open-events.js.map +1 -1
- package/src/lib/runtime/platform-runtime-deps.d.ts +9 -5
- package/src/lib/runtime/platform-runtime-deps.js +31 -24
- package/src/lib/runtime/platform-runtime-deps.js.map +1 -1
- package/src/lib/runtime/send-job.js +20 -17
- package/src/lib/runtime/send-job.js.map +1 -1
- package/src/lib/runtime/sync-job.js +10 -5
- package/src/lib/runtime/sync-job.js.map +1 -1
- package/src/lib/storage/do-not-contact-store.d.ts +8 -0
- package/src/lib/storage/do-not-contact-store.js +13 -0
- package/src/lib/storage/do-not-contact-store.js.map +1 -1
- package/src/lib/testing/stand-in-record-system.d.ts +54 -0
- package/src/lib/testing/stand-in-record-system.js +243 -0
- package/src/lib/testing/stand-in-record-system.js.map +1 -0
- package/src/lib/transfer/do-not-contact-transfer.d.ts +129 -0
- package/src/lib/transfer/do-not-contact-transfer.js +801 -0
- package/src/lib/transfer/do-not-contact-transfer.js.map +1 -0
- package/src/lib/transfer/plan-gate.d.ts +25 -0
- package/src/lib/transfer/plan-gate.js +35 -0
- package/src/lib/transfer/plan-gate.js.map +1 -0
- package/src/lib/transfer/platform-transfer-deps.d.ts +24 -0
- package/src/lib/transfer/platform-transfer-deps.js +39 -0
- package/src/lib/transfer/platform-transfer-deps.js.map +1 -0
- package/src/lib/transfer/sequences-package.d.ts +48 -0
- package/src/lib/transfer/sequences-package.js +93 -0
- package/src/lib/transfer/sequences-package.js.map +1 -0
- package/src/lib/transfer/sequences-package.server.d.ts +31 -0
- package/src/lib/transfer/sequences-package.server.js +207 -0
- package/src/lib/transfer/sequences-package.server.js.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/enroll-people.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WHO CAN BE ENROLLED, AND WHAT THE REP STILL OWES (AGL-2980).\n *\n * The enroll dialog shows every person a view or a search named, each\n * marked eligible, blocked, or waiting on the rep; Confirm asks the same\n * question again, on the server, with what the rep supplied. Both answers\n * come from the engine's `evaluateOutreachGates` — this module only reads\n * the people and asks it the right questions.\n *\n * ## Three questions of one pure function\n *\n * The gates refuse a cold contact until the rep writes a personal line and\n * ticks the attestations, and refuse an address in an unknown country until\n * the rep confirms it is a US business address. So a preview asks:\n *\n * 1. as the person stands, with nothing confirmed — allowed means\n * ELIGIBLE;\n * 2. as if the rep confirmed everything they can — refused means BLOCKED,\n * for the reasons that remain, which no tick can clear;\n * 3. otherwise the person is WAITING ON THE REP, for what (1) found\n * missing.\n *\n * The confirmation in (2) is hypothetical and never stored: Confirm stamps\n * only what the rep ticked, with their uid and the time, and asks again.\n *\n * ## One enrollment per person per sequence, ever\n *\n * The enrollment's id is the sequence and the contact\n * (`outreachEnrollmentId`), and it is written with `create()`. A person who\n * finished, replied or was stopped is not sent the same emails a second\n * time by being enrolled again, and two members confirming the same person\n * at once write one enrollment.\n *==========================================*/\n\nimport { normalizeContactEmail, contactDisplayName, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmLeadDisplayName, crmLeadStatus } from '@aglyn/aglyn/app-utils/crm'\nimport { seenOnlyThroughGrant, visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport {\n evaluateOutreachGates,\n type OutreachGateBlock,\n type OutreachGateHold,\n type OutreachGateLookups,\n} from '../engine/gates'\nimport { outreachAttestationsFrom } from '../engine/enrollment-state'\nimport {\n OUTREACH_ATTESTATION_KINDS,\n type OutreachAttestationKind,\n type OutreachAttestations,\n type OutreachSequenceSettings,\n} from '../model/outreach.types'\nimport type {\n OutreachEnrollBlock,\n OutreachEnrollGateway,\n OutreachEnrollPreviewPerson,\n OutreachPersonRef,\n} from '../model/outreach-api'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/**\n * One person as the preview and the enroll read them: a contact, or a lead\n * the sequence's site holds (AGL-3234).\n *\n * ## A lead is judged as the contact it would be\n *\n * The gates, the merge fields and the country rule all read a CONTACT\n * document — its facet's sources, stage, address, company and title. A lead\n * carries the same facts in its own shape, so rather than teach every gate\n * two records, a lead is handed to them as {@link leadAsContact}: a\n * contact-shaped view whose one facet, under the sequence's group, holds\n * what the lead holds. An imported lead has no inbound source and is cold;\n * one that wrote in through a form is not; a lead is never a customer; its\n * address decides its country; and `{{contact.firstName}}` or\n * `{{contact.company}}` in a step reads the lead's name and company text,\n * so a sequence written for contacts sends to leads unchanged — which is\n * also what lets an enrollment made on a lead keep sending after the lead\n * converts and the view becomes the real contact.\n */\nexport interface OutreachEnrollCandidate {\n /** The record's own id: the contact's, or the lead's person key. */\n personId: string\n target: 'contact' | 'lead'\n /** The contact's id; `''` for a lead. */\n contactId: string\n /** The lead's person key; `null` for a contact. */\n leadId: string | null\n /**\n * The contact document (`orgs/{orgId}/contacts/{id}`), or for a lead the\n * contact-shaped view of it — see the module note. `null` when the record\n * no longer exists.\n */\n contact: Record<string, unknown> | null\n /** The lead document as stored, for a lead; `null` for a contact. */\n lead: Record<string, unknown> | null\n /** Whether the sequence's site may see the record. A lead is the site's own. */\n visible: boolean\n /** The name the sequence's site knows them by; `''` for none. */\n name: string\n /** The primary address, normalized, or `null` when there is none. */\n email: string | null\n /** The company the contact is filed under at that site, when there is one. */\n company: Record<string, unknown> | null\n /** A lead already converted: the contact it became. Enroll that instead. */\n convertedContactId: string | null\n /** A lead whose address the workspace already holds as a contact. Enroll that instead. */\n heldAsContactId: string | null\n}\n\n/**\n * A lead as the gates and the merge fields read a contact — see the\n * module note. The facet is the sequence's group's, which is the one every\n * reader asks for. The lead's `sources` — `form:{id}`, `booking`, `import`,\n * `manual`, `api`, `signup` — become the facet's source flags by kind, so\n * the inbound rule reads them as it reads a contact's.\n */\nexport function leadAsContact(\n lead: Record<string, unknown>,\n contactGroupId: string,\n): Record<string, unknown> {\n const sources: Record<string, true> = {}\n for (const raw of Array.isArray(lead['sources']) ? lead['sources'] : []) {\n const source = String(raw)\n const kind = source.startsWith('form:') ? 'form' : source === 'signup' ? 'member' : source\n if (kind) sources[kind] = true\n }\n return {\n email: lead['email'],\n name: lead['name'],\n // The verdict on the address (AGL-3245) is the lead's own top-level\n // field, as it is the contact's, so the gates quote it either way.\n ...(lead['emailState'] && typeof lead['emailState'] === 'object' ? { emailState: lead['emailState'] } : {}),\n facets: {\n [contactGroupId]: {\n sources,\n ...(lead['address'] && typeof lead['address'] === 'object' ? { address: lead['address'] } : {}),\n ...(typeof lead['company'] === 'string' ? { companyName: lead['company'] } : {}),\n ...(typeof lead['jobTitle'] === 'string' ? { jobTitle: lead['jobTitle'] } : {}),\n ...(typeof lead['phone'] === 'string' ? { phone: lead['phone'] } : {}),\n ...(Array.isArray(lead['tags']) ? { tags: lead['tags'] } : {}),\n },\n },\n }\n}\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * The people, as the sequence's site knows them, and the company each\n * contact is filed under there — batched reads for everyone: the contacts\n * and the leads by id, the companies once, and for each lead one address\n * lookup, because a lead the workspace already holds as a contact is that\n * contact's to enroll.\n */\nexport async function readOutreachEnrollCandidates(\n firestore: Firestore,\n input: { orgId: string; hostId: string; contactGroupId: string; people: readonly OutreachPersonRef[] },\n): Promise<OutreachEnrollCandidate[]> {\n if (!input.people.length) return []\n const org = firestore.collection('orgs').doc(input.orgId)\n // Beside the contacts, on the org (AGL-3275).\n const leads = org.collection('leads')\n const snapshots = await getAllChunked(\n firestore,\n input.people.map((person) =>\n person.kind === 'lead' ? leads.doc(person.id) : org.collection('contacts').doc(person.id),\n ),\n )\n const read = await Promise.all(\n input.people.map(async (person, index) => {\n const data = snapshots[index]?.exists ? (snapshots[index].data() as Record<string, unknown>) : null\n if (person.kind === 'lead') {\n const email = data ? normalizeContactEmail(data['email']) : null\n const held =\n data && email ? await findContactByEmail(org.collection('contacts'), email) : null\n return {\n personId: person.id,\n target: 'lead' as const,\n contactId: '',\n leadId: person.id,\n contact: data ? leadAsContact(data, input.contactGroupId) : null,\n lead: data,\n // A lead is the site's own record — unless another site only\n // SHARED it with this one (AGL-3336): seen, not held, and a\n // sequence is a site's own outreach.\n visible: data !== null && !seenOnlyThroughGrant(data, input.hostId),\n name: data ? crmLeadDisplayName(data) : '',\n email,\n companyId: '',\n convertedContactId: data && typeof data['convertedContactId'] === 'string' ? data['convertedContactId'] : null,\n heldAsContactId: held ? held.id : null,\n }\n }\n return {\n personId: person.id,\n target: 'contact' as const,\n contactId: person.id,\n leadId: null,\n contact: data,\n lead: null,\n visible: data\n ? visibleToHost(data['visibleTo'] as string[] | undefined, input.hostId) &&\n !seenOnlyThroughGrant(data, input.hostId)\n : false,\n name: data ? contactDisplayName(data, input.contactGroupId).trim() : '',\n email: data ? normalizeContactEmail(data['email']) : null,\n companyId: data ? String(readContactFacet(data, input.contactGroupId).companyId ?? '') : '',\n convertedContactId: null,\n heldAsContactId: null,\n }\n }),\n )\n const companyIds = [...new Set(read.map((entry) => entry.companyId).filter(Boolean))]\n const companies = new Map<string, Record<string, unknown>>()\n if (companyIds.length) {\n const found = await getAllChunked(\n firestore,\n companyIds.map((id) => org.collection('companies').doc(id)),\n )\n found.forEach((snapshot, index) => {\n if (snapshot.exists) companies.set(companyIds[index], snapshot.data() as Record<string, unknown>)\n })\n }\n return read.map(({ companyId, ...candidate }) => ({\n ...candidate,\n company: companyId ? (companies.get(companyId) ?? null) : null,\n }))\n}\n\n/** The person as every answer names them. */\nfunction personOf(candidate: OutreachEnrollCandidate) {\n return {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n}\n\n/** What stands in the way before the gates are asked anything. */\nexport function outreachCandidateBlocks(\n candidate: OutreachEnrollCandidate,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollBlock[] {\n if (!candidate.contact) {\n return candidate.target === 'lead'\n ? [{ code: 'lead_missing', reason: \"This lead no longer exists in this sequence's site's CRM.\" }]\n : [{ code: 'contact_missing', reason: 'This contact no longer exists in the CRM.' }]\n }\n const blocks: OutreachEnrollBlock[] = []\n if (candidate.target === 'lead') {\n // A lead that converted, or whose address the workspace already holds\n // as a contact, is that contact's to enroll — one person, one record.\n if (candidate.convertedContactId) {\n blocks.push({\n code: 'lead_converted',\n reason: 'This lead was converted into a contact. Enroll the contact instead.',\n })\n } else if (candidate.heldAsContactId) {\n blocks.push({\n code: 'lead_is_contact',\n reason: 'This address is already a contact in your CRM. Enroll the contact instead.',\n })\n }\n if (crmLeadStatus(candidate.lead) === 'unqualified') {\n blocks.push({\n code: 'lead_unqualified',\n reason: 'This lead was closed as unqualified. Reopen it before enrolling.',\n })\n }\n }\n if (!candidate.visible) {\n blocks.push({\n code: 'not_in_site',\n reason: `This contact isn't in ${facts.siteName || \"this sequence's site\"}'s CRM.`,\n })\n }\n if (!candidate.email) {\n blocks.push({ code: 'no_email', reason: 'This contact has no email address.' })\n }\n if (facts.alreadyInSequence) {\n blocks.push({\n code: 'already_in_sequence',\n reason: \"This person has already been in this sequence, so they won't be sent its emails again.\",\n })\n }\n return blocks\n}\n\n/** Every attestation, stamped for a hypothetical question only — never stored. */\nconst EVERYTHING_CONFIRMED: OutreachAttestations = Object.fromEntries(\n OUTREACH_ATTESTATION_KINDS.map((kind) => [kind, { uid: 'preview', atMs: 1 }]),\n)\n\nconst blocksOf = (blocks: readonly OutreachGateBlock[]): OutreachEnrollBlock[] =>\n blocks.map(({ code, reason }) => ({ code, reason }))\n\nexport interface OutreachGateQuestion {\n candidate: OutreachEnrollCandidate\n lookups: OutreachGateLookups\n /** The sequence's settings, its countries already capped by the organization's. */\n settings: OutreachSequenceSettings\n contactGroupId: string\n}\n\n/**\n * The gateway as the dialog shows it (AGL-3326): the standing the lookups\n * read, and whether the gates would hold a send into it.\n */\nfunction gatewayOf(question: OutreachGateQuestion, hold: OutreachGateHold | null): OutreachEnrollGateway | null {\n const standing = question.lookups?.gateway\n return standing ? { ...standing, hold: hold !== null } : null\n}\n\n/** Where one person stands before the rep confirms anything — see the module note. */\nexport function previewOutreachPerson(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollPreviewPerson {\n const { candidate } = question\n const person = {\n ...personOf(candidate),\n name: candidate.name,\n email: candidate.email,\n }\n const early = outreachCandidateBlocks(candidate, facts)\n if (early.length) {\n return {\n ...person,\n cold: false,\n country: null,\n status: 'blocked',\n blocks: early,\n requires: { personalLine: false, attestations: [] },\n gateway: null,\n }\n }\n const ask = (personalLine: string, attestations: OutreachAttestations) =>\n evaluateOutreachGates({\n email: candidate.email ?? '',\n contact: candidate.contact,\n contactGroupId: question.contactGroupId,\n company: candidate.company,\n settings: question.settings,\n personalLine,\n attestations,\n lookups: question.lookups,\n })\n const asIs = ask('', {})\n const known = { cold: asIs.cold, country: asIs.country.country, gateway: gatewayOf(question, asIs.hold) }\n if (asIs.allowed) {\n return {\n ...person,\n ...known,\n status: 'eligible',\n blocks: [],\n requires: { personalLine: false, attestations: [] },\n }\n }\n // The line is only checked for being present, so any sentence stands in.\n const confirmed = ask('A personal line.', EVERYTHING_CONFIRMED)\n if (!confirmed.allowed) {\n return {\n ...person,\n ...known,\n status: 'blocked',\n blocks: blocksOf(confirmed.blocks),\n requires: { personalLine: false, attestations: [] },\n }\n }\n const attestations: OutreachAttestationKind[] = asIs.cold\n ? [...asIs.missingAttestations]\n : asIs.blocks.some((block) => block.code === 'country_unknown')\n ? ['us_business_address']\n : []\n return {\n ...person,\n ...known,\n status: 'needs_confirmation',\n blocks: [],\n requires: {\n personalLine: asIs.blocks.some((block) => block.code === 'personal_line_missing'),\n attestations,\n },\n }\n}\n\nexport interface OutreachEnrollDecision {\n allowed: boolean\n blocks: OutreachEnrollBlock[]\n cold: boolean\n /** The address as the gates normalized it. */\n email: string | null\n /** What the rep confirmed, stamped with who and when. */\n attestations: OutreachAttestations\n /**\n * The gateway hold the gates would put on the send (AGL-3326), which the\n * member enrolling past the red chip releases; `null` when none applies.\n */\n hold: OutreachGateHold | null\n}\n\n/** Confirm's answer for one person, with what the rep supplied — see the module note. */\nexport function decideOutreachEnrollment(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n supplied: {\n personalLine: string\n attestations: readonly unknown[]\n uid: string\n nowMs: number\n },\n): OutreachEnrollDecision {\n const attestations = outreachAttestationsFrom(supplied.attestations, supplied.uid, supplied.nowMs)\n const early = outreachCandidateBlocks(question.candidate, facts)\n if (early.length) {\n return { allowed: false, blocks: early, cold: false, email: question.candidate.email, attestations, hold: null }\n }\n const result = evaluateOutreachGates({\n email: question.candidate.email ?? '',\n contact: question.candidate.contact,\n contactGroupId: question.contactGroupId,\n company: question.candidate.company,\n settings: question.settings,\n personalLine: supplied.personalLine,\n attestations,\n lookups: question.lookups,\n })\n return {\n allowed: result.allowed,\n blocks: blocksOf(result.blocks),\n cold: result.cold,\n email: result.email,\n attestations,\n hold: result.hold,\n }\n}\n"],"names":["normalizeContactEmail","contactDisplayName","readContactFacet","crmLeadDisplayName","crmLeadStatus","seenOnlyThroughGrant","visibleToHost","findContactByEmail","evaluateOutreachGates","outreachAttestationsFrom","OUTREACH_ATTESTATION_KINDS","leadAsContact","lead","contactGroupId","sources","raw","Array","isArray","source","String","kind","startsWith","email","name","emailState","facets","address","companyName","jobTitle","phone","tags","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","readOutreachEnrollCandidates","input","people","org","collection","doc","orgId","leads","map","person","id","read","Promise","all","index","data","exists","held","personId","target","contactId","leadId","contact","visible","hostId","companyId","convertedContactId","heldAsContactId","trim","companyIds","Set","entry","filter","Boolean","companies","Map","found","forEach","snapshot","set","candidate","company","get","personOf","outreachCandidateBlocks","facts","code","reason","blocks","siteName","alreadyInSequence","EVERYTHING_CONFIRMED","Object","fromEntries","uid","atMs","blocksOf","gatewayOf","question","hold","standing","lookups","gateway","previewOutreachPerson","early","cold","country","status","requires","personalLine","attestations","ask","settings","asIs","known","allowed","confirmed","missingAttestations","some","block","decideOutreachEnrollment","supplied","nowMs","result"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAgC4C,GAE5C,SAASA,qBAAqB,EAAEC,kBAAkB,EAAEC,gBAAgB,QAAQ,kCAAiC;AAC7G,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,6BAA4B;AAC9E,SAASC,oBAAoB,EAAEC,aAAa,QAAQ,sCAAqC;AACzF,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SACEC,qBAAqB,QAIhB,qBAAiB;AACxB,SAASC,wBAAwB,Q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vF,OAAO,SAASU,yBACdtB,QAA8B,EAC9Bb,KAAuD,EACvDoC,QAKC;QAQQvB;IANT,MAAMY,eAAetG,yBAAyBiH,SAASX,YAAY,EAAEW,SAAS3B,GAAG,EAAE2B,SAASC,KAAK;IACjG,MAAMlB,QAAQpB,wBAAwBc,SAASlB,SAAS,EAAEK;IAC1D,IAAImB,MAAMpE,MAAM,EAAE;QAChB,OAAO;YAAE+E,SAAS;YAAO3B,QAAQgB;YAAOC,MAAM;YAAOpF,OAAO6E,SAASlB,SAAS,CAAC3D,KAAK;YAAEyF;YAAcX,MAAM;QAAK;IACjH;IACA,MAAMwB,SAASpH,sBAAsB;QACnCc,KAAK,GAAE6E,4BAAAA,SAASlB,SAAS,CAAC3D,KAAK,YAAxB6E,4BAA4B;QACnCpC,SAASoC,SAASlB,SAAS,CAAClB,OAAO;QACnClD,gBAAgBsF,SAAStF,cAAc;QACvCqE,SAASiB,SAASlB,SAAS,CAACC,OAAO;QACnC+B,UAAUd,SAASc,QAAQ;QAC3BH,cAAcY,SAASZ,YAAY;QACnCC;QACAT,SAASH,SAASG,OAAO;IAC3B;IACA,OAAO;QACLc,SAASQ,OAAOR,OAAO;QACvB3B,QAAQQ,SAAS2B,OAAOnC,MAAM;QAC9BiB,MAAMkB,OAAOlB,IAAI;QACjBpF,OAAOsG,OAAOtG,KAAK;QACnByF;QACAX,MAAMwB,OAAOxB,IAAI;IACnB;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/enroll-people.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WHO CAN BE ENROLLED, AND WHAT THE REP STILL OWES (AGL-2980).\n *\n * The enroll dialog shows every person a view or a search named, each\n * marked eligible, blocked, or waiting on the rep; Confirm asks the same\n * question again, on the server, with what the rep supplied. Both answers\n * come from the engine's `evaluateOutreachGates` — this module only reads\n * the people and asks it the right questions.\n *\n * ## Three questions of one pure function\n *\n * The gates refuse a cold contact until the rep writes a personal line and\n * ticks the attestations, and refuse an address in an unknown country until\n * the rep confirms it is a US business address. So a preview asks:\n *\n * 1. as the person stands, with nothing confirmed — allowed means\n * ELIGIBLE;\n * 2. as if the rep confirmed everything they can — refused means BLOCKED,\n * for the reasons that remain, which no tick can clear;\n * 3. otherwise the person is WAITING ON THE REP, for what (1) found\n * missing.\n *\n * The confirmation in (2) is hypothetical and never stored: Confirm stamps\n * only what the rep ticked, with their uid and the time, and asks again.\n *\n * ## One enrollment per person per sequence, ever\n *\n * The enrollment's id is the sequence and the contact\n * (`outreachEnrollmentId`), and it is written with `create()`. A person who\n * finished, replied or was stopped is not sent the same emails a second\n * time by being enrolled again, and two members confirming the same person\n * at once write one enrollment.\n *==========================================*/\n\nimport { normalizeContactEmail, contactDisplayName, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmLeadDisplayName, crmLeadStatus } from '@aglyn/aglyn/app-utils/crm'\nimport { seenOnlyThroughGrant, visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n findPluginPerson,\n readPluginPeople,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport { pluginRecordIndex } from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport {\n evaluateOutreachGates,\n type OutreachGateBlock,\n type OutreachGateHold,\n type OutreachGateLookups,\n} from '../engine/gates'\nimport { outreachAttestationsFrom } from '../engine/enrollment-state'\nimport {\n OUTREACH_ATTESTATION_KINDS,\n type OutreachAttestationKind,\n type OutreachAttestations,\n type OutreachSequenceSettings,\n} from '../model/outreach.types'\nimport type {\n OutreachEnrollBlock,\n OutreachEnrollGateway,\n OutreachEnrollPreviewPerson,\n OutreachPersonRef,\n} from '../model/outreach-api'\n\n/**\n * One person as the preview and the enroll read them: a contact, or a lead\n * the sequence's site holds (AGL-3234).\n *\n * ## A lead is judged as the contact it would be\n *\n * The gates, the merge fields and the country rule all read a CONTACT\n * document — its facet's sources, stage, address, company and title. A lead\n * carries the same facts in its own shape, so rather than teach every gate\n * two records, a lead is handed to them as {@link leadAsContact}: a\n * contact-shaped view whose one facet, under the sequence's group, holds\n * what the lead holds. An imported lead has no inbound source and is cold;\n * one that wrote in through a form is not; a lead is never a customer; its\n * address decides its country; and `{{contact.firstName}}` or\n * `{{contact.company}}` in a step reads the lead's name and company text,\n * so a sequence written for contacts sends to leads unchanged — which is\n * also what lets an enrollment made on a lead keep sending after the lead\n * converts and the view becomes the real contact.\n */\nexport interface OutreachEnrollCandidate {\n /** The record's own id: the contact's, or the lead's person key. */\n personId: string\n target: 'contact' | 'lead'\n /** The contact's id; `''` for a lead. */\n contactId: string\n /** The lead's person key; `null` for a contact. */\n leadId: string | null\n /**\n * The contact as the record system keeps it (`plugin-person-records`), or\n * for a lead the contact-shaped view of it — see the module note. `null`\n * when the record no longer exists.\n */\n contact: Record<string, unknown> | null\n /** The lead document as stored, for a lead; `null` for a contact. */\n lead: Record<string, unknown> | null\n /** Whether the sequence's site may see the record. A lead is the site's own. */\n visible: boolean\n /** The name the sequence's site knows them by; `''` for none. */\n name: string\n /** The primary address, normalized, or `null` when there is none. */\n email: string | null\n /** The company the contact is filed under at that site, when there is one. */\n company: Record<string, unknown> | null\n /** A lead already converted: the contact it became. Enroll that instead. */\n convertedContactId: string | null\n /** A lead whose address the workspace already holds as a contact. Enroll that instead. */\n heldAsContactId: string | null\n}\n\n/**\n * A lead as the gates and the merge fields read a contact — see the\n * module note. The facet is the sequence's group's, which is the one every\n * reader asks for. The lead's `sources` — `form:{id}`, `booking`, `import`,\n * `manual`, `api`, `signup` — become the facet's source flags by kind, so\n * the inbound rule reads them as it reads a contact's.\n */\nexport function leadAsContact(\n lead: Record<string, unknown>,\n contactGroupId: string,\n): Record<string, unknown> {\n const sources: Record<string, true> = {}\n for (const raw of Array.isArray(lead['sources']) ? lead['sources'] : []) {\n const source = String(raw)\n const kind = source.startsWith('form:') ? 'form' : source === 'signup' ? 'member' : source\n if (kind) sources[kind] = true\n }\n return {\n email: lead['email'],\n name: lead['name'],\n // The verdict on the address (AGL-3245) is the lead's own top-level\n // field, as it is the contact's, so the gates quote it either way.\n ...(lead['emailState'] && typeof lead['emailState'] === 'object' ? { emailState: lead['emailState'] } : {}),\n facets: {\n [contactGroupId]: {\n sources,\n ...(lead['address'] && typeof lead['address'] === 'object' ? { address: lead['address'] } : {}),\n ...(typeof lead['company'] === 'string' ? { companyName: lead['company'] } : {}),\n ...(typeof lead['jobTitle'] === 'string' ? { jobTitle: lead['jobTitle'] } : {}),\n ...(typeof lead['phone'] === 'string' ? { phone: lead['phone'] } : {}),\n ...(Array.isArray(lead['tags']) ? { tags: lead['tags'] } : {}),\n },\n },\n }\n}\n\n/**\n * The people, as the sequence's site knows them, and the company each\n * contact is filed under there — asked of the plugin that keeps people\n * (`plugin-person-records`, AGL-3080), never read off its storage: the\n * contacts and the leads at once, the companies once each through its\n * `company` record index, and for each lead one address lookup, because a\n * lead the workspace already holds as a contact is that contact's to enroll.\n * With no plugin keeping people, every person reads as gone.\n */\nexport async function readOutreachEnrollCandidates(input: {\n orgId: string\n hostId: string\n contactGroupId: string\n people: readonly OutreachPersonRef[]\n}): Promise<OutreachEnrollCandidate[]> {\n if (!input.people.length) return []\n const records =\n (await readPluginPeople({\n orgId: input.orgId,\n records: input.people.map((person) => ({ kind: person.kind, id: person.id })),\n })) ?? input.people.map(() => null)\n const read = await Promise.all(\n input.people.map(async (person, index) => {\n const data = records[index] ? { ...records[index]!.data } : null\n if (person.kind === 'lead') {\n const email = data ? normalizeContactEmail(data['email']) : null\n const held = data && email ? await findPluginPerson({ orgId: input.orgId, email }) : null\n return {\n personId: person.id,\n target: 'lead' as const,\n contactId: '',\n leadId: person.id,\n contact: data ? leadAsContact(data, input.contactGroupId) : null,\n lead: data,\n // A lead is the site's own record — unless another site only\n // SHARED it with this one (AGL-3336): seen, not held, and a\n // sequence is a site's own outreach.\n visible: data !== null && !seenOnlyThroughGrant(data, input.hostId),\n name: data ? crmLeadDisplayName(data) : '',\n email,\n companyId: '',\n convertedContactId: data && typeof data['convertedContactId'] === 'string' ? data['convertedContactId'] : null,\n heldAsContactId: held ? held.id : null,\n }\n }\n return {\n personId: person.id,\n target: 'contact' as const,\n contactId: person.id,\n leadId: null,\n contact: data,\n lead: null,\n visible: data\n ? visibleToHost(data['visibleTo'] as string[] | undefined, input.hostId) &&\n !seenOnlyThroughGrant(data, input.hostId)\n : false,\n name: data ? contactDisplayName(data, input.contactGroupId).trim() : '',\n email: data ? normalizeContactEmail(data['email']) : null,\n companyId: data ? String(readContactFacet(data, input.contactGroupId).companyId ?? '') : '',\n convertedContactId: null,\n heldAsContactId: null,\n }\n }),\n )\n const companyIds = [...new Set(read.map((entry) => entry.companyId).filter(Boolean))]\n const companies = new Map<string, Record<string, unknown>>()\n const companyIndex = companyIds.length ? pluginRecordIndex('company') : null\n if (companyIndex) {\n const found = await Promise.all(\n companyIds.map((id) => companyIndex.index.get({ orgId: input.orgId, id })),\n )\n found.forEach((company, index) => {\n if (company) companies.set(companyIds[index], { ...company.facts })\n })\n }\n return read.map(({ companyId, ...candidate }) => ({\n ...candidate,\n company: companyId ? (companies.get(companyId) ?? null) : null,\n }))\n}\n\n/** The person as every answer names them. */\nfunction personOf(candidate: OutreachEnrollCandidate) {\n return {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n}\n\n/** What stands in the way before the gates are asked anything. */\nexport function outreachCandidateBlocks(\n candidate: OutreachEnrollCandidate,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollBlock[] {\n if (!candidate.contact) {\n return candidate.target === 'lead'\n ? [{ code: 'lead_missing', reason: \"This lead no longer exists in this sequence's site's CRM.\" }]\n : [{ code: 'contact_missing', reason: 'This contact no longer exists in the CRM.' }]\n }\n const blocks: OutreachEnrollBlock[] = []\n if (candidate.target === 'lead') {\n // A lead that converted, or whose address the workspace already holds\n // as a contact, is that contact's to enroll — one person, one record.\n if (candidate.convertedContactId) {\n blocks.push({\n code: 'lead_converted',\n reason: 'This lead was converted into a contact. Enroll the contact instead.',\n })\n } else if (candidate.heldAsContactId) {\n blocks.push({\n code: 'lead_is_contact',\n reason: 'This address is already a contact in your CRM. Enroll the contact instead.',\n })\n }\n if (crmLeadStatus(candidate.lead) === 'unqualified') {\n blocks.push({\n code: 'lead_unqualified',\n reason: 'This lead was closed as unqualified. Reopen it before enrolling.',\n })\n }\n }\n if (!candidate.visible) {\n blocks.push({\n code: 'not_in_site',\n reason: `This contact isn't in ${facts.siteName || \"this sequence's site\"}'s CRM.`,\n })\n }\n if (!candidate.email) {\n blocks.push({ code: 'no_email', reason: 'This contact has no email address.' })\n }\n if (facts.alreadyInSequence) {\n blocks.push({\n code: 'already_in_sequence',\n reason: \"This person has already been in this sequence, so they won't be sent its emails again.\",\n })\n }\n return blocks\n}\n\n/** Every attestation, stamped for a hypothetical question only — never stored. */\nconst EVERYTHING_CONFIRMED: OutreachAttestations = Object.fromEntries(\n OUTREACH_ATTESTATION_KINDS.map((kind) => [kind, { uid: 'preview', atMs: 1 }]),\n)\n\nconst blocksOf = (blocks: readonly OutreachGateBlock[]): OutreachEnrollBlock[] =>\n blocks.map(({ code, reason }) => ({ code, reason }))\n\nexport interface OutreachGateQuestion {\n candidate: OutreachEnrollCandidate\n lookups: OutreachGateLookups\n /** The sequence's settings, its countries already capped by the organization's. */\n settings: OutreachSequenceSettings\n contactGroupId: string\n}\n\n/**\n * The gateway as the dialog shows it (AGL-3326): the standing the lookups\n * read, and whether the gates would hold a send into it.\n */\nfunction gatewayOf(question: OutreachGateQuestion, hold: OutreachGateHold | null): OutreachEnrollGateway | null {\n const standing = question.lookups?.gateway\n return standing ? { ...standing, hold: hold !== null } : null\n}\n\n/** Where one person stands before the rep confirms anything — see the module note. */\nexport function previewOutreachPerson(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollPreviewPerson {\n const { candidate } = question\n const person = {\n ...personOf(candidate),\n name: candidate.name,\n email: candidate.email,\n }\n const early = outreachCandidateBlocks(candidate, facts)\n if (early.length) {\n return {\n ...person,\n cold: false,\n country: null,\n status: 'blocked',\n blocks: early,\n requires: { personalLine: false, attestations: [] },\n gateway: null,\n }\n }\n const ask = (personalLine: string, attestations: OutreachAttestations) =>\n evaluateOutreachGates({\n email: candidate.email ?? '',\n contact: candidate.contact,\n contactGroupId: question.contactGroupId,\n company: candidate.company,\n settings: question.settings,\n personalLine,\n attestations,\n lookups: question.lookups,\n })\n const asIs = ask('', {})\n const known = { cold: asIs.cold, country: asIs.country.country, gateway: gatewayOf(question, asIs.hold) }\n if (asIs.allowed) {\n return {\n ...person,\n ...known,\n status: 'eligible',\n blocks: [],\n requires: { personalLine: false, attestations: [] },\n }\n }\n // The line is only checked for being present, so any sentence stands in.\n const confirmed = ask('A personal line.', EVERYTHING_CONFIRMED)\n if (!confirmed.allowed) {\n return {\n ...person,\n ...known,\n status: 'blocked',\n blocks: blocksOf(confirmed.blocks),\n requires: { personalLine: false, attestations: [] },\n }\n }\n const attestations: OutreachAttestationKind[] = asIs.cold\n ? [...asIs.missingAttestations]\n : asIs.blocks.some((block) => block.code === 'country_unknown')\n ? ['us_business_address']\n : []\n return {\n ...person,\n ...known,\n status: 'needs_confirmation',\n blocks: [],\n requires: {\n personalLine: asIs.blocks.some((block) => block.code === 'personal_line_missing'),\n attestations,\n },\n }\n}\n\nexport interface OutreachEnrollDecision {\n allowed: boolean\n blocks: OutreachEnrollBlock[]\n cold: boolean\n /** The address as the gates normalized it. */\n email: string | null\n /** What the rep confirmed, stamped with who and when. */\n attestations: OutreachAttestations\n /**\n * The gateway hold the gates would put on the send (AGL-3326), which the\n * member enrolling past the red chip releases; `null` when none applies.\n */\n hold: OutreachGateHold | null\n}\n\n/** Confirm's answer for one person, with what the rep supplied — see the module note. */\nexport function decideOutreachEnrollment(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n supplied: {\n personalLine: string\n attestations: readonly unknown[]\n uid: string\n nowMs: number\n },\n): OutreachEnrollDecision {\n const attestations = outreachAttestationsFrom(supplied.attestations, supplied.uid, supplied.nowMs)\n const early = outreachCandidateBlocks(question.candidate, facts)\n if (early.length) {\n return { allowed: false, blocks: early, cold: false, email: question.candidate.email, attestations, hold: null }\n }\n const result = evaluateOutreachGates({\n email: question.candidate.email ?? '',\n contact: question.candidate.contact,\n contactGroupId: question.contactGroupId,\n company: question.candidate.company,\n settings: question.settings,\n personalLine: supplied.personalLine,\n attestations,\n lookups: question.lookups,\n })\n return {\n allowed: result.allowed,\n blocks: blocksOf(result.blocks),\n cold: result.cold,\n email: result.email,\n attestations,\n hold: result.hold,\n }\n}\n"],"names":["normalizeContactEmail","contactDisplayName","readContactFacet","crmLeadDisplayName","crmLeadStatus","seenOnlyThroughGrant","visibleToHost","findPluginPerson","readPluginPeople","pluginRecordIndex","evaluateOutreachGates","outreachAttestationsFrom","OUTREACH_ATTESTATION_KINDS","leadAsContact","lead","contactGroupId","sources","raw","Array","isArray","source","String","kind","startsWith","email","name","emailState","facets","address","companyName","jobTitle","phone","tags","readOutreachEnrollCandidates","input","people","length","records","orgId","map","person","id","read","Promise","all","index","data","held","personId","target","contactId","leadId","contact","visible","hostId","companyId","convertedContactId","heldAsContactId","trim","companyIds","Set","entry","filter","Boolean","companies","Map","companyIndex","found","get","forEach","company","set","facts","candidate","personOf","outreachCandidateBlocks","code","reason","blocks","push","siteName","alreadyInSequence","EVERYTHING_CONFIRMED","Object","fromEntries","uid","atMs","blocksOf","gatewayOf","question","hold","standing","lookups","gateway","previewOutreachPerson","early","cold","country","status","requires","personalLine","attestations","ask","settings","asIs","known","allowed","confirmed","missingAttestations","some","block","decideOutreachEnrollment","supplied","nowMs","result"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAgC4C,GAE5C,SAASA,qBAAqB,EAAEC,kBAAkB,EAAEC,gBAAgB,QAAQ,kCAAiC;AAC7G,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,6BAA4B;AAC9E,SAASC,oBAAoB,EAAEC,aAAa,QAAQ,sCAAqC;AACzF,SACEC,gBAAgB,EAChBC,gBAAgB,QACX,oDAAmD;AAC1D,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SACEC,qBAAqB,QAIhB,qBAAiB;AACxB,SAASC,wBAAwB,QAAQ,gCAA4B;AACrE,SACEC,0BAA0B,QAIrB,6BAAyB;AAyDhC;;;;;;CAMC,GACD,OAAO,SAASC,cACdC,IAA6B,EAC7BC,cAAsB;IAEtB,MAAMC,UAAgC,CAAC;IACvC,KAAK,MAAMC,OAAOC,MAAMC,OAAO,CAACL,IAAI,CAAC,UAAU,IAAIA,IAAI,CAAC,UAAU,GAAG,EAAE,CAAE;QACvE,MAAMM,SAASC,OAAOJ;QACtB,MAAMK,OAAOF,OAAOG,UAAU,CAAC,WAAW,SAASH,WAAW,WAAW,WAAWA;QACpF,IAAIE,MAAMN,OAAO,CAACM,KAAK,GAAG;IAC5B;IACA,OAAO;QACLE,OAAOV,IAAI,CAAC,QAAQ;QACpBW,MAAMX,IAAI,CAAC,OAAO;OAGdA,IAAI,CAAC,aAAa,IAAI,OAAOA,IAAI,CAAC,aAAa,KAAK,WAAW;QAAEY,YAAYZ,IAAI,CAAC,aAAa;IAAC,IAAI,CAAC;QACzGa,QAAQ;YACN,CAACZ,eAAe,EAAE;gBAChBC;eACIF,IAAI,CAAC,UAAU,IAAI,OAAOA,IAAI,CAAC,UAAU,KAAK,WAAW;gBAAEc,SAASd,I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C,QACAiE;QACHP,QAAQ;QACRpB,QAAQ,EAAE;QACVqB,UAAU;YACRC,cAAcI,KAAK1B,MAAM,CAAC+B,IAAI,CAAC,CAACC,QAAUA,MAAMlC,IAAI,KAAK;YACzDyB;QACF;;AAEJ;AAiBA,uFAAuF,GACvF,OAAO,SAASU,yBACdtB,QAA8B,EAC9BjB,KAAuD,EACvDwC,QAKC;QAQQvB;IANT,MAAMY,eAAe1F,yBAAyBqG,SAASX,YAAY,EAAEW,SAAS3B,GAAG,EAAE2B,SAASC,KAAK;IACjG,MAAMlB,QAAQpB,wBAAwBc,SAAShB,SAAS,EAAED;IAC1D,IAAIuB,MAAM3D,MAAM,EAAE;QAChB,OAAO;YAAEsE,SAAS;YAAO5B,QAAQiB;YAAOC,MAAM;YAAOxE,OAAOiE,SAAShB,SAAS,CAACjD,KAAK;YAAE6E;YAAcX,MAAM;QAAK;IACjH;IACA,MAAMwB,SAASxG,sBAAsB;QACnCc,KAAK,GAAEiE,4BAAAA,SAAShB,SAAS,CAACjD,KAAK,YAAxBiE,4BAA4B;QACnCrC,SAASqC,SAAShB,SAAS,CAACrB,OAAO;QACnCrC,gBAAgB0E,SAAS1E,cAAc;QACvCuD,SAASmB,SAAShB,SAAS,CAACH,OAAO;QACnCiC,UAAUd,SAASc,QAAQ;QAC3BH,cAAcY,SAASZ,YAAY;QACnCC;QACAT,SAASH,SAASG,OAAO;IAC3B;IACA,OAAO;QACLc,SAASQ,OAAOR,OAAO;QACvB5B,QAAQS,SAAS2B,OAAOpC,MAAM;QAC9BkB,MAAMkB,OAAOlB,IAAI;QACjBxE,OAAO0F,OAAO1F,KAAK;QACnB6E;QACAX,MAAMwB,OAAOxB,IAAI;IACnB;AACF"}
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
* person who asked not to be emailed must not be emailed because a read
|
|
38
38
|
* timed out. One failed list does not blank the others.
|
|
39
39
|
*/ import { consentGroupTopicState } from "@aglyn/aglyn/app-utils/consent-groups";
|
|
40
|
-
import {
|
|
40
|
+
import { pluginPeopleWroteIn } from "@aglyn/aglyn/plugin-manager/plugin-person-records";
|
|
41
41
|
import { readTopicSubscriptionState, TOPIC_OPT_OUTS_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/subscription-topics";
|
|
42
42
|
import { SALES_TOPIC_ID } from "../model/sales-topic.js";
|
|
43
43
|
import { personKey } from "@aglyn/aglyn/app-utils/person-key";
|
|
@@ -110,8 +110,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
110
110
|
...new Set(((_input_consentHostIds = input.consentHostIds) != null ? _input_consentHostIds : []).filter((id)=>id && id !== hostId))
|
|
111
111
|
];
|
|
112
112
|
const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments');
|
|
113
|
-
const
|
|
114
|
-
const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson] = await Promise.all([
|
|
113
|
+
const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson, wroteIn] = await Promise.all([
|
|
115
114
|
keyedLookup(firestore, people, (key)=>firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key), // A released record no longer suppresses.
|
|
116
115
|
(snapshot)=>snapshot.exists && !snapshot.get('releasedAt'), 'platform suppression'),
|
|
117
116
|
keyedGroupLookup(firestore, people, hostIds, (host, key)=>host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key), (snapshot)=>snapshot.exists, // An entry on any site of the group suppresses.
|
|
@@ -143,7 +142,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
143
142
|
return null;
|
|
144
143
|
}),
|
|
145
144
|
Promise.all(people.map(async (person)=>{
|
|
146
|
-
var _person_leadId
|
|
145
|
+
var _person_leadId;
|
|
147
146
|
const open = await Promise.all([
|
|
148
147
|
person.contactId ? enrollments.where('contactId', '==', person.contactId).get() : enrollments.where('leadId', '==', (_person_leadId = person.leadId) != null ? _person_leadId : '').get(),
|
|
149
148
|
enrollments.where('email', '==', person.email).get()
|
|
@@ -167,26 +166,42 @@ async function getAllChunked(firestore, refs) {
|
|
|
167
166
|
console.error('[outreach] enrollment lookup failed; reading as unchecked', error);
|
|
168
167
|
return null;
|
|
169
168
|
});
|
|
170
|
-
// An email the person wrote: filed on the contact, or on the lead
|
|
171
|
-
// while they were one (AGL-3234).
|
|
172
|
-
const inbound = await activities.where(person.contactId ? 'contactId' : 'leadId', '==', (_ref = (_person_contactId = person.contactId) != null ? _person_contactId : person.leadId) != null ? _ref : '').where('direction', '==', 'inbound').limit(1).get().then((snapshot)=>!snapshot.empty).catch((error)=>{
|
|
173
|
-
console.error('[outreach] inbound email lookup failed; reading as cold', error);
|
|
174
|
-
return null;
|
|
175
|
-
});
|
|
176
169
|
return {
|
|
177
170
|
personId: person.personId,
|
|
178
|
-
open
|
|
179
|
-
inbound
|
|
171
|
+
open
|
|
180
172
|
};
|
|
181
|
-
}))
|
|
173
|
+
})),
|
|
174
|
+
// An email the person wrote — filed on the contact, or on the lead while
|
|
175
|
+
// they were one (AGL-3234) — as the record system answers it (AGL-3080).
|
|
176
|
+
// Unknown, never cold, when it cannot say.
|
|
177
|
+
pluginPeopleWroteIn({
|
|
178
|
+
orgId,
|
|
179
|
+
records: people.map((person)=>{
|
|
180
|
+
var _person_leadId;
|
|
181
|
+
return person.contactId ? {
|
|
182
|
+
kind: 'contact',
|
|
183
|
+
id: person.contactId
|
|
184
|
+
} : {
|
|
185
|
+
kind: 'lead',
|
|
186
|
+
id: (_person_leadId = person.leadId) != null ? _person_leadId : ''
|
|
187
|
+
};
|
|
188
|
+
})
|
|
189
|
+
})
|
|
182
190
|
]);
|
|
183
191
|
const byPerson = new Map(perPerson.map((entry)=>[
|
|
184
192
|
entry.personId,
|
|
185
193
|
entry
|
|
186
194
|
]));
|
|
195
|
+
const inboundOf = new Map(people.map((person, index)=>{
|
|
196
|
+
var _ref;
|
|
197
|
+
return [
|
|
198
|
+
person.personId,
|
|
199
|
+
(_ref = wroteIn == null ? void 0 : wroteIn[index]) != null ? _ref : null
|
|
200
|
+
];
|
|
201
|
+
}));
|
|
187
202
|
const lookups = new Map();
|
|
188
203
|
for (const person of people){
|
|
189
|
-
var _platform_get, _site_get, _sales_get, _doNotContact_get, _doNotContactDomain_get, _gateway_get, _ref,
|
|
204
|
+
var _platform_get, _site_get, _sales_get, _doNotContact_get, _doNotContactDomain_get, _gateway_get, _ref, _inboundOf_get;
|
|
190
205
|
const own = byPerson.get(person.personId);
|
|
191
206
|
lookups.set(person.personId, {
|
|
192
207
|
platformSuppressed: (_platform_get = platform.get(person.personId)) != null ? _platform_get : null,
|
|
@@ -197,7 +212,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
197
212
|
gateway: (_gateway_get = gateway.get(person.email)) != null ? _gateway_get : null,
|
|
198
213
|
workspaceMembers: roster,
|
|
199
214
|
openEnrollments: (_ref = own == null ? void 0 : own.open) != null ? _ref : null,
|
|
200
|
-
hasInboundEmail: (
|
|
215
|
+
hasInboundEmail: (_inboundOf_get = inboundOf.get(person.personId)) != null ? _inboundOf_get : null
|
|
201
216
|
});
|
|
202
217
|
}
|
|
203
218
|
return lookups;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/gate-lookups.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE LOOKUPS THE ENROLLMENT GATES DECIDE ON (AGL-2980).\n *\n * `evaluateOutreachGates` is pure: it reads a contact as stored and the\n * RESULTS of the reads the runtime makes. This is those reads, for many\n * people at once — the enroll preview asks about everyone a view names in\n * one pass, and the sending runtime asks about one person before each send\n * with the same function, so the two can never consult different lists.\n *\n * Server only. Every list keyed by address is read with one `getAll` over\n * `personKey` ids — the suppression lists, the sales topic opt-outs, the\n * do-not-contact list — so a lookup costs one round trip however many\n * people it covers, and needs no index that could go missing. The roster\n * is read once. The two per-person facts that are queries — the person's\n * other enrollments and whether they ever wrote in — are equality filters\n * on single fields.\n *\n * ## A read that failed is `null`, and `null` refuses\n *\n * Each lookup is caught on its own and answers `null` for everyone it\n * covered, which the gates read as \"we couldn't check\" and refuse: a\n * person who asked not to be emailed must not be emailed because a read\n * timed out. One failed list does not blank the others.\n */\n\nimport { consentGroupTopicState } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { SALES_TOPIC_ID } from '../model/sales-topic'\nimport type { MemberAddresses } from '@aglyn/aglyn/app-utils/member-email-aliases'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { loadMemberAddressRoster } from '@aglyn/tenant-data-admin/server/member-email-aliases'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from '@aglyn/tenant-data-admin/server/email-suppression'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport type { OutreachEnrollmentStatus } from '../model/outreach.types'\nimport {\n lookupOutreachDoNotContact,\n lookupOutreachDoNotContactDomains,\n} from '../storage/do-not-contact-store'\nimport { type OutreachDomainIntelReadInput, readOutreachGatewayStandings } from '../storage/domain-intel-store'\nimport { outreachOrgCollection } from '../storage/outreach-records'\n\n/**\n * One person to look up: the record they are, and the address the steps go\n * to. `personId` keys the answer — the contact's id, or the lead's person\n * key (AGL-3234); a lead has no contact to look up enrollments or inbound\n * email by, so those reads go by the lead instead.\n */\nexport interface OutreachGateLookupPerson {\n personId: string\n /** The contact's id, or `null` for a lead. */\n contactId: string | null\n /** The lead's person key, or `null` for a contact. */\n leadId: string | null\n email: string\n}\n\nexport interface ReadOutreachGateLookupsInput {\n orgId: string\n /** The sequence's site: whose suppression list and topic opt-outs apply. */\n hostId: string\n /**\n * Every site in the sequence site's consent group, the site included —\n * `consentGroupForHost(org, hostId).hostIds`. An org that declared several\n * sites one sender is one sender to the person who unsubscribed from any of\n * them, so the site suppression list and the sales opt-outs are read on\n * each. Omitted, the site alone.\n */\n consentHostIds?: readonly string[]\n /**\n * The same group's `awaitsConfirmation`: whether a sibling's pending\n * confirmation counts in the sales stream's standing as the sequence\n * site's own does. Omitted, it does not.\n */\n consentAwaitsConfirmation?: boolean\n /**\n * The MX resolver and the clock the domain intel is read with (AGL-3326):\n * a domain's gateway is looked up once a week and cached on the org, and\n * its ledger is read for the windows the hold and the chip judge.\n */\n gateway: OutreachDomainIntelReadInput\n people: readonly OutreachGateLookupPerson[]\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * One keyed list, read for every person at once: `answer` turns each\n * person's document into their answer. An address that cannot be keyed has\n * no document anywhere and is answered as unchecked, and so is everyone\n * when the read fails.\n */\nasync function keyedLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n collection: (key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const answers = new Map<string, T | null>()\n const keyed: Array<{ personId: string; key: string }> = []\n for (const person of people) {\n const key = personKey(person.email)\n if (key) keyed.push({ personId: person.personId, key })\n else answers.set(person.personId, null)\n }\n if (!keyed.length) return answers\n try {\n const snapshots = await getAllChunked(\n firestore,\n keyed.map((entry) => collection(entry.key)),\n )\n keyed.forEach((entry, index) => answers.set(entry.personId, answer(snapshots[index])))\n } catch (error) {\n console.error(`[outreach] ${label} lookup failed; reading as unchecked`, error)\n for (const entry of keyed) answers.set(entry.personId, null)\n }\n return answers\n}\n\n/**\n * The same keyed lookup on every site of a consent group, folded into one\n * answer per person by `fold`. A read that failed anywhere is `null` for the\n * people it covered, so a sibling's unreadable list refuses as the site's own\n * would. A group of one is one lookup, exactly as the site alone.\n */\nasync function keyedGroupLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n hostIds: readonly string[],\n collection: (host: FirebaseFirestore.DocumentReference, key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n fold: (answers: readonly T[]) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const bySite = await Promise.all(\n hostIds.map((id) => {\n const host = firestore.collection('hosts').doc(id)\n return keyedLookup(firestore, people, (key) => collection(host, key), answer, label)\n }),\n )\n if (bySite.length === 1) return bySite[0]\n const folded = new Map<string, T | null>()\n for (const person of people) {\n const answers = bySite.map((site) => site.get(person.personId) ?? null)\n folded.set(\n person.personId,\n answers.some((answer) => answer === null) ? null : fold(answers as T[]),\n )\n }\n return folded\n}\n\n/** Every lookup the gates take, for each person, keyed by person id. */\nexport async function readOutreachGateLookups(\n firestore: Firestore,\n input: ReadOutreachGateLookupsInput,\n): Promise<Map<string, OutreachGateLookups>> {\n const { orgId, hostId, people } = input\n // The sequence's site first, then the rest of its consent group.\n const hostIds = [\n hostId,\n ...new Set((input.consentHostIds ?? []).filter((id) => id && id !== hostId)),\n ]\n const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments')\n const activities = firestore.collection('orgs').doc(orgId).collection(CRM_COLLECTIONS.activities)\n\n const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson] = await Promise.all([\n keyedLookup(\n firestore,\n people,\n (key) => firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key),\n // A released record no longer suppresses.\n (snapshot) => snapshot.exists && !snapshot.get('releasedAt'),\n 'platform suppression',\n ),\n keyedGroupLookup(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key),\n (snapshot) => snapshot.exists,\n // An entry on any site of the group suppresses.\n (answers) => answers.some(Boolean),\n 'site suppression',\n ),\n keyedGroupLookup<TopicSubscriptionState>(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(TOPIC_OPT_OUTS_SUBCOLLECTION).doc(key),\n (snapshot) =>\n readTopicSubscriptionState(\n ((snapshot.exists ? snapshot.get('topics') : null) ?? {})[SALES_TOPIC_ID],\n ),\n // The group's standing, the way the topic filter folds it: leaving the\n // sales stream anywhere in the group is leaving the sender, and a\n // sibling's pending confirmation counts only where the org said the\n // group waits. What a pending standing means for a sales email is the\n // gates' question, not this one.\n (states) =>\n consentGroupTopicState(\n { awaitsConfirmation: input.consentAwaitsConfirmation === true },\n states,\n ),\n 'sales topic',\n ),\n lookupOutreachDoNotContact(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The domain half of the same list (AGL-3244), one `getAll` over the\n // distinct domains the people are at.\n lookupOutreachDoNotContactDomains(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The mail gateway in front of each domain and its record here\n // (AGL-3326), one read over the distinct domains and one over the\n // gateways they name.\n readOutreachGatewayStandings(\n firestore,\n orgId,\n people.map((person) => person.email),\n input.gateway,\n ).catch((error: unknown) => {\n console.error('[outreach] mail gateway lookup failed; reading as unchecked', error)\n return new Map<string, null>()\n }),\n loadMemberAddressRoster(firestore, orgId).catch((error: unknown): MemberAddresses[] | null => {\n console.error('[outreach] roster lookup failed; reading as unchecked', error)\n return null\n }),\n Promise.all(\n people.map(async (person) => {\n const open = await Promise.all([\n person.contactId\n ? enrollments.where('contactId', '==', person.contactId).get()\n : enrollments.where('leadId', '==', person.leadId ?? '').get(),\n enrollments.where('email', '==', person.email).get(),\n ])\n .then(([byContact, byEmail]) => {\n const found = new Map<string, { id: string; sequenceId: string; status: OutreachEnrollmentStatus }>()\n for (const doc of [...byContact.docs, ...byEmail.docs]) {\n found.set(doc.id, {\n id: doc.id,\n sequenceId: String(doc.get('sequenceId') ?? ''),\n status: doc.get('status') as OutreachEnrollmentStatus,\n })\n }\n return [...found.values()]\n })\n .catch((error: unknown) => {\n console.error('[outreach] enrollment lookup failed; reading as unchecked', error)\n return null\n })\n // An email the person wrote: filed on the contact, or on the lead\n // while they were one (AGL-3234).\n const inbound = await activities\n .where(person.contactId ? 'contactId' : 'leadId', '==', person.contactId ?? person.leadId ?? '')\n .where('direction', '==', 'inbound')\n .limit(1)\n .get()\n .then((snapshot) => !snapshot.empty)\n .catch((error: unknown) => {\n console.error('[outreach] inbound email lookup failed; reading as cold', error)\n return null\n })\n return { personId: person.personId, open, inbound }\n }),\n ),\n ])\n\n const byPerson = new Map(perPerson.map((entry) => [entry.personId, entry]))\n const lookups = new Map<string, OutreachGateLookups>()\n for (const person of people) {\n const own = byPerson.get(person.personId)\n lookups.set(person.personId, {\n platformSuppressed: platform.get(person.personId) ?? null,\n hostSuppressed: site.get(person.personId) ?? null,\n salesTopicState: sales.get(person.personId) ?? null,\n doNotContact: doNotContact.get(person.email) ?? null,\n doNotContactDomain: doNotContactDomain.get(person.email) ?? null,\n gateway: gateway.get(person.email) ?? null,\n workspaceMembers: roster,\n openEnrollments: own?.open ?? null,\n hasInboundEmail: own?.inbound ?? null,\n })\n }\n return lookups\n}\n"],"names":["consentGroupTopicState","CRM_COLLECTIONS","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","SALES_TOPIC_ID","personKey","loadMemberAddressRoster","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","lookupOutreachDoNotContact","lookupOutreachDoNotContactDomains","readOutreachGatewayStandings","outreachOrgCollection","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","keyedLookup","people","collection","answer","label","answers","Map","keyed","person","key","email","personId","set","map","entry","forEach","index","error","console","keyedGroupLookup","hostIds","fold","bySite","Promise","all","id","host","doc","folded","site","get","some","readOutreachGateLookups","input","orgId","hostId","Set","consentHostIds","filter","enrollments","activities","platform","sales","doNotContact","doNotContactDomain","gateway","roster","perPerson","snapshot","exists","Boolean","states","awaitsConfirmation","consentAwaitsConfirmation","catch","open","contactId","where","leadId","then","byContact","byEmail","found","docs","sequenceId","String","status","values","inbound","limit","empty","byPerson","lookups","own","platformSuppressed","hostSuppressed","salesTopicState","workspaceMembers","openEnrollments","hasInboundEmail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SACEC,0BAA0B,EAC1BC,4BAA4B,QAEvB,6CAA4C;AACnD,SAASC,cAAc,QAAQ,0BAAsB;AAErD,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,uBAAuB,QAAQ,uDAAsD;AAC9F,SACEC,6BAA6B,EAC7BC,+BAA+B,QAC1B,oDAAmD;AAG1D,SACEC,0BAA0B,EAC1BC,iCAAiC,QAC5B,qCAAiC;AACxC,SAA4CC,4BAA4B,QAAQ,mCAA+B;AAC/G,SAASC,qBAAqB,QAAQ,iCAA6B;AA8CnE,0DAA0D,GAC1D,MAAMC,gBAAgB;AAEtB,eAAeC,cACbC,SAAoB,EACpBC,IAAoD;IAEpD,MAAMC,YAAkD,EAAE;IAC1D,IAAK,IAAIC,QAAQ,GAAGA,QAAQF,KAAKG,MAAM,EAAED,SAASL,cAAe;QAC/DI,UAAUG,IAAI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IyC,UAAUlC,GAAG,CAAC,CAACC,QAAU;YAACA,MAAMH,QAAQ;YAAEG;SAAM;IACzE,MAAM0D,UAAU,IAAIlE;IACpB,KAAK,MAAME,UAAUP,OAAQ;YAGLwC,eACJZ,WACCa,YACHC,mBACMC,yBACXC;QAPX,MAAM4B,MAAMF,SAASzC,GAAG,CAACtB,OAAOG,QAAQ;QACxC6D,QAAQ5D,GAAG,CAACJ,OAAOG,QAAQ,EAAE;YAC3B+D,kBAAkB,GAAEjC,gBAAAA,SAASX,GAAG,CAACtB,OAAOG,QAAQ,aAA5B8B,gBAAiC;YACrDkC,cAAc,GAAE9C,YAAAA,KAAKC,GAAG,CAACtB,OAAOG,QAAQ,aAAxBkB,YAA6B;YAC7C+C,eAAe,GAAElC,aAAAA,MAAMZ,GAAG,CAACtB,OAAOG,QAAQ,aAAzB+B,aAA8B;YAC/CC,YAAY,GAAEA,oBAAAA,aAAab,GAAG,CAACtB,OAAOE,KAAK,aAA7BiC,oBAAkC;YAChDC,kBAAkB,GAAEA,0BAAAA,mBAAmBd,GAAG,CAACtB,OAAOE,KAAK,aAAnCkC,0BAAwC;YAC5DC,OAAO,GAAEA,eAAAA,QAAQf,GAAG,CAACtB,OAAOE,KAAK,aAAxBmC,eAA6B;YACtCgC,kBAAkB/B;YAClBgC,eAAe,UAAEL,uBAAAA,IAAKlB,IAAI,mBAAI;YAC9BwB,eAAe,WAAEN,uBAAAA,IAAKL,OAAO,oBAAI;QACnC;IACF;IACA,OAAOI;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/gate-lookups.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE LOOKUPS THE ENROLLMENT GATES DECIDE ON (AGL-2980).\n *\n * `evaluateOutreachGates` is pure: it reads a contact as stored and the\n * RESULTS of the reads the runtime makes. This is those reads, for many\n * people at once — the enroll preview asks about everyone a view names in\n * one pass, and the sending runtime asks about one person before each send\n * with the same function, so the two can never consult different lists.\n *\n * Server only. Every list keyed by address is read with one `getAll` over\n * `personKey` ids — the suppression lists, the sales topic opt-outs, the\n * do-not-contact list — so a lookup costs one round trip however many\n * people it covers, and needs no index that could go missing. The roster\n * is read once. The two per-person facts that are queries — the person's\n * other enrollments and whether they ever wrote in — are equality filters\n * on single fields.\n *\n * ## A read that failed is `null`, and `null` refuses\n *\n * Each lookup is caught on its own and answers `null` for everyone it\n * covered, which the gates read as \"we couldn't check\" and refuse: a\n * person who asked not to be emailed must not be emailed because a read\n * timed out. One failed list does not blank the others.\n */\n\nimport { consentGroupTopicState } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { pluginPeopleWroteIn } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { SALES_TOPIC_ID } from '../model/sales-topic'\nimport type { MemberAddresses } from '@aglyn/aglyn/app-utils/member-email-aliases'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { loadMemberAddressRoster } from '@aglyn/tenant-data-admin/server/member-email-aliases'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from '@aglyn/tenant-data-admin/server/email-suppression'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport type { OutreachEnrollmentStatus } from '../model/outreach.types'\nimport {\n lookupOutreachDoNotContact,\n lookupOutreachDoNotContactDomains,\n} from '../storage/do-not-contact-store'\nimport { type OutreachDomainIntelReadInput, readOutreachGatewayStandings } from '../storage/domain-intel-store'\nimport { outreachOrgCollection } from '../storage/outreach-records'\n\n/**\n * One person to look up: the record they are, and the address the steps go\n * to. `personId` keys the answer — the contact's id, or the lead's person\n * key (AGL-3234); a lead has no contact to look up enrollments or inbound\n * email by, so those reads go by the lead instead.\n */\nexport interface OutreachGateLookupPerson {\n personId: string\n /** The contact's id, or `null` for a lead. */\n contactId: string | null\n /** The lead's person key, or `null` for a contact. */\n leadId: string | null\n email: string\n}\n\nexport interface ReadOutreachGateLookupsInput {\n orgId: string\n /** The sequence's site: whose suppression list and topic opt-outs apply. */\n hostId: string\n /**\n * Every site in the sequence site's consent group, the site included —\n * `consentGroupForHost(org, hostId).hostIds`. An org that declared several\n * sites one sender is one sender to the person who unsubscribed from any of\n * them, so the site suppression list and the sales opt-outs are read on\n * each. Omitted, the site alone.\n */\n consentHostIds?: readonly string[]\n /**\n * The same group's `awaitsConfirmation`: whether a sibling's pending\n * confirmation counts in the sales stream's standing as the sequence\n * site's own does. Omitted, it does not.\n */\n consentAwaitsConfirmation?: boolean\n /**\n * The MX resolver and the clock the domain intel is read with (AGL-3326):\n * a domain's gateway is looked up once a week and cached on the org, and\n * its ledger is read for the windows the hold and the chip judge.\n */\n gateway: OutreachDomainIntelReadInput\n people: readonly OutreachGateLookupPerson[]\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * One keyed list, read for every person at once: `answer` turns each\n * person's document into their answer. An address that cannot be keyed has\n * no document anywhere and is answered as unchecked, and so is everyone\n * when the read fails.\n */\nasync function keyedLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n collection: (key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const answers = new Map<string, T | null>()\n const keyed: Array<{ personId: string; key: string }> = []\n for (const person of people) {\n const key = personKey(person.email)\n if (key) keyed.push({ personId: person.personId, key })\n else answers.set(person.personId, null)\n }\n if (!keyed.length) return answers\n try {\n const snapshots = await getAllChunked(\n firestore,\n keyed.map((entry) => collection(entry.key)),\n )\n keyed.forEach((entry, index) => answers.set(entry.personId, answer(snapshots[index])))\n } catch (error) {\n console.error(`[outreach] ${label} lookup failed; reading as unchecked`, error)\n for (const entry of keyed) answers.set(entry.personId, null)\n }\n return answers\n}\n\n/**\n * The same keyed lookup on every site of a consent group, folded into one\n * answer per person by `fold`. A read that failed anywhere is `null` for the\n * people it covered, so a sibling's unreadable list refuses as the site's own\n * would. A group of one is one lookup, exactly as the site alone.\n */\nasync function keyedGroupLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n hostIds: readonly string[],\n collection: (host: FirebaseFirestore.DocumentReference, key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n fold: (answers: readonly T[]) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const bySite = await Promise.all(\n hostIds.map((id) => {\n const host = firestore.collection('hosts').doc(id)\n return keyedLookup(firestore, people, (key) => collection(host, key), answer, label)\n }),\n )\n if (bySite.length === 1) return bySite[0]\n const folded = new Map<string, T | null>()\n for (const person of people) {\n const answers = bySite.map((site) => site.get(person.personId) ?? null)\n folded.set(\n person.personId,\n answers.some((answer) => answer === null) ? null : fold(answers as T[]),\n )\n }\n return folded\n}\n\n/** Every lookup the gates take, for each person, keyed by person id. */\nexport async function readOutreachGateLookups(\n firestore: Firestore,\n input: ReadOutreachGateLookupsInput,\n): Promise<Map<string, OutreachGateLookups>> {\n const { orgId, hostId, people } = input\n // The sequence's site first, then the rest of its consent group.\n const hostIds = [\n hostId,\n ...new Set((input.consentHostIds ?? []).filter((id) => id && id !== hostId)),\n ]\n const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments')\n\n const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson, wroteIn] = await Promise.all([\n keyedLookup(\n firestore,\n people,\n (key) => firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key),\n // A released record no longer suppresses.\n (snapshot) => snapshot.exists && !snapshot.get('releasedAt'),\n 'platform suppression',\n ),\n keyedGroupLookup(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key),\n (snapshot) => snapshot.exists,\n // An entry on any site of the group suppresses.\n (answers) => answers.some(Boolean),\n 'site suppression',\n ),\n keyedGroupLookup<TopicSubscriptionState>(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(TOPIC_OPT_OUTS_SUBCOLLECTION).doc(key),\n (snapshot) =>\n readTopicSubscriptionState(\n ((snapshot.exists ? snapshot.get('topics') : null) ?? {})[SALES_TOPIC_ID],\n ),\n // The group's standing, the way the topic filter folds it: leaving the\n // sales stream anywhere in the group is leaving the sender, and a\n // sibling's pending confirmation counts only where the org said the\n // group waits. What a pending standing means for a sales email is the\n // gates' question, not this one.\n (states) =>\n consentGroupTopicState(\n { awaitsConfirmation: input.consentAwaitsConfirmation === true },\n states,\n ),\n 'sales topic',\n ),\n lookupOutreachDoNotContact(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The domain half of the same list (AGL-3244), one `getAll` over the\n // distinct domains the people are at.\n lookupOutreachDoNotContactDomains(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The mail gateway in front of each domain and its record here\n // (AGL-3326), one read over the distinct domains and one over the\n // gateways they name.\n readOutreachGatewayStandings(\n firestore,\n orgId,\n people.map((person) => person.email),\n input.gateway,\n ).catch((error: unknown) => {\n console.error('[outreach] mail gateway lookup failed; reading as unchecked', error)\n return new Map<string, null>()\n }),\n loadMemberAddressRoster(firestore, orgId).catch((error: unknown): MemberAddresses[] | null => {\n console.error('[outreach] roster lookup failed; reading as unchecked', error)\n return null\n }),\n Promise.all(\n people.map(async (person) => {\n const open = await Promise.all([\n person.contactId\n ? enrollments.where('contactId', '==', person.contactId).get()\n : enrollments.where('leadId', '==', person.leadId ?? '').get(),\n enrollments.where('email', '==', person.email).get(),\n ])\n .then(([byContact, byEmail]) => {\n const found = new Map<string, { id: string; sequenceId: string; status: OutreachEnrollmentStatus }>()\n for (const doc of [...byContact.docs, ...byEmail.docs]) {\n found.set(doc.id, {\n id: doc.id,\n sequenceId: String(doc.get('sequenceId') ?? ''),\n status: doc.get('status') as OutreachEnrollmentStatus,\n })\n }\n return [...found.values()]\n })\n .catch((error: unknown) => {\n console.error('[outreach] enrollment lookup failed; reading as unchecked', error)\n return null\n })\n return { personId: person.personId, open }\n }),\n ),\n // An email the person wrote — filed on the contact, or on the lead while\n // they were one (AGL-3234) — as the record system answers it (AGL-3080).\n // Unknown, never cold, when it cannot say.\n pluginPeopleWroteIn({\n orgId,\n records: people.map((person) =>\n person.contactId\n ? { kind: 'contact', id: person.contactId }\n : { kind: 'lead', id: person.leadId ?? '' },\n ),\n }),\n ])\n\n const byPerson = new Map(perPerson.map((entry) => [entry.personId, entry]))\n const inboundOf = new Map(people.map((person, index) => [person.personId, wroteIn?.[index] ?? null]))\n const lookups = new Map<string, OutreachGateLookups>()\n for (const person of people) {\n const own = byPerson.get(person.personId)\n lookups.set(person.personId, {\n platformSuppressed: platform.get(person.personId) ?? null,\n hostSuppressed: site.get(person.personId) ?? null,\n salesTopicState: sales.get(person.personId) ?? null,\n doNotContact: doNotContact.get(person.email) ?? null,\n doNotContactDomain: doNotContactDomain.get(person.email) ?? null,\n gateway: gateway.get(person.email) ?? null,\n workspaceMembers: roster,\n openEnrollments: own?.open ?? null,\n hasInboundEmail: inboundOf.get(person.personId) ?? null,\n })\n }\n return lookups\n}\n"],"names":["consentGroupTopicState","pluginPeopleWroteIn","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","SALES_TOPIC_ID","personKey","loadMemberAddressRoster","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","lookupOutreachDoNotContact","lookupOutreachDoNotContactDomains","readOutreachGatewayStandings","outreachOrgCollection","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","keyedLookup","people","collection","answer","label","answers","Map","keyed","person","key","email","personId","set","map","entry","forEach","index","error","console","keyedGroupLookup","hostIds","fold","bySite","Promise","all","id","host","doc","folded","site","get","some","readOutreachGateLookups","input","orgId","hostId","Set","consentHostIds","filter","enrollments","platform","sales","doNotContact","doNotContactDomain","gateway","roster","perPerson","wroteIn","snapshot","exists","Boolean","states","awaitsConfirmation","consentAwaitsConfirmation","catch","open","contactId","where","leadId","then","byContact","byEmail","found","docs","sequenceId","String","status","values","records","kind","byPerson","inboundOf","lookups","own","platformSuppressed","hostSuppressed","salesTopicState","workspaceMembers","openEnrollments","hasInboundEmail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,mBAAmB,QAAQ,oDAAmD;AACvF,SACEC,0BAA0B,EAC1BC,4BAA4B,QAEvB,6CAA4C;AACnD,SAASC,cAAc,QAAQ,0BAAsB;AAErD,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,uBAAuB,QAAQ,uDAAsD;AAC9F,SACEC,6BAA6B,EAC7BC,+BAA+B,QAC1B,oDAAmD;AAG1D,SACEC,0BAA0B,EAC1BC,iCAAiC,QAC5B,qCAAiC;AACxC,SAA4CC,4BAA4B,QAAQ,mCAA+B;AAC/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n LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The body of an email template a step sends (AGL-2980), read through the
|
|
19
|
+
* record system's `messageTemplate` index (AGL-3080) — never off its
|
|
20
|
+
* storage. `null` for a template that is gone, and for a workspace whose
|
|
21
|
+
* record system keeps none: a step whose template cannot be read sends its
|
|
22
|
+
* own words or nothing, as the caller decides.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readOutreachTemplateBody(orgId: string, templateId: string | null | undefined): Promise<string | null>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { pluginRecordIndex } from "@aglyn/aglyn/plugin-manager/plugin-record-index";
|
|
17
|
+
/**
|
|
18
|
+
* The body of an email template a step sends (AGL-2980), read through the
|
|
19
|
+
* record system's `messageTemplate` index (AGL-3080) — never off its
|
|
20
|
+
* storage. `null` for a template that is gone, and for a workspace whose
|
|
21
|
+
* record system keeps none: a step whose template cannot be read sends its
|
|
22
|
+
* own words or nothing, as the caller decides.
|
|
23
|
+
*/ export async function readOutreachTemplateBody(orgId, templateId) {
|
|
24
|
+
const id = String(templateId != null ? templateId : '').trim();
|
|
25
|
+
const owner = id ? pluginRecordIndex('messageTemplate') : null;
|
|
26
|
+
if (!owner) return null;
|
|
27
|
+
const template = await owner.index.get({
|
|
28
|
+
orgId,
|
|
29
|
+
id
|
|
30
|
+
});
|
|
31
|
+
const body = template == null ? void 0 : template.facts['body'];
|
|
32
|
+
return typeof body === 'string' ? body : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=message-templates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/message-templates.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 { pluginRecordIndex } from '@aglyn/aglyn/plugin-manager/plugin-record-index'\n\n/**\n * The body of an email template a step sends (AGL-2980), read through the\n * record system's `messageTemplate` index (AGL-3080) — never off its\n * storage. `null` for a template that is gone, and for a workspace whose\n * record system keeps none: a step whose template cannot be read sends its\n * own words or nothing, as the caller decides.\n */\nexport async function readOutreachTemplateBody(\n orgId: string,\n templateId: string | null | undefined,\n): Promise<string | null> {\n const id = String(templateId ?? '').trim()\n const owner = id ? pluginRecordIndex('messageTemplate') : null\n if (!owner) return null\n const template = await owner.index.get({ orgId, id })\n const body = template?.facts['body']\n return typeof body === 'string' ? body : null\n}\n"],"names":["pluginRecordIndex","readOutreachTemplateBody","orgId","templateId","id","String","trim","owner","template","index","get","body","facts"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,kDAAiD;AAEnF;;;;;;CAMC,GACD,OAAO,eAAeC,yBACpBC,KAAa,EACbC,UAAqC;IAErC,MAAMC,KAAKC,OAAOF,qBAAAA,aAAc,IAAIG,IAAI;IACxC,MAAMC,QAAQH,KAAKJ,kBAAkB,qBAAqB;IAC1D,IAAI,CAACO,OAAO,OAAO;IACnB,MAAMC,WAAW,MAAMD,MAAME,KAAK,CAACC,GAAG,CAAC;QAAER;QAAOE;IAAG;IACnD,MAAMO,OAAOH,4BAAAA,SAAUI,KAAK,CAAC,OAAO;IACpC,OAAO,OAAOD,SAAS,WAAWA,OAAO;AAC3C"}
|
|
@@ -59,3 +59,19 @@ export interface OutreachClickSummary {
|
|
|
59
59
|
export declare function outreachClickSummary(raw: unknown): OutreachClickSummary;
|
|
60
60
|
/** The Clicks cell: "2 · 1 link", or the count alone when the links are not known. */
|
|
61
61
|
export declare function outreachClickCountLabel(summary: OutreachClickSummary): string;
|
|
62
|
+
/**
|
|
63
|
+
* What the enrollments table says about one person's opens (AGL-3488): the
|
|
64
|
+
* fetches judged theirs, and the ones a machine made — a mail provider's
|
|
65
|
+
* proxy or a scanner — beside them and never in them, as `machineClicks`
|
|
66
|
+
* sits beside `clicks`.
|
|
67
|
+
*/
|
|
68
|
+
export interface OutreachOpenSummary {
|
|
69
|
+
opens: number;
|
|
70
|
+
machineOpens: number;
|
|
71
|
+
lastOpenAtMs: number | null;
|
|
72
|
+
}
|
|
73
|
+
export declare function outreachOpenSummary(raw: unknown): OutreachOpenSummary;
|
|
74
|
+
/** The machine half of the Opens cell: "3 by machines", or `''` when there were none. */
|
|
75
|
+
export declare function outreachMachineOpenLabel(summary: OutreachOpenSummary): string;
|
|
76
|
+
/** The Opens cell as the export writes it: "2", "2 (3 by machines)", or "—" when nothing fetched it. */
|
|
77
|
+
export declare function outreachOpenCountLabel(summary: OutreachOpenSummary): string;
|
|
@@ -93,5 +93,21 @@ export function outreachClickSummary(raw) {
|
|
|
93
93
|
const links = `${summary.linkCount}${summary.linksCapped ? '+' : ''}`;
|
|
94
94
|
return `${summary.clicks} · ${links} ${summary.linkCount === 1 && !summary.linksCapped ? 'link' : 'links'}`;
|
|
95
95
|
}
|
|
96
|
+
export function outreachOpenSummary(raw) {
|
|
97
|
+
const engagement = readOutreachEngagement(raw);
|
|
98
|
+
return {
|
|
99
|
+
opens: engagement.opens,
|
|
100
|
+
machineOpens: engagement.machineOpens,
|
|
101
|
+
lastOpenAtMs: engagement.lastOpenAtMs
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** The machine half of the Opens cell: "3 by machines", or `''` when there were none. */ export function outreachMachineOpenLabel(summary) {
|
|
105
|
+
return summary.machineOpens ? `${summary.machineOpens} by ${summary.machineOpens === 1 ? 'a machine' : 'machines'}` : '';
|
|
106
|
+
}
|
|
107
|
+
/** The Opens cell as the export writes it: "2", "2 (3 by machines)", or "—" when nothing fetched it. */ export function outreachOpenCountLabel(summary) {
|
|
108
|
+
const machines = outreachMachineOpenLabel(summary);
|
|
109
|
+
if (!summary.opens) return machines ? `0 (${machines})` : '—';
|
|
110
|
+
return machines ? `${summary.opens} (${machines})` : String(summary.opens);
|
|
111
|
+
}
|
|
96
112
|
|
|
97
113
|
//# sourceMappingURL=enrollment-engagement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/enrollment-engagement.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 { OUTREACH_ENGAGEMENT_LINKS_MAX, type OutreachEnrollmentEngagement } from './outreach.types'\n\n/**\n * WHAT ONE PERSON DID WITH THE LINKS THEY WERE SENT (AGL-3239), read back\n * from the stored map.\n *\n * Client-safe, and here rather than beside the writer for that reason: the\n * enrollments table renders this in the browser and the click route writes\n * it on the server, and both must agree on what an absent field means.\n *\n * Read defensively, a field at a time. `readOutreachEngagement(undefined)`\n * is what an enrollment that has never been clicked reads as — which is\n * every enrollment of every sequence that does not track clicks, so it is\n * the common case rather than the edge one.\n */\nexport function readOutreachEngagement(raw: unknown): Required<OutreachEnrollmentEngagement> {\n const data = (raw ?? {}) as Record<string, unknown>\n const count = (value: unknown): number => {\n const parsed = Number(value)\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0\n }\n const ms = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n const clicks = count(data['clicks'])\n const machineClicks = count(data['machineClicks'])\n const opens = count(data['opens'])\n const machineOpens = count(data['machineOpens'])\n const links = Array.isArray(data['links'])\n ? [...new Set(data['links'].filter((entry): entry is string => typeof entry === 'string' && entry !== ''))]\n : []\n return {\n clicks,\n firstClickAtMs: ms(data['firstClickAtMs']),\n lastClickAtMs: ms(data['lastClickAtMs']),\n lastClickUrl: typeof data['lastClickUrl'] === 'string' ? data['lastClickUrl'] : null,\n machineClicks,\n links: links.slice(0, OUTREACH_ENGAGEMENT_LINKS_MAX),\n // Never more than the totals they are part of: a history row is written\n // in the same transaction as the count it itemizes.\n loggedClicks: Math.min(count(data['loggedClicks']), clicks),\n loggedMachineClicks: Math.min(count(data['loggedMachineClicks']), machineClicks),\n // Opens (AGL-3395): absent on every enrollment of a sequence that does\n // not count them, and read as none.\n opens,\n firstOpenAtMs: ms(data['firstOpenAtMs']),\n lastOpenAtMs: ms(data['lastOpenAtMs']),\n machineOpens,\n loggedOpens: Math.min(count(data['loggedOpens']), opens + machineOpens),\n }\n}\n\n/**\n * How many rows one enrollment's history holds for its clicks and opens:\n * what the writers compare with `OUTREACH_ENROLLMENT_HISTORY_MAX` before\n * adding another.\n */\nexport function outreachLoggedEngagementRows(engagement: Required<OutreachEnrollmentEngagement>): number {\n return engagement.loggedClicks + engagement.loggedMachineClicks + engagement.loggedOpens\n}\n\n/**\n * What the enrollments table and the detail view say about one person's\n * clicks (AGL-3332), from the engagement alone.\n *\n * `linkCount` is the number of distinct destinations they followed when that\n * number is KNOWN, and `null` when it is not: a click from before the\n * per-click history kept only the last destination, so a person with two\n * such clicks followed one link or two, and neither is claimed.\n * `linksCapped` says the list stopped at {@link OUTREACH_ENGAGEMENT_LINKS_MAX}.\n */\nexport interface OutreachClickSummary {\n clicks: number\n machineClicks: number\n /** Every destination known to have been followed: the history's, and the last one. */\n followed: string[]\n linkCount: number | null\n linksCapped: boolean\n /** Human clicks counted as totals only, with no row of their own. */\n unloggedClicks: number\n unloggedMachineClicks: number\n}\n\nexport function outreachClickSummary(raw: unknown): OutreachClickSummary {\n const engagement = readOutreachEngagement(raw)\n const followed = [...engagement.links]\n if (engagement.lastClickUrl && !followed.includes(engagement.lastClickUrl)) followed.push(engagement.lastClickUrl)\n const unloggedClicks = engagement.clicks - engagement.loggedClicks\n const linksCapped = engagement.links.length >= OUTREACH_ENGAGEMENT_LINKS_MAX\n // Exact when every human click has a row, or when there was only one.\n const exact = unloggedClicks === 0 || (engagement.clicks === 1 && engagement.lastClickUrl !== null)\n return {\n clicks: engagement.clicks,\n machineClicks: engagement.machineClicks,\n followed,\n linkCount: engagement.clicks === 0 ? 0 : exact ? followed.length : null,\n linksCapped,\n unloggedClicks,\n unloggedMachineClicks: engagement.machineClicks - engagement.loggedMachineClicks,\n }\n}\n\n/** The Clicks cell: \"2 · 1 link\", or the count alone when the links are not known. */\nexport function outreachClickCountLabel(summary: OutreachClickSummary): string {\n if (!summary.clicks) return '—'\n if (summary.linkCount === null) return String(summary.clicks)\n const links = `${summary.linkCount}${summary.linksCapped ? '+' : ''}`\n return `${summary.clicks} · ${links} ${summary.linkCount === 1 && !summary.linksCapped ? 'link' : 'links'}`\n}\n"],"names":["OUTREACH_ENGAGEMENT_LINKS_MAX","readOutreachEngagement","raw","data","count","value","parsed","Number","isFinite","Math","floor","ms","clicks","machineClicks","opens","machineOpens","links","Array","isArray","Set","filter","entry","firstClickAtMs","lastClickAtMs","lastClickUrl","slice","loggedClicks","min","loggedMachineClicks","firstOpenAtMs","lastOpenAtMs","loggedOpens","outreachLoggedEngagementRows","engagement","outreachClickSummary","followed","includes","push","unloggedClicks","linksCapped","length","exact","linkCount","unloggedMachineClicks","outreachClickCountLabel","summary","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,6BAA6B,QAA2C,sBAAkB;AAEnG;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,uBAAuBC,GAAY;IACjD,MAAMC,OAAQD,cAAAA,MAAO,CAAC;IACtB,MAAME,QAAQ,CAACC;QACb,MAAMC,SAASC,OAAOF;QACtB,OAAOE,OAAOC,QAAQ,CAACF,WAAWA,SAAS,IAAIG,KAAKC,KAAK,CAACJ,UAAU;IACtE;IACA,MAAMK,KAAK,CAACN,QACV,OAAOA,UAAU,YAAYE,OAAOC,QAAQ,CAACH,SAASA,QAAQ;IAChE,MAAMO,SAASR,MAAMD,IAAI,CAAC,SAAS;IACnC,MAAMU,gBAAgBT,MAAMD,IAAI,CAAC,gBAAgB;IACjD,MAAMW,QAAQV,MAAMD,IAAI,CAAC,QAAQ;IACjC,MAAMY,eAAeX,MAAMD,IAAI,CAAC,eAAe;IAC/C,MAAMa,QAAQC,MAAMC,OAAO,CAACf,IAAI,CAAC,QAAQ,IACrC;W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E,MAAMyC,QAAQH,mBAAmB,KAAML,WAAWrB,MAAM,KAAK,KAAKqB,WAAWT,YAAY,KAAK;IAC9F,OAAO;QACLZ,QAAQqB,WAAWrB,MAAM;QACzBC,eAAeoB,WAAWpB,aAAa;QACvCsB;QACAO,WAAWT,WAAWrB,MAAM,KAAK,IAAI,IAAI6B,QAAQN,SAASK,MAAM,GAAG;QACnED;QACAD;QACAK,uBAAuBV,WAAWpB,aAAa,GAAGoB,WAAWL,mBAAmB;IAClF;AACF;AAEA,oFAAoF,GACpF,OAAO,SAASgB,wBAAwBC,OAA6B;IACnE,IAAI,CAACA,QAAQjC,MAAM,EAAE,OAAO;IAC5B,IAAIiC,QAAQH,SAAS,KAAK,MAAM,OAAOI,OAAOD,QAAQjC,MAAM;IAC5D,MAAMI,QAAQ,GAAG6B,QAAQH,SAAS,GAAGG,QAAQN,WAAW,GAAG,MAAM,IAAI;IACrE,OAAO,GAAGM,QAAQjC,MAAM,CAAC,GAAG,EAAEI,MAAM,CAAC,EAAE6B,QAAQH,SAAS,KAAK,KAAK,CAACG,QAAQN,WAAW,GAAG,SAAS,SAAS;AAC7G"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/enrollment-engagement.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 { OUTREACH_ENGAGEMENT_LINKS_MAX, type OutreachEnrollmentEngagement } from './outreach.types'\n\n/**\n * WHAT ONE PERSON DID WITH THE LINKS THEY WERE SENT (AGL-3239), read back\n * from the stored map.\n *\n * Client-safe, and here rather than beside the writer for that reason: the\n * enrollments table renders this in the browser and the click route writes\n * it on the server, and both must agree on what an absent field means.\n *\n * Read defensively, a field at a time. `readOutreachEngagement(undefined)`\n * is what an enrollment that has never been clicked reads as — which is\n * every enrollment of every sequence that does not track clicks, so it is\n * the common case rather than the edge one.\n */\nexport function readOutreachEngagement(raw: unknown): Required<OutreachEnrollmentEngagement> {\n const data = (raw ?? {}) as Record<string, unknown>\n const count = (value: unknown): number => {\n const parsed = Number(value)\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0\n }\n const ms = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n const clicks = count(data['clicks'])\n const machineClicks = count(data['machineClicks'])\n const opens = count(data['opens'])\n const machineOpens = count(data['machineOpens'])\n const links = Array.isArray(data['links'])\n ? [...new Set(data['links'].filter((entry): entry is string => typeof entry === 'string' && entry !== ''))]\n : []\n return {\n clicks,\n firstClickAtMs: ms(data['firstClickAtMs']),\n lastClickAtMs: ms(data['lastClickAtMs']),\n lastClickUrl: typeof data['lastClickUrl'] === 'string' ? data['lastClickUrl'] : null,\n machineClicks,\n links: links.slice(0, OUTREACH_ENGAGEMENT_LINKS_MAX),\n // Never more than the totals they are part of: a history row is written\n // in the same transaction as the count it itemizes.\n loggedClicks: Math.min(count(data['loggedClicks']), clicks),\n loggedMachineClicks: Math.min(count(data['loggedMachineClicks']), machineClicks),\n // Opens (AGL-3395): absent on every enrollment of a sequence that does\n // not count them, and read as none.\n opens,\n firstOpenAtMs: ms(data['firstOpenAtMs']),\n lastOpenAtMs: ms(data['lastOpenAtMs']),\n machineOpens,\n loggedOpens: Math.min(count(data['loggedOpens']), opens + machineOpens),\n }\n}\n\n/**\n * How many rows one enrollment's history holds for its clicks and opens:\n * what the writers compare with `OUTREACH_ENROLLMENT_HISTORY_MAX` before\n * adding another.\n */\nexport function outreachLoggedEngagementRows(engagement: Required<OutreachEnrollmentEngagement>): number {\n return engagement.loggedClicks + engagement.loggedMachineClicks + engagement.loggedOpens\n}\n\n/**\n * What the enrollments table and the detail view say about one person's\n * clicks (AGL-3332), from the engagement alone.\n *\n * `linkCount` is the number of distinct destinations they followed when that\n * number is KNOWN, and `null` when it is not: a click from before the\n * per-click history kept only the last destination, so a person with two\n * such clicks followed one link or two, and neither is claimed.\n * `linksCapped` says the list stopped at {@link OUTREACH_ENGAGEMENT_LINKS_MAX}.\n */\nexport interface OutreachClickSummary {\n clicks: number\n machineClicks: number\n /** Every destination known to have been followed: the history's, and the last one. */\n followed: string[]\n linkCount: number | null\n linksCapped: boolean\n /** Human clicks counted as totals only, with no row of their own. */\n unloggedClicks: number\n unloggedMachineClicks: number\n}\n\nexport function outreachClickSummary(raw: unknown): OutreachClickSummary {\n const engagement = readOutreachEngagement(raw)\n const followed = [...engagement.links]\n if (engagement.lastClickUrl && !followed.includes(engagement.lastClickUrl)) followed.push(engagement.lastClickUrl)\n const unloggedClicks = engagement.clicks - engagement.loggedClicks\n const linksCapped = engagement.links.length >= OUTREACH_ENGAGEMENT_LINKS_MAX\n // Exact when every human click has a row, or when there was only one.\n const exact = unloggedClicks === 0 || (engagement.clicks === 1 && engagement.lastClickUrl !== null)\n return {\n clicks: engagement.clicks,\n machineClicks: engagement.machineClicks,\n followed,\n linkCount: engagement.clicks === 0 ? 0 : exact ? followed.length : null,\n linksCapped,\n unloggedClicks,\n unloggedMachineClicks: engagement.machineClicks - engagement.loggedMachineClicks,\n }\n}\n\n/** The Clicks cell: \"2 · 1 link\", or the count alone when the links are not known. */\nexport function outreachClickCountLabel(summary: OutreachClickSummary): string {\n if (!summary.clicks) return '—'\n if (summary.linkCount === null) return String(summary.clicks)\n const links = `${summary.linkCount}${summary.linksCapped ? '+' : ''}`\n return `${summary.clicks} · ${links} ${summary.linkCount === 1 && !summary.linksCapped ? 'link' : 'links'}`\n}\n\n/**\n * What the enrollments table says about one person's opens (AGL-3488): the\n * fetches judged theirs, and the ones a machine made — a mail provider's\n * proxy or a scanner — beside them and never in them, as `machineClicks`\n * sits beside `clicks`.\n */\nexport interface OutreachOpenSummary {\n opens: number\n machineOpens: number\n lastOpenAtMs: number | null\n}\n\nexport function outreachOpenSummary(raw: unknown): OutreachOpenSummary {\n const engagement = readOutreachEngagement(raw)\n return {\n opens: engagement.opens,\n machineOpens: engagement.machineOpens,\n lastOpenAtMs: engagement.lastOpenAtMs,\n }\n}\n\n/** The machine half of the Opens cell: \"3 by machines\", or `''` when there were none. */\nexport function outreachMachineOpenLabel(summary: OutreachOpenSummary): string {\n return summary.machineOpens ? `${summary.machineOpens} by ${summary.machineOpens === 1 ? 'a machine' : 'machines'}` : ''\n}\n\n/** The Opens cell as the export writes it: \"2\", \"2 (3 by machines)\", or \"—\" when nothing fetched it. */\nexport function outreachOpenCountLabel(summary: OutreachOpenSummary): string {\n const machines = outreachMachineOpenLabel(summary)\n if (!summary.opens) return machines ? `0 (${machines})` : '—'\n return machines ? `${summary.opens} (${machines})` : String(summary.opens)\n}\n"],"names":["OUTREACH_ENGAGEMENT_LINKS_MAX","readOutreachEngagement","raw","data","count","value","parsed","Number","isFinite","Math","floor","ms","clicks","machineClicks","opens","machineOpens","links","Array","isArray","Set","filter","entry","firstClickAtMs","lastClickAtMs","lastClickUrl","slice","loggedClicks","min","loggedMachineClicks","firstOpenAtMs","lastOpenAtMs","loggedOpens","outreachLoggedEngagementRows","engagement","outreachClickSummary","followed","includes","push","unloggedClicks","linksCapped","length","exact","linkCount","unloggedMachineClicks","outreachClickCountLabel","summary","String","outreachOpenSummary","outreachMachineOpenLabel","outreachOpenCountLabel","machines"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,6BAA6B,QAA2C,sBAAkB;AAEnG;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,uBAAuBC,GAAY;IACjD,MAAMC,OAAQD,cAAAA,MAAO,CAAC;IACtB,MAAME,QAAQ,CAACC;QACb,MAAMC,SAASC,OAAOF;QACtB,OAAOE,OAAOC,QAAQ,CAACF,WAAWA,S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cAAcG,WAAWH,YAAY;IACvC;AACF;AAEA,uFAAuF,GACvF,OAAO,SAASkB,yBAAyBH,OAA4B;IACnE,OAAOA,QAAQ9B,YAAY,GAAG,GAAG8B,QAAQ9B,YAAY,CAAC,IAAI,EAAE8B,QAAQ9B,YAAY,KAAK,IAAI,cAAc,YAAY,GAAG;AACxH;AAEA,sGAAsG,GACtG,OAAO,SAASkC,uBAAuBJ,OAA4B;IACjE,MAAMK,WAAWF,yBAAyBH;IAC1C,IAAI,CAACA,QAAQ/B,KAAK,EAAE,OAAOoC,WAAW,CAAC,GAAG,EAAEA,SAAS,CAAC,CAAC,GAAG;IAC1D,OAAOA,WAAW,GAAGL,QAAQ/B,KAAK,CAAC,EAAE,EAAEoC,SAAS,CAAC,CAAC,GAAGJ,OAAOD,QAAQ/B,KAAK;AAC3E"}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import type { OutreachClickMachineReason } from '../engine/click-tracking';
|
|
18
|
+
import { type OutreachOpenSource } from '../engine/open-source';
|
|
18
19
|
import type { OutreachOpenMachineReason } from '../engine/open-tracking';
|
|
19
20
|
import type { OutreachEnrollmentHistoryEntry, OutreachHistoryAction } from './outreach.types';
|
|
20
21
|
/** A click row as the click route writes it. */
|
|
@@ -25,12 +26,18 @@ export declare function outreachClickHistoryRow(input: {
|
|
|
25
26
|
human: boolean;
|
|
26
27
|
machineReason: OutreachClickMachineReason | null;
|
|
27
28
|
}): Record<string, unknown>;
|
|
28
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* An open row as the short-link route writes it for a tracking image
|
|
31
|
+
* (AGL-3395), with the evidence it was judged on (AGL-3488): the agent the
|
|
32
|
+
* fetch sent, and the network it came from — never its address.
|
|
33
|
+
*/
|
|
29
34
|
export declare function outreachOpenHistoryRow(input: {
|
|
30
35
|
atMs: number;
|
|
31
36
|
stepIndex: number;
|
|
32
37
|
human: boolean;
|
|
33
38
|
machineReason: OutreachOpenMachineReason | null;
|
|
39
|
+
userAgent?: string | null;
|
|
40
|
+
source?: OutreachOpenSource | null;
|
|
34
41
|
}): Record<string, unknown>;
|
|
35
42
|
/** A member's act as the action route writes it. */
|
|
36
43
|
export declare function outreachActionHistoryRow(input: {
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/
|
|
16
|
+
*/ import { OUTREACH_OPEN_SOURCES } from "../engine/open-source.js";
|
|
17
|
+
/**
|
|
17
18
|
* ONE ROW OF AN ENROLLMENT'S HISTORY (AGL-3332), as stored and as read back.
|
|
18
19
|
*
|
|
19
20
|
* Client-safe, beside the other readers, because the click route and the
|
|
@@ -31,7 +32,8 @@ const OPEN_MACHINE_REASONS = [
|
|
|
31
32
|
'too_soon',
|
|
32
33
|
'method',
|
|
33
34
|
'image_proxy',
|
|
34
|
-
'privacy_proxy'
|
|
35
|
+
'privacy_proxy',
|
|
36
|
+
'scanner'
|
|
35
37
|
];
|
|
36
38
|
const ACTIONS = [
|
|
37
39
|
'pause',
|
|
@@ -49,13 +51,20 @@ const ACTIONS = [
|
|
|
49
51
|
machineReason: input.human ? null : input.machineReason
|
|
50
52
|
};
|
|
51
53
|
}
|
|
52
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* An open row as the short-link route writes it for a tracking image
|
|
56
|
+
* (AGL-3395), with the evidence it was judged on (AGL-3488): the agent the
|
|
57
|
+
* fetch sent, and the network it came from — never its address.
|
|
58
|
+
*/ export function outreachOpenHistoryRow(input) {
|
|
59
|
+
var _input_userAgent, _input_source;
|
|
53
60
|
return {
|
|
54
61
|
kind: 'open',
|
|
55
62
|
atMs: input.atMs,
|
|
56
63
|
stepIndex: input.stepIndex,
|
|
57
64
|
human: input.human,
|
|
58
|
-
machineReason: input.human ? null : input.machineReason
|
|
65
|
+
machineReason: input.human ? null : input.machineReason,
|
|
66
|
+
userAgent: (_input_userAgent = input.userAgent) != null ? _input_userAgent : null,
|
|
67
|
+
source: (_input_source = input.source) != null ? _input_source : null
|
|
59
68
|
};
|
|
60
69
|
}
|
|
61
70
|
/** A member's act as the action route writes it. */ export function outreachActionHistoryRow(input) {
|
|
@@ -103,7 +112,10 @@ const ACTIONS = [
|
|
|
103
112
|
atMs,
|
|
104
113
|
stepIndex: Number.isInteger(stepIndex) && stepIndex >= 0 ? stepIndex : 0,
|
|
105
114
|
human,
|
|
106
|
-
machineReason: human ? null : OPEN_MACHINE_REASONS.includes(reason) ? reason : null
|
|
115
|
+
machineReason: human ? null : OPEN_MACHINE_REASONS.includes(reason) ? reason : null,
|
|
116
|
+
// Absent on every row from before AGL-3488, which recorded neither.
|
|
117
|
+
userAgent: typeof data['userAgent'] === 'string' && data['userAgent'] ? data['userAgent'] : null,
|
|
118
|
+
source: OUTREACH_OPEN_SOURCES.includes(data['source']) ? data['source'] : null
|
|
107
119
|
};
|
|
108
120
|
}
|
|
109
121
|
if (data['kind'] === 'action') {
|