@aglyn/plugins-outreach 1.0.0-beta.195 → 1.0.0-beta.196
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/curate-step-dialog.d.ts +50 -0
- package/src/lib/components/curate-step-dialog.js +235 -0
- package/src/lib/components/curate-step-dialog.js.map +1 -0
- package/src/lib/components/curated-step-editor.d.ts +80 -0
- package/src/lib/components/curated-step-editor.js +255 -0
- package/src/lib/components/curated-step-editor.js.map +1 -0
- package/src/lib/components/enroll-dialog.d.ts +15 -0
- package/src/lib/components/enroll-dialog.js +154 -13
- package/src/lib/components/enroll-dialog.js.map +1 -1
- package/src/lib/components/enrollments-table.d.ts +2 -0
- package/src/lib/components/enrollments-table.js +62 -8
- package/src/lib/components/enrollments-table.js.map +1 -1
- package/src/lib/components/use-outreach-api.d.ts +8 -1
- package/src/lib/components/use-outreach-api.js +12 -0
- package/src/lib/components/use-outreach-api.js.map +1 -1
- package/src/lib/constants/api-routes.d.ts +8 -0
- package/src/lib/constants/api-routes.js +6 -0
- package/src/lib/constants/api-routes.js.map +1 -1
- package/src/lib/engine/compose.d.ts +12 -2
- package/src/lib/engine/compose.js +32 -6
- package/src/lib/engine/compose.js.map +1 -1
- package/src/lib/engine/curation-prompt.d.ts +73 -0
- package/src/lib/engine/curation-prompt.js +151 -0
- package/src/lib/engine/curation-prompt.js.map +1 -0
- package/src/lib/engine/enrollment-activity.d.ts +24 -0
- package/src/lib/engine/enrollment-activity.js +25 -0
- package/src/lib/engine/enrollment-activity.js.map +1 -1
- package/src/lib/engine/sequence-validation.d.ts +10 -1
- package/src/lib/engine/sequence-validation.js +54 -0
- package/src/lib/engine/sequence-validation.js.map +1 -1
- package/src/lib/enrollment/step-overrides.d.ts +53 -0
- package/src/lib/enrollment/step-overrides.js +140 -0
- package/src/lib/enrollment/step-overrides.js.map +1 -0
- package/src/lib/model/outreach-api.d.ts +69 -2
- package/src/lib/model/outreach-api.js.map +1 -1
- package/src/lib/model/outreach.types.d.ts +36 -0
- package/src/lib/model/outreach.types.js +18 -0
- package/src/lib/model/outreach.types.js.map +1 -1
- package/src/lib/model/step-preview.d.ts +3 -1
- package/src/lib/model/step-preview.js +6 -3
- package/src/lib/model/step-preview.js.map +1 -1
- package/src/lib/model/stored-records.d.ts +9 -1
- package/src/lib/model/stored-records.js +47 -2
- package/src/lib/model/stored-records.js.map +1 -1
- package/src/lib/routes/curate-routes.d.ts +63 -0
- package/src/lib/routes/curate-routes.js +424 -0
- package/src/lib/routes/curate-routes.js.map +1 -0
- package/src/lib/routes/enroll-routes.d.ts +7 -0
- package/src/lib/routes/enroll-routes.js +58 -4
- package/src/lib/routes/enroll-routes.js.map +1 -1
- package/src/lib/routes/preview-routes.js +15 -1
- package/src/lib/routes/preview-routes.js.map +1 -1
- package/src/lib/routes/register-routes.js +17 -0
- package/src/lib/routes/register-routes.js.map +1 -1
- package/src/lib/runtime/send-job.js +2 -0
- package/src/lib/runtime/send-job.js.map +1 -1
|
@@ -234,6 +234,24 @@ export const OUTREACH_TASK_KIND_LABELS = {
|
|
|
234
234
|
verified_deliverable: 'This address was verified as deliverable'
|
|
235
235
|
};
|
|
236
236
|
/** The longest personal line an enrollment keeps: one sentence, not a letter. */ export const OUTREACH_PERSONAL_LINE_MAX = 300;
|
|
237
|
+
/*==========================================
|
|
238
|
+
* CURATED STEPS (AGL-3324).
|
|
239
|
+
*
|
|
240
|
+
* A step is one template for everyone, plus the personal line. Curating
|
|
241
|
+
* rewrites ONE person's copy of a step — drafted by the workspace's AI from
|
|
242
|
+
* their record and the step's own body as the skeleton, or written by the
|
|
243
|
+
* member — and keeps it on the enrollment, never on the sequence. The send
|
|
244
|
+
* job reads the override in place of the step's subject and body; the
|
|
245
|
+
* tokens, the footer, the click tracking and the plain-text rules still
|
|
246
|
+
* apply to it exactly as they apply to the step.
|
|
247
|
+
*
|
|
248
|
+
* Nothing is stored that a member has not read: a draft lands on the
|
|
249
|
+
* enrollment only when the member confirms it, with who and when.
|
|
250
|
+
*==========================================*/ /** Who wrote the override: the AI, or the member by hand. */ export const OUTREACH_STEP_OVERRIDE_SOURCES = [
|
|
251
|
+
'ai',
|
|
252
|
+
'member'
|
|
253
|
+
];
|
|
254
|
+
/** The sentence a member ticks before a curated draft is stored — a fourth attestation. */ export const OUTREACH_CURATION_CONFIRMATION_LABEL = "I've read this draft, and it goes out to this person as written";
|
|
237
255
|
/**
|
|
238
256
|
* Which CRM record an enrollment names (AGL-3234). A person is a LEAD until
|
|
239
257
|
* somebody qualifies them and a CONTACT after, and a sequence works either:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/outreach.types.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE OUTREACH DOCUMENT MODEL (AGL-2974).\n *\n * One file both halves import — the console reads these documents, the server\n * routes write them — so a field is spelled once. Client-safe: types and\n * constants only, nothing that reaches Firestore.\n *\n * EVERY DOCUMENT HERE IS SERVER-WRITTEN. The Firestore rules let an\n * org-wide member holding `outreach.use` READ the org collections on a\n * workspace that carries `features.outreach`, and refuse every client write,\n * because these documents are the sending engine's state: a client that\n * could write a mailbox could lift its daily cap, and one that could write\n * an enrollment could send a step twice. The credential collection is closed\n * to clients entirely.\n *\n * Lean on purpose. Each type carries what the mailbox and sequence work is\n * known to need and nothing speculative; a field is added where the code\n * that reads it lands. Times are epoch milliseconds throughout, the unit\n * `nextDueAtMs` has to be compared in.\n */\n\n/**\n * Where Outreach keeps its records.\n *\n * Six collections under the organization, and two at the top level. The\n * org-scoped ones are erased with the org, whose erasure deletes the whole\n * `orgs/{orgId}` tree. The top-level ones — credentials, and the short\n * tracking links (AGL-3297) — are keyed by an `orgId` FIELD that a\n * path-scoped delete of `orgs/{orgId}` cannot see: the org erasure sweeps\n * them by that field\n * (`libs/tenant/data/admin/src/lib/server/erase.ts` names it as a literal,\n * which the boundary forces, and `outreach.types.spec.ts` holds the two\n * spellings together, along with the rules').\n */\nexport const OUTREACH_COLLECTIONS = {\n /** `orgs/{orgId}/outreachMailboxes/{mailboxId}` — a connected mailbox. */\n mailboxes: 'outreachMailboxes',\n /** `orgs/{orgId}/outreachSequences/{sequenceId}` — the steps to send. */\n sequences: 'outreachSequences',\n /** `orgs/{orgId}/outreachEnrollments/{enrollmentId}` — one person in one sequence. */\n enrollments: 'outreachEnrollments',\n /**\n * `orgs/{orgId}/outreachSettings/{settingsId}` — the organization's own\n * Outreach settings, one document per concern. `compliance` holds who\n * every email says sent it and the countries Outreach may send to.\n */\n settings: 'outreachSettings',\n /**\n * `orgs/{orgId}/outreachDoNotContact/{key}` — the addresses Outreach never\n * emails for this organization, keyed by `outreachDoNotContactKey`.\n */\n doNotContact: 'outreachDoNotContact',\n /**\n * `orgs/{orgId}/outreachDoNotContactDomains/{domain}` — the domains\n * Outreach never emails for this organization (AGL-3244), keyed by the\n * domain itself: a domain names a company, not a person.\n */\n doNotContactDomains: 'outreachDoNotContactDomains',\n /**\n * `outreachMailboxCredentials/{mailboxId}` — the provider grant behind a\n * mailbox. TOP-LEVEL and closed to every client, staff included, so the\n * token material never shares a readable path with the mailbox it serves.\n */\n mailboxCredentials: 'outreachMailboxCredentials',\n /**\n * `outreachLinks/{linkId}` — what one short tracking link in a sent email\n * points at (AGL-3297): the organization, the enrollment, the step, the\n * link's index and the destination. TOP-LEVEL so the link's id alone\n * resolves it with one read, keyed by an `orgId` FIELD that the org\n * erasure sweeps, and closed to every client.\n */\n links: 'outreachLinks',\n} as const\n\n/** The org-scoped collections, by their {@link OUTREACH_COLLECTIONS} key. */\nexport type OutreachOrgCollection = Exclude<\n keyof typeof OUTREACH_COLLECTIONS,\n 'mailboxCredentials' | 'links'\n>\n\n/** `orgs/{orgId}/<collection>` for one of the org-scoped collections. */\nexport function outreachOrgCollectionPath(\n orgId: string,\n collection: OutreachOrgCollection,\n): string {\n return `orgs/${orgId}/${OUTREACH_COLLECTIONS[collection]}`\n}\n\n/** Stamped by the server on every write. */\nexport interface OutreachTimestamps {\n createdAtMs: number\n updatedAtMs: number\n}\n\n/** The mail providers a mailbox can be connected through. */\nexport const OUTREACH_MAILBOX_PROVIDERS = ['google'] as const\nexport type OutreachMailboxProvider =\n (typeof OUTREACH_MAILBOX_PROVIDERS)[number]\n\n/**\n * Where a mailbox stands.\n *\n * - `connected` — the grant works and the mailbox may send.\n * - `paused` — a member stopped it; enrollments on it wait.\n * - `reconnect_required` — the provider refused the grant (revoked, expired,\n * password changed); nothing sends until the rep connects it again.\n * - `disconnected` — a member removed it; its credential is gone.\n */\nexport const OUTREACH_MAILBOX_STATUSES = [\n 'connected',\n 'paused',\n 'reconnect_required',\n 'disconnected',\n] as const\nexport type OutreachMailboxStatus = (typeof OUTREACH_MAILBOX_STATUSES)[number]\n\n/**\n * The hours a mailbox sends in, in its own {@link OutreachMailbox.timezone}.\n * A step that comes due outside the window waits for the next opening.\n */\nexport interface OutreachSendWindow {\n /** Days of the week it sends on, `0` Sunday through `6` Saturday. */\n days: number[]\n /** Minutes after local midnight the window opens, inclusive. */\n startMinute: number\n /** Minutes after local midnight the window closes, exclusive. */\n endMinute: number\n}\n\n/**\n * One mailbox-local day's sending, as the health panel sums it (AGL-2978).\n */\nexport interface OutreachMailboxDailyHealth {\n sent: number\n bounces: number\n replies: number\n}\n\n/**\n * The counters a mailbox's sending is judged by.\n *\n * `sentToday` is what `dailyCap` refuses against, and it belongs to one\n * mailbox-local day — `sentOnDay` — so a counter from yesterday is read as\n * zero rather than as today's spend.\n */\nexport interface OutreachMailboxHealth {\n sentToday: number\n /** The local day (`YYYY-MM-DD` in the mailbox's timezone) `sentToday` counts. */\n sentOnDay: string | null\n /** Hard bounces on mail this mailbox sent. */\n bounces: number\n /** Replies detected on Outreach threads. */\n replies: number\n lastSentAtMs: number | null\n /** The last provider error, kept until a later send succeeds. */\n lastErrorAtMs: number | null\n lastErrorCode: string | null\n /**\n * Per mailbox-local day (`YYYY-MM-DD`), the sends, bounces and replies\n * counted on it (AGL-2978). The Mailboxes panel shows the last seven days\n * summed; the sending runtime increments the day it counts on and may drop\n * days older than a week. Absent, or empty, until the first send.\n */\n daily?: Record<string, OutreachMailboxDailyHealth>\n /**\n * The mailbox's most recent sends, newest last, at most\n * `OUTREACH_BOUNCE_RATE_WINDOW_SENDS` of them, each marked when a hard\n * bounce came back for it (AGL-2981): the window the bounce-rate pause is\n * judged over. A send is named by a digest of its `Message-ID`, never by\n * its recipient.\n */\n recentSends?: OutreachRecentSend[]\n /** When a reply last called this mailbox's email spam (AGL-2981). */\n lastComplaintAtMs?: number | null\n}\n\n/** One send in {@link OutreachMailboxHealth.recentSends}. */\nexport interface OutreachRecentSend {\n /** A digest of the send's `Message-ID`: what a bounce is matched to. */\n id: string\n atMs: number\n bounced: boolean\n}\n\n/** Why a mailbox paused itself (AGL-2981): the engine's health decision, kept. */\nexport interface OutreachMailboxAutoPause {\n reason: 'bounces_today' | 'bounce_rate' | 'complaint'\n /** The sentence the mailbox's card shows. */\n message: string\n atMs: number\n /** For a complaint, when resuming stops being premature; `null` otherwise. */\n untilMs: number | null\n}\n\n/** Where a mailbox's reply and bounce sync has read to (AGL-2981). */\nexport interface OutreachMailboxSync {\n /** Everything received before this was read by an earlier run, epoch ms. */\n throughMs: number\n /** Gmail ids of messages outside any enrollment's thread already handled. */\n handledMessageIds: string[]\n}\n\n/**\n * An address a connected Google account may send as, which Gmail has\n * verified — its own address, or an alias whose ownership Gmail confirmed\n * (AGL-2978). Only these are offered as a mailbox's `sendAs`.\n */\nexport interface OutreachSendAsAddress {\n email: string\n /** The name Gmail holds for the address, `''` when it holds none. */\n displayName: string\n /** The account's own address. */\n isPrimary: boolean\n /** The address Gmail sends as by default. */\n isDefault: boolean\n}\n\n/**\n * A rep's own mailbox, connected to send Outreach mail\n * (`orgs/{orgId}/outreachMailboxes/{id}`).\n *\n * Its grant lives in {@link OutreachMailboxCredentials} under the same id.\n */\nexport interface OutreachMailbox extends OutreachTimestamps {\n id: string\n provider: OutreachMailboxProvider\n /** The account's own address. */\n email: string\n /** The address mail goes out as: the account's, or an alias it may send as. */\n sendAs: string\n /**\n * The verified addresses `sendAs` may be, as Gmail listed them at the last\n * connect (AGL-2978). A changed alias shows up here on the next reconnect.\n */\n sendAsOptions: OutreachSendAsAddress[]\n /** The From name recipients see. */\n displayName: string\n status: OutreachMailboxStatus\n /** The most mail it sends in one local day, ramp included. */\n dailyCap: number\n window: OutreachSendWindow\n /** IANA zone the window and the day boundary are read in. */\n timezone: string\n /**\n * When the warm-up ramp began, or `null` for a mailbox sending at its full\n * cap. The ramp is measured from here, not from connection, so a paused\n * mailbox can restart it.\n */\n rampStartedAtMs: number | null\n health: OutreachMailboxHealth\n /** The member who connected it, and whose mail it is. */\n connectedByUid: string\n /** When the grant behind it was last connected (AGL-2978). */\n connectedAtMs: number\n /**\n * Set when the mailbox paused ITSELF on its health (AGL-2981), and cleared\n * when a member pauses or resumes it; absent otherwise.\n */\n autoPause?: OutreachMailboxAutoPause | null\n /** The reply and bounce sync's place in the mailbox (AGL-2981). */\n sync?: OutreachMailboxSync | null\n}\n\n/**\n * The provider grant behind one mailbox\n * (`outreachMailboxCredentials/{mailboxId}`).\n *\n * Only the fields every reader relies on are declared here; the token\n * material is added by the code that stores it. `orgId` is REQUIRED, not\n * decorative: the org erasure finds these documents by it, and a credential\n * written without one would outlive its workspace.\n *\n * NAME EVERY SEALED FIELD WITH A SECRET WORD — `refreshToken`,\n * `tokenCiphertext`. The personal-data export discloses these documents with\n * secrets redacted, and its redaction reads field names first: a name\n * carrying `token`, `secret` or `credential` is withheld whatever its value,\n * while a neutral name such as `ciphertext` is judged by the value's shape\n * alone and can be disclosed.\n */\nexport interface OutreachMailboxCredentials extends OutreachTimestamps {\n /** The mailbox id, which is also this document's id. */\n id: string\n orgId: string\n mailboxId: string\n provider: OutreachMailboxProvider\n}\n\n/** A sequence's lifecycle. Only an `active` sequence advances its enrollments. */\nexport const OUTREACH_SEQUENCE_STATUSES = [\n 'draft',\n 'active',\n 'paused',\n 'archived',\n] as const\nexport type OutreachSequenceStatus =\n (typeof OUTREACH_SEQUENCE_STATUSES)[number]\n\n/*==========================================\n * SEQUENCES (AGL-2979).\n *\n * The limits are the outbound playbook's: a person gets at most four emails\n * from one sequence, spaced by business days, and the tasks between them are\n * the rep's own touches — a LinkedIn note, a call. The engine\n * (`../engine/sequence-validation.ts`) holds a stored sequence to them.\n *==========================================*/\n\n/** The most steps one sequence holds, emails and tasks together. */\nexport const OUTREACH_MAX_STEPS = 8\n\n/** The most of those steps that send an email. */\nexport const OUTREACH_MAX_EMAIL_STEPS = 4\n\n/** The longest wait one step may carry, in business days. */\nexport const OUTREACH_MAX_STEP_DELAY_BUSINESS_DAYS = 30\n\n/**\n * The shortest wait before an email that follows an earlier email. The first\n * email may wait `0` — \"the next opening of the window\", or the same day as\n * a task before it — and so may a task, but each later email waits at least\n * this long after the step before it.\n */\nexport const OUTREACH_MIN_EMAIL_FOLLOW_UP_BUSINESS_DAYS = 1\n\n/**\n * One email step.\n *\n * Steps are a union on `kind`, so a later kind joins without reshaping the\n * ones already stored.\n */\nexport interface OutreachEmailStep {\n /** Stable within the sequence, so an edit that reorders steps is traceable. */\n id: string\n kind: 'email'\n /**\n * Business days to wait after the previous step, counted in the mailbox's\n * zone — after enrollment for the first step, where `0` means the next\n * opening of the sending window.\n */\n delayBusinessDays: number\n /**\n * The subject, merge fields allowed. Required on the first email and on\n * any email that starts a new thread; an in-thread email is sent as `Re:`\n * the thread's own subject, so its field is not read.\n */\n subject: string\n /**\n * Whether the email goes out as a reply in the thread the earlier emails\n * started. True by default for every email after the first; the first\n * email always starts the thread, whatever this says.\n */\n replyInThread: boolean\n /** Plain text with merge fields, as its author wrote it; `''` when `templateId` is set. */\n body: string\n /**\n * A CRM email template (`orgs/{orgId}/crmEmailTemplates/{id}`) whose body\n * is sent instead of `body`, or `null`. Only the body is taken from it: the\n * step's own subject is the one that is sent.\n */\n templateId: string | null\n}\n\n/** The rep's own touches a task step asks for. */\nexport const OUTREACH_TASK_KINDS = ['linkedin', 'call', 'todo'] as const\nexport type OutreachTaskKind = (typeof OUTREACH_TASK_KINDS)[number]\n\nexport const OUTREACH_TASK_KIND_LABELS: Record<OutreachTaskKind, string> = {\n linkedin: 'LinkedIn',\n call: 'Call',\n todo: 'To-do',\n}\n\n/** One task step: a CRM task for the rep, created when the step comes due. */\nexport interface OutreachTaskStep {\n id: string\n kind: 'task'\n taskKind: OutreachTaskKind\n /** What the task says, e.g. \"Connect on LinkedIn\". */\n title: string\n /** Business days after the previous step; `0` is the same day. */\n delayBusinessDays: number\n}\n\nexport type OutreachSequenceStep = OutreachEmailStep | OutreachTaskStep\n\n/** The countries a new sequence sends to: the United States alone. */\nexport const OUTREACH_DEFAULT_ALLOWED_COUNTRIES: readonly string[] = ['US']\n\n/** Behavior a sequence applies to every enrollment in it. */\nexport interface OutreachSequenceSettings {\n /**\n * The hours this sequence sends in, replacing its mailbox's own window;\n * `null` sends in the mailbox's. Read in the mailbox's zone either way.\n */\n window: OutreachSendWindow | null\n /**\n * ISO-3166-1 alpha-2 codes a recipient may be in, uppercase. Default\n * {@link OUTREACH_DEFAULT_ALLOWED_COUNTRIES}: Canada, the United Kingdom\n * and most of the EU need a consent basis a cold email does not have.\n */\n allowedCountries: string[]\n /** Whether a contact who is already a customer may be enrolled. Default `false`. */\n allowCustomers: boolean\n /**\n * Whether the links in this sequence's emails are rewritten so clicks are\n * counted (AGL-3239). Default `false`, and `false` on every sequence\n * written before the setting existed: turning it on changes what the\n * recipient sees in the body, which is not a change to make on anyone's\n * behalf.\n *\n * It buys the one engagement number a plain-text sequence can honestly\n * report. It costs a visible link: the destination in the body becomes a\n * signed link on the console that forwards to it. There is no equivalent\n * setting for opens, because a pixel needs an HTML part — see\n * `../engine/click-tracking.ts`.\n */\n trackClicks: boolean\n /**\n * Whether this sequence's emails carry `List-Unsubscribe` and\n * `List-Unsubscribe-Post` (RFC 8058) (AGL-3296). Default `false`, and\n * `false` on every sequence written before the setting existed.\n *\n * On, mail clients draw their own unsubscribe button — Apple Mail as \"This\n * message is from a mailing list\" — which is the easiest way out for the\n * recipient and makes a one-to-one email read as bulk. Off, the footer's\n * \"reply 'no'\" line is the way out; the footer and its postal address are\n * mandatory either way, and the reply classifier stops on a \"no\". The\n * Gmail/Yahoo one-click requirement binds bulk senders (5,000 a day), not a\n * mailbox sending a sequence.\n */\n listUnsubscribe: boolean\n}\n\n/*==========================================\n * WHAT A SEQUENCE MEASURED (AGL-3239).\n *\n * Counters on the sequence document, incremented by the sending runtime and\n * by the click route. They are NOT derived from the enrollments on read: the\n * console lists enrollments a page at a time, so a rollup taken over what is\n * loaded would report the first page's numbers as the sequence's.\n *\n * Every field is optional and every absence means \"not recorded\", never\n * zero. The distinction is the whole of `campaign-report.ts`'s honesty and\n * it is kept here for the same reason: a sequence that ran before this\n * existed has no counters, and reporting its click rate as 0% would publish\n * a fact about our schema as a fact about its recipients.\n *=========================================*/\n\n/**\n * The per-destination click rollup under one sequence:\n * `orgs/{orgId}/outreachSequences/{id}/reports/links`.\n *\n * One document per sequence, holding a bounded map — the campaign rollup's\n * own shape and its own cap, so \"a link\" means the same thing in a rep's\n * report and a marketer's. Here rather than beside the writer, because the\n * console's listener is a browser module and the writer is not.\n */\nexport const OUTREACH_LINK_ROLLUP_PATH = ['reports', 'links'] as const\n\n/** The counters one sequence is judged by. */\nexport interface OutreachSequenceStats {\n /** Email steps that left. One person getting four emails counts four. */\n sent?: number\n /**\n * Distinct enrollments that have had at least one email — the denominator\n * of every engagement rate, and the thing `sent` is not.\n */\n people?: number\n /**\n * At least one email of this sequence went out with its links rewritten.\n *\n * Absent is NOT false; it is \"never recorded\", which is what every\n * sequence sent before the setting existed reads as. Either way the report\n * withholds the click rate rather than showing 0% — see\n * {@link OutreachSequenceStats} above.\n */\n clickTracked?: boolean\n /** Click EVENTS judged a person's. One reader clicking twice counts two. */\n clicks?: number\n /** Enrollments whose FIRST human click was seen: the rate's numerator. */\n uniqueClicks?: number\n /**\n * Clicks a link scanner or a security gateway made, counted apart and\n * never in the rate (`../engine/click-tracking.ts`). Shown, not hidden:\n * a large number here is the reader's evidence that the small number\n * beside it is the real one.\n */\n machineClicks?: number\n /** When a person last followed a link. */\n lastClickAtMs?: number | null\n}\n\n/** What one enrollment did with the links it was sent (AGL-3239). */\nexport interface OutreachEnrollmentEngagement {\n /** Click events judged this person's, machines excluded. */\n clicks: number\n /** The first, which is what makes them one of the sequence's `uniqueClicks`. */\n firstClickAtMs: number | null\n lastClickAtMs: number | null\n /** The destination they followed last, as `campaignLinkKey` reduces it. */\n lastClickUrl: string | null\n /** Clicks on this person's links that were a machine's. */\n machineClicks: number\n}\n\n/** An ordered set of steps sent from one mailbox (`orgs/{orgId}/outreachSequences/{id}`). */\nexport interface OutreachSequence extends OutreachTimestamps {\n id: string\n name: string\n /** The site whose CRM the enrolled people are records of. */\n hostId: string\n /**\n * The mailbox every email step is sent from. A setting of the sequence,\n * kept beside `settings` rather than inside it because enrollments and a\n * mailbox's own screens select sequences by it.\n */\n mailboxId: string\n steps: OutreachSequenceStep[]\n settings: OutreachSequenceSettings\n status: OutreachSequenceStatus\n /**\n * The campaigns the sequence is in (AGL-3254): container ids from the\n * org's `emailCampaigns`, under the field every campaign member carries\n * (`CAMPAIGN_MEMBERSHIP_FIELD`). Everyone enrolled gains them on their\n * own record at enroll time, and what the sequence produces is credited\n * to them. Absent on a sequence saved before it could join one.\n */\n campaignIds?: string[]\n /**\n * What it measured (AGL-3239). Absent until the first email leaves, and\n * absent forever on a sequence that finished before the counters existed.\n */\n stats?: OutreachSequenceStats\n}\n\n/*==========================================\n * ENROLLMENTS (AGL-2979).\n *==========================================*/\n\n/**\n * Where one person's run through a sequence stands.\n *\n * `active` sends and `paused` waits. The rest end the sending, and each says\n * why: `finished` sent every step, `replied` heard back, `bounced` reached a\n * mailbox that does not exist, `opted_out` was asked to stop, `stopped` was\n * ended by a member or a gate, `failed` could not be sent. The transitions\n * between them are the engine's (`../engine/enrollment-state.ts`).\n */\nexport const OUTREACH_ENROLLMENT_STATUSES = [\n 'active',\n 'paused',\n 'finished',\n 'replied',\n 'bounced',\n 'opted_out',\n 'stopped',\n 'failed',\n] as const\nexport type OutreachEnrollmentStatus =\n (typeof OUTREACH_ENROLLMENT_STATUSES)[number]\n\n/**\n * Why an enrollment is not `active`, recorded beside the status. `finished`\n * needs none; each other status allows the reasons\n * `OUTREACH_STOP_REASONS_BY_STATUS` names.\n */\nexport const OUTREACH_STOP_REASONS = [\n /** A person wrote back in the thread. */\n 'reply',\n /** The recipient's server refused the address for good. */\n 'hard_bounce',\n /** A reply asked not to be emailed again. */\n 'opt_out_reply',\n /** The unsubscribe link or header was used. */\n 'unsubscribe',\n /** The address is on the organization's do-not-contact list. */\n 'do_not_contact',\n /** A gate refused the next send — the person became a customer, say. */\n 'gate',\n /** A member paused or stopped it. */\n 'manual',\n /** The sequence was archived with the person still in it. */\n 'sequence_archived',\n /** The provider refused the send for good, or the email could not be composed. */\n 'send_failed',\n] as const\nexport type OutreachStopReason = (typeof OUTREACH_STOP_REASONS)[number]\n\n/** The statuses a stop reason is recorded with, and the reasons each allows. */\nexport const OUTREACH_STOP_REASONS_BY_STATUS: Readonly<\n Record<\n Exclude<OutreachEnrollmentStatus, 'active' | 'finished'>,\n readonly OutreachStopReason[]\n >\n> = {\n paused: ['manual'],\n replied: ['reply'],\n bounced: ['hard_bounce'],\n opted_out: ['opt_out_reply', 'unsubscribe', 'do_not_contact'],\n stopped: ['manual', 'gate', 'sequence_archived'],\n failed: ['send_failed'],\n}\n\n/**\n * What a rep confirms before a COLD contact is enrolled — one with no\n * inbound capture behind them — each recorded with who confirmed it and\n * when, because each is a fact only the rep can know:\n *\n * - `us_business_address`: the address is a business address in the US;\n * - `published_or_given`: they or their company published it, or they gave\n * it to us — never guessed from a name or bought on a list;\n * - `verified_deliverable`: a verifier said it accepts mail.\n */\nexport const OUTREACH_ATTESTATION_KINDS = [\n 'us_business_address',\n 'published_or_given',\n 'verified_deliverable',\n] as const\nexport type OutreachAttestationKind = (typeof OUTREACH_ATTESTATION_KINDS)[number]\n\n/** The sentence a rep ticks for each attestation. */\nexport const OUTREACH_ATTESTATION_LABELS: Record<OutreachAttestationKind, string> = {\n us_business_address: 'This is a US business address',\n published_or_given:\n 'They or their company published this address, or they gave it to us',\n verified_deliverable: 'This address was verified as deliverable',\n}\n\n/** One confirmation, as stored. */\nexport interface OutreachAttestation {\n /** The member who confirmed it. */\n uid: string\n atMs: number\n}\n\n/** The confirmations an enrollment carries, by kind. */\nexport type OutreachAttestations = Partial<\n Record<OutreachAttestationKind, OutreachAttestation>\n>\n\n/** The longest personal line an enrollment keeps: one sentence, not a letter. */\nexport const OUTREACH_PERSONAL_LINE_MAX = 300\n\n/**\n * Which CRM record an enrollment names (AGL-3234). A person is a LEAD until\n * somebody qualifies them and a CONTACT after, and a sequence works either:\n * an enrollment made on a lead follows the lead to the contact it becomes,\n * so the thread and the steps carry on as one enrollment.\n */\nexport const OUTREACH_ENROLLMENT_TARGETS = ['contact', 'lead'] as const\nexport type OutreachEnrollmentTarget = (typeof OUTREACH_ENROLLMENT_TARGETS)[number]\n\n/** One person in one sequence (`orgs/{orgId}/outreachEnrollments/{id}`). */\nexport interface OutreachEnrollment extends OutreachTimestamps {\n id: string\n sequenceId: string\n /**\n * The record the person is (AGL-3234): `contact` for a CRM contact,\n * `lead` for a lead the sequence's site holds. A stored enrollment with\n * no target is a contact's — every enrollment was, before leads could be\n * sequenced.\n */\n target: OutreachEnrollmentTarget\n /**\n * The CRM contact the person is — `''` while the enrollment targets a\n * lead that has not converted. Filled in, beside `target: 'contact'`, the\n * moment the lead becomes a contact.\n */\n contactId: string\n /**\n * `hosts/{hostId}/leads/{leadId}` — the person key — for an enrollment\n * made on a lead; kept once the lead converts, so the lead's page still\n * lists the sequence. `null` for an enrollment made on a contact.\n */\n leadId: string | null\n /**\n * The person's name as the sending site knew it at enrollment, `''` when\n * it had none — what the enrollments table shows beside the address,\n * without a read of every record on the page (AGL-2980).\n */\n contactName: string\n /** The address the steps go to, normalized, captured at enrollment. */\n email: string\n hostId: string\n mailboxId: string\n /** The index into `steps` of the NEXT step to run. */\n stepIndex: number\n /** When that step comes due, or `null` when nothing is waiting. */\n nextDueAtMs: number | null\n status: OutreachEnrollmentStatus\n /** Why the status is not `active`; `null` while active and once finished. */\n stopReason: OutreachStopReason | null\n /** Plain-language detail: the gate's reason, the bounce's diagnostic. */\n stopDetail: string | null\n stoppedAtMs: number | null\n /** The member who paused or stopped it; `null` when the engine did. */\n stoppedByUid: string | null\n /**\n * The rep's signal sentence — why this person, now — merged into the\n * steps as `{{enrollment.personalLine}}`. Required for a cold contact.\n */\n personalLine: string\n /** Whether the contact was cold (no inbound capture) when enrolled. */\n cold: boolean\n attestations: OutreachAttestations\n /** The member who enrolled the person. */\n enrolledByUid: string\n /** The provider thread the next in-thread email is sent into, once one exists. */\n gmailThreadId: string | null\n /** Every provider thread this enrollment has sent into, oldest first — what reply sync watches. */\n gmailThreadIds: string[]\n /** The subject the current thread was started with, as sent. */\n threadSubject: string | null\n /**\n * The `Message-ID`s of the emails sent into the current thread, oldest\n * first, angle brackets included: the next in-thread email answers the\n * last and names them all in `References`.\n */\n messageIds: string[]\n /** When the last step ran. */\n lastSentAtMs: number | null\n /**\n * A sending run's hold on the step it is running (AGL-2981): taken in a\n * transaction before the step runs, cleared when it is recorded. Absent\n * or `null` while no run holds one.\n */\n sendClaim?: OutreachSendClaim | null\n /** Every step the runtime ran, oldest first (AGL-2981). */\n stepRecords?: OutreachStepRecord[]\n /** Gmail ids of this enrollment's thread messages the sync has handled, the last hundred. */\n syncedMessageIds?: string[]\n /**\n * What this person did with the links they were sent (AGL-3239). Absent\n * until their first click, which is why the table reads an absence as\n * \"no clicks\" only for a sequence that tracks them at all.\n */\n engagement?: OutreachEnrollmentEngagement\n /**\n * The sequence's campaigns as they stood when the person was enrolled\n * (AGL-3254): what every outcome of this enrollment is credited to. A\n * campaign the sequence joins later does not claim the people already\n * in it, and one it leaves keeps what it was credited with.\n */\n campaignIds?: string[]\n}\n\n/** A sending run's claim on one enrollment's step (AGL-2981). */\nexport interface OutreachSendClaim {\n /** The run that holds it. */\n token: string\n atMs: number\n stepIndex: number\n /**\n * The `Message-ID` an email step goes out with, minted before the send, so\n * a claim a run died holding is settled by looking for the message rather\n * than by sending it again. `null` for a task step.\n */\n messageId: string | null\n}\n\n/** One step the runtime ran for an enrollment (AGL-2981). */\nexport interface OutreachStepRecord {\n stepIndex: number\n stepId: string\n kind: 'email' | 'task'\n atMs: number\n /** Gmail's id for the sent message. */\n gmailMessageId?: string\n /** Gmail's thread the message went into. */\n gmailThreadId?: string\n /** The `Message-ID` it went out with, angle brackets included. */\n messageId?: string\n /** The subject as sent. */\n subject?: string\n /** The record system's task for a task step; `null` when none could be filed. */\n taskId?: string | null\n /**\n * The destinations this email's links were rewritten to point at, in the\n * order a click token indexes them (AGL-3239). Absent on a step that\n * carried no links, and on every step sent before tracking existed.\n *\n * Kept so the console can say WHICH link a person followed without the\n * token having to carry the URL back to us, and so a rewritten body can be\n * read afterwards for what it actually offered them.\n */\n links?: string[]\n}\n\n/*==========================================\n * ORGANIZATION SETTINGS (AGL-2979).\n *==========================================*/\n\n/**\n * What every Outreach email's footer says about who sent it — the\n * identification and the postal address CAN-SPAM requires on commercial\n * mail. The composer refuses to write an email without a legal name and a\n * postal address, and a sequence cannot be activated without them.\n */\nexport interface OutreachOrgSettings {\n /** The organization's legal name, as the footer prints it: \"Example Co LLC\". */\n legalName: string\n /**\n * The name the solicitation sentence uses when it is not the legal name:\n * \"This is a sales email from Example Co.\" `''` uses the legal\n * name.\n */\n brandName: string\n /**\n * A valid physical postal address: a street address, a USPS PO box, or a\n * private mailbox registered with the USPS. Line breaks are printed as\n * commas.\n */\n postalAddress: string\n}\n\n/** The id of the compliance document in the `settings` collection. */\nexport const OUTREACH_COMPLIANCE_SETTINGS_ID = 'compliance'\n\n/**\n * The organization's Outreach compliance settings\n * (`orgs/{orgId}/outreachSettings/compliance`): the footer's sender identity,\n * and the countries Outreach may send to at all.\n *\n * `allowedCountries` is a CEILING over every sequence's own list — a\n * sequence sends only to the countries both name — so narrowing it here\n * narrows every sequence at once, without editing any of them. Default\n * {@link OUTREACH_DEFAULT_ALLOWED_COUNTRIES}.\n */\nexport interface OutreachComplianceSettings extends OutreachOrgSettings {\n /** ISO-3166-1 alpha-2 codes, uppercase, in the order they were chosen. */\n allowedCountries: string[]\n}\n\n/** The compliance settings as stored, with who changed them last. */\nexport interface OutreachComplianceSettingsDocument\n extends OutreachComplianceSettings {\n /** `0` until the organization first saves them. */\n updatedAtMs: number\n updatedByUid: string | null\n}\n\n/*==========================================\n * DO NOT CONTACT (AGL-2980).\n *\n * The organization's own list of addresses Outreach never emails, whoever\n * enrolls them and from whichever site. A member adds one by hand; the\n * sending runtime adds one when a reply asks to be left alone, when the\n * unsubscribe link is used, and when an address bounces for good.\n *\n * AN ENTRY CARRIES NO ADDRESS. Its id is `outreachDoNotContactKey(email)` —\n * the same hash the platform's suppression lists key by — and that is all a\n * lookup needs, since every caller holds the address it is about to use.\n * So the list keeps working after a person is erased from the workspace,\n * which is exactly when a promise not to email them must still hold, while\n * holding nothing that identifies them.\n *==========================================*/\n\n/** Why an address is on the list. */\nexport const OUTREACH_DO_NOT_CONTACT_REASONS = [\n /** A member put it there. */\n 'manual',\n /** A reply asked not to be emailed again. */\n 'opt_out_reply',\n /** The unsubscribe link or header was used. */\n 'unsubscribe',\n /** Mail to it bounced for good. */\n 'hard_bounce',\n /**\n * The recipient organization's mail gateway refused the sender outright\n * (AGL-3244) — a Barracuda, Proofpoint or Mimecast policy block — which is\n * a verdict on the whole domain, and is filed against it.\n */\n 'gateway_block',\n] as const\nexport type OutreachDoNotContactReason =\n (typeof OUTREACH_DO_NOT_CONTACT_REASONS)[number]\n\n/** What put an address on the list: a member, or the sending runtime. */\nexport const OUTREACH_DO_NOT_CONTACT_SOURCES = ['member', 'runtime'] as const\nexport type OutreachDoNotContactSource =\n (typeof OUTREACH_DO_NOT_CONTACT_SOURCES)[number]\n\n/** One address on the list (`orgs/{orgId}/outreachDoNotContact/{key}`). */\nexport interface OutreachDoNotContactEntry {\n /** `outreachDoNotContactKey` of the address, which is also the document id. */\n key: string\n reason: OutreachDoNotContactReason\n source: OutreachDoNotContactSource\n /** The member who added it; `null` when the runtime did. */\n addedByUid: string | null\n addedAtMs: number\n /** The enrollment that led here, when one did. */\n enrollmentId: string | null\n /** That enrollment's sequence. */\n sequenceId: string | null\n /** Plain-language detail: why the member added it, the bounce's diagnostic. */\n detail: string | null\n}\n\n/**\n * One domain on the list (`orgs/{orgId}/outreachDoNotContactDomains/{domain}`)\n * (AGL-3244): no address at it is emailed, whoever enrolls them.\n *\n * Unlike an address entry it CARRIES THE DOMAIN, in clear, because the\n * Compliance page lists it and a member takes it off by name; a domain is a\n * company's, not a person's, and a person erasure leaves it alone. A member\n * adds one by hand; the sending runtime adds one when a hard bounce reads\n * as the domain's mail gateway refusing the sender rather than one address\n * being unknown.\n */\nexport interface OutreachDoNotContactDomainEntry {\n /** The domain, lower-cased, which is also the document id. */\n domain: string\n reason: OutreachDoNotContactReason\n source: OutreachDoNotContactSource\n /** The member who added it; `null` when the runtime did. */\n addedByUid: string | null\n addedAtMs: number\n /** The enrollment whose bounce led here, when one did. */\n enrollmentId: string | null\n /** That enrollment's sequence. */\n sequenceId: string | null\n /** Plain-language detail: the member's note, or the bounce's diagnostic. */\n detail: string | null\n}\n"],"names":["OUTREACH_COLLECTIONS","mailboxes","sequences","enrollments","settings","doNotContact","doNotContactDomains","mailboxCredentials","links","outreachOrgCollectionPath","orgId","collection","OUTREACH_MAILBOX_PROVIDERS","OUTREACH_MAILBOX_STATUSES","OUTREACH_SEQUENCE_STATUSES","OUTREACH_MAX_STEPS","OUTREACH_MAX_EMAIL_STEPS","OUTREACH_MAX_STEP_DELAY_BUSINESS_DAYS","OUTREACH_MIN_EMAIL_FOLLOW_UP_BUSINESS_DAYS","OUTREACH_TASK_KINDS","OUTREACH_TASK_KIND_LABELS","linkedin","call","todo","OUTREACH_DEFAULT_ALLOWED_COUNTRIES","OUTREACH_LINK_ROLLUP_PATH","OUTREACH_ENROLLMENT_STATUSES","OUTREACH_STOP_REASONS","OUTREACH_STOP_REASONS_BY_STATUS","paused","replied","bounced","opted_out","stopped","failed","OUTREACH_ATTESTATION_KINDS","OUTREACH_ATTESTATION_LABELS","us_business_address","published_or_given","verified_deliverable","OUTREACH_PERSONAL_LINE_MAX","OUTREACH_ENROLLMENT_TARGETS","OUTREACH_COMPLIANCE_SETTINGS_ID","OUTREACH_DO_NOT_CONTACT_REASONS","OUTREACH_DO_NOT_CONTACT_SOURCES"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;CAmBC,GAED;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMA,uBAAuB;IAClC,wEAAwE,GACxEC,WAAW;IACX,uEAAuE,GACvEC,WAAW;IACX,oFAAoF,GACpFC,aAAa;IACb;;;;GAIC,GACDC,UAAU;IACV;;;GAGC,GACDC,cAAc;IACd;;;;GAIC,GACDC,qBAAqB;IACrB;;;;GAIC,GACDC,oBAAoB;IACpB;;;;;;GAMC,GACDC,OAAO;AACT,EAAU;AAQV,uEAAuE,GACvE,OAAO,SAASC,0BACdC,KAAa,EACbC,UAAiC;IAEjC,OAAO,CAAC,KAAK,EAAED,MAAM,CAAC,EAAEV,oBAAoB,CAACW,WAAW,EAAE;AAC5D;AAQA,2DAA2D,GAC3D,OAAO,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iB;IAC7DC,SAAS;QAAC;QAAU;QAAQ;KAAoB;IAChDC,QAAQ;QAAC;KAAc;AACzB,EAAC;AAED;;;;;;;;;CASC,GACD,OAAO,MAAMC,6BAA6B;IACxC;IACA;IACA;CACD,CAAS;AAGV,mDAAmD,GACnD,OAAO,MAAMC,8BAAuE;IAClFC,qBAAqB;IACrBC,oBACE;IACFC,sBAAsB;AACxB,EAAC;AAcD,+EAA+E,GAC/E,OAAO,MAAMC,6BAA6B,IAAG;AAE7C;;;;;CAKC,GACD,OAAO,MAAMC,8BAA8B;IAAC;IAAW;CAAO,CAAS;AAsKvE,oEAAoE,GACpE,OAAO,MAAMC,kCAAkC,aAAY;AAyB3D;;;;;;;;;;;;;;4CAc4C,GAE5C,mCAAmC,GACnC,OAAO,MAAMC,kCAAkC;IAC7C,2BAA2B,GAC3B;IACA,2CAA2C,GAC3C;IACA,6CAA6C,GAC7C;IACA,iCAAiC,GACjC;IACA;;;;GAIC,GACD;CACD,CAAS;AAIV,uEAAuE,GACvE,OAAO,MAAMC,kCAAkC;IAAC;IAAU;CAAU,CAAS"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/outreach.types.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE OUTREACH DOCUMENT MODEL (AGL-2974).\n *\n * One file both halves import — the console reads these documents, the server\n * routes write them — so a field is spelled once. Client-safe: types and\n * constants only, nothing that reaches Firestore.\n *\n * EVERY DOCUMENT HERE IS SERVER-WRITTEN. The Firestore rules let an\n * org-wide member holding `outreach.use` READ the org collections on a\n * workspace that carries `features.outreach`, and refuse every client write,\n * because these documents are the sending engine's state: a client that\n * could write a mailbox could lift its daily cap, and one that could write\n * an enrollment could send a step twice. The credential collection is closed\n * to clients entirely.\n *\n * Lean on purpose. Each type carries what the mailbox and sequence work is\n * known to need and nothing speculative; a field is added where the code\n * that reads it lands. Times are epoch milliseconds throughout, the unit\n * `nextDueAtMs` has to be compared in.\n */\n\n/**\n * Where Outreach keeps its records.\n *\n * Six collections under the organization, and two at the top level. The\n * org-scoped ones are erased with the org, whose erasure deletes the whole\n * `orgs/{orgId}` tree. The top-level ones — credentials, and the short\n * tracking links (AGL-3297) — are keyed by an `orgId` FIELD that a\n * path-scoped delete of `orgs/{orgId}` cannot see: the org erasure sweeps\n * them by that field\n * (`libs/tenant/data/admin/src/lib/server/erase.ts` names it as a literal,\n * which the boundary forces, and `outreach.types.spec.ts` holds the two\n * spellings together, along with the rules').\n */\nexport const OUTREACH_COLLECTIONS = {\n /** `orgs/{orgId}/outreachMailboxes/{mailboxId}` — a connected mailbox. */\n mailboxes: 'outreachMailboxes',\n /** `orgs/{orgId}/outreachSequences/{sequenceId}` — the steps to send. */\n sequences: 'outreachSequences',\n /** `orgs/{orgId}/outreachEnrollments/{enrollmentId}` — one person in one sequence. */\n enrollments: 'outreachEnrollments',\n /**\n * `orgs/{orgId}/outreachSettings/{settingsId}` — the organization's own\n * Outreach settings, one document per concern. `compliance` holds who\n * every email says sent it and the countries Outreach may send to.\n */\n settings: 'outreachSettings',\n /**\n * `orgs/{orgId}/outreachDoNotContact/{key}` — the addresses Outreach never\n * emails for this organization, keyed by `outreachDoNotContactKey`.\n */\n doNotContact: 'outreachDoNotContact',\n /**\n * `orgs/{orgId}/outreachDoNotContactDomains/{domain}` — the domains\n * Outreach never emails for this organization (AGL-3244), keyed by the\n * domain itself: a domain names a company, not a person.\n */\n doNotContactDomains: 'outreachDoNotContactDomains',\n /**\n * `outreachMailboxCredentials/{mailboxId}` — the provider grant behind a\n * mailbox. TOP-LEVEL and closed to every client, staff included, so the\n * token material never shares a readable path with the mailbox it serves.\n */\n mailboxCredentials: 'outreachMailboxCredentials',\n /**\n * `outreachLinks/{linkId}` — what one short tracking link in a sent email\n * points at (AGL-3297): the organization, the enrollment, the step, the\n * link's index and the destination. TOP-LEVEL so the link's id alone\n * resolves it with one read, keyed by an `orgId` FIELD that the org\n * erasure sweeps, and closed to every client.\n */\n links: 'outreachLinks',\n} as const\n\n/** The org-scoped collections, by their {@link OUTREACH_COLLECTIONS} key. */\nexport type OutreachOrgCollection = Exclude<\n keyof typeof OUTREACH_COLLECTIONS,\n 'mailboxCredentials' | 'links'\n>\n\n/** `orgs/{orgId}/<collection>` for one of the org-scoped collections. */\nexport function outreachOrgCollectionPath(\n orgId: string,\n collection: OutreachOrgCollection,\n): string {\n return `orgs/${orgId}/${OUTREACH_COLLECTIONS[collection]}`\n}\n\n/** Stamped by the server on every write. */\nexport interface OutreachTimestamps {\n createdAtMs: number\n updatedAtMs: number\n}\n\n/** The mail providers a mailbox can be connected through. */\nexport const OUTREACH_MAILBOX_PROVIDERS = ['google'] as const\nexport type OutreachMailboxProvider =\n (typeof OUTREACH_MAILBOX_PROVIDERS)[number]\n\n/**\n * Where a mailbox stands.\n *\n * - `connected` — the grant works and the mailbox may send.\n * - `paused` — a member stopped it; enrollments on it wait.\n * - `reconnect_required` — the provider refused the grant (revoked, expired,\n * password changed); nothing sends until the rep connects it again.\n * - `disconnected` — a member removed it; its credential is gone.\n */\nexport const OUTREACH_MAILBOX_STATUSES = [\n 'connected',\n 'paused',\n 'reconnect_required',\n 'disconnected',\n] as const\nexport type OutreachMailboxStatus = (typeof OUTREACH_MAILBOX_STATUSES)[number]\n\n/**\n * The hours a mailbox sends in, in its own {@link OutreachMailbox.timezone}.\n * A step that comes due outside the window waits for the next opening.\n */\nexport interface OutreachSendWindow {\n /** Days of the week it sends on, `0` Sunday through `6` Saturday. */\n days: number[]\n /** Minutes after local midnight the window opens, inclusive. */\n startMinute: number\n /** Minutes after local midnight the window closes, exclusive. */\n endMinute: number\n}\n\n/**\n * One mailbox-local day's sending, as the health panel sums it (AGL-2978).\n */\nexport interface OutreachMailboxDailyHealth {\n sent: number\n bounces: number\n replies: number\n}\n\n/**\n * The counters a mailbox's sending is judged by.\n *\n * `sentToday` is what `dailyCap` refuses against, and it belongs to one\n * mailbox-local day — `sentOnDay` — so a counter from yesterday is read as\n * zero rather than as today's spend.\n */\nexport interface OutreachMailboxHealth {\n sentToday: number\n /** The local day (`YYYY-MM-DD` in the mailbox's timezone) `sentToday` counts. */\n sentOnDay: string | null\n /** Hard bounces on mail this mailbox sent. */\n bounces: number\n /** Replies detected on Outreach threads. */\n replies: number\n lastSentAtMs: number | null\n /** The last provider error, kept until a later send succeeds. */\n lastErrorAtMs: number | null\n lastErrorCode: string | null\n /**\n * Per mailbox-local day (`YYYY-MM-DD`), the sends, bounces and replies\n * counted on it (AGL-2978). The Mailboxes panel shows the last seven days\n * summed; the sending runtime increments the day it counts on and may drop\n * days older than a week. Absent, or empty, until the first send.\n */\n daily?: Record<string, OutreachMailboxDailyHealth>\n /**\n * The mailbox's most recent sends, newest last, at most\n * `OUTREACH_BOUNCE_RATE_WINDOW_SENDS` of them, each marked when a hard\n * bounce came back for it (AGL-2981): the window the bounce-rate pause is\n * judged over. A send is named by a digest of its `Message-ID`, never by\n * its recipient.\n */\n recentSends?: OutreachRecentSend[]\n /** When a reply last called this mailbox's email spam (AGL-2981). */\n lastComplaintAtMs?: number | null\n}\n\n/** One send in {@link OutreachMailboxHealth.recentSends}. */\nexport interface OutreachRecentSend {\n /** A digest of the send's `Message-ID`: what a bounce is matched to. */\n id: string\n atMs: number\n bounced: boolean\n}\n\n/** Why a mailbox paused itself (AGL-2981): the engine's health decision, kept. */\nexport interface OutreachMailboxAutoPause {\n reason: 'bounces_today' | 'bounce_rate' | 'complaint'\n /** The sentence the mailbox's card shows. */\n message: string\n atMs: number\n /** For a complaint, when resuming stops being premature; `null` otherwise. */\n untilMs: number | null\n}\n\n/** Where a mailbox's reply and bounce sync has read to (AGL-2981). */\nexport interface OutreachMailboxSync {\n /** Everything received before this was read by an earlier run, epoch ms. */\n throughMs: number\n /** Gmail ids of messages outside any enrollment's thread already handled. */\n handledMessageIds: string[]\n}\n\n/**\n * An address a connected Google account may send as, which Gmail has\n * verified — its own address, or an alias whose ownership Gmail confirmed\n * (AGL-2978). Only these are offered as a mailbox's `sendAs`.\n */\nexport interface OutreachSendAsAddress {\n email: string\n /** The name Gmail holds for the address, `''` when it holds none. */\n displayName: string\n /** The account's own address. */\n isPrimary: boolean\n /** The address Gmail sends as by default. */\n isDefault: boolean\n}\n\n/**\n * A rep's own mailbox, connected to send Outreach mail\n * (`orgs/{orgId}/outreachMailboxes/{id}`).\n *\n * Its grant lives in {@link OutreachMailboxCredentials} under the same id.\n */\nexport interface OutreachMailbox extends OutreachTimestamps {\n id: string\n provider: OutreachMailboxProvider\n /** The account's own address. */\n email: string\n /** The address mail goes out as: the account's, or an alias it may send as. */\n sendAs: string\n /**\n * The verified addresses `sendAs` may be, as Gmail listed them at the last\n * connect (AGL-2978). A changed alias shows up here on the next reconnect.\n */\n sendAsOptions: OutreachSendAsAddress[]\n /** The From name recipients see. */\n displayName: string\n status: OutreachMailboxStatus\n /** The most mail it sends in one local day, ramp included. */\n dailyCap: number\n window: OutreachSendWindow\n /** IANA zone the window and the day boundary are read in. */\n timezone: string\n /**\n * When the warm-up ramp began, or `null` for a mailbox sending at its full\n * cap. The ramp is measured from here, not from connection, so a paused\n * mailbox can restart it.\n */\n rampStartedAtMs: number | null\n health: OutreachMailboxHealth\n /** The member who connected it, and whose mail it is. */\n connectedByUid: string\n /** When the grant behind it was last connected (AGL-2978). */\n connectedAtMs: number\n /**\n * Set when the mailbox paused ITSELF on its health (AGL-2981), and cleared\n * when a member pauses or resumes it; absent otherwise.\n */\n autoPause?: OutreachMailboxAutoPause | null\n /** The reply and bounce sync's place in the mailbox (AGL-2981). */\n sync?: OutreachMailboxSync | null\n}\n\n/**\n * The provider grant behind one mailbox\n * (`outreachMailboxCredentials/{mailboxId}`).\n *\n * Only the fields every reader relies on are declared here; the token\n * material is added by the code that stores it. `orgId` is REQUIRED, not\n * decorative: the org erasure finds these documents by it, and a credential\n * written without one would outlive its workspace.\n *\n * NAME EVERY SEALED FIELD WITH A SECRET WORD — `refreshToken`,\n * `tokenCiphertext`. The personal-data export discloses these documents with\n * secrets redacted, and its redaction reads field names first: a name\n * carrying `token`, `secret` or `credential` is withheld whatever its value,\n * while a neutral name such as `ciphertext` is judged by the value's shape\n * alone and can be disclosed.\n */\nexport interface OutreachMailboxCredentials extends OutreachTimestamps {\n /** The mailbox id, which is also this document's id. */\n id: string\n orgId: string\n mailboxId: string\n provider: OutreachMailboxProvider\n}\n\n/** A sequence's lifecycle. Only an `active` sequence advances its enrollments. */\nexport const OUTREACH_SEQUENCE_STATUSES = [\n 'draft',\n 'active',\n 'paused',\n 'archived',\n] as const\nexport type OutreachSequenceStatus =\n (typeof OUTREACH_SEQUENCE_STATUSES)[number]\n\n/*==========================================\n * SEQUENCES (AGL-2979).\n *\n * The limits are the outbound playbook's: a person gets at most four emails\n * from one sequence, spaced by business days, and the tasks between them are\n * the rep's own touches — a LinkedIn note, a call. The engine\n * (`../engine/sequence-validation.ts`) holds a stored sequence to them.\n *==========================================*/\n\n/** The most steps one sequence holds, emails and tasks together. */\nexport const OUTREACH_MAX_STEPS = 8\n\n/** The most of those steps that send an email. */\nexport const OUTREACH_MAX_EMAIL_STEPS = 4\n\n/** The longest wait one step may carry, in business days. */\nexport const OUTREACH_MAX_STEP_DELAY_BUSINESS_DAYS = 30\n\n/**\n * The shortest wait before an email that follows an earlier email. The first\n * email may wait `0` — \"the next opening of the window\", or the same day as\n * a task before it — and so may a task, but each later email waits at least\n * this long after the step before it.\n */\nexport const OUTREACH_MIN_EMAIL_FOLLOW_UP_BUSINESS_DAYS = 1\n\n/**\n * One email step.\n *\n * Steps are a union on `kind`, so a later kind joins without reshaping the\n * ones already stored.\n */\nexport interface OutreachEmailStep {\n /** Stable within the sequence, so an edit that reorders steps is traceable. */\n id: string\n kind: 'email'\n /**\n * Business days to wait after the previous step, counted in the mailbox's\n * zone — after enrollment for the first step, where `0` means the next\n * opening of the sending window.\n */\n delayBusinessDays: number\n /**\n * The subject, merge fields allowed. Required on the first email and on\n * any email that starts a new thread; an in-thread email is sent as `Re:`\n * the thread's own subject, so its field is not read.\n */\n subject: string\n /**\n * Whether the email goes out as a reply in the thread the earlier emails\n * started. True by default for every email after the first; the first\n * email always starts the thread, whatever this says.\n */\n replyInThread: boolean\n /** Plain text with merge fields, as its author wrote it; `''` when `templateId` is set. */\n body: string\n /**\n * A CRM email template (`orgs/{orgId}/crmEmailTemplates/{id}`) whose body\n * is sent instead of `body`, or `null`. Only the body is taken from it: the\n * step's own subject is the one that is sent.\n */\n templateId: string | null\n}\n\n/** The rep's own touches a task step asks for. */\nexport const OUTREACH_TASK_KINDS = ['linkedin', 'call', 'todo'] as const\nexport type OutreachTaskKind = (typeof OUTREACH_TASK_KINDS)[number]\n\nexport const OUTREACH_TASK_KIND_LABELS: Record<OutreachTaskKind, string> = {\n linkedin: 'LinkedIn',\n call: 'Call',\n todo: 'To-do',\n}\n\n/** One task step: a CRM task for the rep, created when the step comes due. */\nexport interface OutreachTaskStep {\n id: string\n kind: 'task'\n taskKind: OutreachTaskKind\n /** What the task says, e.g. \"Connect on LinkedIn\". */\n title: string\n /** Business days after the previous step; `0` is the same day. */\n delayBusinessDays: number\n}\n\nexport type OutreachSequenceStep = OutreachEmailStep | OutreachTaskStep\n\n/** The countries a new sequence sends to: the United States alone. */\nexport const OUTREACH_DEFAULT_ALLOWED_COUNTRIES: readonly string[] = ['US']\n\n/** Behavior a sequence applies to every enrollment in it. */\nexport interface OutreachSequenceSettings {\n /**\n * The hours this sequence sends in, replacing its mailbox's own window;\n * `null` sends in the mailbox's. Read in the mailbox's zone either way.\n */\n window: OutreachSendWindow | null\n /**\n * ISO-3166-1 alpha-2 codes a recipient may be in, uppercase. Default\n * {@link OUTREACH_DEFAULT_ALLOWED_COUNTRIES}: Canada, the United Kingdom\n * and most of the EU need a consent basis a cold email does not have.\n */\n allowedCountries: string[]\n /** Whether a contact who is already a customer may be enrolled. Default `false`. */\n allowCustomers: boolean\n /**\n * Whether the links in this sequence's emails are rewritten so clicks are\n * counted (AGL-3239). Default `false`, and `false` on every sequence\n * written before the setting existed: turning it on changes what the\n * recipient sees in the body, which is not a change to make on anyone's\n * behalf.\n *\n * It buys the one engagement number a plain-text sequence can honestly\n * report. It costs a visible link: the destination in the body becomes a\n * signed link on the console that forwards to it. There is no equivalent\n * setting for opens, because a pixel needs an HTML part — see\n * `../engine/click-tracking.ts`.\n */\n trackClicks: boolean\n /**\n * Whether this sequence's emails carry `List-Unsubscribe` and\n * `List-Unsubscribe-Post` (RFC 8058) (AGL-3296). Default `false`, and\n * `false` on every sequence written before the setting existed.\n *\n * On, mail clients draw their own unsubscribe button — Apple Mail as \"This\n * message is from a mailing list\" — which is the easiest way out for the\n * recipient and makes a one-to-one email read as bulk. Off, the footer's\n * \"reply 'no'\" line is the way out; the footer and its postal address are\n * mandatory either way, and the reply classifier stops on a \"no\". The\n * Gmail/Yahoo one-click requirement binds bulk senders (5,000 a day), not a\n * mailbox sending a sequence.\n */\n listUnsubscribe: boolean\n}\n\n/*==========================================\n * WHAT A SEQUENCE MEASURED (AGL-3239).\n *\n * Counters on the sequence document, incremented by the sending runtime and\n * by the click route. They are NOT derived from the enrollments on read: the\n * console lists enrollments a page at a time, so a rollup taken over what is\n * loaded would report the first page's numbers as the sequence's.\n *\n * Every field is optional and every absence means \"not recorded\", never\n * zero. The distinction is the whole of `campaign-report.ts`'s honesty and\n * it is kept here for the same reason: a sequence that ran before this\n * existed has no counters, and reporting its click rate as 0% would publish\n * a fact about our schema as a fact about its recipients.\n *=========================================*/\n\n/**\n * The per-destination click rollup under one sequence:\n * `orgs/{orgId}/outreachSequences/{id}/reports/links`.\n *\n * One document per sequence, holding a bounded map — the campaign rollup's\n * own shape and its own cap, so \"a link\" means the same thing in a rep's\n * report and a marketer's. Here rather than beside the writer, because the\n * console's listener is a browser module and the writer is not.\n */\nexport const OUTREACH_LINK_ROLLUP_PATH = ['reports', 'links'] as const\n\n/** The counters one sequence is judged by. */\nexport interface OutreachSequenceStats {\n /** Email steps that left. One person getting four emails counts four. */\n sent?: number\n /**\n * Distinct enrollments that have had at least one email — the denominator\n * of every engagement rate, and the thing `sent` is not.\n */\n people?: number\n /**\n * At least one email of this sequence went out with its links rewritten.\n *\n * Absent is NOT false; it is \"never recorded\", which is what every\n * sequence sent before the setting existed reads as. Either way the report\n * withholds the click rate rather than showing 0% — see\n * {@link OutreachSequenceStats} above.\n */\n clickTracked?: boolean\n /** Click EVENTS judged a person's. One reader clicking twice counts two. */\n clicks?: number\n /** Enrollments whose FIRST human click was seen: the rate's numerator. */\n uniqueClicks?: number\n /**\n * Clicks a link scanner or a security gateway made, counted apart and\n * never in the rate (`../engine/click-tracking.ts`). Shown, not hidden:\n * a large number here is the reader's evidence that the small number\n * beside it is the real one.\n */\n machineClicks?: number\n /** When a person last followed a link. */\n lastClickAtMs?: number | null\n}\n\n/** What one enrollment did with the links it was sent (AGL-3239). */\nexport interface OutreachEnrollmentEngagement {\n /** Click events judged this person's, machines excluded. */\n clicks: number\n /** The first, which is what makes them one of the sequence's `uniqueClicks`. */\n firstClickAtMs: number | null\n lastClickAtMs: number | null\n /** The destination they followed last, as `campaignLinkKey` reduces it. */\n lastClickUrl: string | null\n /** Clicks on this person's links that were a machine's. */\n machineClicks: number\n}\n\n/** An ordered set of steps sent from one mailbox (`orgs/{orgId}/outreachSequences/{id}`). */\nexport interface OutreachSequence extends OutreachTimestamps {\n id: string\n name: string\n /** The site whose CRM the enrolled people are records of. */\n hostId: string\n /**\n * The mailbox every email step is sent from. A setting of the sequence,\n * kept beside `settings` rather than inside it because enrollments and a\n * mailbox's own screens select sequences by it.\n */\n mailboxId: string\n steps: OutreachSequenceStep[]\n settings: OutreachSequenceSettings\n status: OutreachSequenceStatus\n /**\n * The campaigns the sequence is in (AGL-3254): container ids from the\n * org's `emailCampaigns`, under the field every campaign member carries\n * (`CAMPAIGN_MEMBERSHIP_FIELD`). Everyone enrolled gains them on their\n * own record at enroll time, and what the sequence produces is credited\n * to them. Absent on a sequence saved before it could join one.\n */\n campaignIds?: string[]\n /**\n * What it measured (AGL-3239). Absent until the first email leaves, and\n * absent forever on a sequence that finished before the counters existed.\n */\n stats?: OutreachSequenceStats\n}\n\n/*==========================================\n * ENROLLMENTS (AGL-2979).\n *==========================================*/\n\n/**\n * Where one person's run through a sequence stands.\n *\n * `active` sends and `paused` waits. The rest end the sending, and each says\n * why: `finished` sent every step, `replied` heard back, `bounced` reached a\n * mailbox that does not exist, `opted_out` was asked to stop, `stopped` was\n * ended by a member or a gate, `failed` could not be sent. The transitions\n * between them are the engine's (`../engine/enrollment-state.ts`).\n */\nexport const OUTREACH_ENROLLMENT_STATUSES = [\n 'active',\n 'paused',\n 'finished',\n 'replied',\n 'bounced',\n 'opted_out',\n 'stopped',\n 'failed',\n] as const\nexport type OutreachEnrollmentStatus =\n (typeof OUTREACH_ENROLLMENT_STATUSES)[number]\n\n/**\n * Why an enrollment is not `active`, recorded beside the status. `finished`\n * needs none; each other status allows the reasons\n * `OUTREACH_STOP_REASONS_BY_STATUS` names.\n */\nexport const OUTREACH_STOP_REASONS = [\n /** A person wrote back in the thread. */\n 'reply',\n /** The recipient's server refused the address for good. */\n 'hard_bounce',\n /** A reply asked not to be emailed again. */\n 'opt_out_reply',\n /** The unsubscribe link or header was used. */\n 'unsubscribe',\n /** The address is on the organization's do-not-contact list. */\n 'do_not_contact',\n /** A gate refused the next send — the person became a customer, say. */\n 'gate',\n /** A member paused or stopped it. */\n 'manual',\n /** The sequence was archived with the person still in it. */\n 'sequence_archived',\n /** The provider refused the send for good, or the email could not be composed. */\n 'send_failed',\n] as const\nexport type OutreachStopReason = (typeof OUTREACH_STOP_REASONS)[number]\n\n/** The statuses a stop reason is recorded with, and the reasons each allows. */\nexport const OUTREACH_STOP_REASONS_BY_STATUS: Readonly<\n Record<\n Exclude<OutreachEnrollmentStatus, 'active' | 'finished'>,\n readonly OutreachStopReason[]\n >\n> = {\n paused: ['manual'],\n replied: ['reply'],\n bounced: ['hard_bounce'],\n opted_out: ['opt_out_reply', 'unsubscribe', 'do_not_contact'],\n stopped: ['manual', 'gate', 'sequence_archived'],\n failed: ['send_failed'],\n}\n\n/**\n * What a rep confirms before a COLD contact is enrolled — one with no\n * inbound capture behind them — each recorded with who confirmed it and\n * when, because each is a fact only the rep can know:\n *\n * - `us_business_address`: the address is a business address in the US;\n * - `published_or_given`: they or their company published it, or they gave\n * it to us — never guessed from a name or bought on a list;\n * - `verified_deliverable`: a verifier said it accepts mail.\n */\nexport const OUTREACH_ATTESTATION_KINDS = [\n 'us_business_address',\n 'published_or_given',\n 'verified_deliverable',\n] as const\nexport type OutreachAttestationKind = (typeof OUTREACH_ATTESTATION_KINDS)[number]\n\n/** The sentence a rep ticks for each attestation. */\nexport const OUTREACH_ATTESTATION_LABELS: Record<OutreachAttestationKind, string> = {\n us_business_address: 'This is a US business address',\n published_or_given:\n 'They or their company published this address, or they gave it to us',\n verified_deliverable: 'This address was verified as deliverable',\n}\n\n/** One confirmation, as stored. */\nexport interface OutreachAttestation {\n /** The member who confirmed it. */\n uid: string\n atMs: number\n}\n\n/** The confirmations an enrollment carries, by kind. */\nexport type OutreachAttestations = Partial<\n Record<OutreachAttestationKind, OutreachAttestation>\n>\n\n/** The longest personal line an enrollment keeps: one sentence, not a letter. */\nexport const OUTREACH_PERSONAL_LINE_MAX = 300\n\n/*==========================================\n * CURATED STEPS (AGL-3324).\n *\n * A step is one template for everyone, plus the personal line. Curating\n * rewrites ONE person's copy of a step — drafted by the workspace's AI from\n * their record and the step's own body as the skeleton, or written by the\n * member — and keeps it on the enrollment, never on the sequence. The send\n * job reads the override in place of the step's subject and body; the\n * tokens, the footer, the click tracking and the plain-text rules still\n * apply to it exactly as they apply to the step.\n *\n * Nothing is stored that a member has not read: a draft lands on the\n * enrollment only when the member confirms it, with who and when.\n *==========================================*/\n\n/** Who wrote the override: the AI, or the member by hand. */\nexport const OUTREACH_STEP_OVERRIDE_SOURCES = ['ai', 'member'] as const\nexport type OutreachStepOverrideSource = (typeof OUTREACH_STEP_OVERRIDE_SOURCES)[number]\n\n/** One person's own copy of one step. */\nexport interface OutreachStepOverride {\n /** The subject, merge fields allowed; absent keeps the step's own. Not read on an in-thread email. */\n subject?: string\n /** The plain-text body, merge fields allowed; absent keeps the step's own (or its template's). */\n body?: string\n source: OutreachStepOverrideSource\n /** When the member confirmed it — the moment it was stored, never before. */\n draftedAtMs: number\n /** The member who confirmed it. */\n draftedByUid?: string\n /** An AI draft the member changed before confirming it. */\n edited?: boolean\n /** The prompt the AI was given, for the audit log; absent on a member's own words. */\n prompt?: string\n /** The model that drafted it, for the audit log. */\n model?: string\n}\n\n/** The overrides an enrollment carries, keyed by the step's index as text. */\nexport type OutreachStepOverrides = Record<string, OutreachStepOverride>\n\n/** The sentence a member ticks before a curated draft is stored — a fourth attestation. */\nexport const OUTREACH_CURATION_CONFIRMATION_LABEL =\n \"I've read this draft, and it goes out to this person as written\"\n\n/**\n * Which CRM record an enrollment names (AGL-3234). A person is a LEAD until\n * somebody qualifies them and a CONTACT after, and a sequence works either:\n * an enrollment made on a lead follows the lead to the contact it becomes,\n * so the thread and the steps carry on as one enrollment.\n */\nexport const OUTREACH_ENROLLMENT_TARGETS = ['contact', 'lead'] as const\nexport type OutreachEnrollmentTarget = (typeof OUTREACH_ENROLLMENT_TARGETS)[number]\n\n/** One person in one sequence (`orgs/{orgId}/outreachEnrollments/{id}`). */\nexport interface OutreachEnrollment extends OutreachTimestamps {\n id: string\n sequenceId: string\n /**\n * The record the person is (AGL-3234): `contact` for a CRM contact,\n * `lead` for a lead the sequence's site holds. A stored enrollment with\n * no target is a contact's — every enrollment was, before leads could be\n * sequenced.\n */\n target: OutreachEnrollmentTarget\n /**\n * The CRM contact the person is — `''` while the enrollment targets a\n * lead that has not converted. Filled in, beside `target: 'contact'`, the\n * moment the lead becomes a contact.\n */\n contactId: string\n /**\n * `hosts/{hostId}/leads/{leadId}` — the person key — for an enrollment\n * made on a lead; kept once the lead converts, so the lead's page still\n * lists the sequence. `null` for an enrollment made on a contact.\n */\n leadId: string | null\n /**\n * The person's name as the sending site knew it at enrollment, `''` when\n * it had none — what the enrollments table shows beside the address,\n * without a read of every record on the page (AGL-2980).\n */\n contactName: string\n /** The address the steps go to, normalized, captured at enrollment. */\n email: string\n hostId: string\n mailboxId: string\n /** The index into `steps` of the NEXT step to run. */\n stepIndex: number\n /** When that step comes due, or `null` when nothing is waiting. */\n nextDueAtMs: number | null\n status: OutreachEnrollmentStatus\n /** Why the status is not `active`; `null` while active and once finished. */\n stopReason: OutreachStopReason | null\n /** Plain-language detail: the gate's reason, the bounce's diagnostic. */\n stopDetail: string | null\n stoppedAtMs: number | null\n /** The member who paused or stopped it; `null` when the engine did. */\n stoppedByUid: string | null\n /**\n * The rep's signal sentence — why this person, now — merged into the\n * steps as `{{enrollment.personalLine}}`. Required for a cold contact.\n */\n personalLine: string\n /** Whether the contact was cold (no inbound capture) when enrolled. */\n cold: boolean\n attestations: OutreachAttestations\n /** The member who enrolled the person. */\n enrolledByUid: string\n /** The provider thread the next in-thread email is sent into, once one exists. */\n gmailThreadId: string | null\n /** Every provider thread this enrollment has sent into, oldest first — what reply sync watches. */\n gmailThreadIds: string[]\n /** The subject the current thread was started with, as sent. */\n threadSubject: string | null\n /**\n * The `Message-ID`s of the emails sent into the current thread, oldest\n * first, angle brackets included: the next in-thread email answers the\n * last and names them all in `References`.\n */\n messageIds: string[]\n /** When the last step ran. */\n lastSentAtMs: number | null\n /**\n * A sending run's hold on the step it is running (AGL-2981): taken in a\n * transaction before the step runs, cleared when it is recorded. Absent\n * or `null` while no run holds one.\n */\n sendClaim?: OutreachSendClaim | null\n /** Every step the runtime ran, oldest first (AGL-2981). */\n stepRecords?: OutreachStepRecord[]\n /** Gmail ids of this enrollment's thread messages the sync has handled, the last hundred. */\n syncedMessageIds?: string[]\n /**\n * What this person did with the links they were sent (AGL-3239). Absent\n * until their first click, which is why the table reads an absence as\n * \"no clicks\" only for a sequence that tracks them at all.\n */\n engagement?: OutreachEnrollmentEngagement\n /**\n * The sequence's campaigns as they stood when the person was enrolled\n * (AGL-3254): what every outcome of this enrollment is credited to. A\n * campaign the sequence joins later does not claim the people already\n * in it, and one it leaves keeps what it was credited with.\n */\n campaignIds?: string[]\n /**\n * This person's own copies of steps (AGL-3324), by step index. Absent on\n * an enrollment nobody curated, which sends the sequence's steps as\n * written; a step without an entry sends the same.\n */\n stepOverrides?: OutreachStepOverrides\n}\n\n/** A sending run's claim on one enrollment's step (AGL-2981). */\nexport interface OutreachSendClaim {\n /** The run that holds it. */\n token: string\n atMs: number\n stepIndex: number\n /**\n * The `Message-ID` an email step goes out with, minted before the send, so\n * a claim a run died holding is settled by looking for the message rather\n * than by sending it again. `null` for a task step.\n */\n messageId: string | null\n}\n\n/** One step the runtime ran for an enrollment (AGL-2981). */\nexport interface OutreachStepRecord {\n stepIndex: number\n stepId: string\n kind: 'email' | 'task'\n atMs: number\n /** Gmail's id for the sent message. */\n gmailMessageId?: string\n /** Gmail's thread the message went into. */\n gmailThreadId?: string\n /** The `Message-ID` it went out with, angle brackets included. */\n messageId?: string\n /** The subject as sent. */\n subject?: string\n /** The record system's task for a task step; `null` when none could be filed. */\n taskId?: string | null\n /**\n * The destinations this email's links were rewritten to point at, in the\n * order a click token indexes them (AGL-3239). Absent on a step that\n * carried no links, and on every step sent before tracking existed.\n *\n * Kept so the console can say WHICH link a person followed without the\n * token having to carry the URL back to us, and so a rewritten body can be\n * read afterwards for what it actually offered them.\n */\n links?: string[]\n /**\n * The email went out as this person's curated copy (AGL-3324), and who\n * wrote it. Absent on a step sent as the sequence wrote it.\n */\n curated?: OutreachStepOverrideSource\n}\n\n/*==========================================\n * ORGANIZATION SETTINGS (AGL-2979).\n *==========================================*/\n\n/**\n * What every Outreach email's footer says about who sent it — the\n * identification and the postal address CAN-SPAM requires on commercial\n * mail. The composer refuses to write an email without a legal name and a\n * postal address, and a sequence cannot be activated without them.\n */\nexport interface OutreachOrgSettings {\n /** The organization's legal name, as the footer prints it: \"Example Co LLC\". */\n legalName: string\n /**\n * The name the solicitation sentence uses when it is not the legal name:\n * \"This is a sales email from Example Co.\" `''` uses the legal\n * name.\n */\n brandName: string\n /**\n * A valid physical postal address: a street address, a USPS PO box, or a\n * private mailbox registered with the USPS. Line breaks are printed as\n * commas.\n */\n postalAddress: string\n}\n\n/** The id of the compliance document in the `settings` collection. */\nexport const OUTREACH_COMPLIANCE_SETTINGS_ID = 'compliance'\n\n/**\n * The organization's Outreach compliance settings\n * (`orgs/{orgId}/outreachSettings/compliance`): the footer's sender identity,\n * and the countries Outreach may send to at all.\n *\n * `allowedCountries` is a CEILING over every sequence's own list — a\n * sequence sends only to the countries both name — so narrowing it here\n * narrows every sequence at once, without editing any of them. Default\n * {@link OUTREACH_DEFAULT_ALLOWED_COUNTRIES}.\n */\nexport interface OutreachComplianceSettings extends OutreachOrgSettings {\n /** ISO-3166-1 alpha-2 codes, uppercase, in the order they were chosen. */\n allowedCountries: string[]\n}\n\n/** The compliance settings as stored, with who changed them last. */\nexport interface OutreachComplianceSettingsDocument\n extends OutreachComplianceSettings {\n /** `0` until the organization first saves them. */\n updatedAtMs: number\n updatedByUid: string | null\n}\n\n/*==========================================\n * DO NOT CONTACT (AGL-2980).\n *\n * The organization's own list of addresses Outreach never emails, whoever\n * enrolls them and from whichever site. A member adds one by hand; the\n * sending runtime adds one when a reply asks to be left alone, when the\n * unsubscribe link is used, and when an address bounces for good.\n *\n * AN ENTRY CARRIES NO ADDRESS. Its id is `outreachDoNotContactKey(email)` —\n * the same hash the platform's suppression lists key by — and that is all a\n * lookup needs, since every caller holds the address it is about to use.\n * So the list keeps working after a person is erased from the workspace,\n * which is exactly when a promise not to email them must still hold, while\n * holding nothing that identifies them.\n *==========================================*/\n\n/** Why an address is on the list. */\nexport const OUTREACH_DO_NOT_CONTACT_REASONS = [\n /** A member put it there. */\n 'manual',\n /** A reply asked not to be emailed again. */\n 'opt_out_reply',\n /** The unsubscribe link or header was used. */\n 'unsubscribe',\n /** Mail to it bounced for good. */\n 'hard_bounce',\n /**\n * The recipient organization's mail gateway refused the sender outright\n * (AGL-3244) — a Barracuda, Proofpoint or Mimecast policy block — which is\n * a verdict on the whole domain, and is filed against it.\n */\n 'gateway_block',\n] as const\nexport type OutreachDoNotContactReason =\n (typeof OUTREACH_DO_NOT_CONTACT_REASONS)[number]\n\n/** What put an address on the list: a member, or the sending runtime. */\nexport const OUTREACH_DO_NOT_CONTACT_SOURCES = ['member', 'runtime'] as const\nexport type OutreachDoNotContactSource =\n (typeof OUTREACH_DO_NOT_CONTACT_SOURCES)[number]\n\n/** One address on the list (`orgs/{orgId}/outreachDoNotContact/{key}`). */\nexport interface OutreachDoNotContactEntry {\n /** `outreachDoNotContactKey` of the address, which is also the document id. */\n key: string\n reason: OutreachDoNotContactReason\n source: OutreachDoNotContactSource\n /** The member who added it; `null` when the runtime did. */\n addedByUid: string | null\n addedAtMs: number\n /** The enrollment that led here, when one did. */\n enrollmentId: string | null\n /** That enrollment's sequence. */\n sequenceId: string | null\n /** Plain-language detail: why the member added it, the bounce's diagnostic. */\n detail: string | null\n}\n\n/**\n * One domain on the list (`orgs/{orgId}/outreachDoNotContactDomains/{domain}`)\n * (AGL-3244): no address at it is emailed, whoever enrolls them.\n *\n * Unlike an address entry it CARRIES THE DOMAIN, in clear, because the\n * Compliance page lists it and a member takes it off by name; a domain is a\n * company's, not a person's, and a person erasure leaves it alone. A member\n * adds one by hand; the sending runtime adds one when a hard bounce reads\n * as the domain's mail gateway refusing the sender rather than one address\n * being unknown.\n */\nexport interface OutreachDoNotContactDomainEntry {\n /** The domain, lower-cased, which is also the document id. */\n domain: string\n reason: OutreachDoNotContactReason\n source: OutreachDoNotContactSource\n /** The member who added it; `null` when the runtime did. */\n addedByUid: string | null\n addedAtMs: number\n /** The enrollment whose bounce led here, when one did. */\n enrollmentId: string | null\n /** That enrollment's sequence. */\n sequenceId: string | null\n /** Plain-language detail: the member's note, or the bounce's diagnostic. */\n detail: string | null\n}\n"],"names":["OUTREACH_COLLECTIONS","mailboxes","sequences","enrollments","settings","doNotContact","doNotContactDomains","mailboxCredentials","links","outreachOrgCollectionPath","orgId","collection","OUTREACH_MAILBOX_PROVIDERS","OUTREACH_MAILBOX_STATUSES","OUTREACH_SEQUENCE_STATUSES","OUTREACH_MAX_STEPS","OUTREACH_MAX_EMAIL_STEPS","OUTREACH_MAX_STEP_DELAY_BUSINESS_DAYS","OUTREACH_MIN_EMAIL_FOLLOW_UP_BUSINESS_DAYS","OUTREACH_TASK_KINDS","OUTREACH_TASK_KIND_LABELS","linkedin","call","todo","OUTREACH_DEFAULT_ALLOWED_COUNTRIES","OUTREACH_LINK_ROLLUP_PATH","OUTREACH_ENROLLMENT_STATUSES","OUTREACH_STOP_REASONS","OUTREACH_STOP_REASONS_BY_STATUS","paused","replied","bounced","opted_out","stopped","failed","OUTREACH_ATTESTATION_KINDS","OUTREACH_ATTESTATION_LABELS","us_business_address","published_or_given","verified_deliverable","OUTREACH_PERSONAL_LINE_MAX","OUTREACH_STEP_OVERRIDE_SOURCES","OUTREACH_CURATION_CONFIRMATION_LABEL","OUTREACH_ENROLLMENT_TARGETS","OUTREACH_COMPLIANCE_SETTINGS_ID","OUTREACH_DO_NOT_CONTACT_REASONS","OUTREACH_DO_NOT_CONTACT_SOURCES"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;CAmBC,GAED;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMA,uBAAuB;IAClC,wEAAwE,GACxEC,WAAW;IACX,uEAAuE,GACvEC,WAAW;IACX,oFAAoF,GACpFC,aAAa;IACb;;;;GAIC,GACDC,UAAU;IACV;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import { type OutreachComposeResult } from '../engine/compose';
|
|
19
|
-
import type { OutreachOrgSettings, OutreachSequenceStep } from './outreach.types';
|
|
19
|
+
import type { OutreachOrgSettings, OutreachSequenceStep, OutreachStepOverrides } from './outreach.types';
|
|
20
20
|
/** The person a preview is written to when it names no contact. */
|
|
21
21
|
export declare const OUTREACH_SAMPLE_PERSON: {
|
|
22
22
|
readonly name: "Casey Morgan";
|
|
@@ -40,6 +40,8 @@ export interface OutreachStepPreviewInput {
|
|
|
40
40
|
personalLine: string;
|
|
41
41
|
/** The CRM template's body, when the step names a template. */
|
|
42
42
|
templateBody?: string | null;
|
|
43
|
+
/** The person's own copies of steps (AGL-3324), as the enrollment would carry them. */
|
|
44
|
+
stepOverrides?: OutreachStepOverrides | null;
|
|
43
45
|
}
|
|
44
46
|
/** The step's email, or why it can't be written — see the module note. */
|
|
45
47
|
export declare function previewOutreachStep(input: OutreachStepPreviewInput): OutreachComposeResult;
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
* no thread, so it lends the composer one: the subject the thread would
|
|
27
27
|
* have been started with, rendered for the same person, and a placeholder
|
|
28
28
|
* message id that never leaves the preview.
|
|
29
|
-
*==========================================*/ import {
|
|
29
|
+
*==========================================*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
30
|
+
import { resolveCrmMergeFields } from "@aglyn/aglyn/app-utils/crm-email-templates";
|
|
30
31
|
import { composeOutreachEmail } from "../engine/compose.js";
|
|
31
32
|
import { isInThreadEmailStep } from "../engine/sequence-validation.js";
|
|
32
33
|
/** The holder id the sample person's facet is filed under. */ const SAMPLE_GROUP = 'outreach-preview';
|
|
@@ -79,7 +80,7 @@ import { isInThreadEmailStep } from "../engine/sequence-validation.js";
|
|
|
79
80
|
sequence: {
|
|
80
81
|
steps
|
|
81
82
|
},
|
|
82
|
-
enrollment: {
|
|
83
|
+
enrollment: _extends({
|
|
83
84
|
email: input.email,
|
|
84
85
|
stepIndex: input.stepIndex,
|
|
85
86
|
personalLine: input.personalLine,
|
|
@@ -88,7 +89,9 @@ import { isInThreadEmailStep } from "../engine/sequence-validation.js";
|
|
|
88
89
|
PREVIEW_MESSAGE_ID
|
|
89
90
|
] : [],
|
|
90
91
|
gmailThreadId: threadSubject ? 'preview' : null
|
|
91
|
-
},
|
|
92
|
+
}, input.stepOverrides ? {
|
|
93
|
+
stepOverrides: input.stepOverrides
|
|
94
|
+
} : {}),
|
|
92
95
|
orgSettings: input.orgSettings,
|
|
93
96
|
merge: input.merge,
|
|
94
97
|
templateBody: (_input_templateBody = input.templateBody) != null ? _input_templateBody : null
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/step-preview.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ONE STEP'S EMAIL, AS A PERSON WOULD GET IT (AGL-2980).\n *\n * The editor's live preview and the preview route both show an email\n * before anyone is sent it, and both write it with the engine's own\n * composer — the merge, the footer, the threading — so what the rep reads\n * is what the runtime would send. Client-safe.\n *\n * A step later in the thread is sent as `Re:` the thread's subject, and the\n * composer refuses to write one without a thread to answer. A preview has\n * no thread, so it lends the composer one: the subject the thread would\n * have been started with, rendered for the same person, and a placeholder\n * message id that never leaves the preview.\n *==========================================*/\n\nimport type { CrmMergeContext } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { resolveCrmMergeFields } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { composeOutreachEmail, type OutreachComposeResult } from '../engine/compose'\nimport { isInThreadEmailStep } from '../engine/sequence-validation'\nimport type { OutreachOrgSettings, OutreachSequenceStep } from './outreach.types'\n\n/** The holder id the sample person's facet is filed under. */\nconst SAMPLE_GROUP = 'outreach-preview'\n\n/** The person a preview is written to when it names no contact. */\nexport const OUTREACH_SAMPLE_PERSON = {\n name: 'Casey Morgan',\n email: 'casey.morgan@example.com',\n companyName: 'Example Co',\n jobTitle: 'Head of Operations',\n personalLine: 'I saw Example Co just opened its second location.',\n} as const\n\n/** The merge context of the sample person, from the sender and site given. */\nexport function outreachSampleMergeContext(input: {\n sender?: CrmMergeContext['sender']\n siteName?: string | null\n}): CrmMergeContext {\n return {\n contact: {\n name: OUTREACH_SAMPLE_PERSON.name,\n email: OUTREACH_SAMPLE_PERSON.email,\n facets: {\n [SAMPLE_GROUP]: {\n companyName: OUTREACH_SAMPLE_PERSON.companyName,\n jobTitle: OUTREACH_SAMPLE_PERSON.jobTitle,\n },\n },\n },\n contactGroupId: SAMPLE_GROUP,\n sender: input.sender ?? null,\n site: { name: input.siteName ?? '' },\n }\n}\n\n/** The placeholder a preview lends the composer as the thread's last message. */\nconst PREVIEW_MESSAGE_ID = '<preview@outreach.invalid>'\n\nexport interface OutreachStepPreviewInput {\n steps: readonly OutreachSequenceStep[]\n stepIndex: number\n orgSettings: Pick<OutreachOrgSettings, 'legalName' | 'brandName' | 'postalAddress'> | null\n merge: CrmMergeContext\n /** The recipient's address. */\n email: string\n personalLine: string\n /** The CRM template's body, when the step names a template. */\n templateBody?: string | null\n}\n\n/** The step's email, or why it can't be written — see the module note. */\nexport function previewOutreachStep(input: OutreachStepPreviewInput): OutreachComposeResult {\n const steps = [...input.steps]\n let threadSubject: string | null = null\n if (isInThreadEmailStep(steps, input.stepIndex)) {\n // The thread was started by the latest email before this one that did\n // not itself reply in a thread.\n for (let index = input.stepIndex - 1; index >= 0; index -= 1) {\n const step = steps[index]\n if (step?.kind === 'email' && !isInThreadEmailStep(steps, index)) {\n threadSubject = resolveCrmMergeFields(step.subject, input.merge).text.trim() || null\n break\n }\n }\n }\n return composeOutreachEmail({\n sequence: { steps },\n enrollment: {\n email: input.email,\n stepIndex: input.stepIndex,\n personalLine: input.personalLine,\n threadSubject,\n messageIds: threadSubject ? [PREVIEW_MESSAGE_ID] : [],\n gmailThreadId: threadSubject ? 'preview' : null,\n },\n orgSettings: input.orgSettings,\n merge: input.merge,\n templateBody: input.templateBody ?? null,\n })\n}\n"],"names":["resolveCrmMergeFields","composeOutreachEmail","isInThreadEmailStep","SAMPLE_GROUP","OUTREACH_SAMPLE_PERSON","name","email","companyName","jobTitle","personalLine","outreachSampleMergeContext","input","contact","facets","contactGroupId","sender","site","siteName","PREVIEW_MESSAGE_ID","previewOutreachStep","steps","threadSubject","stepIndex","index","step","kind","subject","merge","text","trim","sequence","enrollment","messageIds","gmailThreadId","orgSettings","templateBody"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;4CAa4C,
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/step-preview.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ONE STEP'S EMAIL, AS A PERSON WOULD GET IT (AGL-2980).\n *\n * The editor's live preview and the preview route both show an email\n * before anyone is sent it, and both write it with the engine's own\n * composer — the merge, the footer, the threading — so what the rep reads\n * is what the runtime would send. Client-safe.\n *\n * A step later in the thread is sent as `Re:` the thread's subject, and the\n * composer refuses to write one without a thread to answer. A preview has\n * no thread, so it lends the composer one: the subject the thread would\n * have been started with, rendered for the same person, and a placeholder\n * message id that never leaves the preview.\n *==========================================*/\n\nimport type { CrmMergeContext } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { resolveCrmMergeFields } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { composeOutreachEmail, type OutreachComposeResult } from '../engine/compose'\nimport { isInThreadEmailStep } from '../engine/sequence-validation'\nimport type { OutreachOrgSettings, OutreachSequenceStep, OutreachStepOverrides } from './outreach.types'\n\n/** The holder id the sample person's facet is filed under. */\nconst SAMPLE_GROUP = 'outreach-preview'\n\n/** The person a preview is written to when it names no contact. */\nexport const OUTREACH_SAMPLE_PERSON = {\n name: 'Casey Morgan',\n email: 'casey.morgan@example.com',\n companyName: 'Example Co',\n jobTitle: 'Head of Operations',\n personalLine: 'I saw Example Co just opened its second location.',\n} as const\n\n/** The merge context of the sample person, from the sender and site given. */\nexport function outreachSampleMergeContext(input: {\n sender?: CrmMergeContext['sender']\n siteName?: string | null\n}): CrmMergeContext {\n return {\n contact: {\n name: OUTREACH_SAMPLE_PERSON.name,\n email: OUTREACH_SAMPLE_PERSON.email,\n facets: {\n [SAMPLE_GROUP]: {\n companyName: OUTREACH_SAMPLE_PERSON.companyName,\n jobTitle: OUTREACH_SAMPLE_PERSON.jobTitle,\n },\n },\n },\n contactGroupId: SAMPLE_GROUP,\n sender: input.sender ?? null,\n site: { name: input.siteName ?? '' },\n }\n}\n\n/** The placeholder a preview lends the composer as the thread's last message. */\nconst PREVIEW_MESSAGE_ID = '<preview@outreach.invalid>'\n\nexport interface OutreachStepPreviewInput {\n steps: readonly OutreachSequenceStep[]\n stepIndex: number\n orgSettings: Pick<OutreachOrgSettings, 'legalName' | 'brandName' | 'postalAddress'> | null\n merge: CrmMergeContext\n /** The recipient's address. */\n email: string\n personalLine: string\n /** The CRM template's body, when the step names a template. */\n templateBody?: string | null\n /** The person's own copies of steps (AGL-3324), as the enrollment would carry them. */\n stepOverrides?: OutreachStepOverrides | null\n}\n\n/** The step's email, or why it can't be written — see the module note. */\nexport function previewOutreachStep(input: OutreachStepPreviewInput): OutreachComposeResult {\n const steps = [...input.steps]\n let threadSubject: string | null = null\n if (isInThreadEmailStep(steps, input.stepIndex)) {\n // The thread was started by the latest email before this one that did\n // not itself reply in a thread.\n for (let index = input.stepIndex - 1; index >= 0; index -= 1) {\n const step = steps[index]\n if (step?.kind === 'email' && !isInThreadEmailStep(steps, index)) {\n threadSubject = resolveCrmMergeFields(step.subject, input.merge).text.trim() || null\n break\n }\n }\n }\n return composeOutreachEmail({\n sequence: { steps },\n enrollment: {\n email: input.email,\n stepIndex: input.stepIndex,\n personalLine: input.personalLine,\n threadSubject,\n messageIds: threadSubject ? [PREVIEW_MESSAGE_ID] : [],\n gmailThreadId: threadSubject ? 'preview' : null,\n ...(input.stepOverrides ? { stepOverrides: input.stepOverrides } : {}),\n },\n orgSettings: input.orgSettings,\n merge: input.merge,\n templateBody: input.templateBody ?? null,\n })\n}\n"],"names":["resolveCrmMergeFields","composeOutreachEmail","isInThreadEmailStep","SAMPLE_GROUP","OUTREACH_SAMPLE_PERSON","name","email","companyName","jobTitle","personalLine","outreachSampleMergeContext","input","contact","facets","contactGroupId","sender","site","siteName","PREVIEW_MESSAGE_ID","previewOutreachStep","steps","threadSubject","stepIndex","index","step","kind","subject","merge","text","trim","sequence","enrollment","messageIds","gmailThreadId","stepOverrides","orgSettings","templateBody"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;4CAa4C;AAG5C,SAASA,qBAAqB,QAAQ,6CAA4C;AAClF,SAASC,oBAAoB,QAAoC,uBAAmB;AACpF,SAASC,mBAAmB,QAAQ,mCAA+B;AAGnE,4DAA4D,GAC5D,MAAMC,eAAe;AAErB,iEAAiE,GACjE,OAAO,MAAMC,yBAAyB;IACpCC,MAAM;IACNC,OAAO;IACPC,aAAa;IACbC,UAAU;IACVC,cAAc;AAChB,EAAU;AAEV,4EAA4E,GAC5E,OAAO,SAASC,2BAA2BC,KAG1C;QAaWA,eACMA;IAbhB,OAAO;QACLC,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AAC;QAEtEC,aAAaxB,MAAMwB,WAAW;QAC9BR,OAAOhB,MAAMgB,KAAK;QAClBS,YAAY,GAAEzB,sBAAAA,MAAMyB,YAAY,YAAlBzB,sBAAsB;IACtC;AACF"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type OutreachEnrollment, type OutreachMailbox, type OutreachSequence, type OutreachSequenceStats } from './outreach.types';
|
|
17
|
+
import { type OutreachEnrollment, type OutreachMailbox, type OutreachSequence, type OutreachSequenceStats, type OutreachStepOverrides } from './outreach.types';
|
|
18
18
|
/** A stored sequence in its model shape, or `null` for no document. */
|
|
19
19
|
export declare function readStoredOutreachSequence(id: string, data: Record<string, unknown> | undefined): OutreachSequence | null;
|
|
20
20
|
/**
|
|
@@ -27,6 +27,14 @@ export declare function readStoredOutreachSequence(id: string, data: Record<stri
|
|
|
27
27
|
* reader could make it.
|
|
28
28
|
*/
|
|
29
29
|
export declare function readOutreachSequenceStats(raw: unknown): OutreachSequenceStats | null;
|
|
30
|
+
/**
|
|
31
|
+
* A stored enrollment's curated steps (AGL-3324), or `undefined` when it
|
|
32
|
+
* carries none worth reading. Read a field at a time, because what is read
|
|
33
|
+
* here is what gets SENT in place of the step: an entry with neither a
|
|
34
|
+
* subject nor a body, or one keyed by something that is not a step index,
|
|
35
|
+
* is dropped rather than sent as an empty email.
|
|
36
|
+
*/
|
|
37
|
+
export declare function readOutreachStepOverrides(raw: unknown): OutreachStepOverrides | undefined;
|
|
30
38
|
/** A stored enrollment in its model shape, or `null` for no document. */
|
|
31
39
|
export declare function readStoredOutreachEnrollment(id: string, data: Record<string, unknown> | undefined): OutreachEnrollment | null;
|
|
32
40
|
/** A stored mailbox with its id, or `null` for no document. */
|
|
@@ -23,7 +23,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
23
23
|
* what decides whether it is sent at all.
|
|
24
24
|
*/ import { normalizeCampaignIds } from "@aglyn/aglyn/app-utils/campaign-membership";
|
|
25
25
|
import { readOutreachSequenceDraft } from "./sequence-draft.js";
|
|
26
|
-
import { OUTREACH_ENROLLMENT_STATUSES, OUTREACH_SEQUENCE_STATUSES, OUTREACH_STOP_REASONS } from "./outreach.types.js";
|
|
26
|
+
import { OUTREACH_ENROLLMENT_STATUSES, OUTREACH_SEQUENCE_STATUSES, OUTREACH_STEP_OVERRIDE_SOURCES, OUTREACH_STOP_REASONS } from "./outreach.types.js";
|
|
27
27
|
const text = (value)=>typeof value === 'string' ? value : '';
|
|
28
28
|
const ms = (value)=>typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
29
29
|
const texts = (value)=>Array.isArray(value) ? value.filter((entry)=>typeof entry === 'string') : [];
|
|
@@ -73,6 +73,45 @@ const texts = (value)=>Array.isArray(value) ? value.filter((entry)=>typeof entry
|
|
|
73
73
|
if (typeof last === 'number' && Number.isFinite(last)) stats.lastClickAtMs = last;
|
|
74
74
|
return Object.keys(stats).length ? stats : null;
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* A stored enrollment's curated steps (AGL-3324), or `undefined` when it
|
|
78
|
+
* carries none worth reading. Read a field at a time, because what is read
|
|
79
|
+
* here is what gets SENT in place of the step: an entry with neither a
|
|
80
|
+
* subject nor a body, or one keyed by something that is not a step index,
|
|
81
|
+
* is dropped rather than sent as an empty email.
|
|
82
|
+
*/ export function readOutreachStepOverrides(raw) {
|
|
83
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
|
|
84
|
+
const overrides = {};
|
|
85
|
+
for (const [key, value] of Object.entries(raw)){
|
|
86
|
+
var _ms;
|
|
87
|
+
if (!/^(0|[1-9]\d*)$/.test(key) || !value || typeof value !== 'object') continue;
|
|
88
|
+
const entry = value;
|
|
89
|
+
const subject = typeof entry['subject'] === 'string' ? entry['subject'] : undefined;
|
|
90
|
+
const body = typeof entry['body'] === 'string' ? entry['body'] : undefined;
|
|
91
|
+
if (subject === undefined && body === undefined) continue;
|
|
92
|
+
const source = entry['source'];
|
|
93
|
+
const override = _extends({}, subject !== undefined ? {
|
|
94
|
+
subject
|
|
95
|
+
} : {}, body !== undefined ? {
|
|
96
|
+
body
|
|
97
|
+
} : {}, {
|
|
98
|
+
// Words nobody can say the source of are read as the member's: the
|
|
99
|
+
// audit line then claims no AI wrote them.
|
|
100
|
+
source: OUTREACH_STEP_OVERRIDE_SOURCES.includes(source) ? source : 'member',
|
|
101
|
+
draftedAtMs: (_ms = ms(entry['draftedAtMs'])) != null ? _ms : 0
|
|
102
|
+
}, typeof entry['draftedByUid'] === 'string' ? {
|
|
103
|
+
draftedByUid: entry['draftedByUid']
|
|
104
|
+
} : {}, entry['edited'] === true ? {
|
|
105
|
+
edited: true
|
|
106
|
+
} : {}, typeof entry['prompt'] === 'string' ? {
|
|
107
|
+
prompt: entry['prompt']
|
|
108
|
+
} : {}, typeof entry['model'] === 'string' ? {
|
|
109
|
+
model: entry['model']
|
|
110
|
+
} : {});
|
|
111
|
+
overrides[key] = override;
|
|
112
|
+
}
|
|
113
|
+
return Object.keys(overrides).length ? overrides : undefined;
|
|
114
|
+
}
|
|
76
115
|
/** A stored enrollment in its model shape, or `null` for no document. */ export function readStoredOutreachEnrollment(id, data) {
|
|
77
116
|
var _ms, _ms1;
|
|
78
117
|
if (!data) return null;
|
|
@@ -84,7 +123,7 @@ const texts = (value)=>Array.isArray(value) ? value.filter((entry)=>typeof entry
|
|
|
84
123
|
// lead's, whatever else it says.
|
|
85
124
|
const leadId = text(data['leadId']) || null;
|
|
86
125
|
const target = data['target'] === 'lead' || data['target'] === undefined && leadId && !text(data['contactId']) ? 'lead' : 'contact';
|
|
87
|
-
|
|
126
|
+
const enrollment = _extends({}, data, {
|
|
88
127
|
id,
|
|
89
128
|
sequenceId: text(data['sequenceId']),
|
|
90
129
|
target,
|
|
@@ -118,6 +157,12 @@ const texts = (value)=>Array.isArray(value) ? value.filter((entry)=>typeof entry
|
|
|
118
157
|
createdAtMs: (_ms = ms(data['createdAtMs'])) != null ? _ms : 0,
|
|
119
158
|
updatedAtMs: (_ms1 = ms(data['updatedAtMs'])) != null ? _ms1 : 0
|
|
120
159
|
});
|
|
160
|
+
// Absent rather than an empty map for an enrollment nobody curated
|
|
161
|
+
// (AGL-3324): the spread above would otherwise carry whatever was stored.
|
|
162
|
+
const stepOverrides = readOutreachStepOverrides(data['stepOverrides']);
|
|
163
|
+
if (stepOverrides) enrollment.stepOverrides = stepOverrides;
|
|
164
|
+
else delete enrollment.stepOverrides;
|
|
165
|
+
return enrollment;
|
|
121
166
|
}
|
|
122
167
|
/** A stored mailbox with its id, or `null` for no document. */ export function readStoredOutreachMailbox(id, data) {
|
|
123
168
|
if (!data) return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/stored-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A stored Outreach document read back into its model shape (AGL-2980),\n * for the server's routes and the console's listeners alike. Client-safe.\n *\n * Read DEFENSIVELY, a field at a time, because the readers act on what they\n * read: a sequence's steps are what gets sent, and an enrollment's status is\n * what decides whether it is sent at all.\n */\n\nimport { normalizeCampaignIds } from '@aglyn/aglyn/app-utils/campaign-membership'\nimport { readOutreachSequenceDraft } from './sequence-draft'\nimport {\n OUTREACH_ENROLLMENT_STATUSES,\n OUTREACH_SEQUENCE_STATUSES,\n OUTREACH_STOP_REASONS,\n type OutreachEnrollment,\n type OutreachEnrollmentStatus,\n type OutreachEnrollmentTarget,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachSequenceStats,\n type OutreachSequenceStatus,\n type OutreachStopReason,\n} from './outreach.types'\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value : ''\nconst ms = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\nconst texts = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : []\n\n/** A stored sequence in its model shape, or `null` for no document. */\nexport function readStoredOutreachSequence(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachSequence | null {\n if (!data) return null\n const draft = readOutreachSequenceDraft(data)\n const status = data['status']\n const stats = readOutreachSequenceStats(data['stats'])\n return {\n id,\n ...draft,\n status: (OUTREACH_SEQUENCE_STATUSES as readonly unknown[]).includes(status)\n ? (status as OutreachSequenceStatus)\n : 'draft',\n // Absent rather than an empty object for a sequence that has none\n // (AGL-3239): the report reads an absent counter as \"not recorded\" and\n // a present one as a number, and `{}` would be neither.\n ...(stats ? { stats } : {}),\n createdAtMs: ms(data['createdAtMs']) ?? 0,\n updatedAtMs: ms(data['updatedAtMs']) ?? 0,\n }\n}\n\n/**\n * A sequence's stored counters (AGL-3239), or `null` when it has none.\n *\n * Every field is carried through only when it is READABLE, so an absence\n * survives the round trip as an absence: the whole of the report's honesty\n * is that a counter nobody wrote is not a zero, and a normalizer that\n * defaulted these to `0` would destroy the distinction here, before any\n * reader could make it.\n */\nexport function readOutreachSequenceStats(\n raw: unknown,\n): OutreachSequenceStats | null {\n if (!raw || typeof raw !== 'object') return null\n const data = raw as Record<string, unknown>\n const stats: OutreachSequenceStats = {}\n for (const key of ['sent', 'people', 'clicks', 'uniqueClicks', 'machineClicks'] as const) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {\n stats[key] = Math.floor(value)\n }\n }\n if (data['clickTracked'] === true) stats.clickTracked = true\n const last = data['lastClickAtMs']\n if (typeof last === 'number' && Number.isFinite(last)) stats.lastClickAtMs = last\n return Object.keys(stats).length ? stats : null\n}\n\n/** A stored enrollment in its model shape, or `null` for no document. */\nexport function readStoredOutreachEnrollment(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachEnrollment | null {\n if (!data) return null\n const status = data['status']\n const stopReason = data['stopReason']\n const stepIndex = Number(data['stepIndex'])\n // An enrollment written before leads could be sequenced (AGL-3234) names\n // no target and is a contact's; one that names a lead and no target is a\n // lead's, whatever else it says.\n const leadId = text(data['leadId']) || null\n const target: OutreachEnrollmentTarget =\n data['target'] === 'lead' || (data['target'] === undefined && leadId && !text(data['contactId']))\n ? 'lead'\n : 'contact'\n return {\n ...(data as unknown as OutreachEnrollment),\n id,\n sequenceId: text(data['sequenceId']),\n target,\n contactId: text(data['contactId']),\n leadId,\n contactName: text(data['contactName']),\n email: text(data['email']),\n hostId: text(data['hostId']),\n mailboxId: text(data['mailboxId']),\n stepIndex: Number.isInteger(stepIndex) && stepIndex >= 0 ? stepIndex : 0,\n nextDueAtMs: ms(data['nextDueAtMs']),\n // A status the model does not name is read as stopped: nothing sends\n // from a document nobody can say the state of.\n status: (OUTREACH_ENROLLMENT_STATUSES as readonly unknown[]).includes(\n status,\n )\n ? (status as OutreachEnrollmentStatus)\n : 'stopped',\n stopReason: (OUTREACH_STOP_REASONS as readonly unknown[]).includes(\n stopReason,\n )\n ? (stopReason as OutreachStopReason)\n : null,\n stopDetail:\n typeof data['stopDetail'] === 'string' ? data['stopDetail'] : null,\n stoppedAtMs: ms(data['stoppedAtMs']),\n stoppedByUid:\n typeof data['stoppedByUid'] === 'string' ? data['stoppedByUid'] : null,\n personalLine: text(data['personalLine']),\n cold: data['cold'] === true,\n enrolledByUid: text(data['enrolledByUid']),\n gmailThreadId:\n typeof data['gmailThreadId'] === 'string' ? data['gmailThreadId'] : null,\n gmailThreadIds: texts(data['gmailThreadIds']),\n threadSubject:\n typeof data['threadSubject'] === 'string' ? data['threadSubject'] : null,\n messageIds: texts(data['messageIds']),\n lastSentAtMs: ms(data['lastSentAtMs']),\n // Absent on an enrollment made before a sequence could join a campaign\n // (AGL-3254), and read as none: nothing is credited to a campaign the\n // enrollment does not name.\n campaignIds: normalizeCampaignIds(data['campaignIds']),\n createdAtMs: ms(data['createdAtMs']) ?? 0,\n updatedAtMs: ms(data['updatedAtMs']) ?? 0,\n }\n}\n\n/** A stored mailbox with its id, or `null` for no document. */\nexport function readStoredOutreachMailbox(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachMailbox | null {\n if (!data) return null\n return { ...(data as unknown as OutreachMailbox), id }\n}\n"],"names":["normalizeCampaignIds","readOutreachSequenceDraft","OUTREACH_ENROLLMENT_STATUSES","OUTREACH_SEQUENCE_STATUSES","OUTREACH_STOP_REASONS","text","value","ms","Number","isFinite","texts","Array","isArray","filter","entry","readStoredOutreachSequence","id","data","draft","status","stats","readOutreachSequenceStats","includes","createdAtMs","updatedAtMs","raw","key","Math","floor","clickTracked","last","lastClickAtMs","Object","keys","length","readStoredOutreachEnrollment","stopReason","stepIndex","leadId","target","undefined","sequenceId","contactId","contactName","email","hostId","mailboxId","isInteger","nextDueAtMs","stopDetail","stoppedAtMs","stoppedByUid","personalLine","cold","enrolledByUid","gmailThreadId","gmailThreadIds","threadSubject","messageIds","lastSentAtMs","campaignIds","readStoredOutreachMailbox"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC,GAED,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,SAASC,yBAAyB,QAAQ,sBAAkB;AAC5D,SACEC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,qBAAqB,QAShB,sBAAkB;AAEzB,MAAMC,OAAO,CAACC,QACZ,OAAOA,UAAU,WAAWA,QAAQ;AACtC,MAAMC,KAAK,CAACD,QACV,OAAOA,UAAU,YAAYE,OAAOC,QAAQ,CAACH,SAASA,QAAQ;AAChE,MAAMI,QAAQ,CAACJ,QACbK,MAAMC,OAAO,CAACN,SACVA,MAAMO,MAAM,C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O,KAAK;QACvBqC,eAAejD,KAAKY,IAAI,CAAC,gBAAgB;QACzCsC,eACE,OAAOtC,IAAI,CAAC,gBAAgB,KAAK,WAAWA,IAAI,CAAC,gBAAgB,GAAG;QACtEuC,gBAAgB9C,MAAMO,IAAI,CAAC,iBAAiB;QAC5CwC,eACE,OAAOxC,IAAI,CAAC,gBAAgB,KAAK,WAAWA,IAAI,CAAC,gBAAgB,GAAG;QACtEyC,YAAYhD,MAAMO,IAAI,CAAC,aAAa;QACpC0C,cAAcpD,GAAGU,IAAI,CAAC,eAAe;QACrC,uEAAuE;QACvE,sEAAsE;QACtE,4BAA4B;QAC5B2C,aAAa5D,qBAAqBiB,IAAI,CAAC,cAAc;QACrDM,WAAW,GAAEhB,MAAAA,GAAGU,IAAI,CAAC,cAAc,aAAtBV,MAA2B;QACxCiB,WAAW,GAAEjB,OAAAA,GAAGU,IAAI,CAAC,cAAc,aAAtBV,OAA2B;;AAE5C;AAEA,6DAA6D,GAC7D,OAAO,SAASsD,0BACd7C,EAAU,EACVC,IAAyC;IAEzC,IAAI,CAACA,MAAM,OAAO;IAClB,OAAO,aAAMA;QAAqCD;;AACpD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/model/stored-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A stored Outreach document read back into its model shape (AGL-2980),\n * for the server's routes and the console's listeners alike. Client-safe.\n *\n * Read DEFENSIVELY, a field at a time, because the readers act on what they\n * read: a sequence's steps are what gets sent, and an enrollment's status is\n * what decides whether it is sent at all.\n */\n\nimport { normalizeCampaignIds } from '@aglyn/aglyn/app-utils/campaign-membership'\nimport { readOutreachSequenceDraft } from './sequence-draft'\nimport {\n OUTREACH_ENROLLMENT_STATUSES,\n OUTREACH_SEQUENCE_STATUSES,\n OUTREACH_STEP_OVERRIDE_SOURCES,\n OUTREACH_STOP_REASONS,\n type OutreachEnrollment,\n type OutreachEnrollmentStatus,\n type OutreachEnrollmentTarget,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachSequenceStats,\n type OutreachSequenceStatus,\n type OutreachStepOverride,\n type OutreachStepOverrides,\n type OutreachStopReason,\n} from './outreach.types'\n\nconst text = (value: unknown): string =>\n typeof value === 'string' ? value : ''\nconst ms = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\nconst texts = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : []\n\n/** A stored sequence in its model shape, or `null` for no document. */\nexport function readStoredOutreachSequence(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachSequence | null {\n if (!data) return null\n const draft = readOutreachSequenceDraft(data)\n const status = data['status']\n const stats = readOutreachSequenceStats(data['stats'])\n return {\n id,\n ...draft,\n status: (OUTREACH_SEQUENCE_STATUSES as readonly unknown[]).includes(status)\n ? (status as OutreachSequenceStatus)\n : 'draft',\n // Absent rather than an empty object for a sequence that has none\n // (AGL-3239): the report reads an absent counter as \"not recorded\" and\n // a present one as a number, and `{}` would be neither.\n ...(stats ? { stats } : {}),\n createdAtMs: ms(data['createdAtMs']) ?? 0,\n updatedAtMs: ms(data['updatedAtMs']) ?? 0,\n }\n}\n\n/**\n * A sequence's stored counters (AGL-3239), or `null` when it has none.\n *\n * Every field is carried through only when it is READABLE, so an absence\n * survives the round trip as an absence: the whole of the report's honesty\n * is that a counter nobody wrote is not a zero, and a normalizer that\n * defaulted these to `0` would destroy the distinction here, before any\n * reader could make it.\n */\nexport function readOutreachSequenceStats(\n raw: unknown,\n): OutreachSequenceStats | null {\n if (!raw || typeof raw !== 'object') return null\n const data = raw as Record<string, unknown>\n const stats: OutreachSequenceStats = {}\n for (const key of ['sent', 'people', 'clicks', 'uniqueClicks', 'machineClicks'] as const) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {\n stats[key] = Math.floor(value)\n }\n }\n if (data['clickTracked'] === true) stats.clickTracked = true\n const last = data['lastClickAtMs']\n if (typeof last === 'number' && Number.isFinite(last)) stats.lastClickAtMs = last\n return Object.keys(stats).length ? stats : null\n}\n\n/**\n * A stored enrollment's curated steps (AGL-3324), or `undefined` when it\n * carries none worth reading. Read a field at a time, because what is read\n * here is what gets SENT in place of the step: an entry with neither a\n * subject nor a body, or one keyed by something that is not a step index,\n * is dropped rather than sent as an empty email.\n */\nexport function readOutreachStepOverrides(raw: unknown): OutreachStepOverrides | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n const overrides: OutreachStepOverrides = {}\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (!/^(0|[1-9]\\d*)$/.test(key) || !value || typeof value !== 'object') continue\n const entry = value as Record<string, unknown>\n const subject = typeof entry['subject'] === 'string' ? entry['subject'] : undefined\n const body = typeof entry['body'] === 'string' ? entry['body'] : undefined\n if (subject === undefined && body === undefined) continue\n const source = entry['source']\n const override: OutreachStepOverride = {\n ...(subject !== undefined ? { subject } : {}),\n ...(body !== undefined ? { body } : {}),\n // Words nobody can say the source of are read as the member's: the\n // audit line then claims no AI wrote them.\n source: (OUTREACH_STEP_OVERRIDE_SOURCES as readonly unknown[]).includes(source)\n ? (source as OutreachStepOverride['source'])\n : 'member',\n draftedAtMs: ms(entry['draftedAtMs']) ?? 0,\n ...(typeof entry['draftedByUid'] === 'string' ? { draftedByUid: entry['draftedByUid'] } : {}),\n ...(entry['edited'] === true ? { edited: true } : {}),\n ...(typeof entry['prompt'] === 'string' ? { prompt: entry['prompt'] } : {}),\n ...(typeof entry['model'] === 'string' ? { model: entry['model'] } : {}),\n }\n overrides[key] = override\n }\n return Object.keys(overrides).length ? overrides : undefined\n}\n\n/** A stored enrollment in its model shape, or `null` for no document. */\nexport function readStoredOutreachEnrollment(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachEnrollment | null {\n if (!data) return null\n const status = data['status']\n const stopReason = data['stopReason']\n const stepIndex = Number(data['stepIndex'])\n // An enrollment written before leads could be sequenced (AGL-3234) names\n // no target and is a contact's; one that names a lead and no target is a\n // lead's, whatever else it says.\n const leadId = text(data['leadId']) || null\n const target: OutreachEnrollmentTarget =\n data['target'] === 'lead' || (data['target'] === undefined && leadId && !text(data['contactId']))\n ? 'lead'\n : 'contact'\n const enrollment: OutreachEnrollment = {\n ...(data as unknown as OutreachEnrollment),\n id,\n sequenceId: text(data['sequenceId']),\n target,\n contactId: text(data['contactId']),\n leadId,\n contactName: text(data['contactName']),\n email: text(data['email']),\n hostId: text(data['hostId']),\n mailboxId: text(data['mailboxId']),\n stepIndex: Number.isInteger(stepIndex) && stepIndex >= 0 ? stepIndex : 0,\n nextDueAtMs: ms(data['nextDueAtMs']),\n // A status the model does not name is read as stopped: nothing sends\n // from a document nobody can say the state of.\n status: (OUTREACH_ENROLLMENT_STATUSES as readonly unknown[]).includes(\n status,\n )\n ? (status as OutreachEnrollmentStatus)\n : 'stopped',\n stopReason: (OUTREACH_STOP_REASONS as readonly unknown[]).includes(\n stopReason,\n )\n ? (stopReason as OutreachStopReason)\n : null,\n stopDetail:\n typeof data['stopDetail'] === 'string' ? data['stopDetail'] : null,\n stoppedAtMs: ms(data['stoppedAtMs']),\n stoppedByUid:\n typeof data['stoppedByUid'] === 'string' ? data['stoppedByUid'] : null,\n personalLine: text(data['personalLine']),\n cold: data['cold'] === true,\n enrolledByUid: text(data['enrolledByUid']),\n gmailThreadId:\n typeof data['gmailThreadId'] === 'string' ? data['gmailThreadId'] : null,\n gmailThreadIds: texts(data['gmailThreadIds']),\n threadSubject:\n typeof data['threadSubject'] === 'string' ? data['threadSubject'] : null,\n messageIds: texts(data['messageIds']),\n lastSentAtMs: ms(data['lastSentAtMs']),\n // Absent on an enrollment made before a sequence could join a campaign\n // (AGL-3254), and read as none: nothing is credited to a campaign the\n // enrollment does not name.\n campaignIds: normalizeCampaignIds(data['campaignIds']),\n createdAtMs: ms(data['createdAtMs']) ?? 0,\n updatedAtMs: ms(data['updatedAtMs']) ?? 0,\n }\n // Absent rather than an empty map for an enrollment nobody curated\n // (AGL-3324): the spread above would otherwise carry whatever was stored.\n const stepOverrides = readOutreachStepOverrides(data['stepOverrides'])\n if (stepOverrides) enrollment.stepOverrides = stepOverrides\n else delete enrollment.stepOverrides\n return enrollment\n}\n\n/** A stored mailbox with its id, or `null` for no document. */\nexport function readStoredOutreachMailbox(\n id: string,\n data: Record<string, unknown> | undefined,\n): OutreachMailbox | null {\n if (!data) return null\n return { ...(data as unknown as OutreachMailbox), id }\n}\n"],"names":["normalizeCampaignIds","readOutreachSequenceDraft","OUTREACH_ENROLLMENT_STATUSES","OUTREACH_SEQUENCE_STATUSES","OUTREACH_STEP_OVERRIDE_SOURCES","OUTREACH_STOP_REASONS","text","value","ms","Number","isFinite","texts","Array","isArray","filter","entry","readStoredOutreachSequence","id","data","draft","status","stats","readOutreachSequenceStats","includes","createdAtMs","updatedAtMs","raw","key","Math","floor","clickTracked","last","lastClickAtMs","Object","keys","length","readOutreachStepOverrides","undefined","overrides","entries","test","subject","body","source","override","draftedAtMs","draftedByUid","edited","prompt","model","readStoredOutreachEnrollment","stopReason","stepIndex","leadId","target","enrollment","sequenceId","contactId","contactName","email","hostId","mailboxId","isInteger","nextDueAtMs","stopDetail","stoppedAtMs","stoppedByUid","personalLine","cold","enrolledByUid","gmailThreadId","gmailThreadIds","threadSubject","messageIds","lastSentAtMs","campaignIds","stepOverrides","readStoredOutreachMailbox"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC,GAED,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,SA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D,OAAO,SAASsB,0BACd5D,EAAU,EACVC,IAAyC;IAEzC,IAAI,CAACA,MAAM,OAAO;IAClB,OAAO,aAAMA;QAAqCD;;AACpD"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { PluginTextGenerator } from '@aglyn/aglyn/plugin-manager/plugin-text-generation';
|
|
18
|
+
import type { PluginWebApiHandler } from '@aglyn/aglyn/server';
|
|
19
|
+
import { type OutreachEnrollRouteDeps } from './enroll-routes';
|
|
20
|
+
/**
|
|
21
|
+
* CURATING ONE PERSON'S EMAILS (AGL-3324): `outreach/curate/draft` and
|
|
22
|
+
* `outreach/curate/save`.
|
|
23
|
+
*
|
|
24
|
+
* A sequence's step is one template for everyone plus the personal line;
|
|
25
|
+
* what an agent-run outbound tool does instead is write each send for each
|
|
26
|
+
* prospect from what it knows about them, and let the seller approve or
|
|
27
|
+
* edit. These two routes are that, with the member's confirmation kept as
|
|
28
|
+
* the one thing that stores anything.
|
|
29
|
+
*
|
|
30
|
+
* DRAFT reads the person the way enrolling reads them — the contact, or the
|
|
31
|
+
* lead as the contact it would be, with the company filed beside them — and
|
|
32
|
+
* asks the workspace's text generator, on the core's seam, for this
|
|
33
|
+
* person's copy of the email steps named: every email step for a person
|
|
34
|
+
* about to be enrolled, the next one for an enrollment. The answer is
|
|
35
|
+
* validated against the playbook's rules and returned with each draft's
|
|
36
|
+
* issues, the prompt and the model. NOTHING IS STORED: the member reads it
|
|
37
|
+
* in the dialog, edits it, ticks the confirmation, and then either enrolls
|
|
38
|
+
* (the enroll route stores the copies with the enrollment) or saves.
|
|
39
|
+
*
|
|
40
|
+
* SAVE stores one confirmed copy on an open enrollment, for a step that
|
|
41
|
+
* has not gone out, validated again — the request is not trusted to have
|
|
42
|
+
* shown the member what it sends — and files "Curated step N" on the
|
|
43
|
+
* person's record with who wrote the words. `override: null` clears a copy,
|
|
44
|
+
* so the step goes back to the sequence's own words.
|
|
45
|
+
*
|
|
46
|
+
* Both read the CRM, so both ask for `data.manage` beside `outreach.use`;
|
|
47
|
+
* the generator applies its own rules — the generation permission, the
|
|
48
|
+
* plan, the switches, the allotments — to the member named, and meters the
|
|
49
|
+
* draft on the member's month and the org's. Outreach never reaches the AI
|
|
50
|
+
* plugin: the seam is the platform's, and a workspace where no plugin
|
|
51
|
+
* generates text is told so in the route's words.
|
|
52
|
+
*/
|
|
53
|
+
/** The purpose the generator's ledger files a draft under. */
|
|
54
|
+
export declare const OUTREACH_CURATION_PURPOSE = "outreach-curate";
|
|
55
|
+
/** The org activity line a saved copy writes. */
|
|
56
|
+
export declare function outreachCuratedActivity(stepIndex: number, cleared: boolean): string;
|
|
57
|
+
export interface OutreachCurateRoutes {
|
|
58
|
+
draft: PluginWebApiHandler;
|
|
59
|
+
save: PluginWebApiHandler;
|
|
60
|
+
}
|
|
61
|
+
export declare function createOutreachCurateRoutes(deps: OutreachEnrollRouteDeps): OutreachCurateRoutes;
|
|
62
|
+
/** The text generator on the core's seam, for the default route deps; `null` when no plugin generates. */
|
|
63
|
+
export type OutreachTextGeneratorReader = () => PluginTextGenerator | null;
|