@aglyn/plugins-outreach 1.0.0-beta.197 → 1.0.0-beta.199
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/compliance-section.d.ts +3 -1
- package/src/lib/components/compliance-section.js +110 -45
- package/src/lib/components/compliance-section.js.map +1 -1
- package/src/lib/components/enroll-dialog.d.ts +7 -1
- package/src/lib/components/enroll-dialog.js +47 -3
- package/src/lib/components/enroll-dialog.js.map +1 -1
- package/src/lib/components/outreach-ui.js +1 -0
- package/src/lib/components/outreach-ui.js.map +1 -1
- package/src/lib/components/sequence-editor.js +25 -24
- package/src/lib/components/sequence-editor.js.map +1 -1
- package/src/lib/engine/delivery-status.d.ts +8 -0
- package/src/lib/engine/delivery-status.js +10 -5
- package/src/lib/engine/delivery-status.js.map +1 -1
- package/src/lib/engine/enrollment-state.d.ts +2 -0
- package/src/lib/engine/enrollment-state.js +2 -2
- package/src/lib/engine/enrollment-state.js.map +1 -1
- package/src/lib/engine/gates.d.ts +28 -1
- package/src/lib/engine/gates.js +28 -1
- package/src/lib/engine/gates.js.map +1 -1
- package/src/lib/engine/mail-gateway.d.ts +97 -0
- package/src/lib/engine/mail-gateway.js +226 -0
- package/src/lib/engine/mail-gateway.js.map +1 -0
- package/src/lib/engine/mailbox-health.d.ts +3 -3
- package/src/lib/engine/mailbox-health.js +17 -11
- package/src/lib/engine/mailbox-health.js.map +1 -1
- package/src/lib/engine/thread-classification.d.ts +2 -0
- package/src/lib/engine/thread-classification.js +2 -1
- package/src/lib/engine/thread-classification.js.map +1 -1
- package/src/lib/enrollment/enroll-people.d.ts +6 -1
- package/src/lib/enrollment/enroll-people.js +18 -4
- package/src/lib/enrollment/enroll-people.js.map +1 -1
- package/src/lib/enrollment/gate-lookups.d.ts +7 -0
- package/src/lib/enrollment/gate-lookups.js +11 -2
- package/src/lib/enrollment/gate-lookups.js.map +1 -1
- package/src/lib/model/outreach-api.d.ts +14 -0
- package/src/lib/model/outreach-api.js.map +1 -1
- package/src/lib/model/outreach.types.d.ts +79 -3
- package/src/lib/model/outreach.types.js +21 -2
- package/src/lib/model/outreach.types.js.map +1 -1
- package/src/lib/routes/enroll-routes.js +23 -4
- package/src/lib/routes/enroll-routes.js.map +1 -1
- package/src/lib/routes/enrollment-routes.js +15 -1
- package/src/lib/routes/enrollment-routes.js.map +1 -1
- package/src/lib/routes/register-routes.js +3 -0
- package/src/lib/routes/register-routes.js.map +1 -1
- package/src/lib/routes/route-deps.d.ts +6 -0
- package/src/lib/routes/route-deps.js.map +1 -1
- package/src/lib/runtime/gateway-ledger.d.ts +46 -0
- package/src/lib/runtime/gateway-ledger.js +113 -0
- package/src/lib/runtime/gateway-ledger.js.map +1 -0
- package/src/lib/runtime/platform-runtime-deps.js +3 -0
- package/src/lib/runtime/platform-runtime-deps.js.map +1 -1
- package/src/lib/runtime/runtime-deps.d.ts +6 -0
- package/src/lib/runtime/runtime-deps.js.map +1 -1
- package/src/lib/runtime/send-job.js +48 -0
- package/src/lib/runtime/send-job.js.map +1 -1
- package/src/lib/runtime/sync-job.d.ts +2 -0
- package/src/lib/runtime/sync-job.js +40 -3
- package/src/lib/runtime/sync-job.js.map +1 -1
- package/src/lib/storage/domain-intel-store.d.ts +107 -0
- package/src/lib/storage/domain-intel-store.js +320 -0
- package/src/lib/storage/domain-intel-store.js.map +1 -0
|
@@ -24,14 +24,21 @@
|
|
|
24
24
|
*
|
|
25
25
|
* - it collects {@link OUTREACH_PAUSE_BOUNCES_PER_DAY} hard bounces in one
|
|
26
26
|
* of its own days; or
|
|
27
|
-
* -
|
|
27
|
+
* - {@link OUTREACH_PAUSE_BOUNCES_PER_WINDOW} of its last
|
|
28
28
|
* {@link OUTREACH_BOUNCE_RATE_WINDOW_SENDS} sends hard-bounced, once the
|
|
29
29
|
* window holds at least {@link OUTREACH_BOUNCE_RATE_MIN_SENDS} of them
|
|
30
|
-
* (AGL-3244). Under that floor one bounce IS the
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
30
|
+
* (AGL-3244). Under that floor one bounce IS the window — 1 of 21 — and a
|
|
31
|
+
* single gateway block on a cold day closed a whole sending window on the
|
|
32
|
+
* strength of one address. A mailbox with fewer sends is still judged on
|
|
33
|
+
* the sends it has by the first rule: a second bounce in one day pauses
|
|
34
|
+
* it whatever the window holds.
|
|
35
|
+
*
|
|
36
|
+
* A COUNT, not a rate (AGL-3326). The rule was "more than 3% of the last
|
|
37
|
+
* 50", and 3% of fifty is one and a half: a bounce from two days ago plus
|
|
38
|
+
* one today made 4%, and paused a mailbox on the strength of history the
|
|
39
|
+
* daily rule had already judged and let pass. Two bounces in one day are
|
|
40
|
+
* the first rule's; the window rule is for a slow drip the days hide, and
|
|
41
|
+
* three of fifty is where a drip stops being one address; or
|
|
35
42
|
* - a reply called its email spam in the last week — a complaint is worth a
|
|
36
43
|
* week of review, and the pause lasts until the week is out.
|
|
37
44
|
*
|
|
@@ -39,7 +46,7 @@
|
|
|
39
46
|
* and the sending server is still retrying it.
|
|
40
47
|
*==========================================*/ /** Hard bounces in one mailbox day that pause the mailbox. */ export const OUTREACH_PAUSE_BOUNCES_PER_DAY = 2;
|
|
41
48
|
/** How many of the most recent sends the bounce rate is taken over. */ export const OUTREACH_BOUNCE_RATE_WINDOW_SENDS = 50;
|
|
42
|
-
/**
|
|
49
|
+
/** Hard bounces in that window that pause the mailbox. */ export const OUTREACH_PAUSE_BOUNCES_PER_WINDOW = 3;
|
|
43
50
|
/**
|
|
44
51
|
* The fewest sends the window must hold before its bounce rate is judged
|
|
45
52
|
* (AGL-3244). Below it the daily rule alone pauses the mailbox.
|
|
@@ -61,12 +68,11 @@ const count = (value)=>{
|
|
|
61
68
|
}
|
|
62
69
|
const sends = Math.min(count(input.recentSends), OUTREACH_BOUNCE_RATE_WINDOW_SENDS);
|
|
63
70
|
const bounces = Math.min(count(input.recentHardBounces), sends);
|
|
64
|
-
if (sends >= OUTREACH_BOUNCE_RATE_MIN_SENDS && bounces
|
|
65
|
-
const percent = (bounces / sends * 100).toFixed(1);
|
|
71
|
+
if (sends >= OUTREACH_BOUNCE_RATE_MIN_SENDS && bounces >= OUTREACH_PAUSE_BOUNCES_PER_WINDOW) {
|
|
66
72
|
return {
|
|
67
73
|
pause: true,
|
|
68
|
-
reason: '
|
|
69
|
-
message: `Paused: ${bounces} of the last ${sends} emails hard-bounced
|
|
74
|
+
reason: 'bounces_in_window',
|
|
75
|
+
message: `Paused: ${bounces} of the last ${sends} emails hard-bounced. Re-check the addresses in your sequences before resuming.`,
|
|
70
76
|
pausedUntilMs: null
|
|
71
77
|
};
|
|
72
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/engine/mailbox-health.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 * WHEN A MAILBOX STOPS ITSELF (AGL-2979).\n *\n * Bounces are the one signal a small sender gets early: at this volume the\n * mailbox providers' own dashboards show nothing, and a list with bad\n * addresses in it shows up as hard bounces days before it shows up as a\n * reputation problem. So a mailbox pauses itself, and a person re-checks\n * the list before it sends again, when:\n *\n * - it collects {@link OUTREACH_PAUSE_BOUNCES_PER_DAY} hard bounces in one\n * of its own days; or\n * -
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/engine/mailbox-health.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 * WHEN A MAILBOX STOPS ITSELF (AGL-2979).\n *\n * Bounces are the one signal a small sender gets early: at this volume the\n * mailbox providers' own dashboards show nothing, and a list with bad\n * addresses in it shows up as hard bounces days before it shows up as a\n * reputation problem. So a mailbox pauses itself, and a person re-checks\n * the list before it sends again, when:\n *\n * - it collects {@link OUTREACH_PAUSE_BOUNCES_PER_DAY} hard bounces in one\n * of its own days; or\n * - {@link OUTREACH_PAUSE_BOUNCES_PER_WINDOW} of its last\n * {@link OUTREACH_BOUNCE_RATE_WINDOW_SENDS} sends hard-bounced, once the\n * window holds at least {@link OUTREACH_BOUNCE_RATE_MIN_SENDS} of them\n * (AGL-3244). Under that floor one bounce IS the window — 1 of 21 — and a\n * single gateway block on a cold day closed a whole sending window on the\n * strength of one address. A mailbox with fewer sends is still judged on\n * the sends it has by the first rule: a second bounce in one day pauses\n * it whatever the window holds.\n *\n * A COUNT, not a rate (AGL-3326). The rule was \"more than 3% of the last\n * 50\", and 3% of fifty is one and a half: a bounce from two days ago plus\n * one today made 4%, and paused a mailbox on the strength of history the\n * daily rule had already judged and let pass. Two bounces in one day are\n * the first rule's; the window rule is for a slow drip the days hide, and\n * three of fifty is where a drip stops being one address; or\n * - a reply called its email spam in the last week — a complaint is worth a\n * week of review, and the pause lasts until the week is out.\n *\n * Only hard bounces count. A soft bounce is a full mailbox or a busy server,\n * and the sending server is still retrying it.\n *==========================================*/\n\n/** Hard bounces in one mailbox day that pause the mailbox. */\nexport const OUTREACH_PAUSE_BOUNCES_PER_DAY = 2\n\n/** How many of the most recent sends the bounce rate is taken over. */\nexport const OUTREACH_BOUNCE_RATE_WINDOW_SENDS = 50\n\n/** Hard bounces in that window that pause the mailbox. */\nexport const OUTREACH_PAUSE_BOUNCES_PER_WINDOW = 3\n\n/**\n * The fewest sends the window must hold before its bounce rate is judged\n * (AGL-3244). Below it the daily rule alone pauses the mailbox.\n */\nexport const OUTREACH_BOUNCE_RATE_MIN_SENDS = 25\n\n/** How long a spam complaint keeps a mailbox paused. */\nexport const OUTREACH_COMPLAINT_PAUSE_MS = 7 * 24 * 60 * 60 * 1000\n\nexport type OutreachHealthPauseReason = 'bounces_today' | 'bounces_in_window' | 'complaint'\n\nexport interface OutreachMailboxHealthInput {\n /** Hard bounces on this mailbox's mail received during its current local day. */\n bouncesToday: number\n /**\n * The mailbox's most recent sends — at most\n * {@link OUTREACH_BOUNCE_RATE_WINDOW_SENDS} of them — and how many of\n * those hard-bounced.\n */\n recentSends: number\n recentHardBounces: number\n /** When a reply last called this mailbox's email spam, or `null`. */\n lastComplaintAtMs?: number | null\n nowMs: number\n}\n\nexport interface OutreachMailboxHealthDecision {\n pause: boolean\n reason: OutreachHealthPauseReason | null\n /** What the mailbox's page says, in a sentence. */\n message: string | null\n /** For a complaint, when the pause may end; `null` when a person has to resume it. */\n pausedUntilMs: number | null\n}\n\nconst count = (value: unknown): number => {\n const number = Number(value)\n return Number.isFinite(number) ? Math.max(0, Math.floor(number)) : 0\n}\n\n/** Whether a mailbox should pause itself now — see the module note. */\nexport function decideOutreachMailboxHealth(\n input: OutreachMailboxHealthInput,\n): OutreachMailboxHealthDecision {\n const bouncesToday = count(input.bouncesToday)\n if (bouncesToday >= OUTREACH_PAUSE_BOUNCES_PER_DAY) {\n return {\n pause: true,\n reason: 'bounces_today',\n message: `Paused after ${bouncesToday} hard bounces today. Re-check the addresses in your sequences before resuming.`,\n pausedUntilMs: null,\n }\n }\n const sends = Math.min(count(input.recentSends), OUTREACH_BOUNCE_RATE_WINDOW_SENDS)\n const bounces = Math.min(count(input.recentHardBounces), sends)\n if (sends >= OUTREACH_BOUNCE_RATE_MIN_SENDS && bounces >= OUTREACH_PAUSE_BOUNCES_PER_WINDOW) {\n return {\n pause: true,\n reason: 'bounces_in_window',\n message: `Paused: ${bounces} of the last ${sends} emails hard-bounced. Re-check the addresses in your sequences before resuming.`,\n pausedUntilMs: null,\n }\n }\n const complaintAtMs = input.lastComplaintAtMs\n if (\n typeof complaintAtMs === 'number' &&\n Number.isFinite(complaintAtMs) &&\n input.nowMs < complaintAtMs + OUTREACH_COMPLAINT_PAUSE_MS\n ) {\n return {\n pause: true,\n reason: 'complaint',\n message:\n 'Paused for a week after a reply called an email spam. Review who your sequences are reaching.',\n pausedUntilMs: complaintAtMs + OUTREACH_COMPLAINT_PAUSE_MS,\n }\n }\n return { pause: false, reason: null, message: null, pausedUntilMs: null }\n}\n"],"names":["OUTREACH_PAUSE_BOUNCES_PER_DAY","OUTREACH_BOUNCE_RATE_WINDOW_SENDS","OUTREACH_PAUSE_BOUNCES_PER_WINDOW","OUTREACH_BOUNCE_RATE_MIN_SENDS","OUTREACH_COMPLAINT_PAUSE_MS","count","value","number","Number","isFinite","Math","max","floor","decideOutreachMailboxHealth","input","bouncesToday","pause","reason","message","pausedUntilMs","sends","min","recentSends","bounces","recentHardBounces","complaintAtMs","lastComplaintAtMs","nowMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CA+B4C,GAE5C,4DAA4D,GAC5D,OAAO,MAAMA,iCAAiC,EAAC;AAE/C,qEAAqE,GACrE,OAAO,MAAMC,oCAAoC,GAAE;AAEnD,wDAAwD,GACxD,OAAO,MAAMC,oCAAoC,EAAC;AAElD;;;CAGC,GACD,OAAO,MAAMC,iCAAiC,GAAE;AAEhD,sDAAsD,GACtD,OAAO,MAAMC,8BAA8B,IAAI,KAAK,KAAK,KAAK,KAAI;AA4BlE,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,OAAOF;IACtB,OAAOE,OAAOC,QAAQ,CAACF,UAAUG,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACL,WAAW;AACrE;AAEA,qEAAqE,GACrE,OAAO,SAASM,4BACdC,KAAiC;IAEjC,MAAMC,eAAeV,MAAMS,MAAMC,YAAY;IAC7C,IAAIA,gBAAgBf,gCAAgC;QAClD,OAAO;YACLgB,OAAO;YACPC,QAAQ;YACRC,SAAS,CAAC,aAAa,EAAEH,aAAa,8EAA8E,CAAC;YACrHI,eAAe;QACjB;IACF;IACA,MAAMC,QAAQV,KAAKW,GAAG,CAAChB,MAAMS,MAAMQ,WAAW,GAAGrB;IACjD,MAAMsB,UAAUb,KAAKW,GAAG,CAAChB,MAAMS,MAAMU,iBAAiB,GAAGJ;IACzD,IAAIA,SAASjB,kCAAkCoB,WAAWrB,mCAAmC;QAC3F,OAAO;YACLc,OAAO;YACPC,QAAQ;YACRC,SAAS,CAAC,QAAQ,EAAEK,QAAQ,aAAa,EAAEH,MAAM,+EAA+E,CAAC;YACjID,eAAe;QACjB;IACF;IACA,MAAMM,gBAAgBX,MAAMY,iBAAiB;IAC7C,IACE,OAAOD,kBAAkB,YACzBjB,OAAOC,QAAQ,CAACgB,kBAChBX,MAAMa,KAAK,GAAGF,gBAAgBrB,6BAC9B;QACA,OAAO;YACLY,OAAO;YACPC,QAAQ;YACRC,SACE;YACFC,eAAeM,gBAAgBrB;QACjC;IACF;IACA,OAAO;QAAEY,OAAO;QAAOC,QAAQ;QAAMC,SAAS;QAAMC,eAAe;IAAK;AAC1E"}
|
|
@@ -21,6 +21,8 @@ export interface OutreachBounceDetail {
|
|
|
21
21
|
recipients: string[];
|
|
22
22
|
status: string | null;
|
|
23
23
|
diagnostic: string | null;
|
|
24
|
+
/** The receiving server the report names, when it does (AGL-3326). */
|
|
25
|
+
remoteMta: string | null;
|
|
24
26
|
}
|
|
25
27
|
export interface OutreachMessageClassification {
|
|
26
28
|
messageId: string;
|
|
@@ -122,7 +122,8 @@ function readableText(message) {
|
|
|
122
122
|
bounce: {
|
|
123
123
|
recipients: report.failedAddresses,
|
|
124
124
|
status: report.status,
|
|
125
|
-
diagnostic: report.diagnostic
|
|
125
|
+
diagnostic: report.diagnostic,
|
|
126
|
+
remoteMta: report.remoteMta
|
|
126
127
|
},
|
|
127
128
|
evidence: report.status ? `Status: ${report.status}` : 'delivery report'
|
|
128
129
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/engine/thread-classification.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 * WHAT CAME BACK (AGL-2979).\n *\n * The runtime reads each enrollment's threads and asks what the new\n * messages mean. Each message is one of:\n *\n * - `self` — the mailbox's own: a step, or the rep writing in the thread.\n * - `hard_bounce` / `soft_bounce` — a delivery report (`./delivery-status.ts`).\n * - `delivery_report` — a mail system's message that reports no failure.\n * - `auto_reply` — an out-of-office or an autoresponder. It POSTPONES the\n * next step and does not stop the sequence: nobody answered.\n * - `opt_out` — a reply that asks to be left alone (`./opt-out-intent.ts`),\n * or a message sent to the unsubscribe address.\n * - `reply` — any other message from anybody else.\n *\n * ## Automatic replies\n *\n * Read from the headers the standards give an autoresponder —\n * `Auto-Submitted` with any value but `no` (RFC 3834), `X-Autoreply`,\n * `X-Autorespond`, `Precedence: auto_reply`, `bulk` or `junk` — and, for\n * the servers that set none, from an out-of-office subject in the usual\n * languages.\n *\n * ## The thread's outcome\n *\n * `opted_out` outranks `replied`, which outranks `bounced`, which outranks\n * `postpone`: an opt-out is a reply that also has to reach the do-not-contact\n * list, a person who wrote back matters more than a report about an earlier\n * send, and an out-of-office only matters when nothing else happened. The\n * bounces that report this recipient are counted either way, because mailbox\n * health counts every one.\n *==========================================*/\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmThreadSubject, emailAddressOf, htmlToPlainText } from '@aglyn/aglyn/app-utils/crm-inbound'\nimport { readOutreachDeliveryReport, isMailerDaemonMessage } from './delivery-status'\nimport { detectOutreachOptOutIntent, detectOutreachOptOutSubject } from './opt-out-intent'\nimport { outreachHeader, type OutreachThreadMessage } from './thread-message'\n\nexport type OutreachMessageKind =\n | 'self'\n | 'hard_bounce'\n | 'soft_bounce'\n | 'delivery_report'\n | 'auto_reply'\n | 'opt_out'\n | 'reply'\n\nexport interface OutreachBounceDetail {\n /** The addresses the report says failed; empty when it names none. */\n recipients: string[]\n status: string | null\n diagnostic: string | null\n}\n\nexport interface OutreachMessageClassification {\n messageId: string\n atMs: number\n kind: OutreachMessageKind\n /** The sender's address, normalized, when the `From` carried one. */\n from: string | null\n /** Set on a bounce. */\n bounce: OutreachBounceDetail | null\n /** An opt-out that calls the email spam. */\n complaint: boolean\n /** What decided it, for the timeline and the log. */\n evidence: string | null\n}\n\nexport interface OutreachMessageContext {\n /** The mailbox's own addresses: the account's and every alias it sends as. */\n selfAddresses: readonly string[]\n /** The address a `List-Unsubscribe` mailto points at, when the runtime set one. */\n unsubscribeAddress?: string | null\n /** The subject the thread was started with, so a new subject can be read on its own. */\n threadSubject?: string | null\n}\n\nconst AUTO_REPLY_SUBJECT = new RegExp(\n [\n '^\\\\s*\\\\[?\\\\s*(',\n 'auto(matic)?[\\\\s-]*(reply|response|responder|answer)',\n '|out[\\\\s-]+of[\\\\s-]+(the[\\\\s-]+)?office',\n '|ooo\\\\b',\n \"|i('m| am) (currently )?(out of the office|away|on (vacation|leave|holiday))\",\n '|(on )?(vacation|holiday|annual leave)[\\\\s-]*(reply|response|notice|message|autoreply)',\n '|away from (the |my )?(office|desk)',\n '|abwesenheitsnotiz|abwesenheit',\n '|r[ée]ponse automatique|absence du bureau',\n '|respuesta autom[áa]tica|fuera de la oficina',\n '|risposta automatica|fuori ufficio',\n '|automatisch antwoord|afwezigheidsbericht',\n '|resposta autom[áa]tica|fora do escrit[óo]rio',\n '|autosvar|automaattinen vastaus',\n ')',\n ].join(''),\n 'i',\n)\n\n/**\n * Why a message is an automatic reply, or `null` when it is not one — see\n * the module note for the headers and subjects read.\n */\nexport function outreachAutoReplyEvidence(\n message: Pick<OutreachThreadMessage, 'headers' | 'subject'>,\n): string | null {\n const autoSubmitted = outreachHeader(message, 'Auto-Submitted').split(';')[0].trim().toLowerCase()\n if (autoSubmitted && autoSubmitted !== 'no') return `Auto-Submitted: ${autoSubmitted}`\n for (const name of ['X-Autoreply', 'X-Autorespond']) {\n const value = outreachHeader(message, name).trim()\n if (value && value.toLowerCase() !== 'no') return `${name}: ${value}`\n }\n const precedence = outreachHeader(message, 'Precedence').trim().toLowerCase()\n if (['auto_reply', 'bulk', 'junk'].includes(precedence)) return `Precedence: ${precedence}`\n const subject = String(message?.subject ?? '').replace(/^\\s*(re|fwd?)\\s*:\\s*/i, '')\n const match = AUTO_REPLY_SUBJECT.exec(subject)\n return match ? `Subject: ${match[0].trim()}` : null\n}\n\nfunction addressesIn(header: string): string[] {\n return header\n .split(',')\n .map((part) => emailAddressOf(part))\n .filter((address): address is string => address !== null)\n}\n\nfunction readableText(message: OutreachThreadMessage): string {\n if (message.textBody && message.textBody.trim()) return message.textBody\n if (message.htmlBody && message.htmlBody.trim()) return htmlToPlainText(message.htmlBody)\n return message.snippet ?? ''\n}\n\n/** What one message in an enrollment's thread is — see the module note. */\nexport function classifyOutreachMessage(\n message: OutreachThreadMessage,\n context: OutreachMessageContext,\n): OutreachMessageClassification {\n const from = emailAddressOf(message.from)\n const base = {\n messageId: String(message.id ?? ''),\n atMs: Number.isFinite(message.internalDateMs) ? message.internalDateMs : 0,\n from,\n bounce: null,\n complaint: false,\n evidence: null,\n }\n\n const report = readOutreachDeliveryReport(message)\n if (report) {\n if (!report.kind) return { ...base, kind: 'delivery_report', evidence: 'delivery report' }\n return {\n ...base,\n kind: report.kind === 'hard' ? 'hard_bounce' : 'soft_bounce',\n bounce: {\n recipients: report.failedAddresses,\n status: report.status,\n diagnostic: report.diagnostic,\n },\n evidence: report.status ? `Status: ${report.status}` : 'delivery report',\n }\n }\n\n const self = new Set(\n (context.selfAddresses ?? [])\n .map((address) => normalizeContactEmail(address))\n .filter((address): address is string => address !== null),\n )\n if (from && self.has(from)) return { ...base, kind: 'self' }\n if (isMailerDaemonMessage(message)) {\n return { ...base, kind: 'delivery_report', evidence: 'mail system message' }\n }\n\n const unsubscribe = normalizeContactEmail(context.unsubscribeAddress)\n if (unsubscribe && addressesIn(message.to ?? '').includes(unsubscribe)) {\n return { ...base, kind: 'opt_out', evidence: `To: ${unsubscribe}` }\n }\n\n const autoReply = outreachAutoReplyEvidence(message)\n if (autoReply) return { ...base, kind: 'auto_reply', evidence: autoReply }\n\n const intent = detectOutreachOptOutIntent(readableText(message))\n if (intent.optOut) {\n return { ...base, kind: 'opt_out', complaint: intent.complaint, evidence: intent.matched }\n }\n // A subject is read only on a message that starts fresh — no `Re:`, and\n // not the thread's own — and only when it says nothing but stop.\n const subject = String(message.subject ?? '').replace(/\\s+/g, ' ').trim()\n const fresh = crmThreadSubject(subject) === subject\n if (subject && fresh && subject !== crmThreadSubject(context.threadSubject)) {\n const subjectIntent = detectOutreachOptOutSubject(subject)\n if (subjectIntent.optOut) {\n return { ...base, kind: 'opt_out', evidence: `Subject: ${subjectIntent.matched}` }\n }\n }\n return { ...base, kind: 'reply' }\n}\n\nexport type OutreachThreadOutcome = 'none' | 'postpone' | 'bounced' | 'replied' | 'opted_out'\n\nexport interface OutreachThreadDecisionInput extends OutreachMessageContext {\n /** The thread's messages, in any order. */\n messages: readonly OutreachThreadMessage[]\n /** The enrollment's recipient. */\n recipient: string\n /** Messages received at or before this instant were handled by an earlier run. */\n afterMs?: number | null\n /** Ids of messages an earlier run handled. */\n handledMessageIds?: readonly string[]\n}\n\nexport interface OutreachThreadDecision {\n outcome: OutreachThreadOutcome\n /** The message that decided the outcome; `null` for `none`. */\n decidedBy: OutreachMessageClassification | null\n /** Every new message, classified, oldest first. */\n classifications: OutreachMessageClassification[]\n /** A new reply called the email spam: the mailbox is paused as well. */\n complaint: boolean\n /** New hard bounces that report this recipient. */\n hardBounces: number\n /** New soft bounces that report this recipient. */\n softBounces: number\n}\n\nconst RANK: Record<OutreachThreadOutcome, number> = {\n none: 0,\n postpone: 1,\n bounced: 2,\n replied: 3,\n opted_out: 4,\n}\n\nconst OUTCOME_OF: Partial<Record<OutreachMessageKind, OutreachThreadOutcome>> = {\n auto_reply: 'postpone',\n hard_bounce: 'bounced',\n reply: 'replied',\n opt_out: 'opted_out',\n}\n\n/** What the new messages in an enrollment's thread mean for it — see the module note. */\nexport function decideOutreachThread(input: OutreachThreadDecisionInput): OutreachThreadDecision {\n const recipient = normalizeContactEmail(input.recipient)\n const handled = new Set(input.handledMessageIds ?? [])\n const afterMs = typeof input.afterMs === 'number' ? input.afterMs : null\n const fresh = [...(input.messages ?? [])]\n .filter((message) => message && !handled.has(message.id))\n .filter((message) => afterMs === null || message.internalDateMs > afterMs)\n .sort((a, b) => a.internalDateMs - b.internalDateMs)\n\n const decision: OutreachThreadDecision = {\n outcome: 'none',\n decidedBy: null,\n classifications: [],\n complaint: false,\n hardBounces: 0,\n softBounces: 0,\n }\n for (const message of fresh) {\n const classification = classifyOutreachMessage(message, input)\n decision.classifications.push(classification)\n const bounce = classification.bounce\n const aboutRecipient =\n !bounce || !bounce.recipients.length || (recipient !== null && bounce.recipients.includes(recipient))\n if (classification.kind === 'hard_bounce' && aboutRecipient) decision.hardBounces += 1\n if (classification.kind === 'soft_bounce' && aboutRecipient) decision.softBounces += 1\n if (classification.complaint) decision.complaint = true\n const outcome = OUTCOME_OF[classification.kind]\n if (!outcome || (classification.kind === 'hard_bounce' && !aboutRecipient)) continue\n if (RANK[outcome] > RANK[decision.outcome]) {\n decision.outcome = outcome\n decision.decidedBy = classification\n }\n }\n return decision\n}\n"],"names":["normalizeContactEmail","crmThreadSubject","emailAddressOf","htmlToPlainText","readOutreachDeliveryReport","isMailerDaemonMessage","detectOutreachOptOutIntent","detectOutreachOptOutSubject","outreachHeader","AUTO_REPLY_SUBJECT","RegExp","join","outreachAutoReplyEvidence","message","autoSubmitted","split","trim","toLowerCase","name","value","precedence","includes","subject","String","replace","match","exec","addressesIn","header","map","part","filter","address","readableText","textBody","htmlBody","snippet","classifyOutreachMessage","context","from","base","messageId","id","atMs","Number","isFinite","internalDateMs","bounce","complaint","evidence","report","kind","recipients","failedAddresses","status","diagnostic","self","Set","selfAddresses","has","unsubscribe","unsubscribeAddress","to","autoReply","intent","optOut","matched","fresh","threadSubject","subjectIntent","RANK","none","postpone","bounced","replied","opted_out","OUTCOME_OF","auto_reply","hard_bounce","reply","opt_out","decideOutreachThread","input","recipient","handled","handledMessageIds","afterMs","messages","sort","a","b","decision","outcome","decidedBy","classifications","hardBounces","softBounces","classification","push","aboutRecipient","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CA+B4C,GAE5C,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,eAAe,QAAQ,qCAAoC;AACtG,SAASC,0BAA0B,EAAEC,qBAAqB,QAAQ,uBAAmB;AACrF,SAASC,0BAA0B,EAAEC,2BAA2B,QAAQ,sBAAkB;AAC1F,SAASC,cAAc,QAAoC,sBAAkB;AAyC7E,MAAMC,qBAAqB,IAAIC,OAC7B;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAACC,IAAI,CAAC,KACP;AAGF;;;CAGC,GACD,OAAO,SAASC,0BACdC,OAA2D;;IAE3D,MAAMC,gBAAgBN,eAAeK,SAAS,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M,CAAC,CAAClB,UAAYA,WAAW,CAACuE,QAAQzB,GAAG,CAAC9C,QAAQ6B,EAAE,GACtDX,MAAM,CAAC,CAAClB,UAAYyE,YAAY,QAAQzE,QAAQiC,cAAc,GAAGwC,SACjEE,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAE3C,cAAc,GAAG4C,EAAE5C,cAAc;IAErD,MAAM6C,WAAmC;QACvCC,SAAS;QACTC,WAAW;QACXC,iBAAiB,EAAE;QACnB9C,WAAW;QACX+C,aAAa;QACbC,aAAa;IACf;IACA,KAAK,MAAMnF,WAAWsD,MAAO;QAC3B,MAAM8B,iBAAiB5D,wBAAwBxB,SAASqE;QACxDS,SAASG,eAAe,CAACI,IAAI,CAACD;QAC9B,MAAMlD,SAASkD,eAAelD,MAAM;QACpC,MAAMoD,iBACJ,CAACpD,UAAU,CAACA,OAAOK,UAAU,CAACgD,MAAM,IAAKjB,cAAc,QAAQpC,OAAOK,UAAU,CAAC/B,QAAQ,CAAC8D;QAC5F,IAAIc,eAAe9C,IAAI,KAAK,iBAAiBgD,gBAAgBR,SAASI,WAAW,IAAI;QACrF,IAAIE,eAAe9C,IAAI,KAAK,iBAAiBgD,gBAAgBR,SAASK,WAAW,IAAI;QACrF,IAAIC,eAAejD,SAAS,EAAE2C,SAAS3C,SAAS,GAAG;QACnD,MAAM4C,UAAUhB,UAAU,CAACqB,eAAe9C,IAAI,CAAC;QAC/C,IAAI,CAACyC,WAAYK,eAAe9C,IAAI,KAAK,iBAAiB,CAACgD,gBAAiB;QAC5E,IAAI7B,IAAI,CAACsB,QAAQ,GAAGtB,IAAI,CAACqB,SAASC,OAAO,CAAC,EAAE;YAC1CD,SAASC,OAAO,GAAGA;YACnBD,SAASE,SAAS,GAAGI;QACvB;IACF;IACA,OAAON;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/engine/thread-classification.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 * WHAT CAME BACK (AGL-2979).\n *\n * The runtime reads each enrollment's threads and asks what the new\n * messages mean. Each message is one of:\n *\n * - `self` — the mailbox's own: a step, or the rep writing in the thread.\n * - `hard_bounce` / `soft_bounce` — a delivery report (`./delivery-status.ts`).\n * - `delivery_report` — a mail system's message that reports no failure.\n * - `auto_reply` — an out-of-office or an autoresponder. It POSTPONES the\n * next step and does not stop the sequence: nobody answered.\n * - `opt_out` — a reply that asks to be left alone (`./opt-out-intent.ts`),\n * or a message sent to the unsubscribe address.\n * - `reply` — any other message from anybody else.\n *\n * ## Automatic replies\n *\n * Read from the headers the standards give an autoresponder —\n * `Auto-Submitted` with any value but `no` (RFC 3834), `X-Autoreply`,\n * `X-Autorespond`, `Precedence: auto_reply`, `bulk` or `junk` — and, for\n * the servers that set none, from an out-of-office subject in the usual\n * languages.\n *\n * ## The thread's outcome\n *\n * `opted_out` outranks `replied`, which outranks `bounced`, which outranks\n * `postpone`: an opt-out is a reply that also has to reach the do-not-contact\n * list, a person who wrote back matters more than a report about an earlier\n * send, and an out-of-office only matters when nothing else happened. The\n * bounces that report this recipient are counted either way, because mailbox\n * health counts every one.\n *==========================================*/\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmThreadSubject, emailAddressOf, htmlToPlainText } from '@aglyn/aglyn/app-utils/crm-inbound'\nimport { readOutreachDeliveryReport, isMailerDaemonMessage } from './delivery-status'\nimport { detectOutreachOptOutIntent, detectOutreachOptOutSubject } from './opt-out-intent'\nimport { outreachHeader, type OutreachThreadMessage } from './thread-message'\n\nexport type OutreachMessageKind =\n | 'self'\n | 'hard_bounce'\n | 'soft_bounce'\n | 'delivery_report'\n | 'auto_reply'\n | 'opt_out'\n | 'reply'\n\nexport interface OutreachBounceDetail {\n /** The addresses the report says failed; empty when it names none. */\n recipients: string[]\n status: string | null\n diagnostic: string | null\n /** The receiving server the report names, when it does (AGL-3326). */\n remoteMta: string | null\n}\n\nexport interface OutreachMessageClassification {\n messageId: string\n atMs: number\n kind: OutreachMessageKind\n /** The sender's address, normalized, when the `From` carried one. */\n from: string | null\n /** Set on a bounce. */\n bounce: OutreachBounceDetail | null\n /** An opt-out that calls the email spam. */\n complaint: boolean\n /** What decided it, for the timeline and the log. */\n evidence: string | null\n}\n\nexport interface OutreachMessageContext {\n /** The mailbox's own addresses: the account's and every alias it sends as. */\n selfAddresses: readonly string[]\n /** The address a `List-Unsubscribe` mailto points at, when the runtime set one. */\n unsubscribeAddress?: string | null\n /** The subject the thread was started with, so a new subject can be read on its own. */\n threadSubject?: string | null\n}\n\nconst AUTO_REPLY_SUBJECT = new RegExp(\n [\n '^\\\\s*\\\\[?\\\\s*(',\n 'auto(matic)?[\\\\s-]*(reply|response|responder|answer)',\n '|out[\\\\s-]+of[\\\\s-]+(the[\\\\s-]+)?office',\n '|ooo\\\\b',\n \"|i('m| am) (currently )?(out of the office|away|on (vacation|leave|holiday))\",\n '|(on )?(vacation|holiday|annual leave)[\\\\s-]*(reply|response|notice|message|autoreply)',\n '|away from (the |my )?(office|desk)',\n '|abwesenheitsnotiz|abwesenheit',\n '|r[ée]ponse automatique|absence du bureau',\n '|respuesta autom[áa]tica|fuera de la oficina',\n '|risposta automatica|fuori ufficio',\n '|automatisch antwoord|afwezigheidsbericht',\n '|resposta autom[áa]tica|fora do escrit[óo]rio',\n '|autosvar|automaattinen vastaus',\n ')',\n ].join(''),\n 'i',\n)\n\n/**\n * Why a message is an automatic reply, or `null` when it is not one — see\n * the module note for the headers and subjects read.\n */\nexport function outreachAutoReplyEvidence(\n message: Pick<OutreachThreadMessage, 'headers' | 'subject'>,\n): string | null {\n const autoSubmitted = outreachHeader(message, 'Auto-Submitted').split(';')[0].trim().toLowerCase()\n if (autoSubmitted && autoSubmitted !== 'no') return `Auto-Submitted: ${autoSubmitted}`\n for (const name of ['X-Autoreply', 'X-Autorespond']) {\n const value = outreachHeader(message, name).trim()\n if (value && value.toLowerCase() !== 'no') return `${name}: ${value}`\n }\n const precedence = outreachHeader(message, 'Precedence').trim().toLowerCase()\n if (['auto_reply', 'bulk', 'junk'].includes(precedence)) return `Precedence: ${precedence}`\n const subject = String(message?.subject ?? '').replace(/^\\s*(re|fwd?)\\s*:\\s*/i, '')\n const match = AUTO_REPLY_SUBJECT.exec(subject)\n return match ? `Subject: ${match[0].trim()}` : null\n}\n\nfunction addressesIn(header: string): string[] {\n return header\n .split(',')\n .map((part) => emailAddressOf(part))\n .filter((address): address is string => address !== null)\n}\n\nfunction readableText(message: OutreachThreadMessage): string {\n if (message.textBody && message.textBody.trim()) return message.textBody\n if (message.htmlBody && message.htmlBody.trim()) return htmlToPlainText(message.htmlBody)\n return message.snippet ?? ''\n}\n\n/** What one message in an enrollment's thread is — see the module note. */\nexport function classifyOutreachMessage(\n message: OutreachThreadMessage,\n context: OutreachMessageContext,\n): OutreachMessageClassification {\n const from = emailAddressOf(message.from)\n const base = {\n messageId: String(message.id ?? ''),\n atMs: Number.isFinite(message.internalDateMs) ? message.internalDateMs : 0,\n from,\n bounce: null,\n complaint: false,\n evidence: null,\n }\n\n const report = readOutreachDeliveryReport(message)\n if (report) {\n if (!report.kind) return { ...base, kind: 'delivery_report', evidence: 'delivery report' }\n return {\n ...base,\n kind: report.kind === 'hard' ? 'hard_bounce' : 'soft_bounce',\n bounce: {\n recipients: report.failedAddresses,\n status: report.status,\n diagnostic: report.diagnostic,\n remoteMta: report.remoteMta,\n },\n evidence: report.status ? `Status: ${report.status}` : 'delivery report',\n }\n }\n\n const self = new Set(\n (context.selfAddresses ?? [])\n .map((address) => normalizeContactEmail(address))\n .filter((address): address is string => address !== null),\n )\n if (from && self.has(from)) return { ...base, kind: 'self' }\n if (isMailerDaemonMessage(message)) {\n return { ...base, kind: 'delivery_report', evidence: 'mail system message' }\n }\n\n const unsubscribe = normalizeContactEmail(context.unsubscribeAddress)\n if (unsubscribe && addressesIn(message.to ?? '').includes(unsubscribe)) {\n return { ...base, kind: 'opt_out', evidence: `To: ${unsubscribe}` }\n }\n\n const autoReply = outreachAutoReplyEvidence(message)\n if (autoReply) return { ...base, kind: 'auto_reply', evidence: autoReply }\n\n const intent = detectOutreachOptOutIntent(readableText(message))\n if (intent.optOut) {\n return { ...base, kind: 'opt_out', complaint: intent.complaint, evidence: intent.matched }\n }\n // A subject is read only on a message that starts fresh — no `Re:`, and\n // not the thread's own — and only when it says nothing but stop.\n const subject = String(message.subject ?? '').replace(/\\s+/g, ' ').trim()\n const fresh = crmThreadSubject(subject) === subject\n if (subject && fresh && subject !== crmThreadSubject(context.threadSubject)) {\n const subjectIntent = detectOutreachOptOutSubject(subject)\n if (subjectIntent.optOut) {\n return { ...base, kind: 'opt_out', evidence: `Subject: ${subjectIntent.matched}` }\n }\n }\n return { ...base, kind: 'reply' }\n}\n\nexport type OutreachThreadOutcome = 'none' | 'postpone' | 'bounced' | 'replied' | 'opted_out'\n\nexport interface OutreachThreadDecisionInput extends OutreachMessageContext {\n /** The thread's messages, in any order. */\n messages: readonly OutreachThreadMessage[]\n /** The enrollment's recipient. */\n recipient: string\n /** Messages received at or before this instant were handled by an earlier run. */\n afterMs?: number | null\n /** Ids of messages an earlier run handled. */\n handledMessageIds?: readonly string[]\n}\n\nexport interface OutreachThreadDecision {\n outcome: OutreachThreadOutcome\n /** The message that decided the outcome; `null` for `none`. */\n decidedBy: OutreachMessageClassification | null\n /** Every new message, classified, oldest first. */\n classifications: OutreachMessageClassification[]\n /** A new reply called the email spam: the mailbox is paused as well. */\n complaint: boolean\n /** New hard bounces that report this recipient. */\n hardBounces: number\n /** New soft bounces that report this recipient. */\n softBounces: number\n}\n\nconst RANK: Record<OutreachThreadOutcome, number> = {\n none: 0,\n postpone: 1,\n bounced: 2,\n replied: 3,\n opted_out: 4,\n}\n\nconst OUTCOME_OF: Partial<Record<OutreachMessageKind, OutreachThreadOutcome>> = {\n auto_reply: 'postpone',\n hard_bounce: 'bounced',\n reply: 'replied',\n opt_out: 'opted_out',\n}\n\n/** What the new messages in an enrollment's thread mean for it — see the module note. */\nexport function decideOutreachThread(input: OutreachThreadDecisionInput): OutreachThreadDecision {\n const recipient = normalizeContactEmail(input.recipient)\n const handled = new Set(input.handledMessageIds ?? [])\n const afterMs = typeof input.afterMs === 'number' ? input.afterMs : null\n const fresh = [...(input.messages ?? [])]\n .filter((message) => message && !handled.has(message.id))\n .filter((message) => afterMs === null || message.internalDateMs > afterMs)\n .sort((a, b) => a.internalDateMs - b.internalDateMs)\n\n const decision: OutreachThreadDecision = {\n outcome: 'none',\n decidedBy: null,\n classifications: [],\n complaint: false,\n hardBounces: 0,\n softBounces: 0,\n }\n for (const message of fresh) {\n const classification = classifyOutreachMessage(message, input)\n decision.classifications.push(classification)\n const bounce = classification.bounce\n const aboutRecipient =\n !bounce || !bounce.recipients.length || (recipient !== null && bounce.recipients.includes(recipient))\n if (classification.kind === 'hard_bounce' && aboutRecipient) decision.hardBounces += 1\n if (classification.kind === 'soft_bounce' && aboutRecipient) decision.softBounces += 1\n if (classification.complaint) decision.complaint = true\n const outcome = OUTCOME_OF[classification.kind]\n if (!outcome || (classification.kind === 'hard_bounce' && !aboutRecipient)) continue\n if (RANK[outcome] > RANK[decision.outcome]) {\n decision.outcome = outcome\n decision.decidedBy = classification\n }\n }\n return decision\n}\n"],"names":["normalizeContactEmail","crmThreadSubject","emailAddressOf","htmlToPlainText","readOutreachDeliveryReport","isMailerDaemonMessage","detectOutreachOptOutIntent","detectOutreachOptOutSubject","outreachHeader","AUTO_REPLY_SUBJECT","RegExp","join","outreachAutoReplyEvidence","message","autoSubmitted","split","trim","toLowerCase","name","value","precedence","includes","subject","String","replace","match","exec","addressesIn","header","map","part","filter","address","readableText","textBody","htmlBody","snippet","classifyOutreachMessage","context","from","base","messageId","id","atMs","Number","isFinite","internalDateMs","bounce","complaint","evidence","report","kind","recipients","failedAddresses","status","diagnostic","remoteMta","self","Set","selfAddresses","has","unsubscribe","unsubscribeAddress","to","autoReply","intent","optOut","matched","fresh","threadSubject","subjectIntent","RANK","none","postpone","bounced","replied","opted_out","OUTCOME_OF","auto_reply","hard_bounce","reply","opt_out","decideOutreachThread","input","recipient","handled","handledMessageIds","afterMs","messages","sort","a","b","decision","outcome","decidedBy","classifications","hardBounces","softBounces","classification","push","aboutRecipient","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CA+B4C,GAE5C,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,eAAe,QAAQ,qCAAoC;AACtG,SAASC,0BAA0B,EAAEC,qBAAqB,QAAQ,uBAAmB;AACrF,SAASC,0BAA0B,EAAEC,2BAA2B,QAAQ,sBAAkB;AAC1F,SAASC,cAAc,QAAoC,sBAAkB;AA2C7E,MAAMC,qBAAqB,IAAIC,OAC7B;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAACC,IAAI,CAAC,KACP;AAGF;;;CAGC,GACD,OAAO,SAASC,0BACdC,OAA2D;;IAE3D,MAAMC,gBAAgBN,eAAeK,SAAS,kBAAkBE,KAAK,CAAC,IAAI,CAAC,EAAE,CAACC,IAAI,GAAGC,WAAW;IAChG,IAAIH,iBAAiBA,kBAAkB,MAAM,OAAO,CAAC,gBAAgB,EAAEA,eAAe;IACtF,KAAK,MAAMI,QAAQ;QAAC;QAAe;KAAgB,CAAE;QACnD,MAAMC,QAAQX,eAAeK,SAASK,MAAMF,IAAI;QAChD,IAAIG,SAASA,MAAMF,WAAW,OAAO,MAAM,OAAO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C,SAAS;QACTC,WAAW;QACXC,iBAAiB,EAAE;QACnB/C,WAAW;QACXgD,aAAa;QACbC,aAAa;IACf;IACA,KAAK,MAAMpF,WAAWuD,MAAO;QAC3B,MAAM8B,iBAAiB7D,wBAAwBxB,SAASsE;QACxDS,SAASG,eAAe,CAACI,IAAI,CAACD;QAC9B,MAAMnD,SAASmD,eAAenD,MAAM;QACpC,MAAMqD,iBACJ,CAACrD,UAAU,CAACA,OAAOK,UAAU,CAACiD,MAAM,IAAKjB,cAAc,QAAQrC,OAAOK,UAAU,CAAC/B,QAAQ,CAAC+D;QAC5F,IAAIc,eAAe/C,IAAI,KAAK,iBAAiBiD,gBAAgBR,SAASI,WAAW,IAAI;QACrF,IAAIE,eAAe/C,IAAI,KAAK,iBAAiBiD,gBAAgBR,SAASK,WAAW,IAAI;QACrF,IAAIC,eAAelD,SAAS,EAAE4C,SAAS5C,SAAS,GAAG;QACnD,MAAM6C,UAAUhB,UAAU,CAACqB,eAAe/C,IAAI,CAAC;QAC/C,IAAI,CAAC0C,WAAYK,eAAe/C,IAAI,KAAK,iBAAiB,CAACiD,gBAAiB;QAC5E,IAAI7B,IAAI,CAACsB,QAAQ,GAAGtB,IAAI,CAACqB,SAASC,OAAO,CAAC,EAAE;YAC1CD,SAASC,OAAO,GAAGA;YACnBD,SAASE,SAAS,GAAGI;QACvB;IACF;IACA,OAAON;AACT"}
|
|
@@ -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 OutreachGateLookups } from '../engine/gates';
|
|
17
|
+
import { type OutreachGateHold, type OutreachGateLookups } from '../engine/gates';
|
|
18
18
|
import { type OutreachAttestations, type OutreachSequenceSettings } from '../model/outreach.types';
|
|
19
19
|
import type { OutreachEnrollBlock, OutreachEnrollPreviewPerson, OutreachPersonRef } from '../model/outreach-api';
|
|
20
20
|
type Firestore = FirebaseFirestore.Firestore;
|
|
@@ -112,6 +112,11 @@ export interface OutreachEnrollDecision {
|
|
|
112
112
|
email: string | null;
|
|
113
113
|
/** What the rep confirmed, stamped with who and when. */
|
|
114
114
|
attestations: OutreachAttestations;
|
|
115
|
+
/**
|
|
116
|
+
* The gateway hold the gates would put on the send (AGL-3326), which the
|
|
117
|
+
* member enrolling past the red chip releases; `null` when none applies.
|
|
118
|
+
*/
|
|
119
|
+
hold: OutreachGateHold | null;
|
|
115
120
|
}
|
|
116
121
|
/** Confirm's answer for one person, with what the rep supplied — see the module note. */
|
|
117
122
|
export declare function decideOutreachEnrollment(question: OutreachGateQuestion, facts: {
|
|
@@ -243,6 +243,16 @@ const blocksOf = (blocks)=>blocks.map(({ code, reason })=>({
|
|
|
243
243
|
code,
|
|
244
244
|
reason
|
|
245
245
|
}));
|
|
246
|
+
/**
|
|
247
|
+
* The gateway as the dialog shows it (AGL-3326): the standing the lookups
|
|
248
|
+
* read, and whether the gates would hold a send into it.
|
|
249
|
+
*/ function gatewayOf(question, hold) {
|
|
250
|
+
var _question_lookups;
|
|
251
|
+
const standing = (_question_lookups = question.lookups) == null ? void 0 : _question_lookups.gateway;
|
|
252
|
+
return standing ? _extends({}, standing, {
|
|
253
|
+
hold: hold !== null
|
|
254
|
+
}) : null;
|
|
255
|
+
}
|
|
246
256
|
/** Where one person stands before the rep confirms anything — see the module note. */ export function previewOutreachPerson(question, facts) {
|
|
247
257
|
const { candidate } = question;
|
|
248
258
|
const person = _extends({}, personOf(candidate), {
|
|
@@ -259,7 +269,8 @@ const blocksOf = (blocks)=>blocks.map(({ code, reason })=>({
|
|
|
259
269
|
requires: {
|
|
260
270
|
personalLine: false,
|
|
261
271
|
attestations: []
|
|
262
|
-
}
|
|
272
|
+
},
|
|
273
|
+
gateway: null
|
|
263
274
|
});
|
|
264
275
|
}
|
|
265
276
|
const ask = (personalLine, attestations)=>{
|
|
@@ -278,7 +289,8 @@ const blocksOf = (blocks)=>blocks.map(({ code, reason })=>({
|
|
|
278
289
|
const asIs = ask('', {});
|
|
279
290
|
const known = {
|
|
280
291
|
cold: asIs.cold,
|
|
281
|
-
country: asIs.country.country
|
|
292
|
+
country: asIs.country.country,
|
|
293
|
+
gateway: gatewayOf(question, asIs.hold)
|
|
282
294
|
};
|
|
283
295
|
if (asIs.allowed) {
|
|
284
296
|
return _extends({}, person, known, {
|
|
@@ -326,7 +338,8 @@ const blocksOf = (blocks)=>blocks.map(({ code, reason })=>({
|
|
|
326
338
|
blocks: early,
|
|
327
339
|
cold: false,
|
|
328
340
|
email: question.candidate.email,
|
|
329
|
-
attestations
|
|
341
|
+
attestations,
|
|
342
|
+
hold: null
|
|
330
343
|
};
|
|
331
344
|
}
|
|
332
345
|
const result = evaluateOutreachGates({
|
|
@@ -344,7 +357,8 @@ const blocksOf = (blocks)=>blocks.map(({ code, reason })=>({
|
|
|
344
357
|
blocks: blocksOf(result.blocks),
|
|
345
358
|
cold: result.cold,
|
|
346
359
|
email: result.email,
|
|
347
|
-
attestations
|
|
360
|
+
attestations,
|
|
361
|
+
hold: result.hold
|
|
348
362
|
};
|
|
349
363
|
}
|
|
350
364
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/enroll-people.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WHO CAN BE ENROLLED, AND WHAT THE REP STILL OWES (AGL-2980).\n *\n * The enroll dialog shows every person a view or a search named, each\n * marked eligible, blocked, or waiting on the rep; Confirm asks the same\n * question again, on the server, with what the rep supplied. Both answers\n * come from the engine's `evaluateOutreachGates` — this module only reads\n * the people and asks it the right questions.\n *\n * ## Three questions of one pure function\n *\n * The gates refuse a cold contact until the rep writes a personal line and\n * ticks the attestations, and refuse an address in an unknown country until\n * the rep confirms it is a US business address. So a preview asks:\n *\n * 1. as the person stands, with nothing confirmed — allowed means\n * ELIGIBLE;\n * 2. as if the rep confirmed everything they can — refused means BLOCKED,\n * for the reasons that remain, which no tick can clear;\n * 3. otherwise the person is WAITING ON THE REP, for what (1) found\n * missing.\n *\n * The confirmation in (2) is hypothetical and never stored: Confirm stamps\n * only what the rep ticked, with their uid and the time, and asks again.\n *\n * ## One enrollment per person per sequence, ever\n *\n * The enrollment's id is the sequence and the contact\n * (`outreachEnrollmentId`), and it is written with `create()`. A person who\n * finished, replied or was stopped is not sent the same emails a second\n * time by being enrolled again, and two members confirming the same person\n * at once write one enrollment.\n *==========================================*/\n\nimport { normalizeContactEmail, contactDisplayName, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmLeadDisplayName, crmLeadStatus } from '@aglyn/aglyn/app-utils/crm'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport {\n evaluateOutreachGates,\n type OutreachGateBlock,\n type OutreachGateLookups,\n} from '../engine/gates'\nimport { outreachAttestationsFrom } from '../engine/enrollment-state'\nimport {\n OUTREACH_ATTESTATION_KINDS,\n type OutreachAttestationKind,\n type OutreachAttestations,\n type OutreachSequenceSettings,\n} from '../model/outreach.types'\nimport type {\n OutreachEnrollBlock,\n OutreachEnrollPreviewPerson,\n OutreachPersonRef,\n} from '../model/outreach-api'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/**\n * One person as the preview and the enroll read them: a contact, or a lead\n * the sequence's site holds (AGL-3234).\n *\n * ## A lead is judged as the contact it would be\n *\n * The gates, the merge fields and the country rule all read a CONTACT\n * document — its facet's sources, stage, address, company and title. A lead\n * carries the same facts in its own shape, so rather than teach every gate\n * two records, a lead is handed to them as {@link leadAsContact}: a\n * contact-shaped view whose one facet, under the sequence's group, holds\n * what the lead holds. An imported lead has no inbound source and is cold;\n * one that wrote in through a form is not; a lead is never a customer; its\n * address decides its country; and `{{contact.firstName}}` or\n * `{{contact.company}}` in a step reads the lead's name and company text,\n * so a sequence written for contacts sends to leads unchanged — which is\n * also what lets an enrollment made on a lead keep sending after the lead\n * converts and the view becomes the real contact.\n */\nexport interface OutreachEnrollCandidate {\n /** The record's own id: the contact's, or the lead's person key. */\n personId: string\n target: 'contact' | 'lead'\n /** The contact's id; `''` for a lead. */\n contactId: string\n /** The lead's person key; `null` for a contact. */\n leadId: string | null\n /**\n * The contact document (`orgs/{orgId}/contacts/{id}`), or for a lead the\n * contact-shaped view of it — see the module note. `null` when the record\n * no longer exists.\n */\n contact: Record<string, unknown> | null\n /** The lead document as stored, for a lead; `null` for a contact. */\n lead: Record<string, unknown> | null\n /** Whether the sequence's site may see the record. A lead is the site's own. */\n visible: boolean\n /** The name the sequence's site knows them by; `''` for none. */\n name: string\n /** The primary address, normalized, or `null` when there is none. */\n email: string | null\n /** The company the contact is filed under at that site, when there is one. */\n company: Record<string, unknown> | null\n /** A lead already converted: the contact it became. Enroll that instead. */\n convertedContactId: string | null\n /** A lead whose address the workspace already holds as a contact. Enroll that instead. */\n heldAsContactId: string | null\n}\n\n/**\n * A lead as the gates and the merge fields read a contact — see the\n * module note. The facet is the sequence's group's, which is the one every\n * reader asks for. The lead's `sources` — `form:{id}`, `booking`, `import`,\n * `manual`, `api`, `signup` — become the facet's source flags by kind, so\n * the inbound rule reads them as it reads a contact's.\n */\nexport function leadAsContact(\n lead: Record<string, unknown>,\n contactGroupId: string,\n): Record<string, unknown> {\n const sources: Record<string, true> = {}\n for (const raw of Array.isArray(lead['sources']) ? lead['sources'] : []) {\n const source = String(raw)\n const kind = source.startsWith('form:') ? 'form' : source === 'signup' ? 'member' : source\n if (kind) sources[kind] = true\n }\n return {\n email: lead['email'],\n name: lead['name'],\n // The verdict on the address (AGL-3245) is the lead's own top-level\n // field, as it is the contact's, so the gates quote it either way.\n ...(lead['emailState'] && typeof lead['emailState'] === 'object' ? { emailState: lead['emailState'] } : {}),\n facets: {\n [contactGroupId]: {\n sources,\n ...(lead['address'] && typeof lead['address'] === 'object' ? { address: lead['address'] } : {}),\n ...(typeof lead['company'] === 'string' ? { companyName: lead['company'] } : {}),\n ...(typeof lead['jobTitle'] === 'string' ? { jobTitle: lead['jobTitle'] } : {}),\n ...(typeof lead['phone'] === 'string' ? { phone: lead['phone'] } : {}),\n ...(Array.isArray(lead['tags']) ? { tags: lead['tags'] } : {}),\n },\n },\n }\n}\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * The people, as the sequence's site knows them, and the company each\n * contact is filed under there — batched reads for everyone: the contacts\n * and the leads by id, the companies once, and for each lead one address\n * lookup, because a lead the workspace already holds as a contact is that\n * contact's to enroll.\n */\nexport async function readOutreachEnrollCandidates(\n firestore: Firestore,\n input: { orgId: string; hostId: string; contactGroupId: string; people: readonly OutreachPersonRef[] },\n): Promise<OutreachEnrollCandidate[]> {\n if (!input.people.length) return []\n const org = firestore.collection('orgs').doc(input.orgId)\n // Beside the contacts, on the org (AGL-3275).\n const leads = org.collection('leads')\n const snapshots = await getAllChunked(\n firestore,\n input.people.map((person) =>\n person.kind === 'lead' ? leads.doc(person.id) : org.collection('contacts').doc(person.id),\n ),\n )\n const read = await Promise.all(\n input.people.map(async (person, index) => {\n const data = snapshots[index]?.exists ? (snapshots[index].data() as Record<string, unknown>) : null\n if (person.kind === 'lead') {\n const email = data ? normalizeContactEmail(data['email']) : null\n const held =\n data && email ? await findContactByEmail(org.collection('contacts'), email) : null\n return {\n personId: person.id,\n target: 'lead' as const,\n contactId: '',\n leadId: person.id,\n contact: data ? leadAsContact(data, input.contactGroupId) : null,\n lead: data,\n // A lead is the site's own record: no scope to check.\n visible: data !== null,\n name: data ? crmLeadDisplayName(data) : '',\n email,\n companyId: '',\n convertedContactId: data && typeof data['convertedContactId'] === 'string' ? data['convertedContactId'] : null,\n heldAsContactId: held ? held.id : null,\n }\n }\n return {\n personId: person.id,\n target: 'contact' as const,\n contactId: person.id,\n leadId: null,\n contact: data,\n lead: null,\n visible: data ? visibleToHost(data['visibleTo'] as string[] | undefined, input.hostId) : false,\n name: data ? contactDisplayName(data, input.contactGroupId).trim() : '',\n email: data ? normalizeContactEmail(data['email']) : null,\n companyId: data ? String(readContactFacet(data, input.contactGroupId).companyId ?? '') : '',\n convertedContactId: null,\n heldAsContactId: null,\n }\n }),\n )\n const companyIds = [...new Set(read.map((entry) => entry.companyId).filter(Boolean))]\n const companies = new Map<string, Record<string, unknown>>()\n if (companyIds.length) {\n const found = await getAllChunked(\n firestore,\n companyIds.map((id) => org.collection('companies').doc(id)),\n )\n found.forEach((snapshot, index) => {\n if (snapshot.exists) companies.set(companyIds[index], snapshot.data() as Record<string, unknown>)\n })\n }\n return read.map(({ companyId, ...candidate }) => ({\n ...candidate,\n company: companyId ? (companies.get(companyId) ?? null) : null,\n }))\n}\n\n/** The person as every answer names them. */\nfunction personOf(candidate: OutreachEnrollCandidate) {\n return {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n}\n\n/** What stands in the way before the gates are asked anything. */\nexport function outreachCandidateBlocks(\n candidate: OutreachEnrollCandidate,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollBlock[] {\n if (!candidate.contact) {\n return candidate.target === 'lead'\n ? [{ code: 'lead_missing', reason: \"This lead no longer exists in this sequence's site's CRM.\" }]\n : [{ code: 'contact_missing', reason: 'This contact no longer exists in the CRM.' }]\n }\n const blocks: OutreachEnrollBlock[] = []\n if (candidate.target === 'lead') {\n // A lead that converted, or whose address the workspace already holds\n // as a contact, is that contact's to enroll — one person, one record.\n if (candidate.convertedContactId) {\n blocks.push({\n code: 'lead_converted',\n reason: 'This lead was converted into a contact. Enroll the contact instead.',\n })\n } else if (candidate.heldAsContactId) {\n blocks.push({\n code: 'lead_is_contact',\n reason: 'This address is already a contact in your CRM. Enroll the contact instead.',\n })\n }\n if (crmLeadStatus(candidate.lead) === 'unqualified') {\n blocks.push({\n code: 'lead_unqualified',\n reason: 'This lead was closed as unqualified. Reopen it before enrolling.',\n })\n }\n }\n if (!candidate.visible) {\n blocks.push({\n code: 'not_in_site',\n reason: `This contact isn't in ${facts.siteName || \"this sequence's site\"}'s CRM.`,\n })\n }\n if (!candidate.email) {\n blocks.push({ code: 'no_email', reason: 'This contact has no email address.' })\n }\n if (facts.alreadyInSequence) {\n blocks.push({\n code: 'already_in_sequence',\n reason: \"This person has already been in this sequence, so they won't be sent its emails again.\",\n })\n }\n return blocks\n}\n\n/** Every attestation, stamped for a hypothetical question only — never stored. */\nconst EVERYTHING_CONFIRMED: OutreachAttestations = Object.fromEntries(\n OUTREACH_ATTESTATION_KINDS.map((kind) => [kind, { uid: 'preview', atMs: 1 }]),\n)\n\nconst blocksOf = (blocks: readonly OutreachGateBlock[]): OutreachEnrollBlock[] =>\n blocks.map(({ code, reason }) => ({ code, reason }))\n\nexport interface OutreachGateQuestion {\n candidate: OutreachEnrollCandidate\n lookups: OutreachGateLookups\n /** The sequence's settings, its countries already capped by the organization's. */\n settings: OutreachSequenceSettings\n contactGroupId: string\n}\n\n/** Where one person stands before the rep confirms anything — see the module note. */\nexport function previewOutreachPerson(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollPreviewPerson {\n const { candidate } = question\n const person = {\n ...personOf(candidate),\n name: candidate.name,\n email: candidate.email,\n }\n const early = outreachCandidateBlocks(candidate, facts)\n if (early.length) {\n return {\n ...person,\n cold: false,\n country: null,\n status: 'blocked',\n blocks: early,\n requires: { personalLine: false, attestations: [] },\n }\n }\n const ask = (personalLine: string, attestations: OutreachAttestations) =>\n evaluateOutreachGates({\n email: candidate.email ?? '',\n contact: candidate.contact,\n contactGroupId: question.contactGroupId,\n company: candidate.company,\n settings: question.settings,\n personalLine,\n attestations,\n lookups: question.lookups,\n })\n const asIs = ask('', {})\n const known = { cold: asIs.cold, country: asIs.country.country }\n if (asIs.allowed) {\n return {\n ...person,\n ...known,\n status: 'eligible',\n blocks: [],\n requires: { personalLine: false, attestations: [] },\n }\n }\n // The line is only checked for being present, so any sentence stands in.\n const confirmed = ask('A personal line.', EVERYTHING_CONFIRMED)\n if (!confirmed.allowed) {\n return {\n ...person,\n ...known,\n status: 'blocked',\n blocks: blocksOf(confirmed.blocks),\n requires: { personalLine: false, attestations: [] },\n }\n }\n const attestations: OutreachAttestationKind[] = asIs.cold\n ? [...asIs.missingAttestations]\n : asIs.blocks.some((block) => block.code === 'country_unknown')\n ? ['us_business_address']\n : []\n return {\n ...person,\n ...known,\n status: 'needs_confirmation',\n blocks: [],\n requires: {\n personalLine: asIs.blocks.some((block) => block.code === 'personal_line_missing'),\n attestations,\n },\n }\n}\n\nexport interface OutreachEnrollDecision {\n allowed: boolean\n blocks: OutreachEnrollBlock[]\n cold: boolean\n /** The address as the gates normalized it. */\n email: string | null\n /** What the rep confirmed, stamped with who and when. */\n attestations: OutreachAttestations\n}\n\n/** Confirm's answer for one person, with what the rep supplied — see the module note. */\nexport function decideOutreachEnrollment(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n supplied: {\n personalLine: string\n attestations: readonly unknown[]\n uid: string\n nowMs: number\n },\n): OutreachEnrollDecision {\n const attestations = outreachAttestationsFrom(supplied.attestations, supplied.uid, supplied.nowMs)\n const early = outreachCandidateBlocks(question.candidate, facts)\n if (early.length) {\n return { allowed: false, blocks: early, cold: false, email: question.candidate.email, attestations }\n }\n const result = evaluateOutreachGates({\n email: question.candidate.email ?? '',\n contact: question.candidate.contact,\n contactGroupId: question.contactGroupId,\n company: question.candidate.company,\n settings: question.settings,\n personalLine: supplied.personalLine,\n attestations,\n lookups: question.lookups,\n })\n return {\n allowed: result.allowed,\n blocks: blocksOf(result.blocks),\n cold: result.cold,\n email: result.email,\n attestations,\n }\n}\n"],"names":["normalizeContactEmail","contactDisplayName","readContactFacet","crmLeadDisplayName","crmLeadStatus","visibleToHost","findContactByEmail","evaluateOutreachGates","outreachAttestationsFrom","OUTREACH_ATTESTATION_KINDS","leadAsContact","lead","contactGroupId","sources","raw","Array","isArray","source","String","kind","startsWith","email","name","emailState","facets","address","companyName","jobTitle","phone","tags","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","readOutreachEnrollCandidates","input","people","org","collection","doc","orgId","leads","map","person","id","read","Promise","all","index","data","exists","held","personId","target","contactId","leadId","contact","visible","companyId","convertedContactId","heldAsContactId","hostId","trim","companyIds","Set","entry","filter","Boolean","companies","Map","found","forEach","snapshot","set","candidate","company","get","personOf","outreachCandidateBlocks","facts","code","reason","blocks","siteName","alreadyInSequence","EVERYTHING_CONFIRMED","Object","fromEntries","uid","atMs","blocksOf","previewOutreachPerson","question","early","cold","country","status","requires","personalLine","attestations","ask","settings","lookups","asIs","known","allowed","confirmed","missingAttestations","some","block","decideOutreachEnrollment","supplied","nowMs","result"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAgC4C,GAE5C,SAASA,qBAAqB,EAAEC,kBAAkB,EAAEC,gBAAgB,QAAQ,kCAAiC;AAC7G,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,6BAA4B;AAC9E,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,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,CAAC3D,KAAK;YAAEoF;QAAa;IACrG;IACA,MAAMc,SAAShH,sBAAsB;QACnCc,KAAK,GAAE6E,4BAAAA,SAASlB,SAAS,CAAC3D,KAAK,YAAxB6E,4BAA4B;QACnCpC,SAASoC,SAASlB,SAAS,CAAClB,OAAO;QACnClD,gBAAgBsF,SAAStF,cAAc;QACvCqE,SAASiB,SAASlB,SAAS,CAACC,OAAO;QACnC0B,UAAUT,SAASS,QAAQ;QAC3BH,cAAca,SAASb,YAAY;QACnCC;QACAG,SAASV,SAASU,OAAO;IAC3B;IACA,OAAO;QACLG,SAASQ,OAAOR,OAAO;QACvBvB,QAAQQ,SAASuB,OAAO/B,MAAM;QAC9BY,MAAMmB,OAAOnB,IAAI;QACjB/E,OAAOkG,OAAOlG,KAAK;QACnBoF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/enroll-people.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WHO CAN BE ENROLLED, AND WHAT THE REP STILL OWES (AGL-2980).\n *\n * The enroll dialog shows every person a view or a search named, each\n * marked eligible, blocked, or waiting on the rep; Confirm asks the same\n * question again, on the server, with what the rep supplied. Both answers\n * come from the engine's `evaluateOutreachGates` — this module only reads\n * the people and asks it the right questions.\n *\n * ## Three questions of one pure function\n *\n * The gates refuse a cold contact until the rep writes a personal line and\n * ticks the attestations, and refuse an address in an unknown country until\n * the rep confirms it is a US business address. So a preview asks:\n *\n * 1. as the person stands, with nothing confirmed — allowed means\n * ELIGIBLE;\n * 2. as if the rep confirmed everything they can — refused means BLOCKED,\n * for the reasons that remain, which no tick can clear;\n * 3. otherwise the person is WAITING ON THE REP, for what (1) found\n * missing.\n *\n * The confirmation in (2) is hypothetical and never stored: Confirm stamps\n * only what the rep ticked, with their uid and the time, and asks again.\n *\n * ## One enrollment per person per sequence, ever\n *\n * The enrollment's id is the sequence and the contact\n * (`outreachEnrollmentId`), and it is written with `create()`. A person who\n * finished, replied or was stopped is not sent the same emails a second\n * time by being enrolled again, and two members confirming the same person\n * at once write one enrollment.\n *==========================================*/\n\nimport { normalizeContactEmail, contactDisplayName, readContactFacet } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmLeadDisplayName, crmLeadStatus } from '@aglyn/aglyn/app-utils/crm'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport {\n evaluateOutreachGates,\n type OutreachGateBlock,\n type OutreachGateHold,\n type OutreachGateLookups,\n} from '../engine/gates'\nimport { outreachAttestationsFrom } from '../engine/enrollment-state'\nimport {\n OUTREACH_ATTESTATION_KINDS,\n type OutreachAttestationKind,\n type OutreachAttestations,\n type OutreachSequenceSettings,\n} from '../model/outreach.types'\nimport type {\n OutreachEnrollBlock,\n OutreachEnrollGateway,\n OutreachEnrollPreviewPerson,\n OutreachPersonRef,\n} from '../model/outreach-api'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/**\n * One person as the preview and the enroll read them: a contact, or a lead\n * the sequence's site holds (AGL-3234).\n *\n * ## A lead is judged as the contact it would be\n *\n * The gates, the merge fields and the country rule all read a CONTACT\n * document — its facet's sources, stage, address, company and title. A lead\n * carries the same facts in its own shape, so rather than teach every gate\n * two records, a lead is handed to them as {@link leadAsContact}: a\n * contact-shaped view whose one facet, under the sequence's group, holds\n * what the lead holds. An imported lead has no inbound source and is cold;\n * one that wrote in through a form is not; a lead is never a customer; its\n * address decides its country; and `{{contact.firstName}}` or\n * `{{contact.company}}` in a step reads the lead's name and company text,\n * so a sequence written for contacts sends to leads unchanged — which is\n * also what lets an enrollment made on a lead keep sending after the lead\n * converts and the view becomes the real contact.\n */\nexport interface OutreachEnrollCandidate {\n /** The record's own id: the contact's, or the lead's person key. */\n personId: string\n target: 'contact' | 'lead'\n /** The contact's id; `''` for a lead. */\n contactId: string\n /** The lead's person key; `null` for a contact. */\n leadId: string | null\n /**\n * The contact document (`orgs/{orgId}/contacts/{id}`), or for a lead the\n * contact-shaped view of it — see the module note. `null` when the record\n * no longer exists.\n */\n contact: Record<string, unknown> | null\n /** The lead document as stored, for a lead; `null` for a contact. */\n lead: Record<string, unknown> | null\n /** Whether the sequence's site may see the record. A lead is the site's own. */\n visible: boolean\n /** The name the sequence's site knows them by; `''` for none. */\n name: string\n /** The primary address, normalized, or `null` when there is none. */\n email: string | null\n /** The company the contact is filed under at that site, when there is one. */\n company: Record<string, unknown> | null\n /** A lead already converted: the contact it became. Enroll that instead. */\n convertedContactId: string | null\n /** A lead whose address the workspace already holds as a contact. Enroll that instead. */\n heldAsContactId: string | null\n}\n\n/**\n * A lead as the gates and the merge fields read a contact — see the\n * module note. The facet is the sequence's group's, which is the one every\n * reader asks for. The lead's `sources` — `form:{id}`, `booking`, `import`,\n * `manual`, `api`, `signup` — become the facet's source flags by kind, so\n * the inbound rule reads them as it reads a contact's.\n */\nexport function leadAsContact(\n lead: Record<string, unknown>,\n contactGroupId: string,\n): Record<string, unknown> {\n const sources: Record<string, true> = {}\n for (const raw of Array.isArray(lead['sources']) ? lead['sources'] : []) {\n const source = String(raw)\n const kind = source.startsWith('form:') ? 'form' : source === 'signup' ? 'member' : source\n if (kind) sources[kind] = true\n }\n return {\n email: lead['email'],\n name: lead['name'],\n // The verdict on the address (AGL-3245) is the lead's own top-level\n // field, as it is the contact's, so the gates quote it either way.\n ...(lead['emailState'] && typeof lead['emailState'] === 'object' ? { emailState: lead['emailState'] } : {}),\n facets: {\n [contactGroupId]: {\n sources,\n ...(lead['address'] && typeof lead['address'] === 'object' ? { address: lead['address'] } : {}),\n ...(typeof lead['company'] === 'string' ? { companyName: lead['company'] } : {}),\n ...(typeof lead['jobTitle'] === 'string' ? { jobTitle: lead['jobTitle'] } : {}),\n ...(typeof lead['phone'] === 'string' ? { phone: lead['phone'] } : {}),\n ...(Array.isArray(lead['tags']) ? { tags: lead['tags'] } : {}),\n },\n },\n }\n}\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * The people, as the sequence's site knows them, and the company each\n * contact is filed under there — batched reads for everyone: the contacts\n * and the leads by id, the companies once, and for each lead one address\n * lookup, because a lead the workspace already holds as a contact is that\n * contact's to enroll.\n */\nexport async function readOutreachEnrollCandidates(\n firestore: Firestore,\n input: { orgId: string; hostId: string; contactGroupId: string; people: readonly OutreachPersonRef[] },\n): Promise<OutreachEnrollCandidate[]> {\n if (!input.people.length) return []\n const org = firestore.collection('orgs').doc(input.orgId)\n // Beside the contacts, on the org (AGL-3275).\n const leads = org.collection('leads')\n const snapshots = await getAllChunked(\n firestore,\n input.people.map((person) =>\n person.kind === 'lead' ? leads.doc(person.id) : org.collection('contacts').doc(person.id),\n ),\n )\n const read = await Promise.all(\n input.people.map(async (person, index) => {\n const data = snapshots[index]?.exists ? (snapshots[index].data() as Record<string, unknown>) : null\n if (person.kind === 'lead') {\n const email = data ? normalizeContactEmail(data['email']) : null\n const held =\n data && email ? await findContactByEmail(org.collection('contacts'), email) : null\n return {\n personId: person.id,\n target: 'lead' as const,\n contactId: '',\n leadId: person.id,\n contact: data ? leadAsContact(data, input.contactGroupId) : null,\n lead: data,\n // A lead is the site's own record: no scope to check.\n visible: data !== null,\n name: data ? crmLeadDisplayName(data) : '',\n email,\n companyId: '',\n convertedContactId: data && typeof data['convertedContactId'] === 'string' ? data['convertedContactId'] : null,\n heldAsContactId: held ? held.id : null,\n }\n }\n return {\n personId: person.id,\n target: 'contact' as const,\n contactId: person.id,\n leadId: null,\n contact: data,\n lead: null,\n visible: data ? visibleToHost(data['visibleTo'] as string[] | undefined, input.hostId) : false,\n name: data ? contactDisplayName(data, input.contactGroupId).trim() : '',\n email: data ? normalizeContactEmail(data['email']) : null,\n companyId: data ? String(readContactFacet(data, input.contactGroupId).companyId ?? '') : '',\n convertedContactId: null,\n heldAsContactId: null,\n }\n }),\n )\n const companyIds = [...new Set(read.map((entry) => entry.companyId).filter(Boolean))]\n const companies = new Map<string, Record<string, unknown>>()\n if (companyIds.length) {\n const found = await getAllChunked(\n firestore,\n companyIds.map((id) => org.collection('companies').doc(id)),\n )\n found.forEach((snapshot, index) => {\n if (snapshot.exists) companies.set(companyIds[index], snapshot.data() as Record<string, unknown>)\n })\n }\n return read.map(({ companyId, ...candidate }) => ({\n ...candidate,\n company: companyId ? (companies.get(companyId) ?? null) : null,\n }))\n}\n\n/** The person as every answer names them. */\nfunction personOf(candidate: OutreachEnrollCandidate) {\n return {\n personId: candidate.personId,\n target: candidate.target,\n contactId: candidate.contactId,\n leadId: candidate.leadId,\n }\n}\n\n/** What stands in the way before the gates are asked anything. */\nexport function outreachCandidateBlocks(\n candidate: OutreachEnrollCandidate,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollBlock[] {\n if (!candidate.contact) {\n return candidate.target === 'lead'\n ? [{ code: 'lead_missing', reason: \"This lead no longer exists in this sequence's site's CRM.\" }]\n : [{ code: 'contact_missing', reason: 'This contact no longer exists in the CRM.' }]\n }\n const blocks: OutreachEnrollBlock[] = []\n if (candidate.target === 'lead') {\n // A lead that converted, or whose address the workspace already holds\n // as a contact, is that contact's to enroll — one person, one record.\n if (candidate.convertedContactId) {\n blocks.push({\n code: 'lead_converted',\n reason: 'This lead was converted into a contact. Enroll the contact instead.',\n })\n } else if (candidate.heldAsContactId) {\n blocks.push({\n code: 'lead_is_contact',\n reason: 'This address is already a contact in your CRM. Enroll the contact instead.',\n })\n }\n if (crmLeadStatus(candidate.lead) === 'unqualified') {\n blocks.push({\n code: 'lead_unqualified',\n reason: 'This lead was closed as unqualified. Reopen it before enrolling.',\n })\n }\n }\n if (!candidate.visible) {\n blocks.push({\n code: 'not_in_site',\n reason: `This contact isn't in ${facts.siteName || \"this sequence's site\"}'s CRM.`,\n })\n }\n if (!candidate.email) {\n blocks.push({ code: 'no_email', reason: 'This contact has no email address.' })\n }\n if (facts.alreadyInSequence) {\n blocks.push({\n code: 'already_in_sequence',\n reason: \"This person has already been in this sequence, so they won't be sent its emails again.\",\n })\n }\n return blocks\n}\n\n/** Every attestation, stamped for a hypothetical question only — never stored. */\nconst EVERYTHING_CONFIRMED: OutreachAttestations = Object.fromEntries(\n OUTREACH_ATTESTATION_KINDS.map((kind) => [kind, { uid: 'preview', atMs: 1 }]),\n)\n\nconst blocksOf = (blocks: readonly OutreachGateBlock[]): OutreachEnrollBlock[] =>\n blocks.map(({ code, reason }) => ({ code, reason }))\n\nexport interface OutreachGateQuestion {\n candidate: OutreachEnrollCandidate\n lookups: OutreachGateLookups\n /** The sequence's settings, its countries already capped by the organization's. */\n settings: OutreachSequenceSettings\n contactGroupId: string\n}\n\n/**\n * The gateway as the dialog shows it (AGL-3326): the standing the lookups\n * read, and whether the gates would hold a send into it.\n */\nfunction gatewayOf(question: OutreachGateQuestion, hold: OutreachGateHold | null): OutreachEnrollGateway | null {\n const standing = question.lookups?.gateway\n return standing ? { ...standing, hold: hold !== null } : null\n}\n\n/** Where one person stands before the rep confirms anything — see the module note. */\nexport function previewOutreachPerson(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n): OutreachEnrollPreviewPerson {\n const { candidate } = question\n const person = {\n ...personOf(candidate),\n name: candidate.name,\n email: candidate.email,\n }\n const early = outreachCandidateBlocks(candidate, facts)\n if (early.length) {\n return {\n ...person,\n cold: false,\n country: null,\n status: 'blocked',\n blocks: early,\n requires: { personalLine: false, attestations: [] },\n gateway: null,\n }\n }\n const ask = (personalLine: string, attestations: OutreachAttestations) =>\n evaluateOutreachGates({\n email: candidate.email ?? '',\n contact: candidate.contact,\n contactGroupId: question.contactGroupId,\n company: candidate.company,\n settings: question.settings,\n personalLine,\n attestations,\n lookups: question.lookups,\n })\n const asIs = ask('', {})\n const known = { cold: asIs.cold, country: asIs.country.country, gateway: gatewayOf(question, asIs.hold) }\n if (asIs.allowed) {\n return {\n ...person,\n ...known,\n status: 'eligible',\n blocks: [],\n requires: { personalLine: false, attestations: [] },\n }\n }\n // The line is only checked for being present, so any sentence stands in.\n const confirmed = ask('A personal line.', EVERYTHING_CONFIRMED)\n if (!confirmed.allowed) {\n return {\n ...person,\n ...known,\n status: 'blocked',\n blocks: blocksOf(confirmed.blocks),\n requires: { personalLine: false, attestations: [] },\n }\n }\n const attestations: OutreachAttestationKind[] = asIs.cold\n ? [...asIs.missingAttestations]\n : asIs.blocks.some((block) => block.code === 'country_unknown')\n ? ['us_business_address']\n : []\n return {\n ...person,\n ...known,\n status: 'needs_confirmation',\n blocks: [],\n requires: {\n personalLine: asIs.blocks.some((block) => block.code === 'personal_line_missing'),\n attestations,\n },\n }\n}\n\nexport interface OutreachEnrollDecision {\n allowed: boolean\n blocks: OutreachEnrollBlock[]\n cold: boolean\n /** The address as the gates normalized it. */\n email: string | null\n /** What the rep confirmed, stamped with who and when. */\n attestations: OutreachAttestations\n /**\n * The gateway hold the gates would put on the send (AGL-3326), which the\n * member enrolling past the red chip releases; `null` when none applies.\n */\n hold: OutreachGateHold | null\n}\n\n/** Confirm's answer for one person, with what the rep supplied — see the module note. */\nexport function decideOutreachEnrollment(\n question: OutreachGateQuestion,\n facts: { siteName: string; alreadyInSequence: boolean },\n supplied: {\n personalLine: string\n attestations: readonly unknown[]\n uid: string\n nowMs: number\n },\n): OutreachEnrollDecision {\n const attestations = outreachAttestationsFrom(supplied.attestations, supplied.uid, supplied.nowMs)\n const early = outreachCandidateBlocks(question.candidate, facts)\n if (early.length) {\n return { allowed: false, blocks: early, cold: false, email: question.candidate.email, attestations, hold: null }\n }\n const result = evaluateOutreachGates({\n email: question.candidate.email ?? '',\n contact: question.candidate.contact,\n contactGroupId: question.contactGroupId,\n company: question.candidate.company,\n settings: question.settings,\n personalLine: supplied.personalLine,\n attestations,\n lookups: question.lookups,\n })\n return {\n allowed: result.allowed,\n blocks: blocksOf(result.blocks),\n cold: result.cold,\n email: result.email,\n attestations,\n hold: result.hold,\n }\n}\n"],"names":["normalizeContactEmail","contactDisplayName","readContactFacet","crmLeadDisplayName","crmLeadStatus","visibleToHost","findContactByEmail","evaluateOutreachGates","outreachAttestationsFrom","OUTREACH_ATTESTATION_KINDS","leadAsContact","lead","contactGroupId","sources","raw","Array","isArray","source","String","kind","startsWith","email","name","emailState","facets","address","companyName","jobTitle","phone","tags","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","readOutreachEnrollCandidates","input","people","org","collection","doc","orgId","leads","map","person","id","read","Promise","all","index","data","exists","held","personId","target","contactId","leadId","contact","visible","companyId","convertedContactId","heldAsContactId","hostId","trim","companyIds","Set","entry","filter","Boolean","companies","Map","found","forEach","snapshot","set","candidate","company","get","personOf","outreachCandidateBlocks","facts","code","reason","blocks","siteName","alreadyInSequence","EVERYTHING_CONFIRMED","Object","fromEntries","uid","atMs","blocksOf","gatewayOf","question","hold","standing","lookups","gateway","previewOutreachPerson","early","cold","country","status","requires","personalLine","attestations","ask","settings","asIs","known","allowed","confirmed","missingAttestations","some","block","decideOutreachEnrollment","supplied","nowMs","result"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAgC4C,GAE5C,SAASA,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cI,KAAKzB,MAAM,CAAC8B,IAAI,CAAC,CAACC,QAAUA,MAAMjC,IAAI,KAAK;YACzDwB;QACF;;AAEJ;AAiBA,uFAAuF,GACvF,OAAO,SAASU,yBACdtB,QAA8B,EAC9Bb,KAAuD,EACvDoC,QAKC;QAQQvB;IANT,MAAMY,eAAetG,yBAAyBiH,SAASX,YAAY,EAAEW,SAAS3B,GAAG,EAAE2B,SAASC,KAAK;IACjG,MAAMlB,QAAQpB,wBAAwBc,SAASlB,SAAS,EAAEK;IAC1D,IAAImB,MAAMpE,MAAM,EAAE;QAChB,OAAO;YAAE+E,SAAS;YAAO3B,QAAQgB;YAAOC,MAAM;YAAOpF,OAAO6E,SAASlB,SAAS,CAAC3D,KAAK;YAAEyF;YAAcX,MAAM;QAAK;IACjH;IACA,MAAMwB,SAASpH,sBAAsB;QACnCc,KAAK,GAAE6E,4BAAAA,SAASlB,SAAS,CAAC3D,KAAK,YAAxB6E,4BAA4B;QACnCpC,SAASoC,SAASlB,SAAS,CAAClB,OAAO;QACnClD,gBAAgBsF,SAAStF,cAAc;QACvCqE,SAASiB,SAASlB,SAAS,CAACC,OAAO;QACnC+B,UAAUd,SAASc,QAAQ;QAC3BH,cAAcY,SAASZ,YAAY;QACnCC;QACAT,SAASH,SAASG,OAAO;IAC3B;IACA,OAAO;QACLc,SAASQ,OAAOR,OAAO;QACvB3B,QAAQQ,SAAS2B,OAAOnC,MAAM;QAC9BiB,MAAMkB,OAAOlB,IAAI;QACjBpF,OAAOsG,OAAOtG,KAAK;QACnByF;QACAX,MAAMwB,OAAOxB,IAAI;IACnB;AACF"}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import type { OutreachGateLookups } from '../engine/gates';
|
|
18
|
+
import { type OutreachDomainIntelReadInput } from '../storage/domain-intel-store';
|
|
18
19
|
/**
|
|
19
20
|
* One person to look up: the record they are, and the address the steps go
|
|
20
21
|
* to. `personId` keys the answer — the contact's id, or the lead's person
|
|
@@ -47,6 +48,12 @@ export interface ReadOutreachGateLookupsInput {
|
|
|
47
48
|
* site's own does. Omitted, it does not.
|
|
48
49
|
*/
|
|
49
50
|
consentAwaitsConfirmation?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* The MX resolver and the clock the domain intel is read with (AGL-3326):
|
|
53
|
+
* a domain's gateway is looked up once a week and cached on the org, and
|
|
54
|
+
* its ledger is read for the windows the hold and the chip judge.
|
|
55
|
+
*/
|
|
56
|
+
gateway: OutreachDomainIntelReadInput;
|
|
50
57
|
people: readonly OutreachGateLookupPerson[];
|
|
51
58
|
}
|
|
52
59
|
type Firestore = FirebaseFirestore.Firestore;
|
|
@@ -43,6 +43,7 @@ import { personKey } from "@aglyn/aglyn/app-utils/person-key";
|
|
|
43
43
|
import { loadCrmInboundRoster } from "@aglyn/tenant-data-admin/server/crm-inbound-email";
|
|
44
44
|
import { EMAIL_SUPPRESSIONS_COLLECTION, HOST_SUPPRESSIONS_SUBCOLLECTION } from "@aglyn/tenant-data-admin/server/email-suppression";
|
|
45
45
|
import { lookupOutreachDoNotContact, lookupOutreachDoNotContactDomains } from "../storage/do-not-contact-store.js";
|
|
46
|
+
import { readOutreachGatewayStandings } from "../storage/domain-intel-store.js";
|
|
46
47
|
import { outreachOrgCollection } from "../storage/outreach-records.js";
|
|
47
48
|
/** `getAll` takes this many references at most per call. */ const GET_ALL_CHUNK = 300;
|
|
48
49
|
async function getAllChunked(firestore, refs) {
|
|
@@ -109,7 +110,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
109
110
|
];
|
|
110
111
|
const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments');
|
|
111
112
|
const activities = firestore.collection('orgs').doc(orgId).collection(CRM_COLLECTIONS.activities);
|
|
112
|
-
const [platform, site, sales, doNotContact, doNotContactDomain, roster, perPerson] = await Promise.all([
|
|
113
|
+
const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson] = await Promise.all([
|
|
113
114
|
keyedLookup(firestore, people, (key)=>firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key), // A released record no longer suppresses.
|
|
114
115
|
(snapshot)=>snapshot.exists && !snapshot.get('releasedAt'), 'platform suppression'),
|
|
115
116
|
keyedGroupLookup(firestore, people, hostIds, (host, key)=>host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key), (snapshot)=>snapshot.exists, // An entry on any site of the group suppresses.
|
|
@@ -129,6 +130,13 @@ async function getAllChunked(firestore, refs) {
|
|
|
129
130
|
// The domain half of the same list (AGL-3244), one `getAll` over the
|
|
130
131
|
// distinct domains the people are at.
|
|
131
132
|
lookupOutreachDoNotContactDomains(firestore, orgId, people.map((person)=>person.email)),
|
|
133
|
+
// The mail gateway in front of each domain and its record here
|
|
134
|
+
// (AGL-3326), one read over the distinct domains and one over the
|
|
135
|
+
// gateways they name.
|
|
136
|
+
readOutreachGatewayStandings(firestore, orgId, people.map((person)=>person.email), input.gateway).catch((error)=>{
|
|
137
|
+
console.error('[outreach] mail gateway lookup failed; reading as unchecked', error);
|
|
138
|
+
return new Map();
|
|
139
|
+
}),
|
|
132
140
|
loadCrmInboundRoster(firestore, orgId).catch((error)=>{
|
|
133
141
|
console.error('[outreach] roster lookup failed; reading as unchecked', error);
|
|
134
142
|
return null;
|
|
@@ -177,7 +185,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
177
185
|
]));
|
|
178
186
|
const lookups = new Map();
|
|
179
187
|
for (const person of people){
|
|
180
|
-
var _platform_get, _site_get, _sales_get, _doNotContact_get, _doNotContactDomain_get, _ref, _ref1;
|
|
188
|
+
var _platform_get, _site_get, _sales_get, _doNotContact_get, _doNotContactDomain_get, _gateway_get, _ref, _ref1;
|
|
181
189
|
const own = byPerson.get(person.personId);
|
|
182
190
|
lookups.set(person.personId, {
|
|
183
191
|
platformSuppressed: (_platform_get = platform.get(person.personId)) != null ? _platform_get : null,
|
|
@@ -185,6 +193,7 @@ async function getAllChunked(firestore, refs) {
|
|
|
185
193
|
salesTopicState: (_sales_get = sales.get(person.personId)) != null ? _sales_get : null,
|
|
186
194
|
doNotContact: (_doNotContact_get = doNotContact.get(person.email)) != null ? _doNotContact_get : null,
|
|
187
195
|
doNotContactDomain: (_doNotContactDomain_get = doNotContactDomain.get(person.email)) != null ? _doNotContactDomain_get : null,
|
|
196
|
+
gateway: (_gateway_get = gateway.get(person.email)) != null ? _gateway_get : null,
|
|
188
197
|
workspaceMembers: roster,
|
|
189
198
|
openEnrollments: (_ref = own == null ? void 0 : own.open) != null ? _ref : null,
|
|
190
199
|
hasInboundEmail: (_ref1 = own == null ? void 0 : own.inbound) != null ? _ref1 : null
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/gate-lookups.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE LOOKUPS THE ENROLLMENT GATES DECIDE ON (AGL-2980).\n *\n * `evaluateOutreachGates` is pure: it reads a contact as stored and the\n * RESULTS of the reads the runtime makes. This is those reads, for many\n * people at once — the enroll preview asks about everyone a view names in\n * one pass, and the sending runtime asks about one person before each send\n * with the same function, so the two can never consult different lists.\n *\n * Server only. Every list keyed by address is read with one `getAll` over\n * `personKey` ids — the suppression lists, the sales topic opt-outs, the\n * do-not-contact list — so a lookup costs one round trip however many\n * people it covers, and needs no index that could go missing. The roster\n * is read once. The two per-person facts that are queries — the person's\n * other enrollments and whether they ever wrote in — are equality filters\n * on single fields.\n *\n * ## A read that failed is `null`, and `null` refuses\n *\n * Each lookup is caught on its own and answers `null` for everyone it\n * covered, which the gates read as \"we couldn't check\" and refuse: a\n * person who asked not to be emailed must not be emailed because a read\n * timed out. One failed list does not blank the others.\n */\n\nimport { consentGroupTopicState } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport {\n EMAIL_TOPIC_SALES,\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/email-topics'\nimport type { MemberAddresses } from '@aglyn/aglyn/app-utils/member-email-aliases'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { loadCrmInboundRoster } from '@aglyn/tenant-data-admin/server/crm-inbound-email'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from '@aglyn/tenant-data-admin/server/email-suppression'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport type { OutreachEnrollmentStatus } from '../model/outreach.types'\nimport {\n lookupOutreachDoNotContact,\n lookupOutreachDoNotContactDomains,\n} from '../storage/do-not-contact-store'\nimport { outreachOrgCollection } from '../storage/outreach-records'\n\n/**\n * One person to look up: the record they are, and the address the steps go\n * to. `personId` keys the answer — the contact's id, or the lead's person\n * key (AGL-3234); a lead has no contact to look up enrollments or inbound\n * email by, so those reads go by the lead instead.\n */\nexport interface OutreachGateLookupPerson {\n personId: string\n /** The contact's id, or `null` for a lead. */\n contactId: string | null\n /** The lead's person key, or `null` for a contact. */\n leadId: string | null\n email: string\n}\n\nexport interface ReadOutreachGateLookupsInput {\n orgId: string\n /** The sequence's site: whose suppression list and topic opt-outs apply. */\n hostId: string\n /**\n * Every site in the sequence site's consent group, the site included —\n * `consentGroupForHost(org, hostId).hostIds`. An org that declared several\n * sites one sender is one sender to the person who unsubscribed from any of\n * them, so the site suppression list and the sales opt-outs are read on\n * each. Omitted, the site alone.\n */\n consentHostIds?: readonly string[]\n /**\n * The same group's `awaitsConfirmation`: whether a sibling's pending\n * confirmation counts in the sales stream's standing as the sequence\n * site's own does. Omitted, it does not.\n */\n consentAwaitsConfirmation?: boolean\n people: readonly OutreachGateLookupPerson[]\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * One keyed list, read for every person at once: `answer` turns each\n * person's document into their answer. An address that cannot be keyed has\n * no document anywhere and is answered as unchecked, and so is everyone\n * when the read fails.\n */\nasync function keyedLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n collection: (key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const answers = new Map<string, T | null>()\n const keyed: Array<{ personId: string; key: string }> = []\n for (const person of people) {\n const key = personKey(person.email)\n if (key) keyed.push({ personId: person.personId, key })\n else answers.set(person.personId, null)\n }\n if (!keyed.length) return answers\n try {\n const snapshots = await getAllChunked(\n firestore,\n keyed.map((entry) => collection(entry.key)),\n )\n keyed.forEach((entry, index) => answers.set(entry.personId, answer(snapshots[index])))\n } catch (error) {\n console.error(`[outreach] ${label} lookup failed; reading as unchecked`, error)\n for (const entry of keyed) answers.set(entry.personId, null)\n }\n return answers\n}\n\n/**\n * The same keyed lookup on every site of a consent group, folded into one\n * answer per person by `fold`. A read that failed anywhere is `null` for the\n * people it covered, so a sibling's unreadable list refuses as the site's own\n * would. A group of one is one lookup, exactly as the site alone.\n */\nasync function keyedGroupLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n hostIds: readonly string[],\n collection: (host: FirebaseFirestore.DocumentReference, key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n fold: (answers: readonly T[]) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const bySite = await Promise.all(\n hostIds.map((id) => {\n const host = firestore.collection('hosts').doc(id)\n return keyedLookup(firestore, people, (key) => collection(host, key), answer, label)\n }),\n )\n if (bySite.length === 1) return bySite[0]\n const folded = new Map<string, T | null>()\n for (const person of people) {\n const answers = bySite.map((site) => site.get(person.personId) ?? null)\n folded.set(\n person.personId,\n answers.some((answer) => answer === null) ? null : fold(answers as T[]),\n )\n }\n return folded\n}\n\n/** Every lookup the gates take, for each person, keyed by person id. */\nexport async function readOutreachGateLookups(\n firestore: Firestore,\n input: ReadOutreachGateLookupsInput,\n): Promise<Map<string, OutreachGateLookups>> {\n const { orgId, hostId, people } = input\n // The sequence's site first, then the rest of its consent group.\n const hostIds = [\n hostId,\n ...new Set((input.consentHostIds ?? []).filter((id) => id && id !== hostId)),\n ]\n const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments')\n const activities = firestore.collection('orgs').doc(orgId).collection(CRM_COLLECTIONS.activities)\n\n const [platform, site, sales, doNotContact, doNotContactDomain, roster, perPerson] = await Promise.all([\n keyedLookup(\n firestore,\n people,\n (key) => firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key),\n // A released record no longer suppresses.\n (snapshot) => snapshot.exists && !snapshot.get('releasedAt'),\n 'platform suppression',\n ),\n keyedGroupLookup(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key),\n (snapshot) => snapshot.exists,\n // An entry on any site of the group suppresses.\n (answers) => answers.some(Boolean),\n 'site suppression',\n ),\n keyedGroupLookup<TopicSubscriptionState>(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(TOPIC_OPT_OUTS_SUBCOLLECTION).doc(key),\n (snapshot) =>\n readTopicSubscriptionState(\n ((snapshot.exists ? snapshot.get('topics') : null) ?? {})[EMAIL_TOPIC_SALES],\n ),\n // The group's standing, the way the topic filter folds it: leaving the\n // sales stream anywhere in the group is leaving the sender, and a\n // sibling's pending confirmation counts only where the org said the\n // group waits. What a pending standing means for a sales email is the\n // gates' question, not this one.\n (states) =>\n consentGroupTopicState(\n { awaitsConfirmation: input.consentAwaitsConfirmation === true },\n states,\n ),\n 'sales topic',\n ),\n lookupOutreachDoNotContact(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The domain half of the same list (AGL-3244), one `getAll` over the\n // distinct domains the people are at.\n lookupOutreachDoNotContactDomains(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n loadCrmInboundRoster(firestore, orgId).catch((error: unknown): MemberAddresses[] | null => {\n console.error('[outreach] roster lookup failed; reading as unchecked', error)\n return null\n }),\n Promise.all(\n people.map(async (person) => {\n const open = await Promise.all([\n person.contactId\n ? enrollments.where('contactId', '==', person.contactId).get()\n : enrollments.where('leadId', '==', person.leadId ?? '').get(),\n enrollments.where('email', '==', person.email).get(),\n ])\n .then(([byContact, byEmail]) => {\n const found = new Map<string, { id: string; sequenceId: string; status: OutreachEnrollmentStatus }>()\n for (const doc of [...byContact.docs, ...byEmail.docs]) {\n found.set(doc.id, {\n id: doc.id,\n sequenceId: String(doc.get('sequenceId') ?? ''),\n status: doc.get('status') as OutreachEnrollmentStatus,\n })\n }\n return [...found.values()]\n })\n .catch((error: unknown) => {\n console.error('[outreach] enrollment lookup failed; reading as unchecked', error)\n return null\n })\n // An email the person wrote: filed on the contact, or on the lead\n // while they were one (AGL-3234).\n const inbound = await activities\n .where(person.contactId ? 'contactId' : 'leadId', '==', person.contactId ?? person.leadId ?? '')\n .where('direction', '==', 'inbound')\n .limit(1)\n .get()\n .then((snapshot) => !snapshot.empty)\n .catch((error: unknown) => {\n console.error('[outreach] inbound email lookup failed; reading as cold', error)\n return null\n })\n return { personId: person.personId, open, inbound }\n }),\n ),\n ])\n\n const byPerson = new Map(perPerson.map((entry) => [entry.personId, entry]))\n const lookups = new Map<string, OutreachGateLookups>()\n for (const person of people) {\n const own = byPerson.get(person.personId)\n lookups.set(person.personId, {\n platformSuppressed: platform.get(person.personId) ?? null,\n hostSuppressed: site.get(person.personId) ?? null,\n salesTopicState: sales.get(person.personId) ?? null,\n doNotContact: doNotContact.get(person.email) ?? null,\n doNotContactDomain: doNotContactDomain.get(person.email) ?? null,\n workspaceMembers: roster,\n openEnrollments: own?.open ?? null,\n hasInboundEmail: own?.inbound ?? null,\n })\n }\n return lookups\n}\n"],"names":["consentGroupTopicState","CRM_COLLECTIONS","EMAIL_TOPIC_SALES","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","personKey","loadCrmInboundRoster","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","lookupOutreachDoNotContact","lookupOutreachDoNotContactDomains","outreachOrgCollection","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","keyedLookup","people","collection","answer","label","answers","Map","keyed","person","key","email","personId","set","map","entry","forEach","index","error","console","keyedGroupLookup","hostIds","fold","bySite","Promise","all","id","host","doc","folded","site","get","some","readOutreachGateLookups","input","orgId","hostId","Set","consentHostIds","filter","enrollments","activities","platform","sales","doNotContact","doNotContactDomain","roster","perPerson","snapshot","exists","Boolean","states","awaitsConfirmation","consentAwaitsConfirmation","catch","open","contactId","where","leadId","then","byContact","byEmail","found","docs","sequenceId","String","status","values","inbound","limit","empty","byPerson","lookups","own","platformSuppressed","hostSuppressed","salesTopicState","workspaceMembers","openEnrollments","hasInboundEmail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,S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GACNtC,GAAG,GACH4B,IAAI,CAAC,CAACX,WAAa,CAACA,SAASsB,KAAK,EAClChB,KAAK,CAAC,CAACpC;gBACNC,QAAQD,KAAK,CAAC,2DAA2DA;gBACzE,OAAO;YACT;YACF,OAAO;gBAAEN,UAAUH,OAAOG,QAAQ;gBAAE2C;gBAAMa;YAAQ;QACpD;KAEH;IAED,MAAMG,WAAW,IAAIhE,IAAIwC,UAAUjC,GAAG,CAAC,CAACC,QAAU;YAACA,MAAMH,QAAQ;YAAEG;SAAM;IACzE,MAAMyD,UAAU,IAAIjE;IACpB,KAAK,MAAME,UAAUP,OAAQ;YAGLwC,eACJZ,WACCa,YACHC,mBACMC;QANtB,MAAM4B,MAAMF,SAASxC,GAAG,CAACtB,OAAOG,QAAQ;QACxC4D,QAAQ3D,GAAG,CAACJ,OAAOG,QAAQ,EAAE;YAC3B8D,kBAAkB,GAAEhC,gBAAAA,SAASX,GAAG,CAACtB,OAAOG,QAAQ,aAA5B8B,gBAAiC;YACrDiC,cAAc,GAAE7C,YAAAA,KAAKC,GAAG,CAACtB,OAAOG,QAAQ,aAAxBkB,YAA6B;YAC7C8C,eAAe,GAAEjC,aAAAA,MAAMZ,GAAG,CAACtB,OAAOG,QAAQ,aAAzB+B,aAA8B;YAC/CC,YAAY,GAAEA,oBAAAA,aAAab,GAAG,CAACtB,OAAOE,KAAK,aAA7BiC,oBAAkC;YAChDC,kBAAkB,GAAEA,0BAAAA,mBAAmBd,GAAG,CAACtB,OAAOE,KAAK,aAAnCkC,0BAAwC;YAC5DgC,kBAAkB/B;YAClBgC,eAAe,UAAEL,uBAAAA,IAAKlB,IAAI,mBAAI;YAC9BwB,eAAe,WAAEN,uBAAAA,IAAKL,OAAO,oBAAI;QACnC;IACF;IACA,OAAOI;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/enrollment/gate-lookups.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * THE LOOKUPS THE ENROLLMENT GATES DECIDE ON (AGL-2980).\n *\n * `evaluateOutreachGates` is pure: it reads a contact as stored and the\n * RESULTS of the reads the runtime makes. This is those reads, for many\n * people at once — the enroll preview asks about everyone a view names in\n * one pass, and the sending runtime asks about one person before each send\n * with the same function, so the two can never consult different lists.\n *\n * Server only. Every list keyed by address is read with one `getAll` over\n * `personKey` ids — the suppression lists, the sales topic opt-outs, the\n * do-not-contact list — so a lookup costs one round trip however many\n * people it covers, and needs no index that could go missing. The roster\n * is read once. The two per-person facts that are queries — the person's\n * other enrollments and whether they ever wrote in — are equality filters\n * on single fields.\n *\n * ## A read that failed is `null`, and `null` refuses\n *\n * Each lookup is caught on its own and answers `null` for everyone it\n * covered, which the gates read as \"we couldn't check\" and refuse: a\n * person who asked not to be emailed must not be emailed because a read\n * timed out. One failed list does not blank the others.\n */\n\nimport { consentGroupTopicState } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport {\n EMAIL_TOPIC_SALES,\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/email-topics'\nimport type { MemberAddresses } from '@aglyn/aglyn/app-utils/member-email-aliases'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { loadCrmInboundRoster } from '@aglyn/tenant-data-admin/server/crm-inbound-email'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from '@aglyn/tenant-data-admin/server/email-suppression'\nimport type { OutreachGateLookups } from '../engine/gates'\nimport type { OutreachEnrollmentStatus } from '../model/outreach.types'\nimport {\n lookupOutreachDoNotContact,\n lookupOutreachDoNotContactDomains,\n} from '../storage/do-not-contact-store'\nimport { type OutreachDomainIntelReadInput, readOutreachGatewayStandings } from '../storage/domain-intel-store'\nimport { outreachOrgCollection } from '../storage/outreach-records'\n\n/**\n * One person to look up: the record they are, and the address the steps go\n * to. `personId` keys the answer — the contact's id, or the lead's person\n * key (AGL-3234); a lead has no contact to look up enrollments or inbound\n * email by, so those reads go by the lead instead.\n */\nexport interface OutreachGateLookupPerson {\n personId: string\n /** The contact's id, or `null` for a lead. */\n contactId: string | null\n /** The lead's person key, or `null` for a contact. */\n leadId: string | null\n email: string\n}\n\nexport interface ReadOutreachGateLookupsInput {\n orgId: string\n /** The sequence's site: whose suppression list and topic opt-outs apply. */\n hostId: string\n /**\n * Every site in the sequence site's consent group, the site included —\n * `consentGroupForHost(org, hostId).hostIds`. An org that declared several\n * sites one sender is one sender to the person who unsubscribed from any of\n * them, so the site suppression list and the sales opt-outs are read on\n * each. Omitted, the site alone.\n */\n consentHostIds?: readonly string[]\n /**\n * The same group's `awaitsConfirmation`: whether a sibling's pending\n * confirmation counts in the sales stream's standing as the sequence\n * site's own does. Omitted, it does not.\n */\n consentAwaitsConfirmation?: boolean\n /**\n * The MX resolver and the clock the domain intel is read with (AGL-3326):\n * a domain's gateway is looked up once a week and cached on the org, and\n * its ledger is read for the windows the hold and the chip judge.\n */\n gateway: OutreachDomainIntelReadInput\n people: readonly OutreachGateLookupPerson[]\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** `getAll` takes this many references at most per call. */\nconst GET_ALL_CHUNK = 300\n\nasync function getAllChunked(\n firestore: Firestore,\n refs: readonly FirebaseFirestore.DocumentReference[],\n): Promise<FirebaseFirestore.DocumentSnapshot[]> {\n const snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n for (let start = 0; start < refs.length; start += GET_ALL_CHUNK) {\n snapshots.push(...(await firestore.getAll(...refs.slice(start, start + GET_ALL_CHUNK))))\n }\n return snapshots\n}\n\n/**\n * One keyed list, read for every person at once: `answer` turns each\n * person's document into their answer. An address that cannot be keyed has\n * no document anywhere and is answered as unchecked, and so is everyone\n * when the read fails.\n */\nasync function keyedLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n collection: (key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const answers = new Map<string, T | null>()\n const keyed: Array<{ personId: string; key: string }> = []\n for (const person of people) {\n const key = personKey(person.email)\n if (key) keyed.push({ personId: person.personId, key })\n else answers.set(person.personId, null)\n }\n if (!keyed.length) return answers\n try {\n const snapshots = await getAllChunked(\n firestore,\n keyed.map((entry) => collection(entry.key)),\n )\n keyed.forEach((entry, index) => answers.set(entry.personId, answer(snapshots[index])))\n } catch (error) {\n console.error(`[outreach] ${label} lookup failed; reading as unchecked`, error)\n for (const entry of keyed) answers.set(entry.personId, null)\n }\n return answers\n}\n\n/**\n * The same keyed lookup on every site of a consent group, folded into one\n * answer per person by `fold`. A read that failed anywhere is `null` for the\n * people it covered, so a sibling's unreadable list refuses as the site's own\n * would. A group of one is one lookup, exactly as the site alone.\n */\nasync function keyedGroupLookup<T>(\n firestore: Firestore,\n people: readonly OutreachGateLookupPerson[],\n hostIds: readonly string[],\n collection: (host: FirebaseFirestore.DocumentReference, key: string) => FirebaseFirestore.DocumentReference,\n answer: (snapshot: FirebaseFirestore.DocumentSnapshot) => T,\n fold: (answers: readonly T[]) => T,\n label: string,\n): Promise<Map<string, T | null>> {\n const bySite = await Promise.all(\n hostIds.map((id) => {\n const host = firestore.collection('hosts').doc(id)\n return keyedLookup(firestore, people, (key) => collection(host, key), answer, label)\n }),\n )\n if (bySite.length === 1) return bySite[0]\n const folded = new Map<string, T | null>()\n for (const person of people) {\n const answers = bySite.map((site) => site.get(person.personId) ?? null)\n folded.set(\n person.personId,\n answers.some((answer) => answer === null) ? null : fold(answers as T[]),\n )\n }\n return folded\n}\n\n/** Every lookup the gates take, for each person, keyed by person id. */\nexport async function readOutreachGateLookups(\n firestore: Firestore,\n input: ReadOutreachGateLookupsInput,\n): Promise<Map<string, OutreachGateLookups>> {\n const { orgId, hostId, people } = input\n // The sequence's site first, then the rest of its consent group.\n const hostIds = [\n hostId,\n ...new Set((input.consentHostIds ?? []).filter((id) => id && id !== hostId)),\n ]\n const enrollments = outreachOrgCollection(firestore, orgId, 'enrollments')\n const activities = firestore.collection('orgs').doc(orgId).collection(CRM_COLLECTIONS.activities)\n\n const [platform, site, sales, doNotContact, doNotContactDomain, gateway, roster, perPerson] = await Promise.all([\n keyedLookup(\n firestore,\n people,\n (key) => firestore.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key),\n // A released record no longer suppresses.\n (snapshot) => snapshot.exists && !snapshot.get('releasedAt'),\n 'platform suppression',\n ),\n keyedGroupLookup(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key),\n (snapshot) => snapshot.exists,\n // An entry on any site of the group suppresses.\n (answers) => answers.some(Boolean),\n 'site suppression',\n ),\n keyedGroupLookup<TopicSubscriptionState>(\n firestore,\n people,\n hostIds,\n (host, key) => host.collection(TOPIC_OPT_OUTS_SUBCOLLECTION).doc(key),\n (snapshot) =>\n readTopicSubscriptionState(\n ((snapshot.exists ? snapshot.get('topics') : null) ?? {})[EMAIL_TOPIC_SALES],\n ),\n // The group's standing, the way the topic filter folds it: leaving the\n // sales stream anywhere in the group is leaving the sender, and a\n // sibling's pending confirmation counts only where the org said the\n // group waits. What a pending standing means for a sales email is the\n // gates' question, not this one.\n (states) =>\n consentGroupTopicState(\n { awaitsConfirmation: input.consentAwaitsConfirmation === true },\n states,\n ),\n 'sales topic',\n ),\n lookupOutreachDoNotContact(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The domain half of the same list (AGL-3244), one `getAll` over the\n // distinct domains the people are at.\n lookupOutreachDoNotContactDomains(\n firestore,\n orgId,\n people.map((person) => person.email),\n ),\n // The mail gateway in front of each domain and its record here\n // (AGL-3326), one read over the distinct domains and one over the\n // gateways they name.\n readOutreachGatewayStandings(\n firestore,\n orgId,\n people.map((person) => person.email),\n input.gateway,\n ).catch((error: unknown) => {\n console.error('[outreach] mail gateway lookup failed; reading as unchecked', error)\n return new Map<string, null>()\n }),\n loadCrmInboundRoster(firestore, orgId).catch((error: unknown): MemberAddresses[] | null => {\n console.error('[outreach] roster lookup failed; reading as unchecked', error)\n return null\n }),\n Promise.all(\n people.map(async (person) => {\n const open = await Promise.all([\n person.contactId\n ? enrollments.where('contactId', '==', person.contactId).get()\n : enrollments.where('leadId', '==', person.leadId ?? '').get(),\n enrollments.where('email', '==', person.email).get(),\n ])\n .then(([byContact, byEmail]) => {\n const found = new Map<string, { id: string; sequenceId: string; status: OutreachEnrollmentStatus }>()\n for (const doc of [...byContact.docs, ...byEmail.docs]) {\n found.set(doc.id, {\n id: doc.id,\n sequenceId: String(doc.get('sequenceId') ?? ''),\n status: doc.get('status') as OutreachEnrollmentStatus,\n })\n }\n return [...found.values()]\n })\n .catch((error: unknown) => {\n console.error('[outreach] enrollment lookup failed; reading as unchecked', error)\n return null\n })\n // An email the person wrote: filed on the contact, or on the lead\n // while they were one (AGL-3234).\n const inbound = await activities\n .where(person.contactId ? 'contactId' : 'leadId', '==', person.contactId ?? person.leadId ?? '')\n .where('direction', '==', 'inbound')\n .limit(1)\n .get()\n .then((snapshot) => !snapshot.empty)\n .catch((error: unknown) => {\n console.error('[outreach] inbound email lookup failed; reading as cold', error)\n return null\n })\n return { personId: person.personId, open, inbound }\n }),\n ),\n ])\n\n const byPerson = new Map(perPerson.map((entry) => [entry.personId, entry]))\n const lookups = new Map<string, OutreachGateLookups>()\n for (const person of people) {\n const own = byPerson.get(person.personId)\n lookups.set(person.personId, {\n platformSuppressed: platform.get(person.personId) ?? null,\n hostSuppressed: site.get(person.personId) ?? null,\n salesTopicState: sales.get(person.personId) ?? null,\n doNotContact: doNotContact.get(person.email) ?? null,\n doNotContactDomain: doNotContactDomain.get(person.email) ?? null,\n gateway: gateway.get(person.email) ?? null,\n workspaceMembers: roster,\n openEnrollments: own?.open ?? null,\n hasInboundEmail: own?.inbound ?? null,\n })\n }\n return lookups\n}\n"],"names":["consentGroupTopicState","CRM_COLLECTIONS","EMAIL_TOPIC_SALES","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","personKey","loadCrmInboundRoster","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","lookupOutreachDoNotContact","lookupOutreachDoNotContactDomains","readOutreachGatewayStandings","outreachOrgCollection","GET_ALL_CHUNK","getAllChunked","firestore","refs","snapshots","start","length","push","getAll","slice","keyedLookup","people","collection","answer","label","answers","Map","keyed","person","key","email","personId","set","map","entry","forEach","index","error","console","keyedGroupLookup","hostIds","fold","bySite","Promise","all","id","host","doc","folded","site","get","some","readOutreachGateLookups","input","orgId","hostId","Set","consentHostIds","filter","enrollments","activities","platform","sales","doNotContact","doNotContactDomain","gateway","roster","perPerson","snapshot","exists","Boolean","states","awaitsConfirmation","consentAwaitsConfirmation","catch","open","contactId","where","leadId","then","byContact","byEmail","found","docs","sequenceId","String","status","values","inbound","limit","empty","byPerson","lookups","own","platformSuppressed","hostSuppressed","salesTopicState","workspaceMembers","openEnrollments","hasInboundEmail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SACEC,iBAAiB,EACjBC,0BAA0B,EAC1BC,4BAA4B,QAEvB,sCAAqC;AAE5C,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,oBAAoB,QAAQ,oDAAmD;A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