@aglyn/plugins-outreach 1.0.0-beta.143
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/LICENSE +201 -0
- package/README.md +93 -0
- package/package.json +52 -0
- package/src/index.d.ts +22 -0
- package/src/index.js +29 -0
- package/src/index.js.map +1 -0
- package/src/lib/components/compliance-section.d.ts +20 -0
- package/src/lib/components/compliance-section.js +291 -0
- package/src/lib/components/compliance-section.js.map +1 -0
- package/src/lib/components/enroll-dialog.d.ts +36 -0
- package/src/lib/components/enroll-dialog.js +656 -0
- package/src/lib/components/enroll-dialog.js.map +1 -0
- package/src/lib/components/enrollments-table.d.ts +28 -0
- package/src/lib/components/enrollments-table.js +375 -0
- package/src/lib/components/enrollments-table.js.map +1 -0
- package/src/lib/components/mailbox-card.d.ts +46 -0
- package/src/lib/components/mailbox-card.js +517 -0
- package/src/lib/components/mailbox-card.js.map +1 -0
- package/src/lib/components/mailboxes-section.d.ts +24 -0
- package/src/lib/components/mailboxes-section.js +258 -0
- package/src/lib/components/mailboxes-section.js.map +1 -0
- package/src/lib/components/outreach-console-page.d.ts +17 -0
- package/src/lib/components/outreach-console-page.js +81 -0
- package/src/lib/components/outreach-console-page.js.map +1 -0
- package/src/lib/components/outreach-console-sections.d.ts +43 -0
- package/src/lib/components/outreach-console-sections.js +55 -0
- package/src/lib/components/outreach-console-sections.js.map +1 -0
- package/src/lib/components/outreach-ui.d.ts +51 -0
- package/src/lib/components/outreach-ui.js +171 -0
- package/src/lib/components/outreach-ui.js.map +1 -0
- package/src/lib/components/send-window-fields.d.ts +25 -0
- package/src/lib/components/send-window-fields.js +178 -0
- package/src/lib/components/send-window-fields.js.map +1 -0
- package/src/lib/components/sequence-detail.d.ts +54 -0
- package/src/lib/components/sequence-detail.js +435 -0
- package/src/lib/components/sequence-detail.js.map +1 -0
- package/src/lib/components/sequence-editor.d.ts +37 -0
- package/src/lib/components/sequence-editor.js +485 -0
- package/src/lib/components/sequence-editor.js.map +1 -0
- package/src/lib/components/sequence-mailbox-picker.d.ts +44 -0
- package/src/lib/components/sequence-mailbox-picker.js +137 -0
- package/src/lib/components/sequence-mailbox-picker.js.map +1 -0
- package/src/lib/components/sequence-preview.d.ts +27 -0
- package/src/lib/components/sequence-preview.js +146 -0
- package/src/lib/components/sequence-preview.js.map +1 -0
- package/src/lib/components/sequence-step-card.d.ts +31 -0
- package/src/lib/components/sequence-step-card.js +326 -0
- package/src/lib/components/sequence-step-card.js.map +1 -0
- package/src/lib/components/sequences-section.d.ts +40 -0
- package/src/lib/components/sequences-section.js +310 -0
- package/src/lib/components/sequences-section.js.map +1 -0
- package/src/lib/components/use-outreach-api.d.ts +38 -0
- package/src/lib/components/use-outreach-api.js +139 -0
- package/src/lib/components/use-outreach-api.js.map +1 -0
- package/src/lib/components/use-outreach-crm.d.ts +50 -0
- package/src/lib/components/use-outreach-crm.js +200 -0
- package/src/lib/components/use-outreach-crm.js.map +1 -0
- package/src/lib/components/use-outreach-data.d.ts +55 -0
- package/src/lib/components/use-outreach-data.js +199 -0
- package/src/lib/components/use-outreach-data.js.map +1 -0
- package/src/lib/components/use-outreach-mailbox-api.d.ts +30 -0
- package/src/lib/components/use-outreach-mailbox-api.js +101 -0
- package/src/lib/components/use-outreach-mailbox-api.js.map +1 -0
- package/src/lib/components/use-outreach-mailboxes.d.ts +22 -0
- package/src/lib/components/use-outreach-mailboxes.js +68 -0
- package/src/lib/components/use-outreach-mailboxes.js.map +1 -0
- package/src/lib/components/use-outreach-settings.d.ts +17 -0
- package/src/lib/components/use-outreach-settings.js +64 -0
- package/src/lib/components/use-outreach-settings.js.map +1 -0
- package/src/lib/constants/api-routes.d.ts +68 -0
- package/src/lib/constants/api-routes.js +57 -0
- package/src/lib/constants/api-routes.js.map +1 -0
- package/src/lib/constants/bundle-common.d.ts +46 -0
- package/src/lib/constants/bundle-common.js +55 -0
- package/src/lib/constants/bundle-common.js.map +1 -0
- package/src/lib/constants/runtime-jobs.d.ts +24 -0
- package/src/lib/constants/runtime-jobs.js +24 -0
- package/src/lib/constants/runtime-jobs.js.map +1 -0
- package/src/lib/declarations.console-server.d.ts +38 -0
- package/src/lib/declarations.console-server.js +99 -0
- package/src/lib/declarations.console-server.js.map +1 -0
- package/src/lib/engine/compose.d.ts +86 -0
- package/src/lib/engine/compose.js +212 -0
- package/src/lib/engine/compose.js.map +1 -0
- package/src/lib/engine/delivery-status.d.ts +53 -0
- package/src/lib/engine/delivery-status.js +184 -0
- package/src/lib/engine/delivery-status.js.map +1 -0
- package/src/lib/engine/do-not-contact.d.ts +18 -0
- package/src/lib/engine/do-not-contact.js +34 -0
- package/src/lib/engine/do-not-contact.js.map +1 -0
- package/src/lib/engine/enrollment-state.d.ts +156 -0
- package/src/lib/engine/enrollment-state.js +303 -0
- package/src/lib/engine/enrollment-state.js.map +1 -0
- package/src/lib/engine/gates.d.ts +125 -0
- package/src/lib/engine/gates.js +232 -0
- package/src/lib/engine/gates.js.map +1 -0
- package/src/lib/engine/index.d.ts +28 -0
- package/src/lib/engine/index.js +33 -0
- package/src/lib/engine/index.js.map +1 -0
- package/src/lib/engine/mailbox-health.d.ts +49 -0
- package/src/lib/engine/mailbox-health.js +83 -0
- package/src/lib/engine/mailbox-health.js.map +1 -0
- package/src/lib/engine/opt-out-intent.d.ts +41 -0
- package/src/lib/engine/opt-out-intent.js +220 -0
- package/src/lib/engine/opt-out-intent.js.map +1 -0
- package/src/lib/engine/recipient-country.d.ts +41 -0
- package/src/lib/engine/recipient-country.js +171 -0
- package/src/lib/engine/recipient-country.js.map +1 -0
- package/src/lib/engine/schedule.d.ts +70 -0
- package/src/lib/engine/schedule.js +115 -0
- package/src/lib/engine/schedule.js.map +1 -0
- package/src/lib/engine/sending-capacity.d.ts +96 -0
- package/src/lib/engine/sending-capacity.js +172 -0
- package/src/lib/engine/sending-capacity.js.map +1 -0
- package/src/lib/engine/sequence-validation.d.ts +90 -0
- package/src/lib/engine/sequence-validation.js +291 -0
- package/src/lib/engine/sequence-validation.js.map +1 -0
- package/src/lib/engine/thread-classification.d.ts +78 -0
- package/src/lib/engine/thread-classification.js +224 -0
- package/src/lib/engine/thread-classification.js.map +1 -0
- package/src/lib/engine/thread-message.d.ts +80 -0
- package/src/lib/engine/thread-message.js +143 -0
- package/src/lib/engine/thread-message.js.map +1 -0
- package/src/lib/enrollment/enroll-people.d.ts +81 -0
- package/src/lib/enrollment/enroll-people.js +250 -0
- package/src/lib/enrollment/enroll-people.js.map +1 -0
- package/src/lib/enrollment/gate-lookups.d.ts +32 -0
- package/src/lib/enrollment/gate-lookups.js +154 -0
- package/src/lib/enrollment/gate-lookups.js.map +1 -0
- package/src/lib/mailboxes/mailbox-api.d.ts +126 -0
- package/src/lib/mailboxes/mailbox-api.js +66 -0
- package/src/lib/mailboxes/mailbox-api.js.map +1 -0
- package/src/lib/mailboxes/mailbox-credentials.d.ts +95 -0
- package/src/lib/mailboxes/mailbox-credentials.js +102 -0
- package/src/lib/mailboxes/mailbox-credentials.js.map +1 -0
- package/src/lib/mailboxes/mailbox-erasure.d.ts +69 -0
- package/src/lib/mailboxes/mailbox-erasure.js +148 -0
- package/src/lib/mailboxes/mailbox-erasure.js.map +1 -0
- package/src/lib/mailboxes/mailbox-gate.d.ts +75 -0
- package/src/lib/mailboxes/mailbox-gate.js +98 -0
- package/src/lib/mailboxes/mailbox-gate.js.map +1 -0
- package/src/lib/mailboxes/mailbox-revoke.d.ts +59 -0
- package/src/lib/mailboxes/mailbox-revoke.js +41 -0
- package/src/lib/mailboxes/mailbox-revoke.js.map +1 -0
- package/src/lib/mailboxes/mailbox-routes.d.ts +119 -0
- package/src/lib/mailboxes/mailbox-routes.js +605 -0
- package/src/lib/mailboxes/mailbox-routes.js.map +1 -0
- package/src/lib/mailboxes/mailbox-settings.d.ts +110 -0
- package/src/lib/mailboxes/mailbox-settings.js +212 -0
- package/src/lib/mailboxes/mailbox-settings.js.map +1 -0
- package/src/lib/mailboxes/mailbox-transport.d.ts +64 -0
- package/src/lib/mailboxes/mailbox-transport.js +94 -0
- package/src/lib/mailboxes/mailbox-transport.js.map +1 -0
- package/src/lib/mailboxes/oauth-redirect.d.ts +41 -0
- package/src/lib/mailboxes/oauth-redirect.js +63 -0
- package/src/lib/mailboxes/oauth-redirect.js.map +1 -0
- package/src/lib/mailboxes/oauth-state.d.ts +152 -0
- package/src/lib/mailboxes/oauth-state.js +212 -0
- package/src/lib/mailboxes/oauth-state.js.map +1 -0
- package/src/lib/mailboxes/outreach-config.d.ts +64 -0
- package/src/lib/mailboxes/outreach-config.js +77 -0
- package/src/lib/mailboxes/outreach-config.js.map +1 -0
- package/src/lib/mailboxes/register-mailbox-routes.d.ts +47 -0
- package/src/lib/mailboxes/register-mailbox-routes.js +135 -0
- package/src/lib/mailboxes/register-mailbox-routes.js.map +1 -0
- package/src/lib/model/compliance-settings.d.ts +78 -0
- package/src/lib/model/compliance-settings.js +155 -0
- package/src/lib/model/compliance-settings.js.map +1 -0
- package/src/lib/model/outreach-api.d.ts +210 -0
- package/src/lib/model/outreach-api.js +28 -0
- package/src/lib/model/outreach-api.js.map +1 -0
- package/src/lib/model/outreach.types.d.ts +563 -0
- package/src/lib/model/outreach.types.js +225 -0
- package/src/lib/model/outreach.types.js.map +1 -0
- package/src/lib/model/sequence-draft.d.ts +84 -0
- package/src/lib/model/sequence-draft.js +239 -0
- package/src/lib/model/sequence-draft.js.map +1 -0
- package/src/lib/model/step-preview.d.ts +45 -0
- package/src/lib/model/step-preview.js +98 -0
- package/src/lib/model/step-preview.js.map +1 -0
- package/src/lib/model/stored-records.d.ts +23 -0
- package/src/lib/model/stored-records.js +84 -0
- package/src/lib/model/stored-records.js.map +1 -0
- package/src/lib/plugin.d.ts +46 -0
- package/src/lib/plugin.js +86 -0
- package/src/lib/plugin.js.map +1 -0
- package/src/lib/routes/enroll-routes.d.ts +64 -0
- package/src/lib/routes/enroll-routes.js +350 -0
- package/src/lib/routes/enroll-routes.js.map +1 -0
- package/src/lib/routes/enrollment-routes.d.ts +19 -0
- package/src/lib/routes/enrollment-routes.js +171 -0
- package/src/lib/routes/enrollment-routes.js.map +1 -0
- package/src/lib/routes/platform-deps.d.ts +51 -0
- package/src/lib/routes/platform-deps.js +66 -0
- package/src/lib/routes/platform-deps.js.map +1 -0
- package/src/lib/routes/preview-routes.d.ts +33 -0
- package/src/lib/routes/preview-routes.js +117 -0
- package/src/lib/routes/preview-routes.js.map +1 -0
- package/src/lib/routes/register-routes.d.ts +22 -0
- package/src/lib/routes/register-routes.js +92 -0
- package/src/lib/routes/register-routes.js.map +1 -0
- package/src/lib/routes/route-deps.d.ts +49 -0
- package/src/lib/routes/route-deps.js +27 -0
- package/src/lib/routes/route-deps.js.map +1 -0
- package/src/lib/routes/route-gate.d.ts +94 -0
- package/src/lib/routes/route-gate.js +87 -0
- package/src/lib/routes/route-gate.js.map +1 -0
- package/src/lib/routes/route-http.d.ts +32 -0
- package/src/lib/routes/route-http.js +62 -0
- package/src/lib/routes/route-http.js.map +1 -0
- package/src/lib/routes/sequence-routes.d.ts +32 -0
- package/src/lib/routes/sequence-routes.js +359 -0
- package/src/lib/routes/sequence-routes.js.map +1 -0
- package/src/lib/routes/settings-routes.d.ts +30 -0
- package/src/lib/routes/settings-routes.js +73 -0
- package/src/lib/routes/settings-routes.js.map +1 -0
- package/src/lib/runtime/enrollment-events.d.ts +86 -0
- package/src/lib/runtime/enrollment-events.js +141 -0
- package/src/lib/runtime/enrollment-events.js.map +1 -0
- package/src/lib/runtime/fixtures/fake-gmail.d.ts +121 -0
- package/src/lib/runtime/fixtures/fake-gmail.js +312 -0
- package/src/lib/runtime/fixtures/fake-gmail.js.map +1 -0
- package/src/lib/runtime/mailbox-health-store.d.ts +47 -0
- package/src/lib/runtime/mailbox-health-store.js +168 -0
- package/src/lib/runtime/mailbox-health-store.js.map +1 -0
- package/src/lib/runtime/person-erasure.d.ts +39 -0
- package/src/lib/runtime/person-erasure.js +57 -0
- package/src/lib/runtime/person-erasure.js.map +1 -0
- package/src/lib/runtime/platform-runtime-deps.d.ts +29 -0
- package/src/lib/runtime/platform-runtime-deps.js +98 -0
- package/src/lib/runtime/platform-runtime-deps.js.map +1 -0
- package/src/lib/runtime/runtime-deps.d.ts +77 -0
- package/src/lib/runtime/runtime-deps.js +18 -0
- package/src/lib/runtime/runtime-deps.js.map +1 -0
- package/src/lib/runtime/send-job.d.ts +42 -0
- package/src/lib/runtime/send-job.js +780 -0
- package/src/lib/runtime/send-job.js.map +1 -0
- package/src/lib/runtime/sync-job.d.ts +41 -0
- package/src/lib/runtime/sync-job.js +480 -0
- package/src/lib/runtime/sync-job.js.map +1 -0
- package/src/lib/runtime/timeline.d.ts +67 -0
- package/src/lib/runtime/timeline.js +93 -0
- package/src/lib/runtime/timeline.js.map +1 -0
- package/src/lib/runtime/unsubscribe-link.d.ts +75 -0
- package/src/lib/runtime/unsubscribe-link.js +121 -0
- package/src/lib/runtime/unsubscribe-link.js.map +1 -0
- package/src/lib/runtime/unsubscribe-route.d.ts +24 -0
- package/src/lib/runtime/unsubscribe-route.js +103 -0
- package/src/lib/runtime/unsubscribe-route.js.map +1 -0
- package/src/lib/server.d.ts +53 -0
- package/src/lib/server.js +94 -0
- package/src/lib/server.js.map +1 -0
- package/src/lib/storage/compliance-settings-store.d.ts +44 -0
- package/src/lib/storage/compliance-settings-store.js +78 -0
- package/src/lib/storage/compliance-settings-store.js.map +1 -0
- package/src/lib/storage/do-not-contact-store.d.ts +60 -0
- package/src/lib/storage/do-not-contact-store.js +168 -0
- package/src/lib/storage/do-not-contact-store.js.map +1 -0
- package/src/lib/storage/outreach-records.d.ts +33 -0
- package/src/lib/storage/outreach-records.js +35 -0
- package/src/lib/storage/outreach-records.js.map +1 -0
- package/src/lib/subprocessors.d.ts +48 -0
- package/src/lib/subprocessors.js +70 -0
- package/src/lib/subprocessors.js.map +1 -0
- package/src/lib/transport/gmail-client.d.ts +145 -0
- package/src/lib/transport/gmail-client.js +229 -0
- package/src/lib/transport/gmail-client.js.map +1 -0
- package/src/lib/transport/gmail-errors.d.ts +84 -0
- package/src/lib/transport/gmail-errors.js +138 -0
- package/src/lib/transport/gmail-errors.js.map +1 -0
- package/src/lib/transport/google-oauth.d.ts +138 -0
- package/src/lib/transport/google-oauth.js +247 -0
- package/src/lib/transport/google-oauth.js.map +1 -0
- package/src/lib/transport/http.d.ts +53 -0
- package/src/lib/transport/http.js +79 -0
- package/src/lib/transport/http.js.map +1 -0
- package/src/lib/transport/rfc5322.d.ts +116 -0
- package/src/lib/transport/rfc5322.js +330 -0
- package/src/lib/transport/rfc5322.js.map +1 -0
- package/src/lib/transport/send-message.d.ts +69 -0
- package/src/lib/transport/send-message.js +77 -0
- package/src/lib/transport/send-message.js.map +1 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { normalizeContactEmail } from "@aglyn/aglyn/app-utils/contacts";
|
|
17
|
+
import { crmInboundExcerpt, emailAddressOf } from "@aglyn/aglyn/app-utils/crm-inbound";
|
|
18
|
+
import { outreachMessageIdHeader } from "../engine/compose.js";
|
|
19
|
+
import { readOutreachDeliveryReport } from "../engine/delivery-status.js";
|
|
20
|
+
import { effectiveOutreachWindow, postponeOutreachForAutoReply } from "../engine/schedule.js";
|
|
21
|
+
import { decideOutreachThread } from "../engine/thread-classification.js";
|
|
22
|
+
import { outreachHeader, outreachThreadMessageFromGmail } from "../engine/thread-message.js";
|
|
23
|
+
import { mailboxRef } from "../mailboxes/mailbox-credentials.js";
|
|
24
|
+
import { markOutreachMailboxReconnectRequired } from "../mailboxes/mailbox-transport.js";
|
|
25
|
+
import { OUTREACH_COLLECTIONS } from "../model/outreach.types.js";
|
|
26
|
+
import { addOutreachDoNotContact } from "../storage/do-not-contact-store.js";
|
|
27
|
+
import { outreachOrgCollection, readStoredOutreachEnrollment, readStoredOutreachMailbox, readStoredOutreachSequence } from "../storage/outreach-records.js";
|
|
28
|
+
import { GmailTransportError, isReconnectRequired } from "../transport/gmail-errors.js";
|
|
29
|
+
import { applyOutreachEvent, recordOutreachOptOut } from "./enrollment-events.js";
|
|
30
|
+
import { applyOutreachMailboxHealth, emptyOutreachHealthDelta } from "./mailbox-health-store.js";
|
|
31
|
+
import { fileOutreachEmail, fileOutreachTask } from "./timeline.js";
|
|
32
|
+
import { outreachUnsubscribeMailbox } from "./unsubscribe-link.js";
|
|
33
|
+
/*==========================================
|
|
34
|
+
* THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.
|
|
35
|
+
*
|
|
36
|
+
* For each connected or paused mailbox, what came back since the last run —
|
|
37
|
+
* read with `format=full`, turned into the engine's message shape and
|
|
38
|
+
* classified by `decideOutreachThread`:
|
|
39
|
+
*
|
|
40
|
+
* - a REPLY stops the enrollment, files the message on the contact's
|
|
41
|
+
* timeline (once per `Message-ID`, under the capture address's own id for
|
|
42
|
+
* it) and gives the rep the task "Reply from <name>";
|
|
43
|
+
* - an OUT-OF-OFFICE postpones the next step a working week from the reply;
|
|
44
|
+
* - an OPT-OUT — a reply asking to be left alone, or a message to the
|
|
45
|
+
* `+unsubscribe` address the `mailto:` names — puts the address on the
|
|
46
|
+
* organization's do-not-contact list and off the site's `sales` topic,
|
|
47
|
+
* and stops every open enrollment of it;
|
|
48
|
+
* - a HARD BOUNCE stops the enrollment, files the address on the platform's
|
|
49
|
+
* suppression list and the do-not-contact list.
|
|
50
|
+
*
|
|
51
|
+
* Four reads find those, each narrowed by Gmail rather than read in full:
|
|
52
|
+
* the threads of this mailbox's enrollments that have new mail; delivery
|
|
53
|
+
* reports outside those threads (a receiving server's own bounce), by
|
|
54
|
+
* searching for the mail systems that send them; messages to the
|
|
55
|
+
* unsubscribe address; and messages from the people this mailbox is
|
|
56
|
+
* writing to, in a thread of their own.
|
|
57
|
+
*
|
|
58
|
+
* Every write it makes is idempotent — the do-not-contact list keeps its
|
|
59
|
+
* first entry, a topic opt-out keeps its first moment, a timeline entry is
|
|
60
|
+
* filed once per message — and the messages it handled are marked AFTER
|
|
61
|
+
* their effects, on the enrollment and on the mailbox, so a run that dies
|
|
62
|
+
* part-way repeats harmless work rather than skipping some. The mailbox's
|
|
63
|
+
* health takes the run's bounces and complaints in one write at the end,
|
|
64
|
+
* which is where it pauses itself.
|
|
65
|
+
*==========================================*/ export { OUTREACH_SYNC_JOB_ID } from "../constants/runtime-jobs.js";
|
|
66
|
+
/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */ export const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60000;
|
|
67
|
+
/** How far a run reads back past the previous one, for mail Gmail indexed late. */ export const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60000;
|
|
68
|
+
/** How long after its last send an enrollment's mail is still watched. */ export const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60000;
|
|
69
|
+
/** The most pages of one search a run reads. */ const SEARCH_PAGES = 5;
|
|
70
|
+
/** Handled message ids a mailbox keeps, and an enrollment keeps. */ const MAILBOX_HANDLED_MAX = 500;
|
|
71
|
+
const ENROLLMENT_HANDLED_MAX = 100;
|
|
72
|
+
/** Addresses in one `from:` search. */ const FROM_CHUNK = 15;
|
|
73
|
+
/** Runs the sync job once — see the module note. */ export async function runOutreachSyncJob(deps, context) {
|
|
74
|
+
const firestore = deps.firestore();
|
|
75
|
+
const report = {
|
|
76
|
+
mailboxes: 0,
|
|
77
|
+
threads: 0,
|
|
78
|
+
replies: 0,
|
|
79
|
+
optOuts: 0,
|
|
80
|
+
bounces: 0,
|
|
81
|
+
postponed: 0,
|
|
82
|
+
paused: 0
|
|
83
|
+
};
|
|
84
|
+
const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get();
|
|
85
|
+
const byOrg = new Map();
|
|
86
|
+
for (const doc of all.docs){
|
|
87
|
+
var _byOrg_get;
|
|
88
|
+
var _doc_ref_parent_parent;
|
|
89
|
+
const orgId = (_doc_ref_parent_parent = doc.ref.parent.parent) == null ? void 0 : _doc_ref_parent_parent.id;
|
|
90
|
+
const mailbox = readStoredOutreachMailbox(doc.id, doc.data());
|
|
91
|
+
if (!orgId || !mailbox || mailbox.status !== 'connected' && mailbox.status !== 'paused') continue;
|
|
92
|
+
byOrg.set(orgId, [
|
|
93
|
+
...(_byOrg_get = byOrg.get(orgId)) != null ? _byOrg_get : [],
|
|
94
|
+
mailbox
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
for (const [orgId, mailboxes] of byOrg){
|
|
98
|
+
if (deps.now() >= context.deadlineMs) break;
|
|
99
|
+
const orgSnapshot = await firestore.collection('orgs').doc(orgId).get();
|
|
100
|
+
const org = orgSnapshot.exists ? orgSnapshot.data() : null;
|
|
101
|
+
if (!org || await deps.orgRefusal(orgId, org)) continue;
|
|
102
|
+
for (const mailbox of mailboxes){
|
|
103
|
+
if (deps.now() >= context.deadlineMs) break;
|
|
104
|
+
try {
|
|
105
|
+
await syncMailbox(deps, firestore, {
|
|
106
|
+
orgId,
|
|
107
|
+
mailbox,
|
|
108
|
+
report,
|
|
109
|
+
nowMs: context.nowMs
|
|
110
|
+
});
|
|
111
|
+
report.mailboxes += 1;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
// One mailbox's failure is its own; the next mailbox is read. A grant
|
|
114
|
+
// Google refused is the mailbox's to reconnect.
|
|
115
|
+
if (isReconnectRequired(error)) {
|
|
116
|
+
await markOutreachMailboxReconnectRequired(firestore, {
|
|
117
|
+
orgId,
|
|
118
|
+
mailboxId: mailbox.id,
|
|
119
|
+
errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',
|
|
120
|
+
nowMs: context.nowMs
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
console.error('[outreach] syncing a mailbox failed', error);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return report;
|
|
128
|
+
}
|
|
129
|
+
/** Every stub a search finds, a few pages deep. */ async function search(client, q) {
|
|
130
|
+
const found = [];
|
|
131
|
+
let pageToken = null;
|
|
132
|
+
for(let page = 0; page < SEARCH_PAGES; page += 1){
|
|
133
|
+
const list = await client.listMessages({
|
|
134
|
+
q,
|
|
135
|
+
maxResults: 100,
|
|
136
|
+
pageToken,
|
|
137
|
+
includeSpamTrash: true
|
|
138
|
+
});
|
|
139
|
+
found.push(...list.messages.filter((message)=>message.id));
|
|
140
|
+
pageToken = list.nextPageToken;
|
|
141
|
+
if (!pageToken) break;
|
|
142
|
+
}
|
|
143
|
+
return found;
|
|
144
|
+
}
|
|
145
|
+
async function syncMailbox(deps, firestore, input) {
|
|
146
|
+
var _mailbox_sendAsOptions, _ref, _ref1, _ref2;
|
|
147
|
+
var _mailbox_sync, _mailbox_sync1, _mailbox_sync2;
|
|
148
|
+
const { orgId, mailbox, report, nowMs } = input;
|
|
149
|
+
const opened = await deps.openMailbox(mailbox.id);
|
|
150
|
+
if (opened.ok === false) {
|
|
151
|
+
if (opened.reason !== 'not-configured') {
|
|
152
|
+
await markOutreachMailboxReconnectRequired(firestore, {
|
|
153
|
+
orgId,
|
|
154
|
+
mailboxId: mailbox.id,
|
|
155
|
+
errorCode: opened.reason,
|
|
156
|
+
nowMs
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const unsubscribe = outreachUnsubscribeMailbox(mailbox.email);
|
|
162
|
+
const context = {
|
|
163
|
+
deps,
|
|
164
|
+
firestore,
|
|
165
|
+
orgId,
|
|
166
|
+
mailbox,
|
|
167
|
+
client: opened.client,
|
|
168
|
+
selfAddresses: [
|
|
169
|
+
mailbox.email,
|
|
170
|
+
mailbox.sendAs,
|
|
171
|
+
...((_mailbox_sendAsOptions = mailbox.sendAsOptions) != null ? _mailbox_sendAsOptions : []).map((option)=>option.email)
|
|
172
|
+
].filter(Boolean),
|
|
173
|
+
unsubscribeAddress: (_ref = unsubscribe == null ? void 0 : unsubscribe.address) != null ? _ref : null,
|
|
174
|
+
sequences: new Map(),
|
|
175
|
+
delta: emptyOutreachHealthDelta(),
|
|
176
|
+
report,
|
|
177
|
+
nowMs
|
|
178
|
+
};
|
|
179
|
+
// The enrollments this mailbox is writing to, by thread and by address.
|
|
180
|
+
const watched = await outreachOrgCollection(firestore, orgId, 'enrollments').where('mailboxId', '==', mailbox.id).where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS).get();
|
|
181
|
+
const byThread = new Map();
|
|
182
|
+
const byAddress = new Map();
|
|
183
|
+
for (const doc of watched.docs){
|
|
184
|
+
var _enrollment_lastSentAtMs, _known_lastSentAtMs;
|
|
185
|
+
const enrollment = readStoredOutreachEnrollment(doc.id, doc.data());
|
|
186
|
+
if (!enrollment) continue;
|
|
187
|
+
for (const threadId of enrollment.gmailThreadIds)byThread.set(threadId, enrollment);
|
|
188
|
+
const known = byAddress.get(enrollment.email);
|
|
189
|
+
if (!known || ((_enrollment_lastSentAtMs = enrollment.lastSentAtMs) != null ? _enrollment_lastSentAtMs : 0) > ((_known_lastSentAtMs = known.lastSentAtMs) != null ? _known_lastSentAtMs : 0)) byAddress.set(enrollment.email, enrollment);
|
|
190
|
+
}
|
|
191
|
+
const sinceMs = Math.max(Number((_mailbox_sync = mailbox.sync) == null ? void 0 : _mailbox_sync.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS;
|
|
192
|
+
const after = `after:${Math.floor(sinceMs / 1000)}`;
|
|
193
|
+
// Every message this run or an earlier one handled outside an enrollment's
|
|
194
|
+
// thread; one message is handled once however many searches find it.
|
|
195
|
+
const handled = new Set((_ref1 = (_mailbox_sync1 = mailbox.sync) == null ? void 0 : _mailbox_sync1.handledMessageIds) != null ? _ref1 : []);
|
|
196
|
+
const newlyHandled = [];
|
|
197
|
+
const markHandled = (id)=>{
|
|
198
|
+
if (handled.has(id)) return;
|
|
199
|
+
handled.add(id);
|
|
200
|
+
newlyHandled.push(id);
|
|
201
|
+
};
|
|
202
|
+
const fresh = (stub)=>!handled.has(stub.id) && !byThread.has(stub.threadId);
|
|
203
|
+
// 1. The enrollments' own threads that have new mail.
|
|
204
|
+
const inbound = await search(context.client, `${after} -from:me`);
|
|
205
|
+
for (const threadId of new Set(inbound.map((stub)=>stub.threadId))){
|
|
206
|
+
const enrollment = byThread.get(threadId);
|
|
207
|
+
if (!enrollment) continue;
|
|
208
|
+
const thread = await context.client.getFullThread(threadId);
|
|
209
|
+
report.threads += 1;
|
|
210
|
+
await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail));
|
|
211
|
+
}
|
|
212
|
+
// 2. Delivery reports outside those threads: a receiving server's bounce.
|
|
213
|
+
for (const stub of (await search(context.client, `${after} from:(mailer-daemon OR postmaster)`))){
|
|
214
|
+
if (!fresh(stub)) continue;
|
|
215
|
+
const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id));
|
|
216
|
+
const delivery = readOutreachDeliveryReport(message);
|
|
217
|
+
if ((delivery == null ? void 0 : delivery.kind) === 'hard') {
|
|
218
|
+
for (const address of delivery.failedAddresses){
|
|
219
|
+
const enrollment = byAddress.get(address);
|
|
220
|
+
if (enrollment) await applyMessages(context, enrollment, [
|
|
221
|
+
message
|
|
222
|
+
]);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
markHandled(stub.id);
|
|
226
|
+
}
|
|
227
|
+
// 3. Messages to the unsubscribe address: whoever wrote asked to leave.
|
|
228
|
+
if (unsubscribe) {
|
|
229
|
+
for (const stub of (await search(context.client, `${after} to:${unsubscribe.address}`))){
|
|
230
|
+
var _ref3;
|
|
231
|
+
var _metadata_headers_find;
|
|
232
|
+
if (handled.has(stub.id)) continue;
|
|
233
|
+
const metadata = await context.client.getMessage(stub.id, {
|
|
234
|
+
metadataHeaders: [
|
|
235
|
+
'From'
|
|
236
|
+
]
|
|
237
|
+
});
|
|
238
|
+
const from = emailAddressOf((_ref3 = (_metadata_headers_find = metadata.headers.find((header)=>header.name.toLowerCase() === 'from')) == null ? void 0 : _metadata_headers_find.value) != null ? _ref3 : '');
|
|
239
|
+
const address = normalizeContactEmail(from);
|
|
240
|
+
if (address && !context.selfAddresses.includes(address)) {
|
|
241
|
+
var _byAddress_get;
|
|
242
|
+
const enrollment = (_byAddress_get = byAddress.get(address)) != null ? _byAddress_get : null;
|
|
243
|
+
await recordOutreachOptOut(deps, {
|
|
244
|
+
orgId,
|
|
245
|
+
email: address,
|
|
246
|
+
source: 'unsubscribe',
|
|
247
|
+
enrollment,
|
|
248
|
+
hostIds: enrollment ? [
|
|
249
|
+
enrollment.hostId
|
|
250
|
+
] : [],
|
|
251
|
+
detail: 'Wrote to the unsubscribe address.',
|
|
252
|
+
nowMs
|
|
253
|
+
});
|
|
254
|
+
report.optOuts += 1;
|
|
255
|
+
}
|
|
256
|
+
markHandled(stub.id);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
// 4. The people this mailbox writes to, answering in a thread of their own.
|
|
260
|
+
const addresses = [
|
|
261
|
+
...byAddress.keys()
|
|
262
|
+
];
|
|
263
|
+
for(let start = 0; start < addresses.length; start += FROM_CHUNK){
|
|
264
|
+
const chunk = addresses.slice(start, start + FROM_CHUNK);
|
|
265
|
+
for (const stub of (await search(context.client, `${after} from:(${chunk.join(' OR ')})`))){
|
|
266
|
+
var _normalizeContactEmail;
|
|
267
|
+
if (!fresh(stub)) continue;
|
|
268
|
+
const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id));
|
|
269
|
+
const enrollment = byAddress.get((_normalizeContactEmail = normalizeContactEmail(emailAddressOf(message.from))) != null ? _normalizeContactEmail : '');
|
|
270
|
+
if (enrollment) await applyMessages(context, enrollment, [
|
|
271
|
+
message
|
|
272
|
+
]);
|
|
273
|
+
markHandled(stub.id);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const paused = await applyOutreachMailboxHealth(deps, {
|
|
277
|
+
orgId,
|
|
278
|
+
mailboxId: mailbox.id,
|
|
279
|
+
delta: context.delta
|
|
280
|
+
});
|
|
281
|
+
if (paused) report.paused += 1;
|
|
282
|
+
await mailboxRef(firestore, orgId, mailbox.id).update({
|
|
283
|
+
sync: {
|
|
284
|
+
throughMs: nowMs,
|
|
285
|
+
handledMessageIds: [
|
|
286
|
+
...(_ref2 = (_mailbox_sync2 = mailbox.sync) == null ? void 0 : _mailbox_sync2.handledMessageIds) != null ? _ref2 : [],
|
|
287
|
+
...newlyHandled
|
|
288
|
+
].slice(-MAILBOX_HANDLED_MAX)
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/** The sequence an enrollment runs through, read once per run. */ async function sequenceOf(context, sequenceId) {
|
|
293
|
+
var _context_sequences_get;
|
|
294
|
+
if (!context.sequences.has(sequenceId)) {
|
|
295
|
+
const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get();
|
|
296
|
+
context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined));
|
|
297
|
+
}
|
|
298
|
+
return (_context_sequences_get = context.sequences.get(sequenceId)) != null ? _context_sequences_get : null;
|
|
299
|
+
}
|
|
300
|
+
/** A message's `Message-ID` in header form, or `null` when it carries none. */ const messageIdOf = (message)=>outreachMessageIdHeader(outreachHeader(message, 'Message-ID'));
|
|
301
|
+
/** A bounce's diagnostic with the recipient's address taken out of it. */ export function scrubbedOutreachDiagnostic(diagnostic, email) {
|
|
302
|
+
if (!diagnostic) return null;
|
|
303
|
+
const pattern = new RegExp(email.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
|
|
304
|
+
return diagnostic.replace(pattern, 'the address');
|
|
305
|
+
}
|
|
306
|
+
/** Files a message the person wrote on their timeline. */ async function fileInbound(context, enrollment, message) {
|
|
307
|
+
var _emailAddressOf, _ref, _message_textBody, _message_htmlBody;
|
|
308
|
+
const messageId = messageIdOf(message);
|
|
309
|
+
if (!messageId) return;
|
|
310
|
+
await fileOutreachEmail(context.deps, {
|
|
311
|
+
orgId: context.orgId,
|
|
312
|
+
hostId: enrollment.hostId,
|
|
313
|
+
contactId: enrollment.contactId,
|
|
314
|
+
direction: 'inbound',
|
|
315
|
+
subject: message.subject,
|
|
316
|
+
from: (_emailAddressOf = emailAddressOf(message.from)) != null ? _emailAddressOf : message.from,
|
|
317
|
+
to: context.mailbox.sendAs || context.mailbox.email,
|
|
318
|
+
messageId,
|
|
319
|
+
inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),
|
|
320
|
+
body: crmInboundExcerpt((_ref = (_message_textBody = message.textBody) != null ? _message_textBody : message.snippet) != null ? _ref : '', (_message_htmlBody = message.htmlBody) != null ? _message_htmlBody : ''),
|
|
321
|
+
atMs: message.internalDateMs,
|
|
322
|
+
byUid: ''
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* What the new messages of one enrollment mean, done: the effects first,
|
|
327
|
+
* each idempotent, then the event and the handled ids in one transaction.
|
|
328
|
+
*/ async function applyMessages(context, enrollment, messages) {
|
|
329
|
+
var _enrollment_syncedMessageIds, _messages_find, _enrollment_messageIds_;
|
|
330
|
+
var _outcome_enrollment;
|
|
331
|
+
const { deps, firestore, report, nowMs } = context;
|
|
332
|
+
const decision = decideOutreachThread({
|
|
333
|
+
messages,
|
|
334
|
+
recipient: enrollment.email,
|
|
335
|
+
handledMessageIds: (_enrollment_syncedMessageIds = enrollment.syncedMessageIds) != null ? _enrollment_syncedMessageIds : [],
|
|
336
|
+
selfAddresses: context.selfAddresses,
|
|
337
|
+
unsubscribeAddress: context.unsubscribeAddress,
|
|
338
|
+
threadSubject: enrollment.threadSubject
|
|
339
|
+
});
|
|
340
|
+
const freshIds = decision.classifications.map((classification)=>classification.messageId).filter(Boolean);
|
|
341
|
+
if (!freshIds.length) return;
|
|
342
|
+
const decidedBy = decision.decidedBy;
|
|
343
|
+
const decidingMessage = decidedBy ? (_messages_find = messages.find((message)=>message.id === decidedBy.messageId)) != null ? _messages_find : null : null;
|
|
344
|
+
const lastSentMessageId = (_enrollment_messageIds_ = enrollment.messageIds[enrollment.messageIds.length - 1]) != null ? _enrollment_messageIds_ : null;
|
|
345
|
+
for (const classification of decision.classifications){
|
|
346
|
+
var _classification_bounce;
|
|
347
|
+
const aboutRecipient = !((_classification_bounce = classification.bounce) == null ? void 0 : _classification_bounce.recipients.length) || classification.bounce.recipients.includes(enrollment.email);
|
|
348
|
+
if (classification.kind === 'hard_bounce' && aboutRecipient) {
|
|
349
|
+
context.delta.bounces.push({
|
|
350
|
+
atMs: classification.atMs || nowMs,
|
|
351
|
+
messageId: lastSentMessageId
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
if (classification.complaint) {
|
|
355
|
+
var _context_delta_complaintAtMs;
|
|
356
|
+
context.delta.complaintAtMs = Math.max((_context_delta_complaintAtMs = context.delta.complaintAtMs) != null ? _context_delta_complaintAtMs : 0, classification.atMs || nowMs);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
let event = null;
|
|
360
|
+
let postponedTo = null;
|
|
361
|
+
switch(decision.outcome){
|
|
362
|
+
case 'opted_out':
|
|
363
|
+
{
|
|
364
|
+
var _ref;
|
|
365
|
+
var _decidedBy_evidence;
|
|
366
|
+
if (decidingMessage) await fileInbound(context, enrollment, decidingMessage);
|
|
367
|
+
await recordOutreachOptOut(deps, {
|
|
368
|
+
orgId: context.orgId,
|
|
369
|
+
email: enrollment.email,
|
|
370
|
+
source: (decidedBy == null ? void 0 : (_decidedBy_evidence = decidedBy.evidence) == null ? void 0 : _decidedBy_evidence.startsWith('To:')) ? 'unsubscribe' : 'opt_out_reply',
|
|
371
|
+
enrollment,
|
|
372
|
+
hostIds: [
|
|
373
|
+
enrollment.hostId
|
|
374
|
+
],
|
|
375
|
+
detail: (_ref = decidedBy == null ? void 0 : decidedBy.evidence) != null ? _ref : null,
|
|
376
|
+
nowMs
|
|
377
|
+
});
|
|
378
|
+
report.optOuts += 1;
|
|
379
|
+
break;
|
|
380
|
+
}
|
|
381
|
+
case 'replied':
|
|
382
|
+
{
|
|
383
|
+
var _ref1;
|
|
384
|
+
if (decidingMessage) {
|
|
385
|
+
await fileInbound(context, enrollment, decidingMessage);
|
|
386
|
+
try {
|
|
387
|
+
var _messageIdOf, _ref2, _decidingMessage_textBody, _decidingMessage_htmlBody;
|
|
388
|
+
await fileOutreachTask(deps, {
|
|
389
|
+
orgId: context.orgId,
|
|
390
|
+
hostId: enrollment.hostId,
|
|
391
|
+
contactId: enrollment.contactId,
|
|
392
|
+
dedupeKey: `reply:${(_messageIdOf = messageIdOf(decidingMessage)) != null ? _messageIdOf : decidingMessage.id}`,
|
|
393
|
+
title: `Reply from ${enrollment.contactName || enrollment.email}`,
|
|
394
|
+
notes: crmInboundExcerpt((_ref2 = (_decidingMessage_textBody = decidingMessage.textBody) != null ? _decidingMessage_textBody : decidingMessage.snippet) != null ? _ref2 : '', (_decidingMessage_htmlBody = decidingMessage.htmlBody) != null ? _decidingMessage_htmlBody : '').slice(0, 500),
|
|
395
|
+
kind: 'email',
|
|
396
|
+
dueAtMs: nowMs,
|
|
397
|
+
assigneeUid: context.mailbox.connectedByUid
|
|
398
|
+
});
|
|
399
|
+
} catch (error) {
|
|
400
|
+
console.error('[outreach] the reply task could not be filed', error);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
context.delta.replies += 1;
|
|
404
|
+
event = {
|
|
405
|
+
type: 'reply',
|
|
406
|
+
atMs: (decidedBy == null ? void 0 : decidedBy.atMs) || nowMs,
|
|
407
|
+
detail: (_ref1 = decidedBy == null ? void 0 : decidedBy.evidence) != null ? _ref1 : null
|
|
408
|
+
};
|
|
409
|
+
report.replies += 1;
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
case 'bounced':
|
|
413
|
+
{
|
|
414
|
+
var _ref3, _ref4;
|
|
415
|
+
var _decidedBy_bounce, _decidedBy_bounce1;
|
|
416
|
+
const diagnostic = scrubbedOutreachDiagnostic((_ref3 = (_ref4 = decidedBy == null ? void 0 : (_decidedBy_bounce = decidedBy.bounce) == null ? void 0 : _decidedBy_bounce.diagnostic) != null ? _ref4 : decidedBy == null ? void 0 : (_decidedBy_bounce1 = decidedBy.bounce) == null ? void 0 : _decidedBy_bounce1.status) != null ? _ref3 : null, enrollment.email);
|
|
417
|
+
await deps.suppressBouncedEmail({
|
|
418
|
+
email: enrollment.email,
|
|
419
|
+
hostId: enrollment.hostId
|
|
420
|
+
});
|
|
421
|
+
await addOutreachDoNotContact(firestore, {
|
|
422
|
+
orgId: context.orgId,
|
|
423
|
+
email: enrollment.email,
|
|
424
|
+
reason: 'hard_bounce',
|
|
425
|
+
source: 'runtime',
|
|
426
|
+
nowMs,
|
|
427
|
+
enrollmentId: enrollment.id,
|
|
428
|
+
sequenceId: enrollment.sequenceId,
|
|
429
|
+
detail: diagnostic
|
|
430
|
+
});
|
|
431
|
+
event = {
|
|
432
|
+
type: 'bounce',
|
|
433
|
+
atMs: (decidedBy == null ? void 0 : decidedBy.atMs) || nowMs,
|
|
434
|
+
detail: diagnostic
|
|
435
|
+
};
|
|
436
|
+
report.bounces += 1;
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
case 'postpone':
|
|
440
|
+
{
|
|
441
|
+
const sequence = await sequenceOf(context, enrollment.sequenceId);
|
|
442
|
+
postponedTo = postponeOutreachForAutoReply({
|
|
443
|
+
nextDueAtMs: enrollment.nextDueAtMs,
|
|
444
|
+
receivedAtMs: (decidedBy == null ? void 0 : decidedBy.atMs) || nowMs,
|
|
445
|
+
timeZone: context.mailbox.timezone,
|
|
446
|
+
window: effectiveOutreachWindow(sequence == null ? void 0 : sequence.settings.window, context.mailbox.window),
|
|
447
|
+
random: deps.random
|
|
448
|
+
});
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
default:
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
const outcome = await applyOutreachEvent(firestore, {
|
|
455
|
+
orgId: context.orgId,
|
|
456
|
+
enrollmentId: enrollment.id,
|
|
457
|
+
event,
|
|
458
|
+
extra: (current)=>{
|
|
459
|
+
var _current_syncedMessageIds;
|
|
460
|
+
const extra = {
|
|
461
|
+
syncedMessageIds: [
|
|
462
|
+
...(_current_syncedMessageIds = current.syncedMessageIds) != null ? _current_syncedMessageIds : [],
|
|
463
|
+
...freshIds
|
|
464
|
+
].slice(-ENROLLMENT_HANDLED_MAX)
|
|
465
|
+
};
|
|
466
|
+
const waiting = current.status === 'active' || current.status === 'paused';
|
|
467
|
+
if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {
|
|
468
|
+
extra['nextDueAtMs'] = postponedTo;
|
|
469
|
+
}
|
|
470
|
+
return extra;
|
|
471
|
+
},
|
|
472
|
+
nowMs
|
|
473
|
+
});
|
|
474
|
+
if (postponedTo !== null && ((_outcome_enrollment = outcome.enrollment) == null ? void 0 : _outcome_enrollment.nextDueAtMs) === postponedTo) report.postponed += 1;
|
|
475
|
+
// The run's own view of the enrollment moves with it, so a second message
|
|
476
|
+
// of it in this run is judged against what this one did.
|
|
477
|
+
if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
//# sourceMappingURL=sync-job.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/sync-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 { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmInboundExcerpt, emailAddressOf } from '@aglyn/aglyn/app-utils/crm-inbound'\nimport { outreachMessageIdHeader } from '../engine/compose'\nimport { readOutreachDeliveryReport } from '../engine/delivery-status'\nimport type { OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { effectiveOutreachWindow, postponeOutreachForAutoReply } from '../engine/schedule'\nimport {\n decideOutreachThread,\n type OutreachMessageClassification,\n type OutreachThreadDecision,\n} from '../engine/thread-classification'\nimport { outreachHeader, outreachThreadMessageFromGmail, type OutreachThreadMessage } from '../engine/thread-message'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { markOutreachMailboxReconnectRequired } from '../mailboxes/mailbox-transport'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n} from '../model/outreach.types'\nimport { addOutreachDoNotContact } from '../storage/do-not-contact-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport type { GmailClient } from '../transport/gmail-client'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { applyOutreachEvent, recordOutreachOptOut } from './enrollment-events'\nimport {\n applyOutreachMailboxHealth,\n emptyOutreachHealthDelta,\n type OutreachMailboxHealthDelta,\n} from './mailbox-health-store'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { fileOutreachEmail, fileOutreachTask } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * For each connected or paused mailbox, what came back since the last run —\n * read with `format=full`, turned into the engine's message shape and\n * classified by `decideOutreachThread`:\n *\n * - a REPLY stops the enrollment, files the message on the contact's\n * timeline (once per `Message-ID`, under the capture address's own id for\n * it) and gives the rep the task \"Reply from <name>\";\n * - an OUT-OF-OFFICE postpones the next step a working week from the reply;\n * - an OPT-OUT — a reply asking to be left alone, or a message to the\n * `+unsubscribe` address the `mailto:` names — puts the address on the\n * organization's do-not-contact list and off the site's `sales` topic,\n * and stops every open enrollment of it;\n * - a HARD BOUNCE stops the enrollment, files the address on the platform's\n * suppression list and the do-not-contact list.\n *\n * Four reads find those, each narrowed by Gmail rather than read in full:\n * the threads of this mailbox's enrollments that have new mail; delivery\n * reports outside those threads (a receiving server's own bounce), by\n * searching for the mail systems that send them; messages to the\n * unsubscribe address; and messages from the people this mailbox is\n * writing to, in a thread of their own.\n *\n * Every write it makes is idempotent — the do-not-contact list keeps its\n * first entry, a topic opt-out keeps its first moment, a timeline entry is\n * filed once per message — and the messages it handled are marked AFTER\n * their effects, on the enrollment and on the mailbox, so a run that dies\n * part-way repeats harmless work rather than skipping some. The mailbox's\n * health takes the run's bounces and complaints in one write at the end,\n * which is where it pauses itself.\n *==========================================*/\n\nexport { OUTREACH_SYNC_JOB_ID } from '../constants/runtime-jobs'\n\n/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */\nexport const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60_000\n\n/** How far a run reads back past the previous one, for mail Gmail indexed late. */\nexport const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60_000\n\n/** How long after its last send an enrollment's mail is still watched. */\nexport const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60_000\n\n/** The most pages of one search a run reads. */\nconst SEARCH_PAGES = 5\n/** Handled message ids a mailbox keeps, and an enrollment keeps. */\nconst MAILBOX_HANDLED_MAX = 500\nconst ENROLLMENT_HANDLED_MAX = 100\n/** Addresses in one `from:` search. */\nconst FROM_CHUNK = 15\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OutreachSyncReport {\n [key: string]: number\n mailboxes: number\n threads: number\n replies: number\n optOuts: number\n bounces: number\n postponed: number\n paused: number\n}\n\ninterface SyncContext {\n deps: OutreachRuntimeDeps\n firestore: Firestore\n orgId: string\n mailbox: OutreachMailbox\n client: GmailClient\n selfAddresses: string[]\n unsubscribeAddress: string | null\n sequences: Map<string, OutreachSequence | null>\n delta: OutreachMailboxHealthDelta\n report: OutreachSyncReport\n nowMs: number\n}\n\n/** Runs the sync job once — see the module note. */\nexport async function runOutreachSyncJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSyncReport> {\n const firestore = deps.firestore()\n const report: OutreachSyncReport = {\n mailboxes: 0,\n threads: 0,\n replies: 0,\n optOuts: 0,\n bounces: 0,\n postponed: 0,\n paused: 0,\n }\n const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get()\n const byOrg = new Map<string, OutreachMailbox[]>()\n for (const doc of all.docs) {\n const orgId = doc.ref.parent.parent?.id\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!orgId || !mailbox || (mailbox.status !== 'connected' && mailbox.status !== 'paused')) continue\n byOrg.set(orgId, [...(byOrg.get(orgId) ?? []), mailbox])\n }\n for (const [orgId, mailboxes] of byOrg) {\n if (deps.now() >= context.deadlineMs) break\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))) continue\n for (const mailbox of mailboxes) {\n if (deps.now() >= context.deadlineMs) break\n try {\n await syncMailbox(deps, firestore, { orgId, mailbox, report, nowMs: context.nowMs })\n report.mailboxes += 1\n } catch (error) {\n // One mailbox's failure is its own; the next mailbox is read. A grant\n // Google refused is the mailbox's to reconnect.\n if (isReconnectRequired(error)) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',\n nowMs: context.nowMs,\n })\n }\n console.error('[outreach] syncing a mailbox failed', error)\n }\n }\n }\n return report\n}\n\n/** Every stub a search finds, a few pages deep. */\nasync function search(\n client: GmailClient,\n q: string,\n): Promise<Array<{ id: string; threadId: string }>> {\n const found: Array<{ id: string; threadId: string }> = []\n let pageToken: string | null = null\n for (let page = 0; page < SEARCH_PAGES; page += 1) {\n const list = await client.listMessages({ q, maxResults: 100, pageToken, includeSpamTrash: true })\n found.push(...list.messages.filter((message) => message.id))\n pageToken = list.nextPageToken\n if (!pageToken) break\n }\n return found\n}\n\nasync function syncMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: { orgId: string; mailbox: OutreachMailbox; report: OutreachSyncReport; nowMs: number },\n): Promise<void> {\n const { orgId, mailbox, report, nowMs } = input\n const opened = await deps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason !== 'not-configured') {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n }\n return\n }\n const unsubscribe = outreachUnsubscribeMailbox(mailbox.email)\n const context: SyncContext = {\n deps,\n firestore,\n orgId,\n mailbox,\n client: opened.client,\n selfAddresses: [\n mailbox.email,\n mailbox.sendAs,\n ...(mailbox.sendAsOptions ?? []).map((option) => option.email),\n ].filter(Boolean),\n unsubscribeAddress: unsubscribe?.address ?? null,\n sequences: new Map(),\n delta: emptyOutreachHealthDelta(),\n report,\n nowMs,\n }\n\n // The enrollments this mailbox is writing to, by thread and by address.\n const watched = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('mailboxId', '==', mailbox.id)\n .where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n .get()\n const byThread = new Map<string, OutreachEnrollment>()\n const byAddress = new Map<string, OutreachEnrollment>()\n for (const doc of watched.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment) continue\n for (const threadId of enrollment.gmailThreadIds) byThread.set(threadId, enrollment)\n const known = byAddress.get(enrollment.email)\n if (!known || (enrollment.lastSentAtMs ?? 0) > (known.lastSentAtMs ?? 0)) byAddress.set(enrollment.email, enrollment)\n }\n\n const sinceMs = Math.max(Number(mailbox.sync?.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS\n const after = `after:${Math.floor(sinceMs / 1000)}`\n // Every message this run or an earlier one handled outside an enrollment's\n // thread; one message is handled once however many searches find it.\n const handled = new Set(mailbox.sync?.handledMessageIds ?? [])\n const newlyHandled: string[] = []\n const markHandled = (id: string) => {\n if (handled.has(id)) return\n handled.add(id)\n newlyHandled.push(id)\n }\n const fresh = (stub: { id: string; threadId: string }) => !handled.has(stub.id) && !byThread.has(stub.threadId)\n\n // 1. The enrollments' own threads that have new mail.\n const inbound = await search(context.client, `${after} -from:me`)\n for (const threadId of new Set(inbound.map((stub) => stub.threadId))) {\n const enrollment = byThread.get(threadId)\n if (!enrollment) continue\n const thread = await context.client.getFullThread(threadId)\n report.threads += 1\n await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail))\n }\n\n // 2. Delivery reports outside those threads: a receiving server's bounce.\n for (const stub of await search(context.client, `${after} from:(mailer-daemon OR postmaster)`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const delivery = readOutreachDeliveryReport(message)\n if (delivery?.kind === 'hard') {\n for (const address of delivery.failedAddresses) {\n const enrollment = byAddress.get(address)\n if (enrollment) await applyMessages(context, enrollment, [message])\n }\n }\n markHandled(stub.id)\n }\n\n // 3. Messages to the unsubscribe address: whoever wrote asked to leave.\n if (unsubscribe) {\n for (const stub of await search(context.client, `${after} to:${unsubscribe.address}`)) {\n if (handled.has(stub.id)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: ['From'] })\n const from = emailAddressOf(metadata.headers.find((header) => header.name.toLowerCase() === 'from')?.value ?? '')\n const address = normalizeContactEmail(from)\n if (address && !context.selfAddresses.includes(address)) {\n const enrollment = byAddress.get(address) ?? null\n await recordOutreachOptOut(deps, {\n orgId,\n email: address,\n source: 'unsubscribe',\n enrollment,\n hostIds: enrollment ? [enrollment.hostId] : [],\n detail: 'Wrote to the unsubscribe address.',\n nowMs,\n })\n report.optOuts += 1\n }\n markHandled(stub.id)\n }\n }\n\n // 4. The people this mailbox writes to, answering in a thread of their own.\n const addresses = [...byAddress.keys()]\n for (let start = 0; start < addresses.length; start += FROM_CHUNK) {\n const chunk = addresses.slice(start, start + FROM_CHUNK)\n for (const stub of await search(context.client, `${after} from:(${chunk.join(' OR ')})`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const enrollment = byAddress.get(normalizeContactEmail(emailAddressOf(message.from)) ?? '')\n if (enrollment) await applyMessages(context, enrollment, [message])\n markHandled(stub.id)\n }\n }\n\n const paused = await applyOutreachMailboxHealth(deps, { orgId, mailboxId: mailbox.id, delta: context.delta })\n if (paused) report.paused += 1\n await mailboxRef(firestore, orgId, mailbox.id).update({\n sync: {\n throughMs: nowMs,\n handledMessageIds: [...(mailbox.sync?.handledMessageIds ?? []), ...newlyHandled].slice(-MAILBOX_HANDLED_MAX),\n },\n })\n}\n\n/** The sequence an enrollment runs through, read once per run. */\nasync function sequenceOf(context: SyncContext, sequenceId: string): Promise<OutreachSequence | null> {\n if (!context.sequences.has(sequenceId)) {\n const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get()\n context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined))\n }\n return context.sequences.get(sequenceId) ?? null\n}\n\n/** A message's `Message-ID` in header form, or `null` when it carries none. */\nconst messageIdOf = (message: OutreachThreadMessage) => outreachMessageIdHeader(outreachHeader(message, 'Message-ID'))\n\n/** A bounce's diagnostic with the recipient's address taken out of it. */\nexport function scrubbedOutreachDiagnostic(diagnostic: string | null, email: string): string | null {\n if (!diagnostic) return null\n const pattern = new RegExp(email.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi')\n return diagnostic.replace(pattern, 'the address')\n}\n\n/** Files a message the person wrote on their timeline. */\nasync function fileInbound(context: SyncContext, enrollment: OutreachEnrollment, message: OutreachThreadMessage) {\n const messageId = messageIdOf(message)\n if (!messageId) return\n await fileOutreachEmail(context.deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n contactId: enrollment.contactId,\n direction: 'inbound',\n subject: message.subject,\n from: emailAddressOf(message.from) ?? message.from,\n to: context.mailbox.sendAs || context.mailbox.email,\n messageId,\n inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),\n body: crmInboundExcerpt(message.textBody ?? message.snippet ?? '', message.htmlBody ?? ''),\n atMs: message.internalDateMs,\n byUid: '',\n })\n}\n\n/**\n * What the new messages of one enrollment mean, done: the effects first,\n * each idempotent, then the event and the handled ids in one transaction.\n */\nasync function applyMessages(\n context: SyncContext,\n enrollment: OutreachEnrollment,\n messages: readonly OutreachThreadMessage[],\n): Promise<void> {\n const { deps, firestore, report, nowMs } = context\n const decision: OutreachThreadDecision = decideOutreachThread({\n messages,\n recipient: enrollment.email,\n handledMessageIds: enrollment.syncedMessageIds ?? [],\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const freshIds = decision.classifications.map((classification) => classification.messageId).filter(Boolean)\n if (!freshIds.length) return\n const decidedBy: OutreachMessageClassification | null = decision.decidedBy\n const decidingMessage = decidedBy ? messages.find((message) => message.id === decidedBy.messageId) ?? null : null\n const lastSentMessageId = enrollment.messageIds[enrollment.messageIds.length - 1] ?? null\n\n for (const classification of decision.classifications) {\n const aboutRecipient =\n !classification.bounce?.recipients.length || classification.bounce.recipients.includes(enrollment.email)\n if (classification.kind === 'hard_bounce' && aboutRecipient) {\n context.delta.bounces.push({ atMs: classification.atMs || nowMs, messageId: lastSentMessageId })\n }\n if (classification.complaint) {\n context.delta.complaintAtMs = Math.max(context.delta.complaintAtMs ?? 0, classification.atMs || nowMs)\n }\n }\n\n let event: OutreachEnrollmentEvent | null = null\n let postponedTo: number | null = null\n switch (decision.outcome) {\n case 'opted_out': {\n if (decidingMessage) await fileInbound(context, enrollment, decidingMessage)\n await recordOutreachOptOut(deps, {\n orgId: context.orgId,\n email: enrollment.email,\n source: decidedBy?.evidence?.startsWith('To:') ? 'unsubscribe' : 'opt_out_reply',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: decidedBy?.evidence ?? null,\n nowMs,\n })\n report.optOuts += 1\n break\n }\n case 'replied': {\n if (decidingMessage) {\n await fileInbound(context, enrollment, decidingMessage)\n try {\n await fileOutreachTask(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n contactId: enrollment.contactId,\n dedupeKey: `reply:${messageIdOf(decidingMessage) ?? decidingMessage.id}`,\n title: `Reply from ${enrollment.contactName || enrollment.email}`,\n notes: crmInboundExcerpt(decidingMessage.textBody ?? decidingMessage.snippet ?? '', decidingMessage.htmlBody ?? '').slice(0, 500),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: context.mailbox.connectedByUid,\n })\n } catch (error) {\n console.error('[outreach] the reply task could not be filed', error)\n }\n }\n context.delta.replies += 1\n event = { type: 'reply', atMs: decidedBy?.atMs || nowMs, detail: decidedBy?.evidence ?? null }\n report.replies += 1\n break\n }\n case 'bounced': {\n const diagnostic = scrubbedOutreachDiagnostic(decidedBy?.bounce?.diagnostic ?? decidedBy?.bounce?.status ?? null, enrollment.email)\n await deps.suppressBouncedEmail({ email: enrollment.email, hostId: enrollment.hostId })\n await addOutreachDoNotContact(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n reason: 'hard_bounce',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n event = { type: 'bounce', atMs: decidedBy?.atMs || nowMs, detail: diagnostic }\n report.bounces += 1\n break\n }\n case 'postpone': {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n postponedTo = postponeOutreachForAutoReply({\n nextDueAtMs: enrollment.nextDueAtMs,\n receivedAtMs: decidedBy?.atMs || nowMs,\n timeZone: context.mailbox.timezone,\n window: effectiveOutreachWindow(sequence?.settings.window, context.mailbox.window),\n random: deps.random,\n })\n break\n }\n default:\n break\n }\n\n const outcome = await applyOutreachEvent(firestore, {\n orgId: context.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: (current) => {\n const extra: Record<string, unknown> = {\n syncedMessageIds: [...(current.syncedMessageIds ?? []), ...freshIds].slice(-ENROLLMENT_HANDLED_MAX),\n }\n const waiting = current.status === 'active' || current.status === 'paused'\n if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {\n extra['nextDueAtMs'] = postponedTo\n }\n return extra\n },\n nowMs,\n })\n if (postponedTo !== null && outcome.enrollment?.nextDueAtMs === postponedTo) report.postponed += 1\n // The run's own view of the enrollment moves with it, so a second message\n // of it in this run is judged against what this one did.\n if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment)\n}\n"],"names":["normalizeContactEmail","crmInboundExcerpt","emailAddressOf","outreachMessageIdHeader","readOutreachDeliveryReport","effectiveOutreachWindow","postponeOutreachForAutoReply","decideOutreachThread","outreachHeader","outreachThreadMessageFromGmail","mailboxRef","markOutreachMailboxReconnectRequired","OUTREACH_COLLECTIONS","addOutreachDoNotContact","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","applyOutreachEvent","recordOutreachOptOut","applyOutreachMailboxHealth","emptyOutreachHealthDelta","fileOutreachEmail","fileOutreachTask","outreachUnsubscribeMailbox","OUTREACH_SYNC_JOB_ID","OUTREACH_SYNC_LOOKBACK_MS","OUTREACH_SYNC_OVERLAP_MS","OUTREACH_SYNC_WATCH_MS","SEARCH_PAGES","MAILBOX_HANDLED_MAX","ENROLLMENT_HANDLED_MAX","FROM_CHUNK","runOutreachSyncJob","deps","context","firestore","report","mailboxes","threads","replies","optOuts","bounces","postponed","paused","all","collectionGroup","get","byOrg","Map","doc","docs","orgId","ref","parent","id","mailbox","data","status","set","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","syncMailbox","nowMs","error","mailboxId","errorCode","code","console","search","client","q","found","pageToken","page","list","listMessages","maxResults","includeSpamTrash","push","messages","filter","message","nextPageToken","input","opened","openMailbox","ok","reason","unsubscribe","email","selfAddresses","sendAs","sendAsOptions","map","option","Boolean","unsubscribeAddress","address","sequences","delta","watched","where","byThread","byAddress","enrollment","known","threadId","gmailThreadIds","lastSentAtMs","sinceMs","Math","max","Number","sync","throughMs","after","floor","handled","Set","handledMessageIds","newlyHandled","markHandled","has","add","fresh","stub","inbound","thread","getFullThread","applyMessages","getFullMessage","delivery","kind","failedAddresses","metadata","getMessage","metadataHeaders","from","headers","find","header","name","toLowerCase","value","includes","source","hostIds","hostId","detail","addresses","keys","start","length","chunk","slice","join","update","sequenceOf","sequenceId","snapshot","undefined","messageIdOf","scrubbedOutreachDiagnostic","diagnostic","pattern","RegExp","replace","fileInbound","messageId","contactId","direction","subject","to","inReplyTo","body","textBody","snippet","htmlBody","atMs","internalDateMs","byUid","outcome","decision","recipient","syncedMessageIds","threadSubject","freshIds","classifications","classification","decidedBy","decidingMessage","lastSentMessageId","messageIds","aboutRecipient","bounce","recipients","complaint","complaintAtMs","event","postponedTo","evidence","startsWith","dedupeKey","title","contactName","notes","dueAtMs","assigneeUid","connectedByUid","type","suppressBouncedEmail","enrollmentId","sequence","nextDueAtMs","received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,QAAQ7E,UAAU,qBAAlB6E,oBAAoBgC,WAAW,MAAKd,aAAaxK,OAAOM,SAAS,IAAI;IACjG,0EAA0E;IAC1E,yDAAyD;IACzD,IAAIgJ,QAAQ7E,UAAU,EAAEuH,OAAOC,MAAM,CAACxH,YAAY6E,QAAQ7E,UAAU;AACtE"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { PluginRecordTaskKind, PluginRecordWrite } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline';
|
|
18
|
+
import type { OutreachTaskKind } from '../model/outreach.types';
|
|
19
|
+
import type { OutreachRuntimeDeps } from './runtime-deps';
|
|
20
|
+
/**
|
|
21
|
+
* OUTREACH ON THE CONTACT'S TIMELINE (AGL-2981).
|
|
22
|
+
*
|
|
23
|
+
* Every email a sequence sends, every reply it reads, and every task it
|
|
24
|
+
* asks of the rep goes onto the contact's record through the core's
|
|
25
|
+
* record-timeline seam — whichever plugin keeps the workspace's records —
|
|
26
|
+
* never by writing that plugin's documents. An email is filed once per
|
|
27
|
+
* `Message-ID`, under the id the capture address would file a forwarded copy
|
|
28
|
+
* by; a task once per the key given here.
|
|
29
|
+
*
|
|
30
|
+
* The timeline is bookkeeping beside the act: an email has already left
|
|
31
|
+
* when it is filed, so a writer that refuses or fails is logged and the
|
|
32
|
+
* send stands. A workspace with no record system files nothing.
|
|
33
|
+
*/
|
|
34
|
+
/** The record system's word for a step's task kind. */
|
|
35
|
+
export declare const OUTREACH_TASK_KIND_TO_RECORD: Record<OutreachTaskKind, PluginRecordTaskKind>;
|
|
36
|
+
/** Files one email on a contact; never throws. */
|
|
37
|
+
export declare function fileOutreachEmail(deps: Pick<OutreachRuntimeDeps, 'timeline'>, input: {
|
|
38
|
+
orgId: string;
|
|
39
|
+
hostId: string;
|
|
40
|
+
contactId: string;
|
|
41
|
+
direction: 'outbound' | 'inbound';
|
|
42
|
+
subject: string;
|
|
43
|
+
from: string;
|
|
44
|
+
to: string | null;
|
|
45
|
+
messageId: string;
|
|
46
|
+
inReplyTo?: string | null;
|
|
47
|
+
body: string;
|
|
48
|
+
atMs: number;
|
|
49
|
+
byUid: string;
|
|
50
|
+
byName?: string | null;
|
|
51
|
+
}): Promise<PluginRecordWrite | null>;
|
|
52
|
+
/**
|
|
53
|
+
* Files one task on a contact. Answers the record system's answer, `null`
|
|
54
|
+
* when the workspace keeps no records; a writer that THROWS is the caller's,
|
|
55
|
+
* which a step waits out rather than completing without its task.
|
|
56
|
+
*/
|
|
57
|
+
export declare function fileOutreachTask(deps: Pick<OutreachRuntimeDeps, 'timeline'>, input: {
|
|
58
|
+
orgId: string;
|
|
59
|
+
hostId: string;
|
|
60
|
+
contactId: string;
|
|
61
|
+
dedupeKey: string;
|
|
62
|
+
title: string;
|
|
63
|
+
notes?: string | null;
|
|
64
|
+
kind: PluginRecordTaskKind;
|
|
65
|
+
dueAtMs: number;
|
|
66
|
+
assigneeUid: string;
|
|
67
|
+
}): Promise<PluginRecordWrite | null>;
|