@aglyn/plugins-outreach 1.0.0-beta.220 → 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/routes/enroll-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n containerMembershipField,\n contactContainerFieldPath,\n normalizeContainerIds,\n} from '@aglyn/aglyn/app-utils/container-membership'\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { scopeTokensForHost, seenOnlyThroughGrant } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n CRM_COLLECTIONS,\n crmLeadStatus,\n crmViewIsListed,\n isCrmLeadOpen,\n normalizeCrmViewFilters,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { dynamicListDimensionsForCrmView } from '@aglyn/aglyn/app-utils/dynamic-list-rule'\nimport type { PluginRecordTimelineWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport type { PluginTextGenerator } from '@aglyn/aglyn/plugin-manager/plugin-text-generation'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { restampCrmListFieldsAt } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { outreachCuratedEntry, outreachEnrolledEntry } from '../engine/enrollment-activity'\nimport {\n buildOutreachEnrollment,\n planOutreachFirstDue,\n readOutreachStartStepIndex,\n} from '../engine/enrollment-state'\nimport { outreachEnrollmentSearchTokens } from '../enrollment/enrollment-search'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport {\n decideOutreachEnrollment,\n previewOutreachPerson,\n readOutreachEnrollCandidates,\n type OutreachEnrollCandidate,\n type OutreachGateQuestion,\n} from '../enrollment/enroll-people'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport {\n outreachStepOverridesRefused,\n readOutreachStepOverrideRequests,\n type OutreachStepOverrideRead,\n} from '../enrollment/step-overrides'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_ENROLL_BATCH_MAX,\n type OutreachEnrollOutcome,\n type OutreachEnrollPreviewResponse,\n type OutreachEnrollResponse,\n type OutreachPersonRef,\n} from '../model/outreach-api'\nimport type { OutreachSequence, OutreachStepOverrides } from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { type OutreachDomainIntelReadInput, outreachMailboxSendingDomain } from '../storage/domain-intel-store'\nimport { fileOutreachNote } from '../runtime/timeline'\nimport {\n outreachEnrollmentId,\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_SEQUENCE_ACTIVITY_TARGET, type OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller, type OutreachRouteExtraPermission } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * ENROLLING PEOPLE IN A SEQUENCE (AGL-2980): `outreach/enroll/preview` and\n * `outreach/enroll`.\n *\n * The preview reads the people a saved Contacts view or a search named —\n * at most {@link OUTREACH_ENROLL_BATCH_MAX} — and says where each stands:\n * eligible, blocked with the gate's own sentence, or waiting on the rep for\n * a personal line and the attestations only they can make. Confirm reads\n * everything again and asks the gates again with what the rep supplied,\n * because a preview is a picture of a moment: someone can unsubscribe\n * between the two, and a request can claim anything. Nothing the preview\n * answered is trusted by the enroll.\n *\n * Both read the CRM's people, so both ask for `data.manage` beside\n * `outreach.use` — the permission the contacts' own rules read with, so\n * Outreach is no side door into the address book.\n *\n * Only an ACTIVE sequence takes people: enrolling schedules the first step\n * in the mailbox's hours, and a draft's steps and a paused sequence's timing\n * are not yet what will be sent.\n *\n * Confirm may name `startStepIndex` (AGL-3228) for people who already had\n * the earlier steps by hand: everyone in the request begins at that step,\n * scheduled by its own delay from now, and the steps before it are marked\n * skipped on their enrollments. Absent, it is the first step; a step the\n * sequence does not have refuses the whole request.\n */\n\n/** The permission enrolling reads the CRM with. */\nexport const OUTREACH_READS_PEOPLE: OutreachRouteExtraPermission = {\n key: 'data.manage',\n refusal: \"Enrolling reads your CRM's contacts, and your role does not include Manage data.\",\n}\n\n/** Everything enrolling reaches beyond the routes' own dependencies. */\nexport interface OutreachEnrollRouteDeps extends OutreachRouteDeps {\n /**\n * The addresses a saved Contacts view selects among one site's contacts,\n * read the way the dynamic-list sweep reads one, and whether the read\n * reached the whole view before its budget.\n */\n crmViewEmails(input: { hostId: string; viewId: string }): Promise<{ emails: string[]; complete: boolean }>\n /**\n * The workspace's record system on the timeline seam (AGL-3274), when a\n * plugin keeps one: the enroll files \"Enrolled in\" on the person's record\n * — the runtime's `timeline`, reached the same way.\n */\n timeline(): PluginRecordTimelineWriter | null\n /**\n * The workspace's text generator on the core's text-generation seam\n * (AGL-3324), which drafts one person's copies of the steps; `null` when\n * no plugin generates text, and the curate route says so.\n */\n textGenerator(): PluginTextGenerator | null\n}\n\nexport interface OutreachEnrollRoutes {\n preview: PluginWebApiHandler\n confirm: PluginWebApiHandler\n}\n\n/** The activity line an enroll writes. */\nexport function outreachEnrolledActivity(count: number): string {\n return count === 1\n ? 'Enrolled 1 person in a sequence'\n : `Enrolled ${count} people in a sequence`\n}\n\n/** Lookups for a person the gates will never be asked about: every one unchecked. */\nconst UNCHECKED: OutreachGateLookups = {\n platformSuppressed: null,\n hostSuppressed: null,\n salesTopicState: null,\n doNotContact: null,\n doNotContactDomain: null,\n workspaceMembers: null,\n openEnrollments: null,\n hasInboundEmail: null,\n gateway: null,\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */\nconst ALREADY_EXISTS = 6\n\nasync function loadActiveSequence(\n firestore: Firestore,\n orgId: string,\n rawSequenceId: unknown,\n): Promise<Response | OutreachSequence> {\n const sequenceId = readOutreachDocumentId(rawSequenceId)\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to enroll people in.')\n const snapshot = await outreachOrgCollection(firestore, orgId, 'sequences').doc(sequenceId).get()\n const sequence = readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n if (sequence.status === 'archived') {\n return outreachRefusal(409, 'sequence-archived', 'This sequence is archived and takes no one new.')\n }\n if (sequence.status !== 'active') {\n return outreachRefusal(409, 'sequence-not-active', 'Activate this sequence before enrolling people.')\n }\n return sequence\n}\n\n/** What every person in one request is judged against. */\ninterface EnrollContext {\n settings: OutreachGateQuestion['settings']\n contactGroupId: string\n /** The sequence site's consent group, whose opt-outs all apply. */\n consentHostIds: readonly string[]\n /** Whether that group's sites wait for each other's confirmation click. */\n consentAwaitsConfirmation: boolean\n siteName: string\n}\n\nasync function enrollContext(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n): Promise<EnrollContext> {\n const [orgSettings, host] = await Promise.all([\n readOutreachComplianceSettingsDoc(firestore, caller.orgId),\n firestore.collection('hosts').doc(sequence.hostId).get(),\n ])\n const consentGroup = consentGroupForHost(caller.org, sequence.hostId)\n return {\n // The organization's countries are a ceiling over the sequence's.\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n orgSettings.allowedCountries,\n ),\n },\n contactGroupId: consentGroup.groupId,\n consentHostIds: consentGroup.hostIds,\n consentAwaitsConfirmation: consentGroup.awaitsConfirmation,\n siteName: host.exists ? String(host.get('name') ?? '') : '',\n }\n}\n\n/**\n * The candidates, the enrollments they already have here, and the gates'\n * lookups — every map keyed by the person's own id.\n *\n * \"Already in this sequence\" is answered two ways (AGL-3234): by the id the\n * person's enrollment would have, and by any enrollment in this sequence\n * that carries the person's ADDRESS. The second is what keeps a contact\n * from being enrolled beside the lead they were converted from: the lead's\n * enrollment followed them, under the lead's key, and still names them.\n */\n/**\n * The domain the sequence's mailbox sends from (AGL-3328), whose gateway\n * ledger the Check-people chips read — or `null` when the mailbox cannot\n * be read, which shows the gateways without a history.\n */\nasync function sequenceSendingDomain(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n): Promise<string | null> {\n if (!sequence.mailboxId) return null\n try {\n const snapshot = await outreachOrgCollection(firestore, orgId, 'mailboxes').doc(sequence.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(sequence.mailboxId, snapshot?.exists ? snapshot.data() : undefined)\n return outreachMailboxSendingDomain(mailbox)\n } catch (error) {\n console.error('[outreach] the sequence mailbox could not be read for its sending domain', error)\n return null\n }\n}\n\nasync function readPeople(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n context: EnrollContext,\n people: readonly OutreachPersonRef[],\n gateway: OutreachDomainIntelReadInput,\n): Promise<{\n candidates: OutreachEnrollCandidate[]\n enrolledHere: Set<string>\n lookups: Map<string, OutreachGateLookups>\n}> {\n const candidates = await readOutreachEnrollCandidates(firestore, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n contactGroupId: context.contactGroupId,\n people,\n })\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n const existing = candidates.length\n ? await firestore.getAll(\n ...candidates.map((candidate) => enrollments.doc(outreachEnrollmentId(sequence.id, candidate.personId))),\n )\n : []\n const enrolledHere = new Set(\n candidates.filter((_candidate, index) => existing[index]?.exists).map((candidate) => candidate.personId),\n )\n const askable = candidates.filter((candidate) => candidate.contact && candidate.visible && candidate.email)\n const lookups = askable.length\n ? await readOutreachGateLookups(firestore, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n consentHostIds: context.consentHostIds,\n consentAwaitsConfirmation: context.consentAwaitsConfirmation,\n gateway,\n people: askable.map((candidate) => ({\n personId: candidate.personId,\n contactId: candidate.contactId || null,\n leadId: candidate.leadId,\n email: String(candidate.email),\n })),\n })\n : new Map<string, OutreachGateLookups>()\n for (const candidate of askable) {\n const open = lookups.get(candidate.personId)?.openEnrollments ?? []\n if (open.some((entry) => entry.sequenceId === sequence.id)) enrolledHere.add(candidate.personId)\n }\n return { candidates, enrolledHere, lookups }\n}\n\nconst uniqueIds = (values: unknown): string[] =>\n Array.isArray(values)\n ? [...new Set(values.map(readOutreachDocumentId).filter((id): id is string => id !== null))]\n : []\n\n/** The most leads a saved Leads view reads — the Leads list's own window. */\nconst LEADS_VIEW_WINDOW = 200\n\n/**\n * The people a saved LEADS view selects (AGL-3234): the sequence's site's\n * most recently seen leads, narrowed by the view's status clause the way\n * the Leads list narrows its window — open leads when the view names no\n * status, one status when it does, everything for `all`. The person key IS\n * the id, so there is no address to resolve — and since AGL-3275 the window is\n * narrowed by `visibleTo` rather than by the collection's parent.\n */\nasync function leadsViewPeople(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n filters: ReturnType<typeof normalizeCrmViewFilters>,\n): Promise<{ people: OutreachPersonRef[]; total: number; truncated: boolean }> {\n const statusClause = filters.find((clause) => clause.field === 'status' && clause.op === 'equals')\n const wanted = String(statusClause?.value ?? 'open')\n /*\n * SCOPED (AGL-3275). The collection is org-wide, so the window is narrowed\n * to what the sequence's site may see before it is ordered — otherwise an\n * agency's sequence would offer another client's people to enroll. The\n * composite index for `visibleTo array-contains-any` + `lastSeenAtMs desc`\n * is in `cloud/firestore.indexes.json`.\n */\n const window = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('leads')\n .where('visibleTo', 'array-contains-any', scopeTokensForHost(sequence.hostId))\n .orderBy('lastSeenAtMs', 'desc')\n .limit(LEADS_VIEW_WINDOW + 1)\n .get()\n const matching = window.docs.slice(0, LEADS_VIEW_WINDOW).filter((doc) => {\n const lead = doc.data() as Record<string, unknown>\n // Held, not merely seen: a lead shared with this site (AGL-3336) is not\n // its to sequence.\n if (seenOnlyThroughGrant(lead, sequence.hostId)) return false\n if (wanted === 'all') return true\n if (wanted === 'open') return isCrmLeadOpen(lead as never) && !lead['convertedContactId']\n return crmLeadStatus(lead as never) === wanted\n })\n return {\n people: matching.slice(0, OUTREACH_ENROLL_BATCH_MAX).map((doc) => ({ kind: 'lead', id: doc.id })),\n total: matching.length,\n truncated: matching.length > OUTREACH_ENROLL_BATCH_MAX || window.docs.length > LEADS_VIEW_WINDOW,\n }\n}\n\nexport function createOutreachEnrollRoutes(deps: OutreachEnrollRouteDeps): OutreachEnrollRoutes {\n /**\n * The person joins the sequence's campaigns (AGL-3254), the moment they\n * are enrolled: `arrayUnion` on the lead's own `campaignIds`, or on the\n * contact's facet for the sequence's site — the same field, the same\n * shape, every other campaign member carries — and `enrolled` credited\n * to each campaign. After the enrollment is created and never before:\n * a person the create refused joins nothing. Neither write may fail the\n * enrollment, which already exists; a membership that could not be\n * stamped is one the list's bulk bar can add by hand.\n */\n async function joinSequenceCampaigns(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n contactGroupId: string,\n candidate: OutreachEnrollCandidate,\n nowMs: number,\n ): Promise<void> {\n const campaignIds = normalizeContainerIds(sequence.campaignIds)\n if (!campaignIds.length) return\n try {\n const ref =\n candidate.target === 'lead' && candidate.leadId\n ? firestore.collection('orgs').doc(orgId).collection('leads').doc(candidate.leadId)\n : candidate.contactId\n ? firestore.collection('orgs').doc(orgId).collection('contacts').doc(candidate.contactId)\n : null\n if (ref) {\n const field =\n candidate.target === 'lead' ? containerMembershipField('campaign') : contactContainerFieldPath(contactGroupId, 'campaign')\n await ref.update({ [field]: FieldValue.arrayUnion(...campaignIds), updatedAt: FieldValue.serverTimestamp() })\n // A lead's campaigns are what the Leads list's Campaign filter reads\n // under a site (AGL-3321): restamped from the lead as it now stands.\n if (candidate.target === 'lead') await restampCrmListFieldsAt(ref, 'leads')\n }\n } catch (error) {\n console.error('[outreach] the enrolled person could not join the sequence’s campaigns', error)\n }\n try {\n await deps.creditCampaign({ hostId: sequence.hostId, orgId, campaignIds, outcome: 'enrolled', atMs: nowMs })\n } catch (error) {\n console.error('[outreach] the enrollment could not be credited to the sequence’s campaigns', error)\n }\n }\n\n /**\n * The names of the sequence's campaigns as they stand, for the entry the\n * enroll files on the person's record (AGL-3274) — the org's containers of\n * the `campaign` kind. Read once per request, not per person; a container\n * that is gone answers nothing and the entry names the rest.\n */\n async function sequenceCampaignNames(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n ): Promise<string[]> {\n const campaignIds = normalizeContainerIds(sequence.campaignIds)\n if (!campaignIds.length || !orgId) return []\n try {\n const found = await readOrgContainers(firestore, 'campaign', orgId, campaignIds)\n return found.map((container) => container.name).filter(Boolean)\n } catch (error) {\n console.error('[outreach] the sequence’s campaigns could not be named for the record', error)\n return []\n }\n }\n\n /**\n * The people a source names, the batch limit applied: every contact a\n * search picked, every lead picked from the sequence's site, or the\n * people a saved Contacts or Leads view selects there — contacts found by\n * address, leads by their own key.\n */\n async function sourcePeople(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n source: Record<string, unknown>,\n ): Promise<Response | { people: OutreachPersonRef[]; total: number; truncated: boolean }> {\n if (source['kind'] === 'contacts' || source['kind'] === 'leads') {\n const kind = source['kind'] === 'leads' ? 'lead' : 'contact'\n const ids = uniqueIds(kind === 'lead' ? source['leadIds'] : source['contactIds'])\n if (!ids.length) return outreachRefusal(400, 'invalid-request', 'Pick the people to enroll.')\n return {\n people: ids.slice(0, OUTREACH_ENROLL_BATCH_MAX).map((id) => ({ kind, id })),\n total: ids.length,\n truncated: ids.length > OUTREACH_ENROLL_BATCH_MAX,\n }\n }\n if (source['kind'] !== 'view') {\n return outreachRefusal(400, 'invalid-request', 'Enroll people from a saved view or a search.')\n }\n const viewId = readOutreachDocumentId(source['viewId'])\n const view = viewId\n ? await firestore.collection('orgs').doc(caller.orgId).collection(CRM_COLLECTIONS.views).doc(viewId).get()\n : null\n const data = view?.exists ? (view.data() as Record<string, unknown>) : null\n // A colleague's private view is theirs: it is not listed for this\n // reader, so it does not exist for them here either.\n if (\n !viewId ||\n !data ||\n !crmViewIsListed({ shared: data['shared'] === true, ownerUid: String(data['ownerUid'] ?? '') }, caller.uid)\n ) {\n return outreachRefusal(404, 'view-not-found', 'That saved view no longer exists.')\n }\n if (data['section'] === 'leads') {\n return leadsViewPeople(firestore, caller.orgId, sequence, normalizeCrmViewFilters(data['filters']))\n }\n if (data['section'] !== 'contacts') {\n return outreachRefusal(400, 'view-unsupported', 'Enroll from a saved view of Contacts or Leads.')\n }\n const { unsupported } = dynamicListDimensionsForCrmView(normalizeCrmViewFilters(data['filters']))\n if (unsupported.length) {\n // Dropping the filter enrolling cannot read would enroll more people\n // than the view shows, so the view is refused whole.\n return outreachRefusal(\n 400,\n 'view-unsupported',\n `This view filters on ${unsupported.map((clause) => clause.label || clause.field).join(', ')}, which enrolling can't apply. Pick another view, or search.`,\n )\n }\n const { emails, complete } = await deps.crmViewEmails({ hostId: sequence.hostId, viewId })\n const ordered = [...new Set(emails)].sort()\n const contacts = firestore.collection('orgs').doc(caller.orgId).collection('contacts')\n const found = await Promise.all(\n ordered\n .slice(0, OUTREACH_ENROLL_BATCH_MAX)\n .map((email) => findContactByEmail(contacts, email, { hostId: sequence.hostId })),\n )\n return {\n people: [...new Set(found.filter((snapshot) => snapshot).map((snapshot) => String(snapshot?.id)))].map(\n (id) => ({ kind: 'contact', id }),\n ),\n total: ordered.length,\n truncated: ordered.length > OUTREACH_ENROLL_BATCH_MAX || !complete,\n }\n }\n\n const preview: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate, [OUTREACH_READS_PEOPLE])\n if (caller instanceof Response) return caller\n const firestore = deps.firestore()\n const sequence = await loadActiveSequence(firestore, caller.orgId, body['sequenceId'])\n if (sequence instanceof Response) return sequence\n const source = body['source'] && typeof body['source'] === 'object' ? (body['source'] as Record<string, unknown>) : {}\n const named = await sourcePeople(firestore, caller, sequence, source)\n if (named instanceof Response) return named\n const context = await enrollContext(firestore, caller, sequence)\n const { candidates, enrolledHere, lookups } = await readPeople(\n firestore,\n caller,\n sequence,\n context,\n named.people,\n {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs: deps.now(),\n sendingDomain: await sequenceSendingDomain(firestore, caller.orgId, sequence),\n },\n )\n const people = candidates.map((candidate) =>\n previewOutreachPerson(\n {\n candidate,\n lookups: lookups.get(candidate.personId) ?? UNCHECKED,\n settings: context.settings,\n contactGroupId: context.contactGroupId,\n },\n { siteName: context.siteName, alreadyInSequence: enrolledHere.has(candidate.personId) },\n ),\n )\n return outreachOk({\n ok: true,\n people,\n total: named.total,\n truncated: named.truncated,\n } satisfies OutreachEnrollPreviewResponse)\n }\n\n const confirm: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate, [OUTREACH_READS_PEOPLE])\n if (caller instanceof Response) return caller\n const firestore = deps.firestore()\n const sequence = await loadActiveSequence(firestore, caller.orgId, body['sequenceId'])\n if (sequence instanceof Response) return sequence\n\n const nowMs = deps.now()\n const start = readOutreachStartStepIndex(body['startStepIndex'], sequence.steps)\n if (start.refusal !== null) return outreachRefusal(400, 'invalid-start-step', start.refusal)\n const startStepIndex = start.startStepIndex\n // Each person once, by whichever record they are: a contact by id, or a\n // lead by its key (AGL-3234). A person named both ways is a contact.\n const requested = new Map<\n string,\n { ref: OutreachPersonRef; personalLine: string; attestations: unknown[]; overrides: OutreachStepOverrideRead }\n >()\n for (const entry of Array.isArray(body['people']) ? body['people'] : []) {\n const person = (entry && typeof entry === 'object' ? entry : {}) as Record<string, unknown>\n const contactId = readOutreachDocumentId(person['contactId'])\n const leadId = readOutreachDocumentId(person['leadId'])\n const ref: OutreachPersonRef | null = contactId\n ? { kind: 'contact', id: contactId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : null\n if (!ref || requested.has(ref.id)) continue\n // The steps the member curated for this person (AGL-3324), validated\n // here rather than trusted: a copy that breaks a rule refuses the\n // whole request, so nobody is enrolled with a copy the route dropped.\n const overrides = readOutreachStepOverrideRequests(\n person['stepOverrides'],\n sequence.steps,\n { uid: caller.uid, nowMs },\n startStepIndex,\n )\n if (outreachStepOverridesRefused(overrides)) {\n return outreachRefusal(\n 400,\n 'invalid-override',\n overrides.refusal ?? 'A curated step breaks a rule every sequence email keeps.',\n { issues: overrides.issues },\n )\n }\n requested.set(ref.id, {\n ref,\n personalLine: typeof person['personalLine'] === 'string' ? person['personalLine'] : '',\n attestations: Array.isArray(person['attestations']) ? person['attestations'] : [],\n overrides,\n })\n }\n if (!requested.size) return outreachRefusal(400, 'invalid-request', 'Pick the people to enroll.')\n if (requested.size > OUTREACH_ENROLL_BATCH_MAX) {\n return outreachRefusal(\n 400,\n 'invalid-request',\n `Enroll at most ${OUTREACH_ENROLL_BATCH_MAX} people at a time.`,\n )\n }\n\n const mailboxSnapshot = sequence.mailboxId\n ? await outreachOrgCollection(firestore, caller.orgId, 'mailboxes').doc(sequence.mailboxId).get()\n : null\n const mailbox = readStoredOutreachMailbox(\n sequence.mailboxId,\n mailboxSnapshot?.exists ? mailboxSnapshot.data() : undefined,\n )\n if (!mailbox || mailbox.status === 'disconnected') {\n return outreachRefusal(\n 409,\n 'mailbox-unavailable',\n \"This sequence's mailbox is no longer connected. Choose another mailbox for it before enrolling people.\",\n )\n }\n if (planOutreachFirstDue({ sequence, mailbox, enrolledAtMs: nowMs, random: deps.random, startStepIndex }) === null) {\n return outreachRefusal(\n 409,\n 'mailbox-unavailable',\n \"This sequence's sending hours never open in its mailbox's timezone. Fix the hours before enrolling people.\",\n )\n }\n\n const context = await enrollContext(firestore, caller, sequence)\n const { candidates, enrolledHere, lookups } = await readPeople(\n firestore,\n caller,\n sequence,\n context,\n [...requested.values()].map((entry) => entry.ref),\n {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n },\n )\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n const campaignNames = await sequenceCampaignNames(firestore, caller.orgId, sequence)\n // The member's name for the curated entries (AGL-3324), read once per\n // request and only when a person carries a curated step.\n let memberNameRead: Promise<string | null> | null = null\n const memberName = () => {\n memberNameRead ??= firestore\n .collection('orgs')\n .doc(caller.orgId)\n .collection('members')\n .doc(caller.uid)\n .get()\n .then(\n (member) =>\n (member.exists\n ? String(member.get('displayName') ?? '').trim() || String(member.get('email') ?? '').trim()\n : '') || caller.email,\n )\n .catch(() => caller.email)\n return memberNameRead\n }\n const results: OutreachEnrollOutcome[] = await Promise.all(\n candidates.map(async (candidate): Promise<OutreachEnrollOutcome> => {\n const named = {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n const supplied = requested.get(candidate.personId) ?? {\n personalLine: '',\n attestations: [],\n overrides: { overrides: {}, issues: [], refusal: null } satisfies OutreachStepOverrideRead,\n }\n const stepOverrides: OutreachStepOverrides = supplied.overrides.overrides\n const decision = decideOutreachEnrollment(\n {\n candidate,\n lookups: lookups.get(candidate.personId) ?? UNCHECKED,\n settings: context.settings,\n contactGroupId: context.contactGroupId,\n },\n { siteName: context.siteName, alreadyInSequence: enrolledHere.has(candidate.personId) },\n { personalLine: supplied.personalLine, attestations: supplied.attestations, uid: caller.uid, nowMs },\n )\n if (!decision.allowed || !decision.email) {\n return { ...named, email: candidate.email, outcome: 'blocked', blocks: decision.blocks }\n }\n const id = outreachEnrollmentId(sequence.id, candidate.personId)\n const enrollment = buildOutreachEnrollment({\n id,\n sequence,\n mailbox,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n contactName: candidate.name,\n email: decision.email,\n cold: decision.cold,\n personalLine: supplied.personalLine,\n attestations: decision.attestations,\n enrolledByUid: caller.uid,\n nowMs,\n random: deps.random,\n startStepIndex,\n })\n // The member ticked this person past the red gateway chip\n // (AGL-3326): that is their say-so, stamped as the hold's release,\n // so the engine does not hold the send they were just shown.\n if (decision.hold) {\n enrollment.gatewayHold = {\n gateway: decision.hold.gateway,\n heldAtMs: null,\n releasedByUid: caller.uid,\n releasedAtMs: nowMs,\n }\n }\n // The person's own copies of steps (AGL-3324) ride with the\n // enrollment from its first write: nothing sends between.\n if (Object.keys(stepOverrides).length) enrollment.stepOverrides = stepOverrides\n // What the enrollments table searches the person by (AGL-3321),\n // from the name and address this document captures for good.\n enrollment.searchTokens = outreachEnrollmentSearchTokens(enrollment)\n // Nobody has clicked yet (AGL-3332): stored, because the \"Clicked: No\"\n // filter is a query, and a query cannot find a field's absence.\n enrollment.clicked = false\n try {\n await enrollments.doc(id).create(enrollment)\n } catch (error) {\n if ((error as { code?: unknown })?.code !== ALREADY_EXISTS) throw error\n return {\n ...named,\n email: candidate.email,\n outcome: 'blocked',\n blocks: [\n {\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 }\n }\n await joinSequenceCampaigns(firestore, caller.orgId, sequence, context.contactGroupId, candidate, nowMs)\n // The person's record says so (AGL-3274): \"Enrolled in <sequence>\",\n // with the campaigns it carried them into, once per enrollment.\n const entry = outreachEnrolledEntry({\n enrollmentId: id,\n sequenceName: sequence.name,\n campaignNames,\n startStepIndex,\n })\n await fileOutreachNote(deps, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: entry.dedupeKey,\n body: entry.body,\n atMs: nowMs,\n })\n // And one line per step the member curated for them (AGL-3324),\n // after the enrollment's own, so the record reads in order.\n for (const [key, override] of Object.entries(stepOverrides)) {\n const curated = outreachCuratedEntry({\n enrollmentId: id,\n stepIndex: Number(key),\n source: override.source,\n edited: override.edited === true,\n memberName: await memberName(),\n atMs: nowMs,\n })\n await fileOutreachNote(deps, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: curated.dedupeKey,\n body: curated.body,\n atMs: nowMs,\n })\n }\n return { ...named, email: decision.email, outcome: 'enrolled', enrollmentId: id }\n }),\n )\n const enrolled = results.filter((result) => result.outcome === 'enrolled').length\n if (enrolled) {\n await deps.logOrgActivity(\n caller.orgId,\n { uid: caller.uid, email: caller.email },\n outreachEnrolledActivity(enrolled),\n { type: OUTREACH_SEQUENCE_ACTIVITY_TARGET, id: sequence.id, name: sequence.name },\n )\n }\n return outreachOk({ ok: true, results, enrolled } satisfies OutreachEnrollResponse)\n }\n\n return { preview, confirm }\n}\n"],"names":["containerMembershipField","contactContainerFieldPath","normalizeContainerIds","consentGroupForHost","scopeTokensForHost","seenOnlyThroughGrant","CRM_COLLECTIONS","crmLeadStatus","crmViewIsListed","isCrmLeadOpen","normalizeCrmViewFilters","dynamicListDimensionsForCrmView","findContactByEmail","readOrgContainers","restampCrmListFieldsAt","FieldValue","outreachCuratedEntry","outreachEnrolledEntry","buildOutreachEnrollment","planOutreachFirstDue","readOutreachStartStepIndex","outreachEnrollmentSearchTokens","decideOutreachEnrollment","previewOutreachPerson","readOutreachEnrollCandidates","readOutreachGateLookups","outreachStepOverridesRefused","readOutreachStepOverrideRequests","effectiveOutreachAllowedCountries","OUTREACH_ENROLL_BATCH_MAX","readOutreachComplianceSettingsDoc","outreachMailboxSendingDomain","fileOutreachNote","outreachEnrollmentId","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_SEQUENCE_ACTIVITY_TARGET","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","OUTREACH_READS_PEOPLE","key","refusal","outreachEnrolledActivity","count","UNCHECKED","platformSuppressed","hostSuppressed","salesTopicState","doNotContact","doNotContactDomain","workspaceMembers","openEnrollments","hasInboundEmail","gateway","ALREADY_EXISTS","loadActiveSequence","firestore","orgId","rawSequenceId","sequenceId","snapshot","doc","get","sequence","exists","data","undefined","status","enrollContext","caller","host","orgSettings","Promise","all","collection","hostId","consentGroup","org","settings","allowedCountries","contactGroupId","groupId","consentHostIds","hostIds","consentAwaitsConfirmation","awaitsConfirmation","siteName","String","sequenceSendingDomain","mailboxId","mailbox","error","console","readPeople","context","people","candidates","enrollments","existing","length","getAll","map","candidate","id","personId","enrolledHere","Set","filter","_candidate","index","askable","contact","visible","email","lookups","contactId","leadId","Map","open","some","entry","add","uniqueIds","values","Array","isArray","LEADS_VIEW_WINDOW","leadsViewPeople","filters","statusClause","find","clause","field","op","wanted","value","window","where","orderBy","limit","matching","docs","slice","lead","kind","total","truncated","createOutreachEnrollRoutes","deps","joinSequenceCampaigns","nowMs","campaignIds","ref","target","update","arrayUnion","updatedAt","serverTimestamp","creditCampaign","outcome","atMs","sequenceCampaignNames","found","container","name","Boolean","sourcePeople","source","ids","viewId","view","views","shared","ownerUid","uid","unsupported","label","join","emails","complete","crmViewEmails","ordered","sort","contacts","preview","request","method","body","gate","Response","named","resolveMx","resolveAddress","now","sendingDomain","alreadyInSequence","has","ok","confirm","start","steps","startStepIndex","requested","person","overrides","issues","set","personalLine","attestations","size","mailboxSnapshot","enrolledAtMs","random","campaignNames","memberNameRead","memberName","then","member","trim","catch","results","supplied","stepOverrides","decision","allowed","blocks","enrollment","contactName","cold","enrolledByUid","hold","gatewayHold","heldAtMs","releasedByUid","releasedAtMs","Object","keys","searchTokens","clicked","create","code","reason","enrollmentId","sequenceName","link","dedupeKey","override","entries","curated","stepIndex","Number","edited","enrolled","result","logOrgActivity","type"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,yBAAyB,EACzBC,qBAAqB,QAChB,8CAA6C;AACpD,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,sCAAqC;AAC9F,SACEC,eAAe,EACfC,aAAa,EACbC,eAAe,EACfC,aAAa,EACbC,uBAAuB,QAClB,6BAA4B;AACnC,SAASC,+BAA+B,QAAQ,2CAA0C;AAI1F,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,mCAA+B;AAC3F,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,0BAA0B,QACrB,gCAA4B;AACnC,SAASC,8BAA8B,QAAQ,qCAAiC;AAEhF,SACEC,wBAAwB,EACxBC,qBAAqB,EACrBC,4BAA4B,QAGvB,iCAA6B;AACpC,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SACEC,4BAA4B,EAC5BC,gCAAgC,QAE3B,kCAA8B;AACrC,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SACEC,yBAAyB,QAKpB,2BAAuB;AAE9B,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SAA4CC,4BAA4B,QAAQ,mCAA+B;AAC/G,SAASC,gBAAgB,QAAQ,yBAAqB;AACtD,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,qBAAqB,EACrBC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,iCAAiC,QAAgC,kBAAc;AACxF,SAASC,iBAAiB,QAAqE,kBAA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AAY,MAAMA;oBAClBvD,MAAMV;gBACR;gBACA,MAAM5H,iBAAiB0H,MAAM;oBAC3B3F,OAAOY,OAAOZ,KAAK;oBACnBkB,QAAQZ,SAASY,MAAM;oBACvByK,MAAMxN,uBAAuBsM;oBAC7BmB,WAAWG,QAAQH,SAAS;oBAC5B1D,MAAM6D,QAAQ7D,IAAI;oBAClB3B,MAAMV;gBACR;YACF;YACA,OAAO,aAAKwC;gBAAO7E,OAAO8G,SAAS9G,KAAK;gBAAE8C,SAAS;gBAAYmF,cAAc3I;;QAC/E;QAEF,MAAMqJ,WAAWhC,QAAQjH,MAAM,CAAC,CAACkJ,SAAWA,OAAO9F,OAAO,KAAK,YAAY5D,MAAM;QACjF,IAAIyJ,UAAU;YACZ,MAAMxG,KAAK0G,cAAc,CACvBzL,OAAOZ,KAAK,EACZ;gBAAEqH,KAAKzG,OAAOyG,GAAG;gBAAE7D,OAAO5C,OAAO4C,KAAK;YAAC,GACvCvE,yBAAyBkN,WACzB;gBAAEG,MAAM/N;gBAAmCuE,IAAIxC,SAASwC,EAAE;gBAAE6D,MAAMrG,SAASqG,IAAI;YAAC;QAEpF;QACA,OAAOjI,WAAW;YAAEkK,IAAI;YAAMuB;YAASgC;QAAS;IAClD;IAEA,OAAO;QAAEpE;QAASc;IAAQ;AAC5B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/enroll-routes.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 { stampRecordOrigin } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport { normalizeContainerIds } from '@aglyn/aglyn/app-utils/container-membership'\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport {\n filePluginPersonUnder,\n pluginPeopleInView,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport type { PluginRecordTimelineWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport type { PluginTextGenerator } from '@aglyn/aglyn/plugin-manager/plugin-text-generation'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { outreachCuratedEntry, outreachEnrolledEntry } from '../engine/enrollment-activity'\nimport {\n buildOutreachEnrollment,\n planOutreachFirstDue,\n readOutreachStartStepIndex,\n} from '../engine/enrollment-state'\nimport { outreachEnrollmentSearchTokens } from '../enrollment/enrollment-search'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport {\n decideOutreachEnrollment,\n previewOutreachPerson,\n readOutreachEnrollCandidates,\n type OutreachEnrollCandidate,\n type OutreachGateQuestion,\n} from '../enrollment/enroll-people'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport {\n outreachStepOverridesRefused,\n readOutreachStepOverrideRequests,\n type OutreachStepOverrideRead,\n} from '../enrollment/step-overrides'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_ENROLL_BATCH_MAX,\n type OutreachEnrollOutcome,\n type OutreachEnrollPreviewResponse,\n type OutreachEnrollResponse,\n type OutreachPersonRef,\n} from '../model/outreach-api'\nimport type { OutreachSequence, OutreachStepOverrides } from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { type OutreachDomainIntelReadInput, outreachMailboxSendingDomain } from '../storage/domain-intel-store'\nimport { fileOutreachNote } from '../runtime/timeline'\nimport {\n outreachEnrollmentId,\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_SEQUENCE_ACTIVITY_TARGET, type OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller, type OutreachRouteExtraPermission } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * ENROLLING PEOPLE IN A SEQUENCE (AGL-2980): `outreach/enroll/preview` and\n * `outreach/enroll`.\n *\n * The preview reads the people a saved Contacts view or a search named —\n * at most {@link OUTREACH_ENROLL_BATCH_MAX} — and says where each stands:\n * eligible, blocked with the gate's own sentence, or waiting on the rep for\n * a personal line and the attestations only they can make. Confirm reads\n * everything again and asks the gates again with what the rep supplied,\n * because a preview is a picture of a moment: someone can unsubscribe\n * between the two, and a request can claim anything. Nothing the preview\n * answered is trusted by the enroll.\n *\n * Both read the CRM's people, so both ask for `data.manage` beside\n * `outreach.use` — the permission the contacts' own rules read with, so\n * Outreach is no side door into the address book.\n *\n * Only an ACTIVE sequence takes people: enrolling schedules the first step\n * in the mailbox's hours, and a draft's steps and a paused sequence's timing\n * are not yet what will be sent.\n *\n * Confirm may name `startStepIndex` (AGL-3228) for people who already had\n * the earlier steps by hand: everyone in the request begins at that step,\n * scheduled by its own delay from now, and the steps before it are marked\n * skipped on their enrollments. Absent, it is the first step; a step the\n * sequence does not have refuses the whole request.\n */\n\n/** The permission enrolling reads the CRM with. */\nexport const OUTREACH_READS_PEOPLE: OutreachRouteExtraPermission = {\n key: 'data.manage',\n refusal: \"Enrolling reads your CRM's contacts, and your role does not include Manage data.\",\n}\n\n/** Everything enrolling reaches beyond the routes' own dependencies. */\nexport interface OutreachEnrollRouteDeps extends OutreachRouteDeps {\n /**\n * The workspace's record system on the timeline seam (AGL-3274), when a\n * plugin keeps one: the enroll files \"Enrolled in\" on the person's record\n * — the runtime's `timeline`, reached the same way.\n */\n timeline(): PluginRecordTimelineWriter | null\n /**\n * The workspace's text generator on the core's text-generation seam\n * (AGL-3324), which drafts one person's copies of the steps; `null` when\n * no plugin generates text, and the curate route says so.\n */\n textGenerator(): PluginTextGenerator | null\n}\n\nexport interface OutreachEnrollRoutes {\n preview: PluginWebApiHandler\n confirm: PluginWebApiHandler\n}\n\n/** The activity line an enroll writes. */\nexport function outreachEnrolledActivity(count: number): string {\n return count === 1\n ? 'Enrolled 1 person in a sequence'\n : `Enrolled ${count} people in a sequence`\n}\n\n/** Lookups for a person the gates will never be asked about: every one unchecked. */\nconst UNCHECKED: OutreachGateLookups = {\n platformSuppressed: null,\n hostSuppressed: null,\n salesTopicState: null,\n doNotContact: null,\n doNotContactDomain: null,\n workspaceMembers: null,\n openEnrollments: null,\n hasInboundEmail: null,\n gateway: null,\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */\nconst ALREADY_EXISTS = 6\n\nasync function loadActiveSequence(\n firestore: Firestore,\n orgId: string,\n rawSequenceId: unknown,\n): Promise<Response | OutreachSequence> {\n const sequenceId = readOutreachDocumentId(rawSequenceId)\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to enroll people in.')\n const snapshot = await outreachOrgCollection(firestore, orgId, 'sequences').doc(sequenceId).get()\n const sequence = readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n if (sequence.status === 'archived') {\n return outreachRefusal(409, 'sequence-archived', 'This sequence is archived and takes no one new.')\n }\n if (sequence.status !== 'active') {\n return outreachRefusal(409, 'sequence-not-active', 'Activate this sequence before enrolling people.')\n }\n return sequence\n}\n\n/** What every person in one request is judged against. */\ninterface EnrollContext {\n settings: OutreachGateQuestion['settings']\n contactGroupId: string\n /** The sequence site's consent group, whose opt-outs all apply. */\n consentHostIds: readonly string[]\n /** Whether that group's sites wait for each other's confirmation click. */\n consentAwaitsConfirmation: boolean\n siteName: string\n}\n\nasync function enrollContext(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n): Promise<EnrollContext> {\n const [orgSettings, host] = await Promise.all([\n readOutreachComplianceSettingsDoc(firestore, caller.orgId),\n firestore.collection('hosts').doc(sequence.hostId).get(),\n ])\n const consentGroup = consentGroupForHost(caller.org, sequence.hostId)\n return {\n // The organization's countries are a ceiling over the sequence's.\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n orgSettings.allowedCountries,\n ),\n },\n contactGroupId: consentGroup.groupId,\n consentHostIds: consentGroup.hostIds,\n consentAwaitsConfirmation: consentGroup.awaitsConfirmation,\n siteName: host.exists ? String(host.get('name') ?? '') : '',\n }\n}\n\n/**\n * The candidates, the enrollments they already have here, and the gates'\n * lookups — every map keyed by the person's own id.\n *\n * \"Already in this sequence\" is answered two ways (AGL-3234): by the id the\n * person's enrollment would have, and by any enrollment in this sequence\n * that carries the person's ADDRESS. The second is what keeps a contact\n * from being enrolled beside the lead they were converted from: the lead's\n * enrollment followed them, under the lead's key, and still names them.\n */\n/**\n * The domain the sequence's mailbox sends from (AGL-3328), whose gateway\n * ledger the Check-people chips read — or `null` when the mailbox cannot\n * be read, which shows the gateways without a history.\n */\nasync function sequenceSendingDomain(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n): Promise<string | null> {\n if (!sequence.mailboxId) return null\n try {\n const snapshot = await outreachOrgCollection(firestore, orgId, 'mailboxes').doc(sequence.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(sequence.mailboxId, snapshot?.exists ? snapshot.data() : undefined)\n return outreachMailboxSendingDomain(mailbox)\n } catch (error) {\n console.error('[outreach] the sequence mailbox could not be read for its sending domain', error)\n return null\n }\n}\n\nasync function readPeople(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n context: EnrollContext,\n people: readonly OutreachPersonRef[],\n gateway: OutreachDomainIntelReadInput,\n): Promise<{\n candidates: OutreachEnrollCandidate[]\n enrolledHere: Set<string>\n lookups: Map<string, OutreachGateLookups>\n}> {\n const candidates = await readOutreachEnrollCandidates({\n orgId: caller.orgId,\n hostId: sequence.hostId,\n contactGroupId: context.contactGroupId,\n people,\n })\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n const existing = candidates.length\n ? await firestore.getAll(\n ...candidates.map((candidate) => enrollments.doc(outreachEnrollmentId(sequence.id, candidate.personId))),\n )\n : []\n const enrolledHere = new Set(\n candidates.filter((_candidate, index) => existing[index]?.exists).map((candidate) => candidate.personId),\n )\n const askable = candidates.filter((candidate) => candidate.contact && candidate.visible && candidate.email)\n const lookups = askable.length\n ? await readOutreachGateLookups(firestore, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n consentHostIds: context.consentHostIds,\n consentAwaitsConfirmation: context.consentAwaitsConfirmation,\n gateway,\n people: askable.map((candidate) => ({\n personId: candidate.personId,\n contactId: candidate.contactId || null,\n leadId: candidate.leadId,\n email: String(candidate.email),\n })),\n })\n : new Map<string, OutreachGateLookups>()\n for (const candidate of askable) {\n const open = lookups.get(candidate.personId)?.openEnrollments ?? []\n if (open.some((entry) => entry.sequenceId === sequence.id)) enrolledHere.add(candidate.personId)\n }\n return { candidates, enrolledHere, lookups }\n}\n\nconst uniqueIds = (values: unknown): string[] =>\n Array.isArray(values)\n ? [...new Set(values.map(readOutreachDocumentId).filter((id): id is string => id !== null))]\n : []\n\nexport function createOutreachEnrollRoutes(deps: OutreachEnrollRouteDeps): OutreachEnrollRoutes {\n /**\n * The person joins the sequence's campaigns (AGL-3254), the moment they\n * are enrolled: `arrayUnion` on the lead's own `campaignIds`, or on the\n * contact's facet for the sequence's site — the same field, the same\n * shape, every other campaign member carries — and `enrolled` credited\n * to each campaign. After the enrollment is created and never before:\n * a person the create refused joins nothing. Neither write may fail the\n * enrollment, which already exists; a membership that could not be\n * stamped is one the list's bulk bar can add by hand.\n */\n async function joinSequenceCampaigns(\n orgId: string,\n sequence: OutreachSequence,\n candidate: OutreachEnrollCandidate,\n nowMs: number,\n ): Promise<void> {\n const campaignIds = normalizeContainerIds(sequence.campaignIds)\n if (!campaignIds.length) return\n try {\n const id = candidate.target === 'lead' ? candidate.leadId : candidate.contactId\n if (id) {\n // Filed by the plugin that keeps people (AGL-3080), as the sequence's\n // site holds the person: on a lead its own field, on a contact the\n // site's facet — the field every other campaign member carries.\n await filePluginPersonUnder({\n hostId: sequence.hostId,\n orgId,\n record: { kind: candidate.target, id },\n containerKind: 'campaign',\n ids: campaignIds,\n })\n }\n } catch (error) {\n console.error('[outreach] the enrolled person could not join the sequence’s campaigns', error)\n }\n try {\n await deps.creditCampaign({ hostId: sequence.hostId, orgId, campaignIds, outcome: 'enrolled', atMs: nowMs })\n } catch (error) {\n console.error('[outreach] the enrollment could not be credited to the sequence’s campaigns', error)\n }\n }\n\n /**\n * The names of the sequence's campaigns as they stand, for the entry the\n * enroll files on the person's record (AGL-3274) — the org's containers of\n * the `campaign` kind. Read once per request, not per person; a container\n * that is gone answers nothing and the entry names the rest.\n */\n async function sequenceCampaignNames(\n firestore: Firestore,\n orgId: string,\n sequence: OutreachSequence,\n ): Promise<string[]> {\n const campaignIds = normalizeContainerIds(sequence.campaignIds)\n if (!campaignIds.length || !orgId) return []\n try {\n const found = await readOrgContainers(firestore, 'campaign', orgId, campaignIds)\n return found.map((container) => container.name).filter(Boolean)\n } catch (error) {\n console.error('[outreach] the sequence’s campaigns could not be named for the record', error)\n return []\n }\n }\n\n /**\n * The people a source names, the batch limit applied: every contact a\n * search picked, every lead picked from the sequence's site, or the\n * people a saved Contacts or Leads view selects there — contacts found by\n * address, leads by their own key.\n */\n async function sourcePeople(\n caller: OutreachRouteCaller,\n sequence: OutreachSequence,\n source: Record<string, unknown>,\n ): Promise<Response | { people: OutreachPersonRef[]; total: number; truncated: boolean }> {\n if (source['kind'] === 'contacts' || source['kind'] === 'leads') {\n const kind = source['kind'] === 'leads' ? 'lead' : 'contact'\n const ids = uniqueIds(kind === 'lead' ? source['leadIds'] : source['contactIds'])\n if (!ids.length) return outreachRefusal(400, 'invalid-request', 'Pick the people to enroll.')\n return {\n people: ids.slice(0, OUTREACH_ENROLL_BATCH_MAX).map((id) => ({ kind, id })),\n total: ids.length,\n truncated: ids.length > OUTREACH_ENROLL_BATCH_MAX,\n }\n }\n if (source['kind'] !== 'view') {\n return outreachRefusal(400, 'invalid-request', 'Enroll people from a saved view or a search.')\n }\n const viewId = readOutreachDocumentId(source['viewId'])\n // The record system takes the view for the sequence's site (AGL-3080):\n // a colleague's private view is theirs, so it does not exist for this\n // member; a Leads view takes the site's leads by the view's status, a\n // Contacts view the contacts it selects there.\n const taken = viewId\n ? await pluginPeopleInView({\n orgId: caller.orgId,\n hostId: sequence.hostId,\n viewId,\n viewerUid: caller.uid,\n limit: OUTREACH_ENROLL_BATCH_MAX,\n })\n : null\n if (!taken || (taken.ok === false && taken.reason === 'not-found')) {\n return outreachRefusal(404, 'view-not-found', 'That saved view no longer exists.')\n }\n if (taken.ok === false && taken.reason === 'not-people') {\n return outreachRefusal(400, 'view-unsupported', 'Enroll from a saved view of Contacts or Leads.')\n }\n if (taken.ok === false) {\n // Dropping the filter enrolling cannot read would enroll more people\n // than the view shows, so the view is refused whole.\n return outreachRefusal(\n 400,\n 'view-unsupported',\n `This view filters on ${(taken.unsupported ?? []).join(', ') || 'something'}, which enrolling can't apply. Pick another view, or search.`,\n )\n }\n return {\n people: taken.people.map((person) => ({ kind: person.kind === 'lead' ? 'lead' : 'contact', id: person.id })),\n total: taken.total,\n truncated: taken.truncated,\n }\n }\n\n const preview: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate, [OUTREACH_READS_PEOPLE])\n if (caller instanceof Response) return caller\n const firestore = deps.firestore()\n const sequence = await loadActiveSequence(firestore, caller.orgId, body['sequenceId'])\n if (sequence instanceof Response) return sequence\n const source = body['source'] && typeof body['source'] === 'object' ? (body['source'] as Record<string, unknown>) : {}\n const named = await sourcePeople(caller, sequence, source)\n if (named instanceof Response) return named\n const context = await enrollContext(firestore, caller, sequence)\n const { candidates, enrolledHere, lookups } = await readPeople(\n firestore,\n caller,\n sequence,\n context,\n named.people,\n {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs: deps.now(),\n sendingDomain: await sequenceSendingDomain(firestore, caller.orgId, sequence),\n },\n )\n const people = candidates.map((candidate) =>\n previewOutreachPerson(\n {\n candidate,\n lookups: lookups.get(candidate.personId) ?? UNCHECKED,\n settings: context.settings,\n contactGroupId: context.contactGroupId,\n },\n { siteName: context.siteName, alreadyInSequence: enrolledHere.has(candidate.personId) },\n ),\n )\n return outreachOk({\n ok: true,\n people,\n total: named.total,\n truncated: named.truncated,\n } satisfies OutreachEnrollPreviewResponse)\n }\n\n const confirm: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate, [OUTREACH_READS_PEOPLE])\n if (caller instanceof Response) return caller\n const firestore = deps.firestore()\n const sequence = await loadActiveSequence(firestore, caller.orgId, body['sequenceId'])\n if (sequence instanceof Response) return sequence\n\n const nowMs = deps.now()\n const start = readOutreachStartStepIndex(body['startStepIndex'], sequence.steps)\n if (start.refusal !== null) return outreachRefusal(400, 'invalid-start-step', start.refusal)\n const startStepIndex = start.startStepIndex\n // Each person once, by whichever record they are: a contact by id, or a\n // lead by its key (AGL-3234). A person named both ways is a contact.\n const requested = new Map<\n string,\n { ref: OutreachPersonRef; personalLine: string; attestations: unknown[]; overrides: OutreachStepOverrideRead }\n >()\n for (const entry of Array.isArray(body['people']) ? body['people'] : []) {\n const person = (entry && typeof entry === 'object' ? entry : {}) as Record<string, unknown>\n const contactId = readOutreachDocumentId(person['contactId'])\n const leadId = readOutreachDocumentId(person['leadId'])\n const ref: OutreachPersonRef | null = contactId\n ? { kind: 'contact', id: contactId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : null\n if (!ref || requested.has(ref.id)) continue\n // The steps the member curated for this person (AGL-3324), validated\n // here rather than trusted: a copy that breaks a rule refuses the\n // whole request, so nobody is enrolled with a copy the route dropped.\n const overrides = readOutreachStepOverrideRequests(\n person['stepOverrides'],\n sequence.steps,\n { uid: caller.uid, nowMs },\n startStepIndex,\n )\n if (outreachStepOverridesRefused(overrides)) {\n return outreachRefusal(\n 400,\n 'invalid-override',\n overrides.refusal ?? 'A curated step breaks a rule every sequence email keeps.',\n { issues: overrides.issues },\n )\n }\n requested.set(ref.id, {\n ref,\n personalLine: typeof person['personalLine'] === 'string' ? person['personalLine'] : '',\n attestations: Array.isArray(person['attestations']) ? person['attestations'] : [],\n overrides,\n })\n }\n if (!requested.size) return outreachRefusal(400, 'invalid-request', 'Pick the people to enroll.')\n if (requested.size > OUTREACH_ENROLL_BATCH_MAX) {\n return outreachRefusal(\n 400,\n 'invalid-request',\n `Enroll at most ${OUTREACH_ENROLL_BATCH_MAX} people at a time.`,\n )\n }\n\n const mailboxSnapshot = sequence.mailboxId\n ? await outreachOrgCollection(firestore, caller.orgId, 'mailboxes').doc(sequence.mailboxId).get()\n : null\n const mailbox = readStoredOutreachMailbox(\n sequence.mailboxId,\n mailboxSnapshot?.exists ? mailboxSnapshot.data() : undefined,\n )\n if (!mailbox || mailbox.status === 'disconnected') {\n return outreachRefusal(\n 409,\n 'mailbox-unavailable',\n \"This sequence's mailbox is no longer connected. Choose another mailbox for it before enrolling people.\",\n )\n }\n if (planOutreachFirstDue({ sequence, mailbox, enrolledAtMs: nowMs, random: deps.random, startStepIndex }) === null) {\n return outreachRefusal(\n 409,\n 'mailbox-unavailable',\n \"This sequence's sending hours never open in its mailbox's timezone. Fix the hours before enrolling people.\",\n )\n }\n\n const context = await enrollContext(firestore, caller, sequence)\n const { candidates, enrolledHere, lookups } = await readPeople(\n firestore,\n caller,\n sequence,\n context,\n [...requested.values()].map((entry) => entry.ref),\n {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n },\n )\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n const campaignNames = await sequenceCampaignNames(firestore, caller.orgId, sequence)\n // The member's name for the curated entries (AGL-3324), read once per\n // request and only when a person carries a curated step.\n let memberNameRead: Promise<string | null> | null = null\n const memberName = () => {\n memberNameRead ??= firestore\n .collection('orgs')\n .doc(caller.orgId)\n .collection('members')\n .doc(caller.uid)\n .get()\n .then(\n (member) =>\n (member.exists\n ? String(member.get('displayName') ?? '').trim() || String(member.get('email') ?? '').trim()\n : '') || caller.email,\n )\n .catch(() => caller.email)\n return memberNameRead\n }\n const results: OutreachEnrollOutcome[] = await Promise.all(\n candidates.map(async (candidate): Promise<OutreachEnrollOutcome> => {\n const named = {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n const supplied = requested.get(candidate.personId) ?? {\n personalLine: '',\n attestations: [],\n overrides: { overrides: {}, issues: [], refusal: null } satisfies OutreachStepOverrideRead,\n }\n const stepOverrides: OutreachStepOverrides = supplied.overrides.overrides\n const decision = decideOutreachEnrollment(\n {\n candidate,\n lookups: lookups.get(candidate.personId) ?? UNCHECKED,\n settings: context.settings,\n contactGroupId: context.contactGroupId,\n },\n { siteName: context.siteName, alreadyInSequence: enrolledHere.has(candidate.personId) },\n { personalLine: supplied.personalLine, attestations: supplied.attestations, uid: caller.uid, nowMs },\n )\n if (!decision.allowed || !decision.email) {\n return { ...named, email: candidate.email, outcome: 'blocked', blocks: decision.blocks }\n }\n const id = outreachEnrollmentId(sequence.id, candidate.personId)\n const enrollment = buildOutreachEnrollment({\n id,\n sequence,\n mailbox,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n contactName: candidate.name,\n email: decision.email,\n cold: decision.cold,\n personalLine: supplied.personalLine,\n attestations: decision.attestations,\n enrolledByUid: caller.uid,\n nowMs,\n random: deps.random,\n startStepIndex,\n })\n // The member ticked this person past the red gateway chip\n // (AGL-3326): that is their say-so, stamped as the hold's release,\n // so the engine does not hold the send they were just shown.\n if (decision.hold) {\n enrollment.gatewayHold = {\n gateway: decision.hold.gateway,\n heldAtMs: null,\n releasedByUid: caller.uid,\n releasedAtMs: nowMs,\n }\n }\n // The person's own copies of steps (AGL-3324) ride with the\n // enrollment from its first write: nothing sends between.\n if (Object.keys(stepOverrides).length) enrollment.stepOverrides = stepOverrides\n // What the enrollments table searches the person by (AGL-3321),\n // from the name and address this document captures for good.\n enrollment.searchTokens = outreachEnrollmentSearchTokens(enrollment)\n // Nobody has clicked yet (AGL-3332): stored, because the \"Clicked: No\"\n // filter is a query, and a query cannot find a field's absence.\n enrollment.clicked = false\n try {\n await enrollments.doc(id).create(enrollment)\n } catch (error) {\n if ((error as { code?: unknown })?.code !== ALREADY_EXISTS) throw error\n return {\n ...named,\n email: candidate.email,\n outcome: 'blocked',\n blocks: [\n {\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 }\n }\n await joinSequenceCampaigns(caller.orgId, sequence, candidate, nowMs)\n // A person reached first by this sequence came from it (AGL-3519):\n // the record system stamps its Sequence lead source on a record\n // naming none, and leaves any other alone.\n await stampRecordOrigin({\n orgId: caller.orgId,\n hostId: sequence.hostId,\n email: decision.email,\n origin: 'sequence',\n })\n // The person's record says so (AGL-3274): \"Enrolled in <sequence>\",\n // with the campaigns it carried them into, once per enrollment.\n const entry = outreachEnrolledEntry({\n enrollmentId: id,\n sequenceName: sequence.name,\n campaignNames,\n startStepIndex,\n })\n await fileOutreachNote(deps, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: entry.dedupeKey,\n body: entry.body,\n atMs: nowMs,\n })\n // And one line per step the member curated for them (AGL-3324),\n // after the enrollment's own, so the record reads in order.\n for (const [key, override] of Object.entries(stepOverrides)) {\n const curated = outreachCuratedEntry({\n enrollmentId: id,\n stepIndex: Number(key),\n source: override.source,\n edited: override.edited === true,\n memberName: await memberName(),\n atMs: nowMs,\n })\n await fileOutreachNote(deps, {\n orgId: caller.orgId,\n hostId: sequence.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: curated.dedupeKey,\n body: curated.body,\n atMs: nowMs,\n })\n }\n return { ...named, email: decision.email, outcome: 'enrolled', enrollmentId: id }\n }),\n )\n const enrolled = results.filter((result) => result.outcome === 'enrolled').length\n if (enrolled) {\n await deps.logOrgActivity(\n caller.orgId,\n { uid: caller.uid, email: caller.email },\n outreachEnrolledActivity(enrolled),\n { type: OUTREACH_SEQUENCE_ACTIVITY_TARGET, id: sequence.id, name: sequence.name },\n )\n }\n return outreachOk({ ok: true, results, enrolled } satisfies OutreachEnrollResponse)\n }\n\n return { preview, confirm }\n}\n"],"names":["stampRecordOrigin","normalizeContainerIds","consentGroupForHost","filePluginPersonUnder","pluginPeopleInView","readOrgContainers","outreachCuratedEntry","outreachEnrolledEntry","buildOutreachEnrollment","planOutreachFirstDue","readOutreachStartStepIndex","outreachEnrollmentSearchTokens","decideOutreachEnrollment","previewOutreachPerson","readOutreachEnrollCandidates","readOutreachGateLookups","outreachStepOverridesRefused","readOutreachStepOverrideRequests","effectiveOutreachAllowedCountries","OUTREACH_ENROLL_BATCH_MAX","readOutreachComplianceSettingsDoc","outreachMailboxSendingDomain","fileOutreachNote","outreachEnrollmentId","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_SEQUENCE_ACTIVITY_TARGET","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","OUTREACH_READS_PEOPLE","key","refusal","outreachEnrolledActivity","count","UNCHECKED","platformSuppressed","hostSuppressed","salesTopicState","doNotContact","doNotContactDomain","workspaceMembers","openEnrollments","hasInboundEmail","gateway","ALREADY_EXISTS","loadActiveSequence","firestore","orgId","rawSequenceId","sequenceId","snapshot","doc","get","sequence","exists","data","undefined","status","enrollContext","caller","host","orgSettings","Promise","all","collection","hostId","consentGroup","org","settings","allowedCountries","contactGroupId","groupId","consentHostIds","hostIds","consentAwaitsConfirmation","awaitsConfirmation","siteName","String","sequenceSendingDomain","mailboxId","mailbox","error","console","readPeople","context","people","candidates","enrollments","existing","length","getAll","map","candidate","id","personId","enrolledHere","Set","filter","_candidate","index","askable","contact","visible","email","lookups","contactId","leadId","Map","open","some","entry","add","uniqueIds","values","Array","isArray","createOutreachEnrollRoutes","deps","joinSequenceCampaigns","nowMs","campaignIds","target","record","kind","containerKind","ids","creditCampaign","outcome","atMs","sequenceCampaignNames","found","container","name","Boolean","sourcePeople","source","slice","total","truncated","viewId","taken","viewerUid","uid","limit","ok","reason","unsupported","join","person","preview","request","method","body","gate","Response","named","resolveMx","resolveAddress","now","sendingDomain","alreadyInSequence","has","confirm","start","steps","startStepIndex","requested","ref","overrides","issues","set","personalLine","attestations","size","mailboxSnapshot","enrolledAtMs","random","campaignNames","memberNameRead","memberName","then","member","trim","catch","results","supplied","stepOverrides","decision","allowed","blocks","enrollment","contactName","cold","enrolledByUid","hold","gatewayHold","heldAtMs","releasedByUid","releasedAtMs","Object","keys","searchTokens","clicked","create","code","origin","enrollmentId","sequenceName","link","dedupeKey","override","entries","curated","stepIndex","Number","edited","enrolled","result","logOrgActivity","type"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,mDAAkD;AACpF,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,kBAAkB,QACb,oDAAmD;AAI1D,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,mCAA+B;AAC3F,SACEC,uBAAuB,EACv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C,OAAO4C,KAAK;YAAC,GACvCvE,yBAAyBwL,WACzB;gBAAEG,MAAMrM;gBAAmCuE,IAAIxC,SAASwC,EAAE;gBAAEuC,MAAM/E,SAAS+E,IAAI;YAAC;QAEpF;QACA,OAAO3G,WAAW;YAAEuH,IAAI;YAAMwC;YAASgC;QAAS;IAClD;IAEA,OAAO;QAAEnE;QAASa;IAAQ;AAC5B"}
|
|
@@ -14,7 +14,6 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { creditCampaignSequenceOutcome } from '@aglyn/tenant-data-admin/server/campaign-conversion-attribution';
|
|
18
17
|
import { stampRecordEmailState } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state';
|
|
19
18
|
import { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown';
|
|
20
19
|
import { logOrgActivity } from '@aglyn/tenant-data-admin/server/organizations';
|
|
@@ -22,8 +21,9 @@ import { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions';
|
|
|
22
21
|
import { listTrackingHosts, removeTrackingHost, resolveTrackingLinkOrigin, setUpTrackingHost, verifyTrackingHost } from '@aglyn/tenant-data-admin/server/tracking-hosts';
|
|
23
22
|
/**
|
|
24
23
|
* The platform's heavier server modules the Outreach routes reach
|
|
25
|
-
* (AGL-2980): the permission resolver, the lockdown verdict
|
|
26
|
-
* log
|
|
24
|
+
* (AGL-2980): the permission resolver, the lockdown verdict and the
|
|
25
|
+
* activity log. A saved view's people are the record system's to take
|
|
26
|
+
* (`plugin-person-records`).
|
|
27
27
|
*
|
|
28
28
|
* Imported here statically, and this module is loaded by
|
|
29
29
|
* `register-routes.ts` the first time a request needs one of them: the
|
|
@@ -33,22 +33,10 @@ import { listTrackingHosts, removeTrackingHost, resolveTrackingLinkOrigin, setUp
|
|
|
33
33
|
* module of this plugin keeps every import of the platform's libraries a
|
|
34
34
|
* static one.
|
|
35
35
|
*/
|
|
36
|
-
export {
|
|
36
|
+
export { listTrackingHosts, lockdownRefusal, logOrgActivity, removeTrackingHost, resolveOrgPermissions, resolveTrackingLinkOrigin, setUpTrackingHost, stampRecordEmailState, verifyTrackingHost, };
|
|
37
37
|
/**
|
|
38
38
|
* Whether the member holds a CATALOG permission (`data.manage`) as the
|
|
39
39
|
* org's roles resolve it — custom role and per-member overrides included.
|
|
40
40
|
* A lookup that failed has not shown the member holds it.
|
|
41
41
|
*/
|
|
42
42
|
export declare function holdsOrgCatalogPermission(uid: string, orgId: string, key: string): Promise<boolean>;
|
|
43
|
-
/**
|
|
44
|
-
* The addresses a saved Contacts view selects among one site's contacts,
|
|
45
|
-
* read by the dynamic-list sweep's own scan, and whether it reached the
|
|
46
|
-
* whole view.
|
|
47
|
-
*/
|
|
48
|
-
export declare function crmViewEmails(input: {
|
|
49
|
-
hostId: string;
|
|
50
|
-
viewId: string;
|
|
51
|
-
}): Promise<{
|
|
52
|
-
emails: string[];
|
|
53
|
-
complete: boolean;
|
|
54
|
-
}>;
|
|
@@ -13,17 +13,16 @@
|
|
|
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
|
-
*/ import {
|
|
17
|
-
import { collectDynamicListCandidates } from "@aglyn/tenant-data-admin/server/dynamic-list-materialize";
|
|
18
|
-
import { stampRecordEmailState } from "@aglyn/aglyn/plugin-manager/plugin-record-email-state";
|
|
16
|
+
*/ import { stampRecordEmailState } from "@aglyn/aglyn/plugin-manager/plugin-record-email-state";
|
|
19
17
|
import { lockdownRefusal } from "@aglyn/tenant-data-admin/server/lockdown";
|
|
20
18
|
import { logOrgActivity, memberHasOrgPermission, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
|
|
21
19
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
22
20
|
import { listTrackingHosts, removeTrackingHost, resolveTrackingLinkOrigin, setUpTrackingHost, verifyTrackingHost } from "@aglyn/tenant-data-admin/server/tracking-hosts";
|
|
23
21
|
/**
|
|
24
22
|
* The platform's heavier server modules the Outreach routes reach
|
|
25
|
-
* (AGL-2980): the permission resolver, the lockdown verdict
|
|
26
|
-
* log
|
|
23
|
+
* (AGL-2980): the permission resolver, the lockdown verdict and the
|
|
24
|
+
* activity log. A saved view's people are the record system's to take
|
|
25
|
+
* (`plugin-person-records`).
|
|
27
26
|
*
|
|
28
27
|
* Imported here statically, and this module is loaded by
|
|
29
28
|
* `register-routes.ts` the first time a request needs one of them: the
|
|
@@ -32,7 +31,7 @@ import { listTrackingHosts, removeTrackingHost, resolveTrackingLinkOrigin, setUp
|
|
|
32
31
|
* alone reaches the whole tenant data barrel. Loading them through one
|
|
33
32
|
* module of this plugin keeps every import of the platform's libraries a
|
|
34
33
|
* static one.
|
|
35
|
-
*/ export {
|
|
34
|
+
*/ export { listTrackingHosts, lockdownRefusal, logOrgActivity, removeTrackingHost, resolveOrgPermissions, resolveTrackingLinkOrigin, setUpTrackingHost, stampRecordEmailState, verifyTrackingHost, };
|
|
36
35
|
/**
|
|
37
36
|
* Whether the member holds a CATALOG permission (`data.manage`) as the
|
|
38
37
|
* org's roles resolve it — custom role and per-member overrides included.
|
|
@@ -46,24 +45,5 @@ import { listTrackingHosts, removeTrackingHost, resolveTrackingLinkOrigin, setUp
|
|
|
46
45
|
return false;
|
|
47
46
|
}
|
|
48
47
|
}
|
|
49
|
-
/**
|
|
50
|
-
* The addresses a saved Contacts view selects among one site's contacts,
|
|
51
|
-
* read by the dynamic-list sweep's own scan, and whether it reached the
|
|
52
|
-
* whole view.
|
|
53
|
-
*/ export async function crmViewEmails(input) {
|
|
54
|
-
const scan = await collectDynamicListCandidates({
|
|
55
|
-
hostId: input.hostId,
|
|
56
|
-
rule: {
|
|
57
|
-
sources: [
|
|
58
|
-
'contacts'
|
|
59
|
-
],
|
|
60
|
-
viewId: input.viewId
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
return {
|
|
64
|
-
emails: scan.candidates.map((candidate)=>candidate.email),
|
|
65
|
-
complete: scan.complete
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
48
|
|
|
69
49
|
//# sourceMappingURL=platform-deps.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/platform-deps.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 {
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/platform-deps.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 { stampRecordEmailState } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport {\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n listTrackingHosts,\n removeTrackingHost,\n resolveTrackingLinkOrigin,\n setUpTrackingHost,\n verifyTrackingHost,\n} from '@aglyn/tenant-data-admin/server/tracking-hosts'\n\n/**\n * The platform's heavier server modules the Outreach routes reach\n * (AGL-2980): the permission resolver, the lockdown verdict and the\n * activity log. A saved view's people are the record system's to take\n * (`plugin-person-records`).\n *\n * Imported here statically, and this module is loaded by\n * `register-routes.ts` the first time a request needs one of them: the\n * manifest loads Outreach's server bundle into every console API process\n * whether or not an Outreach route is ever called, and `org-permissions`\n * alone reaches the whole tenant data barrel. Loading them through one\n * module of this plugin keeps every import of the platform's libraries a\n * static one.\n */\n\nexport {\n listTrackingHosts,\n lockdownRefusal,\n logOrgActivity,\n removeTrackingHost,\n resolveOrgPermissions,\n resolveTrackingLinkOrigin,\n setUpTrackingHost,\n stampRecordEmailState,\n verifyTrackingHost,\n}\n\n/**\n * Whether the member holds a CATALOG permission (`data.manage`) as the\n * org's roles resolve it — custom role and per-member overrides included.\n * A lookup that failed has not shown the member holds it.\n */\nexport async function holdsOrgCatalogPermission(uid: string, orgId: string, key: string): Promise<boolean> {\n try {\n const membership = await resolveOrgMembership(uid, orgId)\n if (!membership?.member) return false\n return (\n (await memberHasOrgPermission(\n orgId,\n membership.member,\n key as Parameters<typeof memberHasOrgPermission>[2],\n )) === true\n )\n } catch {\n return false\n }\n}\n"],"names":["stampRecordEmailState","lockdownRefusal","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","resolveOrgPermissions","listTrackingHosts","removeTrackingHost","resolveTrackingLinkOrigin","setUpTrackingHost","verifyTrackingHost","holdsOrgCatalogPermission","uid","orgId","key","membership","member"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wDAAuD;AAC7F,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SACEC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,iBAAiB,EACjBC,kBAAkB,EAClBC,yBAAyB,EACzBC,iBAAiB,EACjBC,kBAAkB,QACb,iDAAgD;AAEvD;;;;;;;;;;;;;CAaC,GAED,SACEJ,iBAAiB,EACjBL,eAAe,EACfC,cAAc,EACdK,kBAAkB,EAClBF,qBAAqB,EACrBG,yBAAyB,EACzBC,iBAAiB,EACjBT,qBAAqB,EACrBU,kBAAkB,KACnB;AAED;;;;CAIC,GACD,OAAO,eAAeC,0BAA0BC,GAAW,EAAEC,KAAa,EAAEC,GAAW;IACrF,IAAI;QACF,MAAMC,aAAa,MAAMX,qBAAqBQ,KAAKC;QACnD,IAAI,EAACE,8BAAAA,WAAYC,MAAM,GAAE,OAAO;QAChC,OACE,AAAC,MAAMb,uBACLU,OACAE,WAAWC,MAAM,EACjBF,SACK;IAEX,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -16,12 +16,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { consentGroupForHost } from "@aglyn/aglyn/app-utils/consent-groups";
|
|
18
18
|
import { normalizeContactEmail } from "@aglyn/aglyn/app-utils/contacts";
|
|
19
|
-
import { CRM_COLLECTIONS } from "@aglyn/aglyn/app-utils/crm";
|
|
20
|
-
import { normalizeCrmEmailTemplate } from "@aglyn/aglyn/app-utils/crm-email-templates";
|
|
21
19
|
import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
20
|
+
import { readPluginPeople } from "@aglyn/aglyn/plugin-manager/plugin-person-records";
|
|
22
21
|
import { readOutreachStartStepIndex } from "../engine/enrollment-state.js";
|
|
23
22
|
import { firstEmailStepIndex } from "../engine/sequence-validation.js";
|
|
24
23
|
import { leadAsContact } from "../enrollment/enroll-people.js";
|
|
24
|
+
import { readOutreachTemplateBody } from "../enrollment/message-templates.js";
|
|
25
25
|
import { outreachStepOverridesRefused, readOutreachStepOverrideRequests } from "../enrollment/step-overrides.js";
|
|
26
26
|
import { OUTREACH_SAMPLE_PERSON, outreachSampleMergeContext, previewOutreachStep } from "../model/step-preview.js";
|
|
27
27
|
import { readOutreachComplianceSettingsDoc } from "../storage/compliance-settings-store.js";
|
|
@@ -33,7 +33,7 @@ import { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachDocu
|
|
|
33
33
|
* The gate, then the sequence, the step and everything the step is rendered
|
|
34
34
|
* from — as the request body names them — or the refusal that stops it.
|
|
35
35
|
*/ export async function readOutreachStepRender(deps, request, body) {
|
|
36
|
-
var _host_get, _normalizeContactEmail;
|
|
36
|
+
var _ref, _host_get, _normalizeContactEmail;
|
|
37
37
|
const contactId = body['contactId'] === undefined ? null : readOutreachDocumentId(body['contactId']);
|
|
38
38
|
if (body['contactId'] !== undefined && !contactId) {
|
|
39
39
|
return outreachRefusal(400, 'invalid-request', 'Name the contact to preview for.');
|
|
@@ -50,7 +50,6 @@ import { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachDocu
|
|
|
50
50
|
const sequenceId = readOutreachDocumentId(body['sequenceId']);
|
|
51
51
|
if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to preview.');
|
|
52
52
|
const firestore = deps.firestore();
|
|
53
|
-
const org = firestore.collection('orgs').doc(caller.orgId);
|
|
54
53
|
const snapshot = await outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(sequenceId).get();
|
|
55
54
|
const sequence = readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined);
|
|
56
55
|
if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.');
|
|
@@ -78,22 +77,35 @@ import { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachDocu
|
|
|
78
77
|
issues: overrides.issues
|
|
79
78
|
});
|
|
80
79
|
}
|
|
81
|
-
|
|
80
|
+
// The person, as the record system keeps them (AGL-3080). A lead is one
|
|
81
|
+
// org row (AGL-3275); the site is still required because a lead preview is
|
|
82
|
+
// rendered in a site's context.
|
|
83
|
+
const person = contactId ? {
|
|
84
|
+
kind: 'contact',
|
|
85
|
+
id: contactId
|
|
86
|
+
} : leadId && sequence.hostId ? {
|
|
87
|
+
kind: 'lead',
|
|
88
|
+
id: leadId
|
|
89
|
+
} : null;
|
|
90
|
+
const [orgSettings, mailboxSnapshot, host, templateBody, people] = await Promise.all([
|
|
82
91
|
readOutreachComplianceSettingsDoc(firestore, caller.orgId),
|
|
83
92
|
sequence.mailboxId ? outreachOrgCollection(firestore, caller.orgId, 'mailboxes').doc(sequence.mailboxId).get() : null,
|
|
84
93
|
sequence.hostId ? firestore.collection('hosts').doc(sequence.hostId).get() : null,
|
|
85
|
-
step.templateId ?
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
94
|
+
step.templateId ? readOutreachTemplateBody(caller.orgId, step.templateId) : null,
|
|
95
|
+
person ? readPluginPeople({
|
|
96
|
+
orgId: caller.orgId,
|
|
97
|
+
records: [
|
|
98
|
+
person
|
|
99
|
+
]
|
|
100
|
+
}) : null
|
|
90
101
|
]);
|
|
91
|
-
const
|
|
102
|
+
const record = (_ref = people == null ? void 0 : people[0]) != null ? _ref : null;
|
|
103
|
+
const leadData = (person == null ? void 0 : person.kind) === 'lead' && record ? _extends({}, record.data) : null;
|
|
92
104
|
if (leadId && !leadData) {
|
|
93
105
|
return outreachRefusal(404, 'contact-not-found', "That lead isn't in this sequence's site's CRM.");
|
|
94
106
|
}
|
|
95
107
|
const contactGroupId = consentGroupForHost(caller.org, sequence.hostId).groupId;
|
|
96
|
-
const contactData = (
|
|
108
|
+
const contactData = (person == null ? void 0 : person.kind) === 'contact' && record ? _extends({}, record.data) : leadData ? leadAsContact(leadData, contactGroupId) : null;
|
|
97
109
|
if (contactId && (!contactData || !visibleToHost(contactData['visibleTo'], sequence.hostId))) {
|
|
98
110
|
return outreachRefusal(404, 'contact-not-found', "That contact isn't in this sequence's site's CRM.");
|
|
99
111
|
}
|
|
@@ -129,7 +141,7 @@ import { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachDocu
|
|
|
129
141
|
merge,
|
|
130
142
|
email: contactData ? (_normalizeContactEmail = normalizeContactEmail(contactData['email'])) != null ? _normalizeContactEmail : '' : OUTREACH_SAMPLE_PERSON.email,
|
|
131
143
|
personalLine,
|
|
132
|
-
templateBody
|
|
144
|
+
templateBody,
|
|
133
145
|
stepOverrides: overrides.overrides
|
|
134
146
|
}, startStepIndex > 0 ? {
|
|
135
147
|
startStepIndex
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/preview-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { normalizeCrmEmailTemplate } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOutreachStartStepIndex } from '../engine/enrollment-state'\nimport { firstEmailStepIndex } from '../engine/sequence-validation'\nimport { leadAsContact } from '../enrollment/enroll-people'\nimport { outreachStepOverridesRefused, readOutreachStepOverrideRequests } from '../enrollment/step-overrides'\nimport type { OutreachPreviewResponse } from '../model/outreach-api'\nimport type { OutreachEmailStep, OutreachMailbox, OutreachSequence } from '../model/outreach.types'\nimport {\n OUTREACH_SAMPLE_PERSON,\n outreachSampleMergeContext,\n previewOutreachStep,\n type OutreachStepPreviewInput,\n} from '../model/step-preview'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_READS_PEOPLE } from './enroll-routes'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * ONE EMAIL OF A SAVED SEQUENCE, AS A PERSON WOULD GET IT (AGL-2980):\n * `outreach/preview`.\n *\n * Written from what is stored — the sequence, the CRM template a step names,\n * the mailbox it sends as, the organization's footer — by the engine's own\n * composer (`previewOutreachStep`), for a real contact with the personal\n * line the rep is writing, or for a sample person. The enroll dialog shows\n * it beside each person before Confirm, so the rep reads the sentence they\n * wrote in the email it goes into.\n *\n * A real contact is read from the CRM, so naming one asks for `data.manage`\n * as enrolling does; the sample person asks for nothing more.\n *\n * The reading is {@link readOutreachStepRender}, shared with the test send\n * (`step-test-routes.ts`, AGL-3325): a test is the preview's own email,\n * sent — so both routes read the same records through the same gate, and\n * what a member reads on screen is what arrives in their inbox.\n */\n\n/** What a preview and a test both read before the composer runs. */\nexport interface OutreachStepRender {\n caller: OutreachRouteCaller\n sequence: OutreachSequence\n stepIndex: number\n step: OutreachEmailStep\n /** The sequence's mailbox as stored, or `null` when it names none or the mailbox is gone. */\n mailbox: OutreachMailbox | null\n /** The composer's input: the person, the line, the footer, the template. */\n input: OutreachStepPreviewInput\n}\n\n/**\n * The gate, then the sequence, the step and everything the step is rendered\n * from — as the request body names them — or the refusal that stops it.\n */\nexport async function readOutreachStepRender(\n deps: OutreachRouteDeps,\n request: Request,\n body: Record<string, unknown>,\n): Promise<Response | OutreachStepRender> {\n const contactId = body['contactId'] === undefined ? null : readOutreachDocumentId(body['contactId'])\n if (body['contactId'] !== undefined && !contactId) {\n return outreachRefusal(400, 'invalid-request', 'Name the contact to preview for.')\n }\n // A lead the sequence's site holds (AGL-3234), previewed as the contact it would be.\n const leadId = body['leadId'] === undefined ? null : readOutreachDocumentId(body['leadId'])\n if (body['leadId'] !== undefined && !leadId) {\n return outreachRefusal(400, 'invalid-request', 'Name the lead to preview for.')\n }\n const caller = await outreachRouteGate(\n request,\n body['orgId'],\n deps.gate,\n contactId || leadId ? [OUTREACH_READS_PEOPLE] : [],\n )\n if (caller instanceof Response) return caller\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to preview.')\n const firestore = deps.firestore()\n const org = firestore.collection('orgs').doc(caller.orgId)\n const snapshot = await outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(sequenceId).get()\n const sequence = readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n\n // Where the enrollment would begin (AGL-3228): the email written is the\n // first one sent from there, and it starts the thread.\n const start = readOutreachStartStepIndex(body['startStepIndex'], sequence.steps)\n if (start.refusal !== null) return outreachRefusal(400, 'invalid-start-step', start.refusal)\n const startStepIndex = start.startStepIndex\n const requested = body['stepIndex']\n const stepIndex =\n typeof requested === 'number' ? requested : firstEmailStepIndex(sequence.steps, startStepIndex)\n const step = sequence.steps[stepIndex]\n if (step?.kind !== 'email') {\n return outreachRefusal(\n 400,\n 'invalid-request',\n stepIndex < 0 && startStepIndex > 0\n ? `No email is sent from step ${startStepIndex + 1} on.`\n : 'That step does not send an email.',\n )\n }\n // The person's copies of steps as the dialog holds them (AGL-3324): the\n // preview shows the curated version, held to the rules a stored one is —\n // and a test send (AGL-3325) sends it.\n const overrides = readOutreachStepOverrideRequests(\n body['stepOverrides'],\n sequence.steps,\n { uid: caller.uid, nowMs: deps.now() },\n startStepIndex,\n )\n if (outreachStepOverridesRefused(overrides)) {\n return outreachRefusal(\n 400,\n 'invalid-override',\n overrides.refusal ?? 'A curated step breaks a rule every sequence email keeps.',\n { issues: overrides.issues },\n )\n }\n\n const [orgSettings, mailboxSnapshot, host, template, contact, lead] = await Promise.all([\n readOutreachComplianceSettingsDoc(firestore, caller.orgId),\n sequence.mailboxId ? outreachOrgCollection(firestore, caller.orgId, 'mailboxes').doc(sequence.mailboxId).get() : null,\n sequence.hostId ? firestore.collection('hosts').doc(sequence.hostId).get() : null,\n step.templateId ? org.collection(CRM_COLLECTIONS.emailTemplates).doc(step.templateId).get() : null,\n contactId ? org.collection('contacts').doc(contactId).get() : null,\n // One org row (AGL-3275); the site is still required because a lead\n // preview is rendered in a site's context.\n leadId && sequence.hostId ? org.collection('leads').doc(leadId).get() : null,\n ])\n const leadData = lead?.exists ? (lead.data() as Record<string, unknown>) : null\n if (leadId && !leadData) {\n return outreachRefusal(404, 'contact-not-found', \"That lead isn't in this sequence's site's CRM.\")\n }\n const contactGroupId = consentGroupForHost(caller.org, sequence.hostId).groupId\n const contactData = contact?.exists\n ? (contact.data() as Record<string, unknown>)\n : leadData\n ? leadAsContact(leadData, contactGroupId)\n : null\n if (\n contactId &&\n (!contactData || !visibleToHost(contactData['visibleTo'] as string[] | undefined, sequence.hostId))\n ) {\n return outreachRefusal(404, 'contact-not-found', \"That contact isn't in this sequence's site's CRM.\")\n }\n const mailbox = readStoredOutreachMailbox(\n sequence.mailboxId,\n mailboxSnapshot?.exists ? mailboxSnapshot.data() : undefined,\n )\n const sender = mailbox ? { name: mailbox.displayName, email: mailbox.sendAs || mailbox.email } : null\n const siteName = host?.exists ? String(host.get('name') ?? '') : ''\n const merge = contactData\n ? {\n contact: contactData,\n contactGroupId,\n lead: leadData,\n sender,\n site: { name: siteName },\n }\n : outreachSampleMergeContext({ sender, siteName })\n const personalLine =\n typeof body['personalLine'] === 'string'\n ? body['personalLine']\n : contactData\n ? ''\n : OUTREACH_SAMPLE_PERSON.personalLine\n return {\n caller,\n sequence,\n stepIndex,\n step,\n mailbox,\n input: {\n steps: sequence.steps,\n stepIndex,\n orgSettings,\n merge,\n email: contactData ? (normalizeContactEmail(contactData['email']) ?? '') : OUTREACH_SAMPLE_PERSON.email,\n personalLine,\n templateBody: template?.exists\n ? normalizeCrmEmailTemplate(template.data() as Record<string, unknown>).body\n : null,\n stepOverrides: overrides.overrides,\n ...(startStepIndex > 0 ? { startStepIndex } : {}),\n },\n }\n}\n\nexport function createOutreachPreviewRoute(deps: OutreachRouteDeps): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const loaded = await readOutreachStepRender(deps, request, body)\n if (loaded instanceof Response) return loaded\n const result = previewOutreachStep(loaded.input)\n return outreachOk({\n ok: true,\n stepIndex: loaded.stepIndex,\n subject: result.email?.subject ?? '',\n text: result.email?.text ?? '',\n unresolvedFields: result.unresolvedFields,\n error: result.error,\n } satisfies OutreachPreviewResponse)\n }\n}\n"],"names":["consentGroupForHost","normalizeContactEmail","CRM_COLLECTIONS","normalizeCrmEmailTemplate","visibleToHost","readOutreachStartStepIndex","firstEmailStepIndex","leadAsContact","outreachStepOverridesRefused","readOutreachStepOverrideRequests","OUTREACH_SAMPLE_PERSON","outreachSampleMergeContext","previewOutreachStep","readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_READS_PEOPLE","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","readOutreachStepRender","deps","request","body","host","contactId","undefined","leadId","caller","gate","Response","sequenceId","firestore","org","collection","doc","orgId","snapshot","get","sequence","exists","data","start","steps","refusal","startStepIndex","requested","stepIndex","step","kind","overrides","uid","nowMs","now","issues","orgSettings","mailboxSnapshot","template","contact","lead","Promise","all","mailboxId","hostId","templateId","emailTemplates","leadData","contactGroupId","groupId","contactData","mailbox","sender","name","displayName","email","sendAs","siteName","String","merge","site","personalLine","input","templateBody","stepOverrides","createOutreachPreviewRoute","result","method","loaded","ok","subject","text","unresolvedFields","error"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,yBAAyB,QAAQ,6CAA4C;AACtF,SAASC,aAAa,QAAQ,sCAAqC;AAEnE,SAASC,0BAA0B,QAAQ,gCAA4B;AACvE,SAASC,mBAAmB,QAAQ,mCAA+B;AACnE,SAASC,aAAa,QAAQ,iCAA6B;AAC3D,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,kCAA8B;AAG7G,SACEC,sBAAsB,EACtBC,0BAA0B,EAC1BC,mBAAmB,QAEd,2BAAuB;AAC9B,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,qBAAqB,QAAQ,qBAAiB;AAEvD,SAASC,iBAAiB,QAAkC,kBAAc;AAC1E,SACEC,wBAAwB,EACxBC,UAAU,EACVC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,QACf,kBAAc;AAkCrB;;;CAGC,GACD,OAAO,eAAeC,uBACpBC,IAAuB,EACvBC,OAAgB,EAChBC,IAA6B;QA6FUC,WA2Bb3B;IAtH1B,MAAM4B,YAAYF,IAAI,CAAC,YAAY,KAAKG,YAAY,OAAOR,uBAAuBK,IAAI,CAAC,YAAY;IACnG,IAAIA,IAAI,CAAC,YAAY,KAAKG,aAAa,CAACD,WAAW;QACjD,OAAOR,gBAAgB,KAAK,mBAAmB;IACjD;IACA,qFAAqF;IACrF,MAAMU,SAASJ,IAAI,CAAC,SAAS,KAAKG,YAAY,OAAOR,uBAAuBK,IAAI,CAAC,SAAS;IAC1F,IAAIA,IAAI,CAAC,SAAS,KAAKG,aAAa,CAACC,QAAQ;QAC3C,OAAOV,gBAA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AAiB,IAAI;YAAEA;QAAe,IAAI,CAAC;IAEnD;AACF;AAEA,OAAO,SAASuC,2BAA2B/D,IAAuB;IAChE,OAAO,OAAOC;;YASD+D,eACHA;QATR,IAAI/D,QAAQgE,MAAM,KAAK,QAAQ,OAAOvE,yBAAyB;QAC/D,MAAMQ,OAAO,MAAMJ,qBAAqBG;QACxC,MAAMiE,SAAS,MAAMnE,uBAAuBC,MAAMC,SAASC;QAC3D,IAAIgE,kBAAkBzD,UAAU,OAAOyD;QACvC,MAAMF,SAAS7E,oBAAoB+E,OAAON,KAAK;QAC/C,OAAOjE,WAAW;YAChBwE,IAAI;YACJzC,WAAWwC,OAAOxC,SAAS;YAC3B0C,OAAO,WAAEJ,gBAAAA,OAAOX,KAAK,qBAAZW,cAAcI,OAAO,mBAAI;YAClCC,IAAI,YAAEL,iBAAAA,OAAOX,KAAK,qBAAZW,eAAcK,IAAI,oBAAI;YAC5BC,kBAAkBN,OAAOM,gBAAgB;YACzCC,OAAOP,OAAOO,KAAK;QACrB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/preview-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { readPluginPeople } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOutreachStartStepIndex } from '../engine/enrollment-state'\nimport { firstEmailStepIndex } from '../engine/sequence-validation'\nimport { leadAsContact } from '../enrollment/enroll-people'\nimport { readOutreachTemplateBody } from '../enrollment/message-templates'\nimport { outreachStepOverridesRefused, readOutreachStepOverrideRequests } from '../enrollment/step-overrides'\nimport type { OutreachPreviewResponse } from '../model/outreach-api'\nimport type { OutreachEmailStep, OutreachMailbox, OutreachSequence } from '../model/outreach.types'\nimport {\n OUTREACH_SAMPLE_PERSON,\n outreachSampleMergeContext,\n previewOutreachStep,\n type OutreachStepPreviewInput,\n} from '../model/step-preview'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_READS_PEOPLE } from './enroll-routes'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * ONE EMAIL OF A SAVED SEQUENCE, AS A PERSON WOULD GET IT (AGL-2980):\n * `outreach/preview`.\n *\n * Written from what is stored — the sequence, the CRM template a step names,\n * the mailbox it sends as, the organization's footer — by the engine's own\n * composer (`previewOutreachStep`), for a real contact with the personal\n * line the rep is writing, or for a sample person. The enroll dialog shows\n * it beside each person before Confirm, so the rep reads the sentence they\n * wrote in the email it goes into.\n *\n * A real contact is read from the CRM, so naming one asks for `data.manage`\n * as enrolling does; the sample person asks for nothing more.\n *\n * The reading is {@link readOutreachStepRender}, shared with the test send\n * (`step-test-routes.ts`, AGL-3325): a test is the preview's own email,\n * sent — so both routes read the same records through the same gate, and\n * what a member reads on screen is what arrives in their inbox.\n */\n\n/** What a preview and a test both read before the composer runs. */\nexport interface OutreachStepRender {\n caller: OutreachRouteCaller\n sequence: OutreachSequence\n stepIndex: number\n step: OutreachEmailStep\n /** The sequence's mailbox as stored, or `null` when it names none or the mailbox is gone. */\n mailbox: OutreachMailbox | null\n /** The composer's input: the person, the line, the footer, the template. */\n input: OutreachStepPreviewInput\n}\n\n/**\n * The gate, then the sequence, the step and everything the step is rendered\n * from — as the request body names them — or the refusal that stops it.\n */\nexport async function readOutreachStepRender(\n deps: OutreachRouteDeps,\n request: Request,\n body: Record<string, unknown>,\n): Promise<Response | OutreachStepRender> {\n const contactId = body['contactId'] === undefined ? null : readOutreachDocumentId(body['contactId'])\n if (body['contactId'] !== undefined && !contactId) {\n return outreachRefusal(400, 'invalid-request', 'Name the contact to preview for.')\n }\n // A lead the sequence's site holds (AGL-3234), previewed as the contact it would be.\n const leadId = body['leadId'] === undefined ? null : readOutreachDocumentId(body['leadId'])\n if (body['leadId'] !== undefined && !leadId) {\n return outreachRefusal(400, 'invalid-request', 'Name the lead to preview for.')\n }\n const caller = await outreachRouteGate(\n request,\n body['orgId'],\n deps.gate,\n contactId || leadId ? [OUTREACH_READS_PEOPLE] : [],\n )\n if (caller instanceof Response) return caller\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to preview.')\n const firestore = deps.firestore()\n const snapshot = await outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(sequenceId).get()\n const sequence = readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n\n // Where the enrollment would begin (AGL-3228): the email written is the\n // first one sent from there, and it starts the thread.\n const start = readOutreachStartStepIndex(body['startStepIndex'], sequence.steps)\n if (start.refusal !== null) return outreachRefusal(400, 'invalid-start-step', start.refusal)\n const startStepIndex = start.startStepIndex\n const requested = body['stepIndex']\n const stepIndex =\n typeof requested === 'number' ? requested : firstEmailStepIndex(sequence.steps, startStepIndex)\n const step = sequence.steps[stepIndex]\n if (step?.kind !== 'email') {\n return outreachRefusal(\n 400,\n 'invalid-request',\n stepIndex < 0 && startStepIndex > 0\n ? `No email is sent from step ${startStepIndex + 1} on.`\n : 'That step does not send an email.',\n )\n }\n // The person's copies of steps as the dialog holds them (AGL-3324): the\n // preview shows the curated version, held to the rules a stored one is —\n // and a test send (AGL-3325) sends it.\n const overrides = readOutreachStepOverrideRequests(\n body['stepOverrides'],\n sequence.steps,\n { uid: caller.uid, nowMs: deps.now() },\n startStepIndex,\n )\n if (outreachStepOverridesRefused(overrides)) {\n return outreachRefusal(\n 400,\n 'invalid-override',\n overrides.refusal ?? 'A curated step breaks a rule every sequence email keeps.',\n { issues: overrides.issues },\n )\n }\n\n // The person, as the record system keeps them (AGL-3080). A lead is one\n // org row (AGL-3275); the site is still required because a lead preview is\n // rendered in a site's context.\n const person = contactId\n ? ({ kind: 'contact', id: contactId } as const)\n : leadId && sequence.hostId\n ? ({ kind: 'lead', id: leadId } as const)\n : null\n const [orgSettings, mailboxSnapshot, host, templateBody, people] = await Promise.all([\n readOutreachComplianceSettingsDoc(firestore, caller.orgId),\n sequence.mailboxId ? outreachOrgCollection(firestore, caller.orgId, 'mailboxes').doc(sequence.mailboxId).get() : null,\n sequence.hostId ? firestore.collection('hosts').doc(sequence.hostId).get() : null,\n step.templateId ? readOutreachTemplateBody(caller.orgId, step.templateId) : null,\n person ? readPluginPeople({ orgId: caller.orgId, records: [person] }) : null,\n ])\n const record = people?.[0] ?? null\n const leadData = person?.kind === 'lead' && record ? { ...record.data } : null\n if (leadId && !leadData) {\n return outreachRefusal(404, 'contact-not-found', \"That lead isn't in this sequence's site's CRM.\")\n }\n const contactGroupId = consentGroupForHost(caller.org, sequence.hostId).groupId\n const contactData =\n person?.kind === 'contact' && record\n ? { ...record.data }\n : leadData\n ? leadAsContact(leadData, contactGroupId)\n : null\n if (\n contactId &&\n (!contactData || !visibleToHost(contactData['visibleTo'] as string[] | undefined, sequence.hostId))\n ) {\n return outreachRefusal(404, 'contact-not-found', \"That contact isn't in this sequence's site's CRM.\")\n }\n const mailbox = readStoredOutreachMailbox(\n sequence.mailboxId,\n mailboxSnapshot?.exists ? mailboxSnapshot.data() : undefined,\n )\n const sender = mailbox ? { name: mailbox.displayName, email: mailbox.sendAs || mailbox.email } : null\n const siteName = host?.exists ? String(host.get('name') ?? '') : ''\n const merge = contactData\n ? {\n contact: contactData,\n contactGroupId,\n lead: leadData,\n sender,\n site: { name: siteName },\n }\n : outreachSampleMergeContext({ sender, siteName })\n const personalLine =\n typeof body['personalLine'] === 'string'\n ? body['personalLine']\n : contactData\n ? ''\n : OUTREACH_SAMPLE_PERSON.personalLine\n return {\n caller,\n sequence,\n stepIndex,\n step,\n mailbox,\n input: {\n steps: sequence.steps,\n stepIndex,\n orgSettings,\n merge,\n email: contactData ? (normalizeContactEmail(contactData['email']) ?? '') : OUTREACH_SAMPLE_PERSON.email,\n personalLine,\n templateBody,\n stepOverrides: overrides.overrides,\n ...(startStepIndex > 0 ? { startStepIndex } : {}),\n },\n }\n}\n\nexport function createOutreachPreviewRoute(deps: OutreachRouteDeps): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const loaded = await readOutreachStepRender(deps, request, body)\n if (loaded instanceof Response) return loaded\n const result = previewOutreachStep(loaded.input)\n return outreachOk({\n ok: true,\n stepIndex: loaded.stepIndex,\n subject: result.email?.subject ?? '',\n text: result.email?.text ?? '',\n unresolvedFields: result.unresolvedFields,\n error: result.error,\n } satisfies OutreachPreviewResponse)\n }\n}\n"],"names":["consentGroupForHost","normalizeContactEmail","visibleToHost","readPluginPeople","readOutreachStartStepIndex","firstEmailStepIndex","leadAsContact","readOutreachTemplateBody","outreachStepOverridesRefused","readOutreachStepOverrideRequests","OUTREACH_SAMPLE_PERSON","outreachSampleMergeContext","previewOutreachStep","readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_READS_PEOPLE","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","readOutreachStepRender","deps","request","body","host","contactId","undefined","leadId","caller","gate","Response","sequenceId","firestore","snapshot","orgId","doc","get","sequence","exists","data","start","steps","refusal","startStepIndex","requested","stepIndex","step","kind","overrides","uid","nowMs","now","issues","person","id","hostId","orgSettings","mailboxSnapshot","templateBody","people","Promise","all","mailboxId","collection","templateId","records","record","leadData","contactGroupId","org","groupId","contactData","mailbox","sender","name","displayName","email","sendAs","siteName","String","merge","contact","lead","site","personalLine","input","stepOverrides","createOutreachPreviewRoute","result","method","loaded","ok","subject","text","unresolvedFields","error"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,gBAAgB,QAAQ,oDAAmD;AAEpF,SAASC,0BAA0B,QAAQ,gCAA4B;AACvE,SAASC,mBAAmB,QAAQ,mCAA+B;AACnE,SAASC,aAAa,QAAQ,iCAA6B;AAC3D,SAASC,wBAAwB,QAAQ,qCAAiC;AAC1E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,kCAA8B;AAG7G,SACEC,sBAAsB,EACtBC,0BAA0B,EAC1BC,mBAAmB,QAEd,2BAAuB;AAC9B,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,qBAAqB,QAAQ,qBAAiB;AAEvD,SAASC,iBAAiB,QAAkC,kBAAc;AAC1E,SACEC,wBAAwB,EACxBC,UAAU,EACVC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,QACf,kBAAc;AAkCrB;;;CAGC,GACD,OAAO,eAAeC,uBACpBC,IAAuB,EACvBC,OAAgB,EAChBC,IAA6B;cAmGUC,WA2Bb3B;IA5H1B,MA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,CAAC,eAAe,GACpBgD,cACE,KACAjE,uBAAuB8E,YAAY;IAC3C,OAAO;QACLxD;QACAS;QACAQ;QACAC;QACA0B;QACAa,OAAO;YACL5C,OAAOJ,SAASI,KAAK;YACrBI;YACAW;YACAwB;YACAJ,OAAOL,eAAe1E,yBAAAA,sBAAsB0E,WAAW,CAAC,QAAQ,aAA1C1E,yBAA+C,KAAMS,uBAAuBsE,KAAK;YACvGQ;YACA1B;YACA4B,eAAetC,UAAUA,SAAS;WAC9BL,iBAAiB,IAAI;YAAEA;QAAe,IAAI,CAAC;IAEnD;AACF;AAEA,OAAO,SAAS4C,2BAA2BlE,IAAuB;IAChE,OAAO,OAAOC;;YASDkE,eACHA;QATR,IAAIlE,QAAQmE,MAAM,KAAK,QAAQ,OAAO1E,yBAAyB;QAC/D,MAAMQ,OAAO,MAAMJ,qBAAqBG;QACxC,MAAMoE,SAAS,MAAMtE,uBAAuBC,MAAMC,SAASC;QAC3D,IAAImE,kBAAkB5D,UAAU,OAAO4D;QACvC,MAAMF,SAAShF,oBAAoBkF,OAAOL,KAAK;QAC/C,OAAOrE,WAAW;YAChB2E,IAAI;YACJ9C,WAAW6C,OAAO7C,SAAS;YAC3B+C,OAAO,WAAEJ,gBAAAA,OAAOZ,KAAK,qBAAZY,cAAcI,OAAO,mBAAI;YAClCC,IAAI,YAAEL,iBAAAA,OAAOZ,KAAK,qBAAZY,eAAcK,IAAI,oBAAI;YAC5BC,kBAAkBN,OAAOM,gBAAgB;YACzCC,OAAOP,OAAOO,KAAK;QACrB;IACF;AACF"}
|
|
@@ -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
|
-
*/ import {
|
|
16
|
+
*/ import { creditConversionOutcome } from "@aglyn/aglyn/plugin-manager/plugin-conversion-credit";
|
|
17
|
+
import { pluginRecordTimelineWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-timeline";
|
|
17
18
|
import { pluginTextGenerator } from "@aglyn/aglyn/plugin-manager/plugin-text-generation";
|
|
18
19
|
import { registerPluginApiRoute } from "@aglyn/aglyn/server";
|
|
19
20
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
@@ -64,18 +65,19 @@ export function defaultOutreachRouteDeps() {
|
|
|
64
65
|
now: Date.now,
|
|
65
66
|
random: Math.random,
|
|
66
67
|
logOrgActivity: async (orgId, actor, action, target)=>(await platform()).logOrgActivity(orgId, actor, action, target),
|
|
67
|
-
crmViewEmails: async (input)=>(await platform()).crmViewEmails(input),
|
|
68
68
|
stampRecordEmailState: async (stamp)=>{
|
|
69
69
|
await (await platform()).stampRecordEmailState(stamp);
|
|
70
70
|
},
|
|
71
|
+
// Through the plugin that credits outcomes (`plugin-conversion-credit`),
|
|
72
|
+
// which never throws and answers nothing where no plugin credits them.
|
|
71
73
|
creditCampaign: async ({ hostId, orgId, campaignIds, outcome, atMs })=>{
|
|
72
|
-
await (
|
|
74
|
+
await creditConversionOutcome({
|
|
73
75
|
hostId,
|
|
74
76
|
orgId,
|
|
75
|
-
campaignIds,
|
|
77
|
+
containerIds: campaignIds,
|
|
76
78
|
outcome,
|
|
77
79
|
atMs
|
|
78
|
-
}
|
|
80
|
+
});
|
|
79
81
|
},
|
|
80
82
|
// The record system's writer (AGL-3274), resolved per call the way the
|
|
81
83
|
// runtime resolves it: the CRM registers at boot, and a request that
|