@aglyn/plugins-outreach 1.0.0-beta.151 → 1.0.0-beta.153
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/README.md +5 -1
- package/package.json +12 -12
- package/src/lib/components/compliance-section.js +1 -1
- package/src/lib/components/compliance-section.js.map +1 -1
- package/src/lib/components/enroll-dialog.js +142 -32
- package/src/lib/components/enroll-dialog.js.map +1 -1
- package/src/lib/components/enrollments-table.js +37 -8
- package/src/lib/components/enrollments-table.js.map +1 -1
- package/src/lib/components/mailbox-card.d.ts +3 -0
- package/src/lib/components/mailbox-card.js +44 -8
- package/src/lib/components/mailbox-card.js.map +1 -1
- package/src/lib/components/use-outreach-crm.d.ts +20 -1
- package/src/lib/components/use-outreach-crm.js +78 -4
- package/src/lib/components/use-outreach-crm.js.map +1 -1
- package/src/lib/components/use-outreach-mailbox-api.d.ts +2 -1
- package/src/lib/components/use-outreach-mailbox-api.js +5 -3
- package/src/lib/components/use-outreach-mailbox-api.js.map +1 -1
- package/src/lib/declarations.console-server.js +14 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/engine/compose.d.ts +7 -2
- package/src/lib/engine/compose.js +11 -5
- package/src/lib/engine/compose.js.map +1 -1
- package/src/lib/engine/enrollment-state.d.ts +6 -1
- package/src/lib/engine/enrollment-state.js +3 -1
- package/src/lib/engine/enrollment-state.js.map +1 -1
- package/src/lib/engine/opt-out-intent.js +1 -1
- package/src/lib/engine/opt-out-intent.js.map +1 -1
- package/src/lib/enrollment/enroll-people.d.ts +52 -7
- package/src/lib/enrollment/enroll-people.js +109 -12
- package/src/lib/enrollment/enroll-people.js.map +1 -1
- package/src/lib/enrollment/gate-lookups.d.ts +12 -3
- package/src/lib/enrollment/gate-lookups.js +17 -14
- package/src/lib/enrollment/gate-lookups.js.map +1 -1
- package/src/lib/mailboxes/mailbox-api.d.ts +27 -2
- package/src/lib/mailboxes/mailbox-api.js.map +1 -1
- package/src/lib/mailboxes/mailbox-routes.js +52 -8
- package/src/lib/mailboxes/mailbox-routes.js.map +1 -1
- package/src/lib/mailboxes/oauth-redirect.d.ts +15 -4
- package/src/lib/mailboxes/oauth-redirect.js +15 -6
- package/src/lib/mailboxes/oauth-redirect.js.map +1 -1
- package/src/lib/model/outreach-api.d.ts +39 -8
- package/src/lib/model/outreach-api.js.map +1 -1
- package/src/lib/model/outreach.types.d.ts +29 -4
- package/src/lib/model/outreach.types.js +9 -0
- package/src/lib/model/outreach.types.js.map +1 -1
- package/src/lib/model/stored-records.js +7 -0
- package/src/lib/model/stored-records.js.map +1 -1
- package/src/lib/routes/enroll-routes.js +112 -39
- package/src/lib/routes/enroll-routes.js.map +1 -1
- package/src/lib/routes/preview-routes.js +18 -5
- package/src/lib/routes/preview-routes.js.map +1 -1
- package/src/lib/runtime/lead-records.d.ts +26 -0
- package/src/lib/runtime/lead-records.js +84 -0
- package/src/lib/runtime/lead-records.js.map +1 -0
- package/src/lib/runtime/send-job.js +30 -12
- package/src/lib/runtime/send-job.js.map +1 -1
- package/src/lib/runtime/sync-job.js +11 -3
- package/src/lib/runtime/sync-job.js.map +1 -1
- package/src/lib/runtime/timeline.d.ts +6 -4
- package/src/lib/runtime/timeline.js +3 -7
- package/src/lib/runtime/timeline.js.map +1 -1
- package/src/lib/storage/outreach-records.d.ts +21 -2
- package/src/lib/storage/outreach-records.js +31 -2
- package/src/lib/storage/outreach-records.js.map +1 -1
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /**
|
|
17
|
+
* WHAT A SEQUENCE DOES TO A LEAD'S OWN RECORD (AGL-3234).
|
|
18
|
+
*
|
|
19
|
+
* Two touches, both on `hosts/{hostId}/leads/{leadId}` — the record system's
|
|
20
|
+
* document, written in the record system's vocabulary (`@aglyn/aglyn`'s lead
|
|
21
|
+
* statuses), never through an import of the CRM plugin:
|
|
22
|
+
*
|
|
23
|
+
* - a REPLY moves a lead nobody has touched from New to Working. Somebody
|
|
24
|
+
* wrote back; the lead is being worked, and a queue that still showed it
|
|
25
|
+
* as New would send a rep to open a conversation already open. A lead
|
|
26
|
+
* already Working, closed, or converted is left as it is — a reply does
|
|
27
|
+
* not reopen a verdict or move a contact's record.
|
|
28
|
+
* - a CONVERSION re-points every enrollment made on the lead at the contact
|
|
29
|
+
* it became: the record system tells every plugin through its
|
|
30
|
+
* lead-conversion seam, and this is Sequences' share of it. The
|
|
31
|
+
* enrollment keeps its id, its thread and its place in the steps, and
|
|
32
|
+
* keeps naming the lead beside the contact, so both pages list it.
|
|
33
|
+
*
|
|
34
|
+
* Neither throws: a status that could not be moved is one a rep moves by
|
|
35
|
+
* hand, and an enrollment that could not follow its lead is one the next
|
|
36
|
+
* send stops as `contact_missing` and a rep re-enrolls.
|
|
37
|
+
*/ import { crmLeadStatus } from "@aglyn/aglyn/app-utils/crm";
|
|
38
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
39
|
+
import { outreachOrgCollection } from "../storage/outreach-records.js";
|
|
40
|
+
/** Firestore refuses a batch of more than 500 writes. */ const BATCH_LIMIT = 450;
|
|
41
|
+
/** A lead nobody has touched, once somebody replied: Working. `true` when it moved. */ export async function markOutreachLeadWorking(firestore, input) {
|
|
42
|
+
try {
|
|
43
|
+
var _snapshot_data;
|
|
44
|
+
const ref = firestore.collection('hosts').doc(input.hostId).collection('leads').doc(input.leadId);
|
|
45
|
+
const snapshot = await ref.get();
|
|
46
|
+
if (!snapshot.exists) return false;
|
|
47
|
+
const lead = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
|
|
48
|
+
if (lead['convertedContactId'] || crmLeadStatus(lead) !== 'new') return false;
|
|
49
|
+
await ref.set({
|
|
50
|
+
status: 'working',
|
|
51
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
52
|
+
}, {
|
|
53
|
+
merge: true
|
|
54
|
+
});
|
|
55
|
+
return true;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
console.error('[outreach] the lead could not be marked working', input.hostId, input.leadId, error);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Every enrollment made on the lead now names the contact it became. */ export async function followOutreachLeadToContact(firestore, input) {
|
|
62
|
+
const enrollments = outreachOrgCollection(firestore, input.orgId, 'enrollments');
|
|
63
|
+
const rows = await enrollments.where('leadId', '==', input.leadId).get();
|
|
64
|
+
const refs = rows.docs.filter((row)=>{
|
|
65
|
+
var _row_get;
|
|
66
|
+
return row.get('target') !== 'contact' || String((_row_get = row.get('contactId')) != null ? _row_get : '') !== input.contactId;
|
|
67
|
+
}).map((row)=>row.ref);
|
|
68
|
+
for(let start = 0; start < refs.length; start += BATCH_LIMIT){
|
|
69
|
+
const batch = firestore.batch();
|
|
70
|
+
for (const ref of refs.slice(start, start + BATCH_LIMIT)){
|
|
71
|
+
batch.update(ref, {
|
|
72
|
+
target: 'contact',
|
|
73
|
+
contactId: input.contactId,
|
|
74
|
+
updatedAtMs: Date.now()
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
await batch.commit();
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
enrollments: refs.length
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=lead-records.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/lead-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHAT A SEQUENCE DOES TO A LEAD'S OWN RECORD (AGL-3234).\n *\n * Two touches, both on `hosts/{hostId}/leads/{leadId}` — the record system's\n * document, written in the record system's vocabulary (`@aglyn/aglyn`'s lead\n * statuses), never through an import of the CRM plugin:\n *\n * - a REPLY moves a lead nobody has touched from New to Working. Somebody\n * wrote back; the lead is being worked, and a queue that still showed it\n * as New would send a rep to open a conversation already open. A lead\n * already Working, closed, or converted is left as it is — a reply does\n * not reopen a verdict or move a contact's record.\n * - a CONVERSION re-points every enrollment made on the lead at the contact\n * it became: the record system tells every plugin through its\n * lead-conversion seam, and this is Sequences' share of it. The\n * enrollment keeps its id, its thread and its place in the steps, and\n * keeps naming the lead beside the contact, so both pages list it.\n *\n * Neither throws: a status that could not be moved is one a rep moves by\n * hand, and an enrollment that could not follow its lead is one the next\n * send stops as `contact_missing` and a rep re-enrolls.\n */\n\nimport { crmLeadStatus } from '@aglyn/aglyn/app-utils/crm'\nimport type {\n PluginLeadConversionReport,\n PluginLeadConversionRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { outreachOrgCollection } from '../storage/outreach-records'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Firestore refuses a batch of more than 500 writes. */\nconst BATCH_LIMIT = 450\n\n/** A lead nobody has touched, once somebody replied: Working. `true` when it moved. */\nexport async function markOutreachLeadWorking(\n firestore: Firestore,\n input: { hostId: string; leadId: string },\n): Promise<boolean> {\n try {\n const ref = firestore.collection('hosts').doc(input.hostId).collection('leads').doc(input.leadId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return false\n const lead = snapshot.data() ?? {}\n if (lead['convertedContactId'] || crmLeadStatus(lead as never) !== 'new') return false\n await ref.set({ status: 'working', updatedAt: FieldValue.serverTimestamp() }, { merge: true })\n return true\n } catch (error) {\n console.error('[outreach] the lead could not be marked working', input.hostId, input.leadId, error)\n return false\n }\n}\n\n/** Every enrollment made on the lead now names the contact it became. */\nexport async function followOutreachLeadToContact(\n firestore: Firestore,\n input: Pick<PluginLeadConversionRequest, 'orgId' | 'leadId' | 'contactId'>,\n): Promise<PluginLeadConversionReport> {\n const enrollments = outreachOrgCollection(firestore, input.orgId, 'enrollments')\n const rows = await enrollments.where('leadId', '==', input.leadId).get()\n const refs = rows.docs\n .filter((row) => row.get('target') !== 'contact' || String(row.get('contactId') ?? '') !== input.contactId)\n .map((row) => row.ref)\n for (let start = 0; start < refs.length; start += BATCH_LIMIT) {\n const batch = firestore.batch()\n for (const ref of refs.slice(start, start + BATCH_LIMIT)) {\n batch.update(ref, { target: 'contact', contactId: input.contactId, updatedAtMs: Date.now() })\n }\n await batch.commit()\n }\n return { enrollments: refs.length }\n}\n"],"names":["crmLeadStatus","FieldValue","outreachOrgCollection","BATCH_LIMIT","markOutreachLeadWorking","firestore","input","snapshot","ref","collection","doc","hostId","leadId","get","exists","lead","data","set","status","updatedAt","serverTimestamp","merge","error","console","followOutreachLeadToContact","enrollments","orgId","rows","where","refs","docs","filter","row","String","contactId","map","start","length","batch","slice","update","target","updatedAtMs","Date","now","commit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;CAqBC,GAED,SAASA,aAAa,QAAQ,6BAA4B;AAK1D,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,qBAAq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,YAAa;QAC7D,MAAMmC,QAAQjC,UAAUiC,KAAK;QAC7B,KAAK,MAAM9B,OAAOqB,KAAKU,KAAK,CAACH,OAAOA,QAAQjC,aAAc;YACxDmC,MAAME,MAAM,CAAChC,KAAK;gBAAEiC,QAAQ;gBAAWP,WAAW5B,MAAM4B,SAAS;gBAAEQ,aAAaC,KAAKC,GAAG;YAAG;QAC7F;QACA,MAAMN,MAAMO,MAAM;IACpB;IACA,OAAO;QAAEpB,aAAaI,KAAKQ,MAAM;IAAC;AACpC"}
|
|
@@ -30,7 +30,7 @@ import { markOutreachMailboxReconnectRequired } from "../mailboxes/mailbox-trans
|
|
|
30
30
|
import { effectiveOutreachAllowedCountries } from "../model/compliance-settings.js";
|
|
31
31
|
import { OUTREACH_COLLECTIONS } from "../model/outreach.types.js";
|
|
32
32
|
import { readOutreachComplianceSettingsDoc } from "../storage/compliance-settings-store.js";
|
|
33
|
-
import { outreachOrgCollection, readStoredOutreachEnrollment, readStoredOutreachMailbox, readStoredOutreachSequence } from "../storage/outreach-records.js";
|
|
33
|
+
import { outreachEnrollmentLink, outreachEnrollmentPerson, outreachOrgCollection, readStoredOutreachEnrollment, readStoredOutreachMailbox, readStoredOutreachSequence } from "../storage/outreach-records.js";
|
|
34
34
|
import { GmailTransportError, isReconnectRequired } from "../transport/gmail-errors.js";
|
|
35
35
|
import { Rfc5322MessageError } from "../transport/rfc5322.js";
|
|
36
36
|
import { sendComposedOutreachEmail } from "../transport/send-message.js";
|
|
@@ -246,25 +246,32 @@ async function runMailbox(deps, firestore, input) {
|
|
|
246
246
|
for (const [hostId, enrollments] of byHost){
|
|
247
247
|
var _host_get;
|
|
248
248
|
const contactGroupId = consentGroupForHost(org, hostId).groupId;
|
|
249
|
+
// Each by the record it names — the contact, or the lead while the
|
|
250
|
+
// person is one (AGL-3234) — keyed by that record's id.
|
|
249
251
|
const [candidatesRead, lookupsRead, host] = await Promise.all([
|
|
250
252
|
readOutreachEnrollCandidates(firestore, {
|
|
251
253
|
orgId,
|
|
252
254
|
hostId,
|
|
253
255
|
contactGroupId,
|
|
254
|
-
|
|
256
|
+
people: enrollments.map(outreachEnrollmentPerson)
|
|
255
257
|
}),
|
|
256
258
|
readOutreachGateLookups(firestore, {
|
|
257
259
|
orgId,
|
|
258
260
|
hostId,
|
|
259
|
-
people: enrollments.map((enrollment)=>
|
|
260
|
-
|
|
261
|
+
people: enrollments.map((enrollment)=>{
|
|
262
|
+
const person = outreachEnrollmentPerson(enrollment);
|
|
263
|
+
return {
|
|
264
|
+
personId: person.id,
|
|
265
|
+
contactId: person.kind === 'contact' ? person.id : null,
|
|
266
|
+
leadId: person.kind === 'lead' ? person.id : null,
|
|
261
267
|
email: enrollment.email
|
|
262
|
-
}
|
|
268
|
+
};
|
|
269
|
+
})
|
|
263
270
|
}),
|
|
264
271
|
firestore.collection('hosts').doc(hostId).get()
|
|
265
272
|
]);
|
|
266
|
-
for (const person of candidatesRead)people.set(person.
|
|
267
|
-
for (const [
|
|
273
|
+
for (const person of candidatesRead)people.set(person.personId, person);
|
|
274
|
+
for (const [personId, answer] of lookupsRead)lookups.set(personId, answer);
|
|
268
275
|
siteNames.set(hostId, host.exists ? String((_host_get = host.get('name')) != null ? _host_get : '') : '');
|
|
269
276
|
}
|
|
270
277
|
for (const candidate of selection.emails){
|
|
@@ -274,11 +281,12 @@ async function runMailbox(deps, firestore, input) {
|
|
|
274
281
|
continue;
|
|
275
282
|
}
|
|
276
283
|
const enrollment = candidate.enrollment;
|
|
284
|
+
const personId = outreachEnrollmentPerson(enrollment).id;
|
|
277
285
|
await runEmailStep(deps, firestore, run, {
|
|
278
286
|
enrollment,
|
|
279
287
|
sequence: candidate.sequence,
|
|
280
|
-
person: (_people_get = people.get(
|
|
281
|
-
lookups: (_lookups_get = lookups.get(
|
|
288
|
+
person: (_people_get = people.get(personId)) != null ? _people_get : null,
|
|
289
|
+
lookups: (_lookups_get = lookups.get(personId)) != null ? _lookups_get : null,
|
|
282
290
|
siteName: (_siteNames_get = siteNames.get(enrollment.hostId)) != null ? _siteNames_get : ''
|
|
283
291
|
});
|
|
284
292
|
}
|
|
@@ -470,7 +478,7 @@ async function openClient(deps, firestore, run) {
|
|
|
470
478
|
const written = await fileOutreachTask(deps, {
|
|
471
479
|
orgId: run.orgId,
|
|
472
480
|
hostId: enrollment.hostId,
|
|
473
|
-
|
|
481
|
+
link: outreachEnrollmentLink(enrollment),
|
|
474
482
|
dedupeKey: `step:${enrollment.id}:${step.id}`,
|
|
475
483
|
title: step.title,
|
|
476
484
|
notes: `From sequence step ${enrollment.stepIndex + 1}.`,
|
|
@@ -530,9 +538,15 @@ async function runEmailStep(deps, firestore, run, input) {
|
|
|
530
538
|
atMs: nowMs,
|
|
531
539
|
byUid: null,
|
|
532
540
|
reason: 'gate',
|
|
533
|
-
detail: 'This contact no longer exists in the CRM.'
|
|
541
|
+
detail: enrollment.target === 'lead' ? "This lead no longer exists in the sequence's site's CRM." : 'This contact no longer exists in the CRM.'
|
|
534
542
|
}, 'stopped');
|
|
535
543
|
}
|
|
544
|
+
if (person.convertedContactId && enrollment.target === 'lead') {
|
|
545
|
+
// The lead converted and the enrollment has not followed it yet: the
|
|
546
|
+
// conversion's listener re-points it, and the next run sends as the contact.
|
|
547
|
+
report.held += 1;
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
536
550
|
if (!person.visible) {
|
|
537
551
|
return stop({
|
|
538
552
|
type: 'stop',
|
|
@@ -582,8 +596,12 @@ async function runEmailStep(deps, firestore, run, input) {
|
|
|
582
596
|
enrollment,
|
|
583
597
|
orgSettings: run.settings,
|
|
584
598
|
merge: {
|
|
599
|
+
// For a lead, the contact-shaped view of it (`leadAsContact`), so a
|
|
600
|
+
// step written with `{{contact.*}}` reads the lead; `{{lead.*}}` reads
|
|
601
|
+
// the lead's own document beside it.
|
|
585
602
|
contact: person.contact,
|
|
586
603
|
contactGroupId,
|
|
604
|
+
lead: person.lead,
|
|
587
605
|
sender: {
|
|
588
606
|
name: mailbox.displayName,
|
|
589
607
|
email: sender.address
|
|
@@ -707,7 +725,7 @@ async function runEmailStep(deps, firestore, run, input) {
|
|
|
707
725
|
await fileOutreachEmail(deps, {
|
|
708
726
|
orgId: run.orgId,
|
|
709
727
|
hostId: enrollment.hostId,
|
|
710
|
-
|
|
728
|
+
link: outreachEnrollmentLink(enrollment),
|
|
711
729
|
direction: 'outbound',
|
|
712
730
|
subject: sent.subject,
|
|
713
731
|
from: sender.address,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/send-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { normalizeCrmEmailTemplate } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { randomUUID } from 'node:crypto'\nimport { composeOutreachEmail } from '../engine/compose'\nimport { planOutreachStepCompletion, type OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { evaluateOutreachGates, type OutreachGateBlock, type OutreachGateLookups } from '../engine/gates'\nimport {\n outreachSentToday,\n outreachTickAllowance,\n selectDueOutreachEnrollments,\n type OutreachDueCandidate,\n} from '../engine/sending-capacity'\nimport { readOutreachEnrollCandidates, type OutreachEnrollCandidate } from '../enrollment/enroll-people'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachEffectiveDailyCap, outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport { markOutreachMailboxReconnectRequired, type OpenedOutreachMailbox } from '../mailboxes/mailbox-transport'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachComplianceSettingsDocument,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachStepRecord,\n type OutreachTaskStep,\n} from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { applyOutreachEvent } from './enrollment-events'\nimport { outreachSendDigest, withRecentSend } from './mailbox-health-store'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { fileOutreachEmail, fileOutreachTask, OUTREACH_TASK_KIND_TO_RECORD } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SEND JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * ## What comes due\n *\n * One collection-group read finds every active enrollment whose next step\n * is due, oldest first, bounded per run. They are grouped by workspace and\n * mailbox, and each group is judged before anything is sent:\n *\n * - the workspace: Outreach switched on, entitled and released to it;\n * - the mailbox: an enrollment whose mailbox is gone, disconnected, or whose\n * member left the organization is STOPPED — nothing will ever send it, and\n * leaving it active would show a sequence that is not running. A paused\n * mailbox, or one waiting to be reconnected, holds its enrollments;\n * - the member it sends as: a lockdown of the platform, the workspace or the\n * member holds everything.\n *\n * ## How much goes\n *\n * The engine's per-run allowance — the day's cap and ramp, spread across\n * the window, at most five a run — picks the enrollments (follow-ups first);\n * a task step is due whenever its time comes and spends no allowance.\n *\n * ## One send, exactly once\n *\n * Each email is CLAIMED before it is sent: a transaction over the enrollment\n * and its mailbox checks the enrollment is still active on the same step\n * with no live claim, and that the mailbox's day has room under its cap,\n * then writes the claim and reserves the day's count. Two runs racing for\n * one enrollment write one claim; two racing for one mailbox's last slot\n * reserve it once. The claim carries the `Message-ID` minted for the send,\n * so a claim a run died holding is settled by finding the message in the\n * mailbox rather than by sending it a second time. A send that fails hands\n * its reservation back.\n *\n * Before it is claimed, every gate is asked again — the do-not-contact\n * list, the suppression lists, the sales topic, the roster, the other\n * sequences — because a person enrolled on Monday can unsubscribe by\n * Thursday. A lookup that could not be made holds the send; a gate that\n * refuses stops the enrollment, saying why.\n *==========================================*/\n\nexport { OUTREACH_SEND_JOB_ID } from '../constants/runtime-jobs'\n\n/** The most due enrollments one run reads. */\nexport const OUTREACH_SEND_SCAN_LIMIT = 300\n\n/** How long a claim holds before a later run settles it. */\nexport const OUTREACH_CLAIM_STALE_MS = 10 * 60_000\n\n/** What one run did, for the tick's answer. */\nexport interface OutreachSendReport {\n [key: string]: number\n due: number\n sent: number\n tasks: number\n /** Stopped by a gate or an unusable mailbox. */\n stopped: number\n /** Paused for the rep to fix, or failed for good. */\n failed: number\n /** Due, and left for a later run: the allowance, a lookup, a hold. */\n held: number\n /** Claims a dead run left, settled. */\n recovered: number\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface MailboxRun {\n orgId: string\n org: Record<string, unknown>\n mailbox: OutreachMailbox\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n deadlineMs: number\n opened: OpenedOutreachMailbox | null\n /** Set once the mailbox itself cannot send this run. */\n stopped: boolean\n templates: Map<string, string | null>\n}\n\nconst blankReport = (): OutreachSendReport => ({\n due: 0,\n sent: 0,\n tasks: 0,\n stopped: 0,\n failed: 0,\n held: 0,\n recovered: 0,\n})\n\n/** Runs the send job once — see the module note. */\nexport async function runOutreachSendJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSendReport> {\n const firestore = deps.firestore()\n const report = blankReport()\n const due = await firestore\n .collectionGroup(OUTREACH_COLLECTIONS.enrollments)\n .where('status', '==', 'active')\n .where('nextDueAtMs', '<=', context.nowMs)\n .orderBy('nextDueAtMs')\n .limit(OUTREACH_SEND_SCAN_LIMIT)\n .get()\n report.due = due.size\n const byOrg = new Map<string, Map<string, OutreachEnrollment[]>>()\n for (const doc of due.docs) {\n const orgId = doc.ref.parent.parent?.id\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!orgId || !enrollment) continue\n const mailboxes = byOrg.get(orgId) ?? new Map<string, OutreachEnrollment[]>()\n mailboxes.set(enrollment.mailboxId, [...(mailboxes.get(enrollment.mailboxId) ?? []), enrollment])\n byOrg.set(orgId, mailboxes)\n }\n\n for (const [orgId, mailboxes] of byOrg) {\n const waiting = [...mailboxes.values()].reduce((sum, list) => sum + list.length, 0)\n if (deps.now() >= context.deadlineMs) {\n report.held += waiting\n continue\n }\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) {\n report.held += waiting\n continue\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, orgId)\n for (const [mailboxId, enrollments] of mailboxes) {\n await runMailbox(deps, firestore, { orgId, org, mailboxId, enrollments, settings, report, context })\n }\n }\n return report\n}\n\n/** The reason an unusable mailbox stops an enrollment, or `null` for a usable one. */\nasync function unusableMailbox(\n firestore: Firestore,\n orgId: string,\n mailbox: OutreachMailbox | null,\n): Promise<string | null> {\n if (!mailbox) return 'The mailbox this sequence sends from was removed.'\n if (mailbox.status === 'disconnected') return 'The mailbox this sequence sends from was disconnected.'\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(mailbox.connectedByUid).get()\n return member.exists\n ? null\n : 'The member who connected the mailbox this sequence sends from is no longer in the organization.'\n}\n\nasync function runMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n mailboxId: string\n enrollments: OutreachEnrollment[]\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n context: { nowMs: number; deadlineMs: number }\n },\n): Promise<void> {\n const { orgId, org, report, context } = input\n const nowMs = context.nowMs\n const snapshot = await mailboxRef(firestore, orgId, input.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(input.mailboxId, snapshot.exists ? snapshot.data() : undefined)\n const unusable = await unusableMailbox(firestore, orgId, mailbox)\n if (unusable || !mailbox) {\n for (const enrollment of input.enrollments) {\n const outcome = await applyOutreachEvent(firestore, {\n orgId,\n enrollmentId: enrollment.id,\n event: { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: unusable },\n nowMs,\n })\n if (outcome.changed) report.stopped += 1\n }\n return\n }\n if (mailbox.status !== 'connected' || (await deps.sendRefusal({ orgId, org, uid: mailbox.connectedByUid }))) {\n report.held += input.enrollments.length\n return\n }\n\n const run: MailboxRun = {\n orgId,\n org,\n mailbox,\n settings: input.settings,\n report,\n deadlineMs: context.deadlineMs,\n opened: null,\n stopped: false,\n templates: new Map(),\n }\n const sequenceIds = [...new Set(input.enrollments.map((enrollment) => enrollment.sequenceId))]\n const sequenceSnapshots = await firestore.getAll(\n ...sequenceIds.map((id) => outreachOrgCollection(firestore, orgId, 'sequences').doc(id)),\n )\n const sequences = new Map<string, OutreachSequence>()\n sequenceSnapshots.forEach((sequenceSnapshot, index) => {\n const sequence = readStoredOutreachSequence(\n sequenceIds[index],\n sequenceSnapshot.exists ? sequenceSnapshot.data() : undefined,\n )\n if (sequence) sequences.set(sequence.id, sequence)\n })\n\n const candidates: OutreachDueCandidate[] = []\n for (const enrollment of input.enrollments) {\n const sequence = sequences.get(enrollment.sequenceId)\n const claim = enrollment.sendClaim\n if (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS) continue\n if (claim && sequence) {\n if (await recoverClaim(deps, firestore, run, enrollment, sequence)) report.recovered += 1\n continue\n }\n if (sequence) candidates.push({ enrollment, sequence })\n }\n\n const allowance = outreachTickAllowance({ mailbox, nowMs })\n const selection = selectDueOutreachEnrollments({ candidates, mailbox, nowMs, allowance: allowance.allowance })\n report.held += selection.deferred.length\n\n for (const candidate of selection.tasks) {\n if (deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n if (await runTaskStep(deps, firestore, run, candidate)) report.tasks += 1\n }\n if (!selection.emails.length) return\n\n // The people behind the emails, read once per site: the contact and its\n // company, and every lookup the gates decide on.\n const people = new Map<string, OutreachEnrollCandidate>()\n const lookups = new Map<string, OutreachGateLookups>()\n const byHost = new Map<string, OutreachEnrollment[]>()\n for (const candidate of selection.emails) {\n const enrollment = candidate.enrollment as OutreachEnrollment\n byHost.set(enrollment.hostId, [...(byHost.get(enrollment.hostId) ?? []), enrollment])\n }\n const siteNames = new Map<string, string>()\n for (const [hostId, enrollments] of byHost) {\n const contactGroupId = consentGroupForHost(org, hostId).groupId\n const [candidatesRead, lookupsRead, host] = await Promise.all([\n readOutreachEnrollCandidates(firestore, {\n orgId,\n hostId,\n contactGroupId,\n contactIds: enrollments.map((enrollment) => enrollment.contactId),\n }),\n readOutreachGateLookups(firestore, {\n orgId,\n hostId,\n people: enrollments.map((enrollment) => ({ contactId: enrollment.contactId, email: enrollment.email })),\n }),\n firestore.collection('hosts').doc(hostId).get(),\n ])\n for (const person of candidatesRead) people.set(person.contactId, person)\n for (const [contactId, answer] of lookupsRead) lookups.set(contactId, answer)\n siteNames.set(hostId, host.exists ? String(host.get('name') ?? '') : '')\n }\n\n for (const candidate of selection.emails) {\n if (run.stopped || deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n const enrollment = candidate.enrollment as OutreachEnrollment\n await runEmailStep(deps, firestore, run, {\n enrollment,\n sequence: candidate.sequence as OutreachSequence,\n person: people.get(enrollment.contactId) ?? null,\n lookups: lookups.get(enrollment.contactId) ?? null,\n siteName: siteNames.get(enrollment.hostId) ?? '',\n })\n }\n}\n\n/** Any lookup the runtime could not make: the send waits for a run that can. */\nfunction uncheckable(lookups: OutreachGateLookups | null): boolean {\n return !lookups || Object.values(lookups).some((value) => value === null)\n}\n\n/** The event a gate's refusal ends an enrollment with. */\nfunction gateEvent(blocks: readonly OutreachGateBlock[], atMs: number): OutreachEnrollmentEvent {\n const optedOut = blocks.find((block) => block.code === 'do_not_contact' || block.code === 'sales_opted_out')\n if (optedOut) return { type: 'opt_out', atMs, reason: 'do_not_contact', detail: optedOut.reason }\n return { type: 'stop', atMs, byUid: null, reason: 'gate', detail: blocks.map((block) => block.reason).join(' ') }\n}\n\n/** The sender line a mailbox's mail goes out with. */\nconst senderOf = (mailbox: OutreachMailbox) => ({\n address: mailbox.sendAs || mailbox.email,\n name: mailbox.displayName || null,\n})\n\nasync function openClient(deps: OutreachRuntimeDeps, firestore: Firestore, run: MailboxRun) {\n const opened = (run.opened ??= await deps.openMailbox(run.mailbox.id))\n if (opened.ok === true) return opened.client\n run.stopped = true\n if (opened.reason !== 'not-configured') {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: run.orgId,\n mailboxId: run.mailbox.id,\n errorCode: opened.reason,\n nowMs: deps.now(),\n })\n }\n return null\n}\n\n/**\n * Claims one step: the enrollment still active on the same step with no\n * live claim, and — for an email — a slot under the mailbox's cap today,\n * reserved in the same transaction.\n */\nasync function claimStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n messageId: string | null,\n): Promise<'claimed' | 'taken' | 'cap'> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([transaction.get(enrollmentRef), transaction.get(boxRef)])\n const stored = readStoredOutreachEnrollment(enrollment.id, current.exists ? current.data() : undefined)\n const claim = stored?.sendClaim\n if (\n !stored ||\n stored.status !== 'active' ||\n stored.stepIndex !== enrollment.stepIndex ||\n stored.nextDueAtMs === null ||\n stored.nextDueAtMs > nowMs ||\n (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS)\n ) {\n return 'taken'\n }\n if (messageId) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.status !== 'connected') return 'taken'\n const sent = outreachSentToday(mailbox.health, nowMs, mailbox.timezone)\n if (sent >= outreachEffectiveDailyCap(mailbox, nowMs)) return 'cap'\n transaction.update(boxRef, {\n 'health.sentToday': sent + 1,\n 'health.sentOnDay': outreachLocalDay(nowMs, mailbox.timezone),\n })\n }\n transaction.update(enrollmentRef, {\n sendClaim: { token: randomUUID(), atMs: nowMs, stepIndex: enrollment.stepIndex, messageId },\n updatedAtMs: nowMs,\n })\n return 'claimed'\n })\n}\n\n/** Drops a claim, and hands an email's reservation back to the mailbox's day. */\nasync function releaseClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: Pick<OutreachEnrollment, 'id'>,\n reserved: boolean,\n event: OutreachEnrollmentEvent | null = null,\n): Promise<void> {\n const nowMs = deps.now()\n await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: () => ({ sendClaim: null }),\n nowMs,\n })\n if (!reserved) return\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n await firestore.runTransaction(async (transaction) => {\n const box = await transaction.get(boxRef)\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.health?.sentOnDay !== outreachLocalDay(nowMs, mailbox.timezone)) return\n transaction.update(boxRef, { 'health.sentToday': Math.max(0, (Number(mailbox.health.sentToday) || 0) - 1) })\n })\n}\n\n/**\n * Records a step that ran: the engine's completion patch, the claim\n * cleared, the step's record kept — and for an email the mailbox's send on\n * its day, its last-sent time and its window of recent sends. Refuses\n * (answers false) when the claim is no longer this run's.\n */\nasync function completeStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n record: OutreachStepRecord\n sent: { messageId: string; threadId: string; subject: string } | null\n claimMessageId: string | null\n },\n): Promise<boolean> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(input.enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([\n transaction.get(enrollmentRef),\n input.sent ? transaction.get(boxRef) : Promise.resolve(null),\n ])\n const stored = readStoredOutreachEnrollment(input.enrollment.id, current.exists ? current.data() : undefined)\n if (!stored?.sendClaim || stored.sendClaim.messageId !== input.claimMessageId) return false\n if (stored.stepIndex !== input.enrollment.stepIndex) return false\n // The step RAN, whatever happened to the enrollment while it did — a\n // member paused it, a reply stopped it — so it is recorded as run, and a\n // resume never sends it twice.\n const plan = planOutreachStepCompletion({\n enrollment: { ...stored, status: 'active' },\n sequence: input.sequence,\n mailbox: run.mailbox,\n completedAtMs: nowMs,\n sent: input.sent,\n random: deps.random,\n })\n const patch: Record<string, unknown> = {\n sendClaim: null,\n stepRecords: [...(stored.stepRecords ?? []), input.record].slice(-20),\n updatedAtMs: nowMs,\n ...(plan.patch ?? {}),\n }\n if (stored.status !== 'active') {\n patch['status'] = stored.status\n if (stored.status !== 'paused') patch['nextDueAtMs'] = null\n }\n transaction.update(enrollmentRef, patch)\n if (input.sent && box?.exists) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.data())\n if (mailbox) {\n const day = outreachLocalDay(nowMs, mailbox.timezone)\n const counts = mailbox.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n transaction.update(boxRef, {\n 'health.lastSentAtMs': nowMs,\n 'health.lastErrorAtMs': null,\n 'health.lastErrorCode': null,\n [`health.daily.${day}`]: { ...counts, sent: (Number(counts.sent) || 0) + 1 },\n 'health.recentSends': withRecentSend(mailbox.health?.recentSends, {\n id: outreachSendDigest(input.sent.messageId),\n atMs: nowMs,\n bounced: false,\n }),\n updatedAtMs: nowMs,\n })\n }\n }\n return true\n })\n}\n\n/** One task step: the rep's task on the contact, then the step recorded. */\nasync function runTaskStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n candidate: OutreachDueCandidate,\n): Promise<boolean> {\n const enrollment = candidate.enrollment as OutreachEnrollment\n const sequence = candidate.sequence as OutreachSequence\n const step = sequence.steps[enrollment.stepIndex] as OutreachTaskStep\n if ((await claimStep(deps, firestore, run, enrollment, null)) !== 'claimed') return false\n const nowMs = deps.now()\n let taskId: string | null\n try {\n const written = await fileOutreachTask(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n contactId: enrollment.contactId,\n dedupeKey: `step:${enrollment.id}:${step.id}`,\n title: step.title,\n notes: `From sequence step ${enrollment.stepIndex + 1}.`,\n kind: OUTREACH_TASK_KIND_TO_RECORD[step.taskKind] ?? 'todo',\n dueAtMs: nowMs,\n assigneeUid: run.mailbox.connectedByUid,\n })\n taskId = written?.ok ? written.id : null\n if (written?.ok === false) console.warn(`[outreach] a task step's task was not filed: ${written.error}`)\n } catch (error) {\n // The record system failed rather than refused: the step waits for a\n // run that can file its task.\n console.error('[outreach] filing a task step failed; the step waits', error)\n await releaseClaim(deps, firestore, run, enrollment, false)\n return false\n }\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: { stepIndex: enrollment.stepIndex, stepId: step.id, kind: 'task', atMs: nowMs, taskId },\n sent: null,\n claimMessageId: null,\n })\n}\n\n/** A CRM template's body, read once per run. */\nasync function templateBody(firestore: Firestore, run: MailboxRun, templateId: string): Promise<string | null> {\n if (!run.templates.has(templateId)) {\n const snapshot = await firestore\n .collection('orgs')\n .doc(run.orgId)\n .collection(CRM_COLLECTIONS.emailTemplates)\n .doc(templateId)\n .get()\n run.templates.set(\n templateId,\n snapshot.exists ? normalizeCrmEmailTemplate(snapshot.data() as Record<string, unknown>).body : null,\n )\n }\n return run.templates.get(templateId) ?? null\n}\n\nasync function runEmailStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n person: OutreachEnrollCandidate | null\n lookups: OutreachGateLookups | null\n siteName: string\n },\n): Promise<void> {\n const { enrollment, sequence, person } = input\n const { report, mailbox } = run\n const nowMs = deps.now()\n const stop = async (event: OutreachEnrollmentEvent, counter: 'stopped' | 'failed') => {\n const outcome = await applyOutreachEvent(firestore, { orgId: run.orgId, enrollmentId: enrollment.id, event, nowMs })\n if (outcome.changed) report[counter] += 1\n }\n\n // Every gate again, on the person as they stand now.\n if (!person?.contact) {\n return stop({ type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: 'This contact no longer exists in the CRM.' }, 'stopped')\n }\n if (!person.visible) {\n return stop(\n { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: \"This contact is no longer in the sequence's site's CRM.\" },\n 'stopped',\n )\n }\n if (uncheckable(input.lookups)) {\n report.held += 1\n return\n }\n const contactGroupId = consentGroupForHost(run.org, enrollment.hostId).groupId\n const gate = evaluateOutreachGates({\n email: enrollment.email,\n contact: person.contact,\n contactGroupId,\n company: person.company,\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n run.settings.allowedCountries,\n ),\n },\n personalLine: enrollment.personalLine,\n attestations: enrollment.attestations,\n enrollmentId: enrollment.id,\n lookups: input.lookups as OutreachGateLookups,\n })\n if (!gate.allowed) return stop(gateEvent(gate.blocks, nowMs), 'stopped')\n\n // The email, with its way out.\n const listUnsubscribeUrl = deps.unsubscribeUrl({ orgId: run.orgId, enrollmentId: enrollment.id })\n const mailto = outreachUnsubscribeMailbox(mailbox.email)\n if (!listUnsubscribeUrl || !mailto) {\n // No link can be minted — no secret, or no HTTPS console origin — and an\n // email without its one-click way out does not leave.\n console.error('[outreach] no unsubscribe link could be minted; nothing sends until one can')\n run.stopped = true\n report.held += 1\n return\n }\n const step = sequence.steps[enrollment.stepIndex]\n const sender = senderOf(mailbox)\n const composed = composeOutreachEmail({\n sequence,\n enrollment,\n orgSettings: run.settings,\n merge: {\n contact: person.contact,\n contactGroupId,\n sender: { name: mailbox.displayName, email: sender.address },\n site: { name: input.siteName },\n },\n templateBody: step?.kind === 'email' && step.templateId ? await templateBody(firestore, run, step.templateId) : null,\n listUnsubscribeUrl,\n listUnsubscribeMailto: mailto.uri,\n })\n if (composed.error || !composed.email) {\n const code = composed.error?.code\n if (code === 'missing_postal_address' || code === 'missing_legal_name') {\n // The organization's footer: nothing of theirs sends until it is set.\n run.stopped = true\n report.held += 1\n return\n }\n if (code === 'invalid_recipient' || code === 'missing_thread' || code === 'not_an_email_step') {\n return stop({ type: 'send_failed', atMs: nowMs, detail: composed.error?.message }, 'failed')\n }\n // The sequence's own words: the rep fixes the step and resumes.\n return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: composed.error?.message }, 'failed')\n }\n if (composed.unresolvedFields.length) {\n const fields = composed.unresolvedFields.map((field) => `{{${field}}}`).join(', ')\n return stop(\n {\n type: 'pause',\n atMs: nowMs,\n byUid: null,\n detail: `Paused before sending: this contact has nothing for ${fields}. Fill it in and resume.`,\n },\n 'failed',\n )\n }\n\n // Claimed, then sent, then recorded.\n const domain = sender.address.slice(sender.address.lastIndexOf('@') + 1)\n const local = randomUUID()\n const messageId = `<${local}@${domain}>`\n const claimed = await claimStep(deps, firestore, run, enrollment, messageId)\n if (claimed !== 'claimed') {\n if (claimed === 'cap') run.stopped = true\n report.held += 1\n return\n }\n const client = await openClient(deps, firestore, run)\n if (!client) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n return\n }\n let sent: Awaited<ReturnType<typeof sendComposedOutreachEmail>>\n try {\n sent = await sendComposedOutreachEmail(client, composed.email, sender, {\n messageIdLocalPart: local,\n messageIdDomain: domain,\n })\n } catch (error) {\n if (error instanceof Rfc5322MessageError || (error instanceof GmailTransportError && error.code === 'invalid_request')) {\n await releaseClaim(deps, firestore, run, enrollment, true, {\n type: 'send_failed',\n atMs: deps.now(),\n detail: `Gmail refused the email: ${error.message}`,\n })\n report.failed += 1\n return\n }\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n run.stopped = true\n const code = error instanceof GmailTransportError ? error.code : 'unexpected'\n if (isReconnectRequired(error)) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: run.orgId,\n mailboxId: mailbox.id,\n errorCode: code,\n nowMs: deps.now(),\n })\n } else {\n await mailboxRef(firestore, run.orgId, mailbox.id)\n .update({ 'health.lastErrorAtMs': deps.now(), 'health.lastErrorCode': code })\n .catch(() => undefined)\n }\n console.error(`[outreach] a send from a mailbox failed (${code}); its sends wait for the next run`)\n return\n }\n\n const record: OutreachStepRecord = {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: sent.gmailMessageId,\n gmailThreadId: sent.threadId,\n messageId: sent.messageId,\n subject: sent.subject,\n }\n await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record,\n sent: { messageId: sent.messageId, threadId: sent.threadId, subject: sent.subject },\n claimMessageId: messageId,\n })\n report.sent += 1\n await fileOutreachEmail(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n contactId: enrollment.contactId,\n direction: 'outbound',\n subject: sent.subject,\n from: sender.address,\n to: composed.email.to,\n messageId: sent.messageId,\n inReplyTo: composed.email.inReplyTo ?? null,\n body: composed.email.text,\n atMs: record.atMs,\n byUid: mailbox.connectedByUid,\n byName: mailbox.displayName || null,\n })\n}\n\n/**\n * Settles a claim a run died holding. A task step's claim is dropped and\n * the step runs again (its task is filed once however often it is asked).\n * An email's claim looks for the message it minted in the mailbox: found,\n * the send happened and is recorded; not found, it did not, and the claim\n * and its reservation are handed back for the next run.\n */\nasync function recoverClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n sequence: OutreachSequence,\n): Promise<boolean> {\n const claim = enrollment.sendClaim\n if (!claim) return false\n if (!claim.messageId) {\n await releaseClaim(deps, firestore, run, enrollment, false)\n return true\n }\n const client = await openClient(deps, firestore, run)\n if (!client) return false\n const bare = claim.messageId.replace(/^<|>$/g, '')\n const found = await client.listMessages({ q: `rfc822msgid:${bare}`, maxResults: 1, includeSpamTrash: true })\n const hit = found.messages[0]\n if (!hit) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n return true\n }\n const message = await client.getMessage(hit.id, { metadataHeaders: ['Subject'] })\n const subject = message.headers.find((header) => header.name.toLowerCase() === 'subject')?.value ?? ''\n const step = sequence.steps[enrollment.stepIndex]\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: hit.id,\n gmailThreadId: hit.threadId,\n messageId: claim.messageId,\n subject,\n },\n sent: { messageId: claim.messageId, threadId: hit.threadId, subject },\n claimMessageId: claim.messageId,\n })\n}\n"],"names":["consentGroupForHost","CRM_COLLECTIONS","normalizeCrmEmailTemplate","randomUUID","composeOutreachEmail","planOutreachStepCompletion","evaluateOutreachGates","outreachSentToday","outreachTickAllowance","selectDueOutreachEnrollments","readOutreachEnrollCandidates","readOutreachGateLookups","mailboxRef","outreachEffectiveDailyCap","outreachLocalDay","markOutreachMailboxReconnectRequired","effectiveOutreachAllowedCountries","OUTREACH_COLLECTIONS","readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","Rfc5322MessageError","sendComposedOutreachEmail","applyOutreachEvent","outreachSendDigest","withRecentSend","fileOutreachEmail","fileOutreachTask","OUTREACH_TASK_KIND_TO_RECORD","outreachUnsubscribeMailbox","OUTREACH_SEND_JOB_ID","OUTREACH_SEND_SCAN_LIMIT","OUTREACH_CLAIM_STALE_MS","blankReport","due","sent","tasks","stopped","failed","held","recovered","runOutreachSendJob","deps","context","firestore","report","collectionGroup","enrollments","where","nowMs","orderBy","limit","get","size","byOrg","Map","doc","docs","mailboxes","orgId","ref","parent","id","enrollment","data","set","mailboxId","waiting","values","reduce","sum","list","length","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","settings","runMailbox","unusableMailbox","mailbox","status","member","connectedByUid","input","snapshot","undefined","unusable","outcome","enrollmentId","event","type","atMs","byUid","reason","detail","changed","sendRefusal","uid","run","opened","templates","sequenceIds","Set","map","sequenceId","sequenceSnapshots","getAll","sequences","forEach","sequenceSnapshot","index","sequence","candidates","claim","sendClaim","recoverClaim","push","allowance","selection","deferred","candidate","runTaskStep","emails","people","lookups","byHost","hostId","siteNames","host","contactGroupId","groupId","candidatesRead","lookupsRead","Promise","all","contactIds","contactId","email","person","answer","String","runEmailStep","siteName","uncheckable","Object","some","value","gateEvent","blocks","optedOut","find","block","code","join","senderOf","address","sendAs","name","displayName","openClient","openMailbox","ok","client","errorCode","claimStep","messageId","enrollmentRef","boxRef","runTransaction","transaction","current","box","stored","stepIndex","nextDueAtMs","health","timezone","update","token","updatedAtMs","releaseClaim","reserved","extra","sentOnDay","Math","max","Number","sentToday","completeStep","plan","resolve","claimMessageId","completedAtMs","random","patch","stepRecords","record","slice","day","counts","daily","bounces","replies","recentSends","bounced","step","steps","taskId","written","dedupeKey","title","notes","kind","taskKind","dueAtMs","assigneeUid","console","warn","error","stepId","templateBody","templateId","has","emailTemplates","body","composed","stop","counter","contact","visible","gate","company","allowedCountries","personalLine","attestations","allowed","listUnsubscribeUrl","unsubscribeUrl","mailto","sender","orgSettings","merge","site","listUnsubscribeMailto","uri","message","unresolvedFields","fields","field","domain","lastIndexOf","local","claimed","messageIdLocalPart","messageIdDomain","catch","gmailMessageId","gmailThreadId","threadId","subject","direction","from","to","inReplyTo","text","byName","bare","replace","found","listMessages","q","maxResults","includeSpamTrash","hit","messages","getMessage","metadataHeaders","headers","header","toLowerCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,yBAAyB,QAAQ,6CAA4C;AACtF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,oBAAoB,QAAQ,uBAAmB;AACxD,SAASC,0BAA0B,QAAsC,gCAA4B;AACrG,SAASC,qBAAqB,QAA0D,qBAAiB;AACzG,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,4BAA4B,QAEvB,gCAA4B;AACnC,SAASC,4BAA4B,QAAsC,iCAA6B;AACxG,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SAASC,yBAAyB,EAAEC,gBAAgB,QAAQ,mCAA+B;AAC3F,SAASC,oCAAoC,QAAoC,oCAAgC;AACjH,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SACEC,oBAAoB,QAOf,6BAAyB;AAChC,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,4BAAwB;AAE3E,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,4BAA4B,QAAQ,gBAAY;AAC9F,SAASC,0BAA0B,QAAQ,wBAAoB;AAE/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAwC4C,GAE5C,SAASC,oBAAoB,QAAQ,+BAA2B;AAEhE,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C,UAAU;IAC/C,MAAMC,QAAQ,MAAM1G,OAAO2G,YAAY,CAAC;QAAEC,GAAG,CAAC,YAAY,EAAEJ,MAAM;QAAEK,YAAY;QAAGC,kBAAkB;IAAK;IAC1G,MAAMC,MAAML,MAAMM,QAAQ,CAAC,EAAE;IAC7B,IAAI,CAACD,KAAK;QACR,MAAM7F,aAAa9I,MAAME,WAAW0D,KAAKvC,YAAY;QACrD,OAAO;IACT;IACA,MAAM0L,UAAU,MAAMnF,OAAOiH,UAAU,CAACF,IAAIvN,EAAE,EAAE;QAAE0N,iBAAiB;YAAC;SAAU;IAAC;IAC/E,MAAMjB,mBAAUd,wBAAAA,QAAQgC,OAAO,CAAC/H,IAAI,CAAC,CAACgI,SAAWA,OAAOzH,IAAI,CAAC0H,WAAW,OAAO,+BAA/DlC,sBAA2EnG,KAAK,mBAAI;IACpG,MAAM2D,OAAO9F,SAAS+F,KAAK,CAACnJ,WAAWkH,SAAS,CAAC;IACjD,OAAOe,aAAatJ,MAAME,WAAW0D,KAAK;QACxCvC;QACAoD;QACAqF,QAAQ;YACNvB,WAAWlH,WAAWkH,SAAS;YAC/B8C,MAAM,WAAEd,wBAAAA,KAAMnJ,EAAE,oBAAI;YACpB0J,MAAM;YACNzH,MAAMrD,KAAK+B,GAAG;YACd2L,gBAAgBiB,IAAIvN,EAAE;YACtBuM,eAAegB,IAAIf,QAAQ;YAC3B7F,WAAWpD,MAAMoD,SAAS;YAC1B8F;QACF;QACApO,MAAM;YAAEsI,WAAWpD,MAAMoD,SAAS;YAAE6F,UAAUe,IAAIf,QAAQ;YAAEC;QAAQ;QACpEpE,gBAAgB9E,MAAMoD,SAAS;IACjC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/send-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { normalizeCrmEmailTemplate } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { randomUUID } from 'node:crypto'\nimport { composeOutreachEmail } from '../engine/compose'\nimport { planOutreachStepCompletion, type OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { evaluateOutreachGates, type OutreachGateBlock, type OutreachGateLookups } from '../engine/gates'\nimport {\n outreachSentToday,\n outreachTickAllowance,\n selectDueOutreachEnrollments,\n type OutreachDueCandidate,\n} from '../engine/sending-capacity'\nimport { readOutreachEnrollCandidates, type OutreachEnrollCandidate } from '../enrollment/enroll-people'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachEffectiveDailyCap, outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport { markOutreachMailboxReconnectRequired, type OpenedOutreachMailbox } from '../mailboxes/mailbox-transport'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachComplianceSettingsDocument,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachStepRecord,\n type OutreachTaskStep,\n} from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachEnrollmentLink,\n outreachEnrollmentPerson,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { applyOutreachEvent } from './enrollment-events'\nimport { outreachSendDigest, withRecentSend } from './mailbox-health-store'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { fileOutreachEmail, fileOutreachTask, OUTREACH_TASK_KIND_TO_RECORD } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SEND JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * ## What comes due\n *\n * One collection-group read finds every active enrollment whose next step\n * is due, oldest first, bounded per run. They are grouped by workspace and\n * mailbox, and each group is judged before anything is sent:\n *\n * - the workspace: Outreach switched on, entitled and released to it;\n * - the mailbox: an enrollment whose mailbox is gone, disconnected, or whose\n * member left the organization is STOPPED — nothing will ever send it, and\n * leaving it active would show a sequence that is not running. A paused\n * mailbox, or one waiting to be reconnected, holds its enrollments;\n * - the member it sends as: a lockdown of the platform, the workspace or the\n * member holds everything.\n *\n * ## How much goes\n *\n * The engine's per-run allowance — the day's cap and ramp, spread across\n * the window, at most five a run — picks the enrollments (follow-ups first);\n * a task step is due whenever its time comes and spends no allowance.\n *\n * ## One send, exactly once\n *\n * Each email is CLAIMED before it is sent: a transaction over the enrollment\n * and its mailbox checks the enrollment is still active on the same step\n * with no live claim, and that the mailbox's day has room under its cap,\n * then writes the claim and reserves the day's count. Two runs racing for\n * one enrollment write one claim; two racing for one mailbox's last slot\n * reserve it once. The claim carries the `Message-ID` minted for the send,\n * so a claim a run died holding is settled by finding the message in the\n * mailbox rather than by sending it a second time. A send that fails hands\n * its reservation back.\n *\n * Before it is claimed, every gate is asked again — the do-not-contact\n * list, the suppression lists, the sales topic, the roster, the other\n * sequences — because a person enrolled on Monday can unsubscribe by\n * Thursday. A lookup that could not be made holds the send; a gate that\n * refuses stops the enrollment, saying why.\n *==========================================*/\n\nexport { OUTREACH_SEND_JOB_ID } from '../constants/runtime-jobs'\n\n/** The most due enrollments one run reads. */\nexport const OUTREACH_SEND_SCAN_LIMIT = 300\n\n/** How long a claim holds before a later run settles it. */\nexport const OUTREACH_CLAIM_STALE_MS = 10 * 60_000\n\n/** What one run did, for the tick's answer. */\nexport interface OutreachSendReport {\n [key: string]: number\n due: number\n sent: number\n tasks: number\n /** Stopped by a gate or an unusable mailbox. */\n stopped: number\n /** Paused for the rep to fix, or failed for good. */\n failed: number\n /** Due, and left for a later run: the allowance, a lookup, a hold. */\n held: number\n /** Claims a dead run left, settled. */\n recovered: number\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface MailboxRun {\n orgId: string\n org: Record<string, unknown>\n mailbox: OutreachMailbox\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n deadlineMs: number\n opened: OpenedOutreachMailbox | null\n /** Set once the mailbox itself cannot send this run. */\n stopped: boolean\n templates: Map<string, string | null>\n}\n\nconst blankReport = (): OutreachSendReport => ({\n due: 0,\n sent: 0,\n tasks: 0,\n stopped: 0,\n failed: 0,\n held: 0,\n recovered: 0,\n})\n\n/** Runs the send job once — see the module note. */\nexport async function runOutreachSendJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSendReport> {\n const firestore = deps.firestore()\n const report = blankReport()\n const due = await firestore\n .collectionGroup(OUTREACH_COLLECTIONS.enrollments)\n .where('status', '==', 'active')\n .where('nextDueAtMs', '<=', context.nowMs)\n .orderBy('nextDueAtMs')\n .limit(OUTREACH_SEND_SCAN_LIMIT)\n .get()\n report.due = due.size\n const byOrg = new Map<string, Map<string, OutreachEnrollment[]>>()\n for (const doc of due.docs) {\n const orgId = doc.ref.parent.parent?.id\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!orgId || !enrollment) continue\n const mailboxes = byOrg.get(orgId) ?? new Map<string, OutreachEnrollment[]>()\n mailboxes.set(enrollment.mailboxId, [...(mailboxes.get(enrollment.mailboxId) ?? []), enrollment])\n byOrg.set(orgId, mailboxes)\n }\n\n for (const [orgId, mailboxes] of byOrg) {\n const waiting = [...mailboxes.values()].reduce((sum, list) => sum + list.length, 0)\n if (deps.now() >= context.deadlineMs) {\n report.held += waiting\n continue\n }\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) {\n report.held += waiting\n continue\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, orgId)\n for (const [mailboxId, enrollments] of mailboxes) {\n await runMailbox(deps, firestore, { orgId, org, mailboxId, enrollments, settings, report, context })\n }\n }\n return report\n}\n\n/** The reason an unusable mailbox stops an enrollment, or `null` for a usable one. */\nasync function unusableMailbox(\n firestore: Firestore,\n orgId: string,\n mailbox: OutreachMailbox | null,\n): Promise<string | null> {\n if (!mailbox) return 'The mailbox this sequence sends from was removed.'\n if (mailbox.status === 'disconnected') return 'The mailbox this sequence sends from was disconnected.'\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(mailbox.connectedByUid).get()\n return member.exists\n ? null\n : 'The member who connected the mailbox this sequence sends from is no longer in the organization.'\n}\n\nasync function runMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n mailboxId: string\n enrollments: OutreachEnrollment[]\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n context: { nowMs: number; deadlineMs: number }\n },\n): Promise<void> {\n const { orgId, org, report, context } = input\n const nowMs = context.nowMs\n const snapshot = await mailboxRef(firestore, orgId, input.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(input.mailboxId, snapshot.exists ? snapshot.data() : undefined)\n const unusable = await unusableMailbox(firestore, orgId, mailbox)\n if (unusable || !mailbox) {\n for (const enrollment of input.enrollments) {\n const outcome = await applyOutreachEvent(firestore, {\n orgId,\n enrollmentId: enrollment.id,\n event: { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: unusable },\n nowMs,\n })\n if (outcome.changed) report.stopped += 1\n }\n return\n }\n if (mailbox.status !== 'connected' || (await deps.sendRefusal({ orgId, org, uid: mailbox.connectedByUid }))) {\n report.held += input.enrollments.length\n return\n }\n\n const run: MailboxRun = {\n orgId,\n org,\n mailbox,\n settings: input.settings,\n report,\n deadlineMs: context.deadlineMs,\n opened: null,\n stopped: false,\n templates: new Map(),\n }\n const sequenceIds = [...new Set(input.enrollments.map((enrollment) => enrollment.sequenceId))]\n const sequenceSnapshots = await firestore.getAll(\n ...sequenceIds.map((id) => outreachOrgCollection(firestore, orgId, 'sequences').doc(id)),\n )\n const sequences = new Map<string, OutreachSequence>()\n sequenceSnapshots.forEach((sequenceSnapshot, index) => {\n const sequence = readStoredOutreachSequence(\n sequenceIds[index],\n sequenceSnapshot.exists ? sequenceSnapshot.data() : undefined,\n )\n if (sequence) sequences.set(sequence.id, sequence)\n })\n\n const candidates: OutreachDueCandidate[] = []\n for (const enrollment of input.enrollments) {\n const sequence = sequences.get(enrollment.sequenceId)\n const claim = enrollment.sendClaim\n if (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS) continue\n if (claim && sequence) {\n if (await recoverClaim(deps, firestore, run, enrollment, sequence)) report.recovered += 1\n continue\n }\n if (sequence) candidates.push({ enrollment, sequence })\n }\n\n const allowance = outreachTickAllowance({ mailbox, nowMs })\n const selection = selectDueOutreachEnrollments({ candidates, mailbox, nowMs, allowance: allowance.allowance })\n report.held += selection.deferred.length\n\n for (const candidate of selection.tasks) {\n if (deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n if (await runTaskStep(deps, firestore, run, candidate)) report.tasks += 1\n }\n if (!selection.emails.length) return\n\n // The people behind the emails, read once per site: the contact and its\n // company, and every lookup the gates decide on.\n const people = new Map<string, OutreachEnrollCandidate>()\n const lookups = new Map<string, OutreachGateLookups>()\n const byHost = new Map<string, OutreachEnrollment[]>()\n for (const candidate of selection.emails) {\n const enrollment = candidate.enrollment as OutreachEnrollment\n byHost.set(enrollment.hostId, [...(byHost.get(enrollment.hostId) ?? []), enrollment])\n }\n const siteNames = new Map<string, string>()\n for (const [hostId, enrollments] of byHost) {\n const contactGroupId = consentGroupForHost(org, hostId).groupId\n // Each by the record it names — the contact, or the lead while the\n // person is one (AGL-3234) — keyed by that record's id.\n const [candidatesRead, lookupsRead, host] = await Promise.all([\n readOutreachEnrollCandidates(firestore, {\n orgId,\n hostId,\n contactGroupId,\n people: enrollments.map(outreachEnrollmentPerson),\n }),\n readOutreachGateLookups(firestore, {\n orgId,\n hostId,\n people: enrollments.map((enrollment) => {\n const person = outreachEnrollmentPerson(enrollment)\n return {\n personId: person.id,\n contactId: person.kind === 'contact' ? person.id : null,\n leadId: person.kind === 'lead' ? person.id : null,\n email: enrollment.email,\n }\n }),\n }),\n firestore.collection('hosts').doc(hostId).get(),\n ])\n for (const person of candidatesRead) people.set(person.personId, person)\n for (const [personId, answer] of lookupsRead) lookups.set(personId, answer)\n siteNames.set(hostId, host.exists ? String(host.get('name') ?? '') : '')\n }\n\n for (const candidate of selection.emails) {\n if (run.stopped || deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n const enrollment = candidate.enrollment as OutreachEnrollment\n const personId = outreachEnrollmentPerson(enrollment).id\n await runEmailStep(deps, firestore, run, {\n enrollment,\n sequence: candidate.sequence as OutreachSequence,\n person: people.get(personId) ?? null,\n lookups: lookups.get(personId) ?? null,\n siteName: siteNames.get(enrollment.hostId) ?? '',\n })\n }\n}\n\n/** Any lookup the runtime could not make: the send waits for a run that can. */\nfunction uncheckable(lookups: OutreachGateLookups | null): boolean {\n return !lookups || Object.values(lookups).some((value) => value === null)\n}\n\n/** The event a gate's refusal ends an enrollment with. */\nfunction gateEvent(blocks: readonly OutreachGateBlock[], atMs: number): OutreachEnrollmentEvent {\n const optedOut = blocks.find((block) => block.code === 'do_not_contact' || block.code === 'sales_opted_out')\n if (optedOut) return { type: 'opt_out', atMs, reason: 'do_not_contact', detail: optedOut.reason }\n return { type: 'stop', atMs, byUid: null, reason: 'gate', detail: blocks.map((block) => block.reason).join(' ') }\n}\n\n/** The sender line a mailbox's mail goes out with. */\nconst senderOf = (mailbox: OutreachMailbox) => ({\n address: mailbox.sendAs || mailbox.email,\n name: mailbox.displayName || null,\n})\n\nasync function openClient(deps: OutreachRuntimeDeps, firestore: Firestore, run: MailboxRun) {\n const opened = (run.opened ??= await deps.openMailbox(run.mailbox.id))\n if (opened.ok === true) return opened.client\n run.stopped = true\n if (opened.reason !== 'not-configured') {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: run.orgId,\n mailboxId: run.mailbox.id,\n errorCode: opened.reason,\n nowMs: deps.now(),\n })\n }\n return null\n}\n\n/**\n * Claims one step: the enrollment still active on the same step with no\n * live claim, and — for an email — a slot under the mailbox's cap today,\n * reserved in the same transaction.\n */\nasync function claimStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n messageId: string | null,\n): Promise<'claimed' | 'taken' | 'cap'> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([transaction.get(enrollmentRef), transaction.get(boxRef)])\n const stored = readStoredOutreachEnrollment(enrollment.id, current.exists ? current.data() : undefined)\n const claim = stored?.sendClaim\n if (\n !stored ||\n stored.status !== 'active' ||\n stored.stepIndex !== enrollment.stepIndex ||\n stored.nextDueAtMs === null ||\n stored.nextDueAtMs > nowMs ||\n (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS)\n ) {\n return 'taken'\n }\n if (messageId) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.status !== 'connected') return 'taken'\n const sent = outreachSentToday(mailbox.health, nowMs, mailbox.timezone)\n if (sent >= outreachEffectiveDailyCap(mailbox, nowMs)) return 'cap'\n transaction.update(boxRef, {\n 'health.sentToday': sent + 1,\n 'health.sentOnDay': outreachLocalDay(nowMs, mailbox.timezone),\n })\n }\n transaction.update(enrollmentRef, {\n sendClaim: { token: randomUUID(), atMs: nowMs, stepIndex: enrollment.stepIndex, messageId },\n updatedAtMs: nowMs,\n })\n return 'claimed'\n })\n}\n\n/** Drops a claim, and hands an email's reservation back to the mailbox's day. */\nasync function releaseClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: Pick<OutreachEnrollment, 'id'>,\n reserved: boolean,\n event: OutreachEnrollmentEvent | null = null,\n): Promise<void> {\n const nowMs = deps.now()\n await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: () => ({ sendClaim: null }),\n nowMs,\n })\n if (!reserved) return\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n await firestore.runTransaction(async (transaction) => {\n const box = await transaction.get(boxRef)\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.health?.sentOnDay !== outreachLocalDay(nowMs, mailbox.timezone)) return\n transaction.update(boxRef, { 'health.sentToday': Math.max(0, (Number(mailbox.health.sentToday) || 0) - 1) })\n })\n}\n\n/**\n * Records a step that ran: the engine's completion patch, the claim\n * cleared, the step's record kept — and for an email the mailbox's send on\n * its day, its last-sent time and its window of recent sends. Refuses\n * (answers false) when the claim is no longer this run's.\n */\nasync function completeStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n record: OutreachStepRecord\n sent: { messageId: string; threadId: string; subject: string } | null\n claimMessageId: string | null\n },\n): Promise<boolean> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(input.enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([\n transaction.get(enrollmentRef),\n input.sent ? transaction.get(boxRef) : Promise.resolve(null),\n ])\n const stored = readStoredOutreachEnrollment(input.enrollment.id, current.exists ? current.data() : undefined)\n if (!stored?.sendClaim || stored.sendClaim.messageId !== input.claimMessageId) return false\n if (stored.stepIndex !== input.enrollment.stepIndex) return false\n // The step RAN, whatever happened to the enrollment while it did — a\n // member paused it, a reply stopped it — so it is recorded as run, and a\n // resume never sends it twice.\n const plan = planOutreachStepCompletion({\n enrollment: { ...stored, status: 'active' },\n sequence: input.sequence,\n mailbox: run.mailbox,\n completedAtMs: nowMs,\n sent: input.sent,\n random: deps.random,\n })\n const patch: Record<string, unknown> = {\n sendClaim: null,\n stepRecords: [...(stored.stepRecords ?? []), input.record].slice(-20),\n updatedAtMs: nowMs,\n ...(plan.patch ?? {}),\n }\n if (stored.status !== 'active') {\n patch['status'] = stored.status\n if (stored.status !== 'paused') patch['nextDueAtMs'] = null\n }\n transaction.update(enrollmentRef, patch)\n if (input.sent && box?.exists) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.data())\n if (mailbox) {\n const day = outreachLocalDay(nowMs, mailbox.timezone)\n const counts = mailbox.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n transaction.update(boxRef, {\n 'health.lastSentAtMs': nowMs,\n 'health.lastErrorAtMs': null,\n 'health.lastErrorCode': null,\n [`health.daily.${day}`]: { ...counts, sent: (Number(counts.sent) || 0) + 1 },\n 'health.recentSends': withRecentSend(mailbox.health?.recentSends, {\n id: outreachSendDigest(input.sent.messageId),\n atMs: nowMs,\n bounced: false,\n }),\n updatedAtMs: nowMs,\n })\n }\n }\n return true\n })\n}\n\n/** One task step: the rep's task on the contact, then the step recorded. */\nasync function runTaskStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n candidate: OutreachDueCandidate,\n): Promise<boolean> {\n const enrollment = candidate.enrollment as OutreachEnrollment\n const sequence = candidate.sequence as OutreachSequence\n const step = sequence.steps[enrollment.stepIndex] as OutreachTaskStep\n if ((await claimStep(deps, firestore, run, enrollment, null)) !== 'claimed') return false\n const nowMs = deps.now()\n let taskId: string | null\n try {\n const written = await fileOutreachTask(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `step:${enrollment.id}:${step.id}`,\n title: step.title,\n notes: `From sequence step ${enrollment.stepIndex + 1}.`,\n kind: OUTREACH_TASK_KIND_TO_RECORD[step.taskKind] ?? 'todo',\n dueAtMs: nowMs,\n assigneeUid: run.mailbox.connectedByUid,\n })\n taskId = written?.ok ? written.id : null\n if (written?.ok === false) console.warn(`[outreach] a task step's task was not filed: ${written.error}`)\n } catch (error) {\n // The record system failed rather than refused: the step waits for a\n // run that can file its task.\n console.error('[outreach] filing a task step failed; the step waits', error)\n await releaseClaim(deps, firestore, run, enrollment, false)\n return false\n }\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: { stepIndex: enrollment.stepIndex, stepId: step.id, kind: 'task', atMs: nowMs, taskId },\n sent: null,\n claimMessageId: null,\n })\n}\n\n/** A CRM template's body, read once per run. */\nasync function templateBody(firestore: Firestore, run: MailboxRun, templateId: string): Promise<string | null> {\n if (!run.templates.has(templateId)) {\n const snapshot = await firestore\n .collection('orgs')\n .doc(run.orgId)\n .collection(CRM_COLLECTIONS.emailTemplates)\n .doc(templateId)\n .get()\n run.templates.set(\n templateId,\n snapshot.exists ? normalizeCrmEmailTemplate(snapshot.data() as Record<string, unknown>).body : null,\n )\n }\n return run.templates.get(templateId) ?? null\n}\n\nasync function runEmailStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n person: OutreachEnrollCandidate | null\n lookups: OutreachGateLookups | null\n siteName: string\n },\n): Promise<void> {\n const { enrollment, sequence, person } = input\n const { report, mailbox } = run\n const nowMs = deps.now()\n const stop = async (event: OutreachEnrollmentEvent, counter: 'stopped' | 'failed') => {\n const outcome = await applyOutreachEvent(firestore, { orgId: run.orgId, enrollmentId: enrollment.id, event, nowMs })\n if (outcome.changed) report[counter] += 1\n }\n\n // Every gate again, on the person as they stand now.\n if (!person?.contact) {\n return stop(\n {\n type: 'stop',\n atMs: nowMs,\n byUid: null,\n reason: 'gate',\n detail:\n enrollment.target === 'lead'\n ? \"This lead no longer exists in the sequence's site's CRM.\"\n : 'This contact no longer exists in the CRM.',\n },\n 'stopped',\n )\n }\n if (person.convertedContactId && enrollment.target === 'lead') {\n // The lead converted and the enrollment has not followed it yet: the\n // conversion's listener re-points it, and the next run sends as the contact.\n report.held += 1\n return\n }\n if (!person.visible) {\n return stop(\n { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: \"This contact is no longer in the sequence's site's CRM.\" },\n 'stopped',\n )\n }\n if (uncheckable(input.lookups)) {\n report.held += 1\n return\n }\n const contactGroupId = consentGroupForHost(run.org, enrollment.hostId).groupId\n const gate = evaluateOutreachGates({\n email: enrollment.email,\n contact: person.contact,\n contactGroupId,\n company: person.company,\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n run.settings.allowedCountries,\n ),\n },\n personalLine: enrollment.personalLine,\n attestations: enrollment.attestations,\n enrollmentId: enrollment.id,\n lookups: input.lookups as OutreachGateLookups,\n })\n if (!gate.allowed) return stop(gateEvent(gate.blocks, nowMs), 'stopped')\n\n // The email, with its way out.\n const listUnsubscribeUrl = deps.unsubscribeUrl({ orgId: run.orgId, enrollmentId: enrollment.id })\n const mailto = outreachUnsubscribeMailbox(mailbox.email)\n if (!listUnsubscribeUrl || !mailto) {\n // No link can be minted — no secret, or no HTTPS console origin — and an\n // email without its one-click way out does not leave.\n console.error('[outreach] no unsubscribe link could be minted; nothing sends until one can')\n run.stopped = true\n report.held += 1\n return\n }\n const step = sequence.steps[enrollment.stepIndex]\n const sender = senderOf(mailbox)\n const composed = composeOutreachEmail({\n sequence,\n enrollment,\n orgSettings: run.settings,\n merge: {\n // For a lead, the contact-shaped view of it (`leadAsContact`), so a\n // step written with `{{contact.*}}` reads the lead; `{{lead.*}}` reads\n // the lead's own document beside it.\n contact: person.contact,\n contactGroupId,\n lead: person.lead,\n sender: { name: mailbox.displayName, email: sender.address },\n site: { name: input.siteName },\n },\n templateBody: step?.kind === 'email' && step.templateId ? await templateBody(firestore, run, step.templateId) : null,\n listUnsubscribeUrl,\n listUnsubscribeMailto: mailto.uri,\n })\n if (composed.error || !composed.email) {\n const code = composed.error?.code\n if (code === 'missing_postal_address' || code === 'missing_legal_name') {\n // The organization's footer: nothing of theirs sends until it is set.\n run.stopped = true\n report.held += 1\n return\n }\n if (code === 'invalid_recipient' || code === 'missing_thread' || code === 'not_an_email_step') {\n return stop({ type: 'send_failed', atMs: nowMs, detail: composed.error?.message }, 'failed')\n }\n // The sequence's own words: the rep fixes the step and resumes.\n return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: composed.error?.message }, 'failed')\n }\n if (composed.unresolvedFields.length) {\n const fields = composed.unresolvedFields.map((field) => `{{${field}}}`).join(', ')\n return stop(\n {\n type: 'pause',\n atMs: nowMs,\n byUid: null,\n detail: `Paused before sending: this contact has nothing for ${fields}. Fill it in and resume.`,\n },\n 'failed',\n )\n }\n\n // Claimed, then sent, then recorded.\n const domain = sender.address.slice(sender.address.lastIndexOf('@') + 1)\n const local = randomUUID()\n const messageId = `<${local}@${domain}>`\n const claimed = await claimStep(deps, firestore, run, enrollment, messageId)\n if (claimed !== 'claimed') {\n if (claimed === 'cap') run.stopped = true\n report.held += 1\n return\n }\n const client = await openClient(deps, firestore, run)\n if (!client) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n return\n }\n let sent: Awaited<ReturnType<typeof sendComposedOutreachEmail>>\n try {\n sent = await sendComposedOutreachEmail(client, composed.email, sender, {\n messageIdLocalPart: local,\n messageIdDomain: domain,\n })\n } catch (error) {\n if (error instanceof Rfc5322MessageError || (error instanceof GmailTransportError && error.code === 'invalid_request')) {\n await releaseClaim(deps, firestore, run, enrollment, true, {\n type: 'send_failed',\n atMs: deps.now(),\n detail: `Gmail refused the email: ${error.message}`,\n })\n report.failed += 1\n return\n }\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n run.stopped = true\n const code = error instanceof GmailTransportError ? error.code : 'unexpected'\n if (isReconnectRequired(error)) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: run.orgId,\n mailboxId: mailbox.id,\n errorCode: code,\n nowMs: deps.now(),\n })\n } else {\n await mailboxRef(firestore, run.orgId, mailbox.id)\n .update({ 'health.lastErrorAtMs': deps.now(), 'health.lastErrorCode': code })\n .catch(() => undefined)\n }\n console.error(`[outreach] a send from a mailbox failed (${code}); its sends wait for the next run`)\n return\n }\n\n const record: OutreachStepRecord = {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: sent.gmailMessageId,\n gmailThreadId: sent.threadId,\n messageId: sent.messageId,\n subject: sent.subject,\n }\n await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record,\n sent: { messageId: sent.messageId, threadId: sent.threadId, subject: sent.subject },\n claimMessageId: messageId,\n })\n report.sent += 1\n await fileOutreachEmail(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'outbound',\n subject: sent.subject,\n from: sender.address,\n to: composed.email.to,\n messageId: sent.messageId,\n inReplyTo: composed.email.inReplyTo ?? null,\n body: composed.email.text,\n atMs: record.atMs,\n byUid: mailbox.connectedByUid,\n byName: mailbox.displayName || null,\n })\n}\n\n/**\n * Settles a claim a run died holding. A task step's claim is dropped and\n * the step runs again (its task is filed once however often it is asked).\n * An email's claim looks for the message it minted in the mailbox: found,\n * the send happened and is recorded; not found, it did not, and the claim\n * and its reservation are handed back for the next run.\n */\nasync function recoverClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n sequence: OutreachSequence,\n): Promise<boolean> {\n const claim = enrollment.sendClaim\n if (!claim) return false\n if (!claim.messageId) {\n await releaseClaim(deps, firestore, run, enrollment, false)\n return true\n }\n const client = await openClient(deps, firestore, run)\n if (!client) return false\n const bare = claim.messageId.replace(/^<|>$/g, '')\n const found = await client.listMessages({ q: `rfc822msgid:${bare}`, maxResults: 1, includeSpamTrash: true })\n const hit = found.messages[0]\n if (!hit) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n return true\n }\n const message = await client.getMessage(hit.id, { metadataHeaders: ['Subject'] })\n const subject = message.headers.find((header) => header.name.toLowerCase() === 'subject')?.value ?? ''\n const step = sequence.steps[enrollment.stepIndex]\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: hit.id,\n gmailThreadId: hit.threadId,\n messageId: claim.messageId,\n subject,\n },\n sent: { messageId: claim.messageId, threadId: hit.threadId, subject },\n claimMessageId: claim.messageId,\n })\n}\n"],"names":["consentGroupForHost","CRM_COLLECTIONS","normalizeCrmEmailTemplate","randomUUID","composeOutreachEmail","planOutreachStepCompletion","evaluateOutreachGates","outreachSentToday","outreachTickAllowance","selectDueOutreachEnrollments","readOutreachEnrollCandidates","readOutreachGateLookups","mailboxRef","outreachEffectiveDailyCap","outreachLocalDay","markOutreachMailboxReconnectRequired","effectiveOutreachAllowedCountries","OUTREACH_COLLECTIONS","readOutreachComplianceSettingsDoc","outreachEnrollmentLink","outreachEnrollmentPerson","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","Rfc5322MessageError","sendComposedOutreachEmail","applyOutreachEvent","outreachSendDigest","withRecentSend","fileOutreachEmail","fileOutreachTask","OUTREACH_TASK_KIND_TO_RECORD","outreachUnsubscribeMailbox","OUTREACH_SEND_JOB_ID","OUTREACH_SEND_SCAN_LIMIT","OUTREACH_CLAIM_STALE_MS","blankReport","due","sent","tasks","stopped","failed","held","recovered","runOutreachSendJob","deps","context","firestore","report","collectionGroup","enrollments","where","nowMs","orderBy","limit","get","size","byOrg","Map","doc","docs","mailboxes","orgId","ref","parent","id","enrollment","data","set","mailboxId","waiting","values","reduce","sum","list","length","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","settings","runMailbox","unusableMailbox","mailbox","status","member","connectedByUid","input","snapshot","undefined","unusable","outcome","enrollmentId","event","type","atMs","byUid","reason","detail","changed","sendRefusal","uid","run","opened","templates","sequenceIds","Set","map","sequenceId","sequenceSnapshots","getAll","sequences","forEach","sequenceSnapshot","index","sequence","candidates","claim","sendClaim","recoverClaim","push","allowance","selection","deferred","candidate","runTaskStep","emails","people","lookups","byHost","hostId","siteNames","host","contactGroupId","groupId","candidatesRead","lookupsRead","Promise","all","person","personId","contactId","kind","leadId","email","answer","String","runEmailStep","siteName","uncheckable","Object","some","value","gateEvent","blocks","optedOut","find","block","code","join","senderOf","address","sendAs","name","displayName","openClient","openMailbox","ok","client","errorCode","claimStep","messageId","enrollmentRef","boxRef","runTransaction","transaction","current","box","stored","stepIndex","nextDueAtMs","health","timezone","update","token","updatedAtMs","releaseClaim","reserved","extra","sentOnDay","Math","max","Number","sentToday","completeStep","plan","resolve","claimMessageId","completedAtMs","random","patch","stepRecords","record","slice","day","counts","daily","bounces","replies","recentSends","bounced","step","steps","taskId","written","link","dedupeKey","title","notes","taskKind","dueAtMs","assigneeUid","console","warn","error","stepId","templateBody","templateId","has","emailTemplates","body","composed","stop","counter","contact","target","convertedContactId","visible","gate","company","allowedCountries","personalLine","attestations","allowed","listUnsubscribeUrl","unsubscribeUrl","mailto","sender","orgSettings","merge","lead","site","listUnsubscribeMailto","uri","message","unresolvedFields","fields","field","domain","lastIndexOf","local","claimed","messageIdLocalPart","messageIdDomain","catch","gmailMessageId","gmailThreadId","threadId","subject","direction","from","to","inReplyTo","text","byName","bare","replace","found","listMessages","q","maxResults","includeSpamTrash","hit","messages","getMessage","metadataHeaders","headers","header","toLowerCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,yBAAyB,QAAQ,6CAA4C;AACtF,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,oBAAoB,QAAQ,uBAAmB;AACxD,SAASC,0BAA0B,QAAsC,gCAA4B;AACrG,SAASC,qBAAqB,QAA0D,qBAAiB;AACzG,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,4BAA4B,QAEvB,gCAA4B;AACnC,SAASC,4BAA4B,QAAsC,iCAA6B;AACxG,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SAASC,yBAAyB,EAAEC,gBAAgB,QAAQ,mCAA+B;AAC3F,SAASC,oCAAoC,QAAoC,oCAAgC;AACjH,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SACEC,oBAAoB,QAOf,6BAAyB;AAChC,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SACEC,sBAAsB,EACtBC,wBAAwB,EACxBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,4BAAwB;AAE3E,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,4BAA4B,QAAQ,gBAAY;AAC9F,SAASC,0BAA0B,QAAQ,wBAAoB;AAE/D;;;;;;;;;;;;;;;;;;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YACpBgF,MAAM;YACN/C,MAAMrD,KAAK+B,GAAG;YACdgM,gBAAgBiB,IAAI5N,EAAE;YACtB4M,eAAegB,IAAIf,QAAQ;YAC3BhG,WAAWtD,MAAMsD,SAAS;YAC1BiG;QACF;QACAzO,MAAM;YAAEwI,WAAWtD,MAAMsD,SAAS;YAAEgG,UAAUe,IAAIf,QAAQ;YAAEC;QAAQ;QACpEvE,gBAAgBhF,MAAMsD,SAAS;IACjC;AACF"}
|
|
@@ -24,10 +24,11 @@ import { mailboxRef } from "../mailboxes/mailbox-credentials.js";
|
|
|
24
24
|
import { markOutreachMailboxReconnectRequired } from "../mailboxes/mailbox-transport.js";
|
|
25
25
|
import { OUTREACH_COLLECTIONS } from "../model/outreach.types.js";
|
|
26
26
|
import { addOutreachDoNotContact } from "../storage/do-not-contact-store.js";
|
|
27
|
-
import { outreachOrgCollection, readStoredOutreachEnrollment, readStoredOutreachMailbox, readStoredOutreachSequence } from "../storage/outreach-records.js";
|
|
27
|
+
import { outreachEnrollmentLink, outreachOrgCollection, readStoredOutreachEnrollment, readStoredOutreachMailbox, readStoredOutreachSequence } from "../storage/outreach-records.js";
|
|
28
28
|
import { GmailTransportError, isReconnectRequired } from "../transport/gmail-errors.js";
|
|
29
29
|
import { applyOutreachEvent, recordOutreachOptOut } from "./enrollment-events.js";
|
|
30
30
|
import { applyOutreachMailboxHealth, emptyOutreachHealthDelta } from "./mailbox-health-store.js";
|
|
31
|
+
import { markOutreachLeadWorking } from "./lead-records.js";
|
|
31
32
|
import { fileOutreachEmail, fileOutreachTask } from "./timeline.js";
|
|
32
33
|
import { outreachUnsubscribeMailbox } from "./unsubscribe-link.js";
|
|
33
34
|
/*==========================================
|
|
@@ -310,7 +311,7 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
310
311
|
await fileOutreachEmail(context.deps, {
|
|
311
312
|
orgId: context.orgId,
|
|
312
313
|
hostId: enrollment.hostId,
|
|
313
|
-
|
|
314
|
+
link: outreachEnrollmentLink(enrollment),
|
|
314
315
|
direction: 'inbound',
|
|
315
316
|
subject: message.subject,
|
|
316
317
|
from: (_emailAddressOf = emailAddressOf(message.from)) != null ? _emailAddressOf : message.from,
|
|
@@ -388,7 +389,7 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
388
389
|
await fileOutreachTask(deps, {
|
|
389
390
|
orgId: context.orgId,
|
|
390
391
|
hostId: enrollment.hostId,
|
|
391
|
-
|
|
392
|
+
link: outreachEnrollmentLink(enrollment),
|
|
392
393
|
dedupeKey: `reply:${(_messageIdOf = messageIdOf(decidingMessage)) != null ? _messageIdOf : decidingMessage.id}`,
|
|
393
394
|
title: `Reply from ${enrollment.contactName || enrollment.email}`,
|
|
394
395
|
notes: crmInboundExcerpt((_ref2 = (_decidingMessage_textBody = decidingMessage.textBody) != null ? _decidingMessage_textBody : decidingMessage.snippet) != null ? _ref2 : '', (_decidingMessage_htmlBody = decidingMessage.htmlBody) != null ? _decidingMessage_htmlBody : '').slice(0, 500),
|
|
@@ -400,6 +401,13 @@ async function syncMailbox(deps, firestore, input) {
|
|
|
400
401
|
console.error('[outreach] the reply task could not be filed', error);
|
|
401
402
|
}
|
|
402
403
|
}
|
|
404
|
+
// A lead somebody wrote back to is being worked (AGL-3234).
|
|
405
|
+
if (enrollment.target === 'lead' && enrollment.leadId) {
|
|
406
|
+
await markOutreachLeadWorking(firestore, {
|
|
407
|
+
hostId: enrollment.hostId,
|
|
408
|
+
leadId: enrollment.leadId
|
|
409
|
+
});
|
|
410
|
+
}
|
|
403
411
|
context.delta.replies += 1;
|
|
404
412
|
event = {
|
|
405
413
|
type: 'reply',
|