@memberjunction/communication-engine 6.3.0-edge.1 → 6.3.0-edge.3
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 +203 -0
- package/dist/CommsActivityWorker.d.ts +130 -0
- package/dist/CommsActivityWorker.d.ts.map +1 -0
- package/dist/CommsActivityWorker.js +1054 -0
- package/dist/CommsActivityWorker.js.map +1 -0
- package/dist/DefaultCommunicationPrincipal.d.ts +62 -0
- package/dist/DefaultCommunicationPrincipal.d.ts.map +1 -0
- package/dist/DefaultCommunicationPrincipal.js +382 -0
- package/dist/DefaultCommunicationPrincipal.js.map +1 -0
- package/dist/Engine.d.ts +54 -1
- package/dist/Engine.d.ts.map +1 -1
- package/dist/Engine.js +123 -2
- package/dist/Engine.js.map +1 -1
- package/dist/LocalJsonCommunicationProvider.d.ts +133 -0
- package/dist/LocalJsonCommunicationProvider.d.ts.map +1 -0
- package/dist/LocalJsonCommunicationProvider.js +1337 -0
- package/dist/LocalJsonCommunicationProvider.js.map +1 -0
- package/dist/V2SendService.d.ts +293 -0
- package/dist/V2SendService.d.ts.map +1 -0
- package/dist/V2SendService.js +2035 -0
- package/dist/V2SendService.js.map +1 -0
- package/dist/compliance/ComplianceGate.d.ts +56 -0
- package/dist/compliance/ComplianceGate.d.ts.map +1 -0
- package/dist/compliance/ComplianceGate.js +452 -0
- package/dist/compliance/ComplianceGate.js.map +1 -0
- package/dist/compliance/JurisdictionResolver.d.ts +82 -0
- package/dist/compliance/JurisdictionResolver.d.ts.map +1 -0
- package/dist/compliance/JurisdictionResolver.js +249 -0
- package/dist/compliance/JurisdictionResolver.js.map +1 -0
- package/dist/compliance/index.d.ts +4 -0
- package/dist/compliance/index.d.ts.map +1 -0
- package/dist/compliance/index.js +4 -0
- package/dist/compliance/index.js.map +1 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.d.ts +22 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.js +76 -0
- package/dist/compliance/rules/ConsentEvidenceRuleDriver.js.map +1 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.d.ts +20 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.js +70 -0
- package/dist/compliance/rules/ConsentExpiryRuleDriver.js.map +1 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.d.ts +22 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.js +65 -0
- package/dist/compliance/rules/ConsentModelRuleDriver.js.map +1 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.d.ts +37 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.js +144 -0
- package/dist/compliance/rules/QuietHoursRuleDriver.js.map +1 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.d.ts +16 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.js +40 -0
- package/dist/compliance/rules/RequireDoubleOptInRuleDriver.js.map +1 -0
- package/dist/compliance/rules/RuleParamUtils.d.ts +13 -0
- package/dist/compliance/rules/RuleParamUtils.d.ts.map +1 -0
- package/dist/compliance/rules/RuleParamUtils.js +51 -0
- package/dist/compliance/rules/RuleParamUtils.js.map +1 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.d.ts +17 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.js +64 -0
- package/dist/compliance/rules/SenderIdentificationRuleDriver.js.map +1 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.d.ts +23 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.js +81 -0
- package/dist/compliance/rules/TrackingConsentRuleDriver.js.map +1 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.d.ts +21 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.js +33 -0
- package/dist/compliance/rules/UnsubscribeHonorWindowRuleDriver.js.map +1 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.d.ts +19 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.d.ts.map +1 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.js +73 -0
- package/dist/compliance/rules/UnsubscribeMechanismRuleDriver.js.map +1 -0
- package/dist/compliance/rules/index.d.ts +10 -0
- package/dist/compliance/rules/index.d.ts.map +1 -0
- package/dist/compliance/rules/index.js +10 -0
- package/dist/compliance/rules/index.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,1054 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { BaseCommunicationPrincipal, BaseCommunicationSuppressionPolicy, CommunicationEngineBase, } from '@memberjunction/communication-types';
|
|
9
|
+
import { LogError, LogStatus, RunView, } from '@memberjunction/core';
|
|
10
|
+
import { EscapeSQLString, MJGlobal, RegisterClass, UUIDMap, UUIDsEqual, } from '@memberjunction/global';
|
|
11
|
+
import { ComputeEndpointHash, NormalizeEndpointAddress, } from './DefaultCommunicationPrincipal.js';
|
|
12
|
+
const DEFAULT_SOFT_BOUNCE_THRESHOLD = 5; // fallback when the Soft Bounce suppression policy sets no threshold; matches the seeded policy
|
|
13
|
+
const DEFAULT_SOFT_BOUNCE_EXPIRY_DAYS = 30; // fallback suppression lifetime when the policy sets no cooldownDays; matches the seeded policy
|
|
14
|
+
const MS_PER_DAY = 86_400_000;
|
|
15
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
/** Length of `MJ: Communication Activities.TargetURL`. */
|
|
17
|
+
const ACTIVITY_TARGET_URL_MAX_LENGTH = 2000;
|
|
18
|
+
/**
|
|
19
|
+
* Processes normalized provider activity events (`comms.activity` WorkQueue worker)
|
|
20
|
+
* and implements GDPR endpoint PII erasure.
|
|
21
|
+
*/
|
|
22
|
+
export class CommsActivityWorker {
|
|
23
|
+
/**
|
|
24
|
+
* Processes a batch of normalized activity events: deduplicates by provider event ID,
|
|
25
|
+
* correlates to logs/endpoints, detects machine opens/clicks, updates endpoint health
|
|
26
|
+
* and suppressions/consent, invokes principal & policy drivers, and optionally persists
|
|
27
|
+
* `MJ: Communication Activities` rows.
|
|
28
|
+
*/
|
|
29
|
+
async ProcessActivityBatch(events, contextUser, options) {
|
|
30
|
+
if (events.length === 0) {
|
|
31
|
+
return { ProcessedCount: 0, DuplicateCount: 0, ErrorCount: 0 };
|
|
32
|
+
}
|
|
33
|
+
const persistActivity = options?.PersistActivity ?? true;
|
|
34
|
+
const preparedEvents = events.map((ev) => this.ensureFirstPartyEventId(ev));
|
|
35
|
+
const deduped = await this.deduplicateEvents(preparedEvents, contextUser);
|
|
36
|
+
const duplicateCount = events.length - deduped.length;
|
|
37
|
+
let processedCount = 0;
|
|
38
|
+
let errorCount = 0;
|
|
39
|
+
let raceDuplicates = 0;
|
|
40
|
+
let unmatchedCount = 0;
|
|
41
|
+
const processedEvents = [];
|
|
42
|
+
const provider = this.getProvider();
|
|
43
|
+
const transactional = isTransactionalProvider(provider) ? provider : undefined;
|
|
44
|
+
for (const event of deduped) {
|
|
45
|
+
let claimedEvent;
|
|
46
|
+
let inTx = false;
|
|
47
|
+
try {
|
|
48
|
+
if (transactional) {
|
|
49
|
+
await transactional.BeginTransaction();
|
|
50
|
+
inTx = true;
|
|
51
|
+
}
|
|
52
|
+
const preCorrelatedLog = !event.CommunicationProviderID
|
|
53
|
+
? await this.correlateEvent(event, contextUser)
|
|
54
|
+
: undefined;
|
|
55
|
+
if (this.isUnmatchedTrackingHit(event, preCorrelatedLog)) {
|
|
56
|
+
if (inTx && transactional) {
|
|
57
|
+
await transactional.CommitTransaction();
|
|
58
|
+
inTx = false;
|
|
59
|
+
}
|
|
60
|
+
unmatchedCount++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (event.ProviderEventID && event.CommunicationProviderID) {
|
|
64
|
+
const claim = await this.claimProviderEvent(event.CommunicationProviderID, event.ProviderEventID, contextUser);
|
|
65
|
+
if (claim.Duplicate) {
|
|
66
|
+
if (inTx && transactional) {
|
|
67
|
+
await transactional.CommitTransaction();
|
|
68
|
+
inTx = false;
|
|
69
|
+
}
|
|
70
|
+
raceDuplicates++;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
claimedEvent = claim.Entity;
|
|
74
|
+
}
|
|
75
|
+
await this.processSingleEvent(event, persistActivity, contextUser, preCorrelatedLog);
|
|
76
|
+
if (inTx && transactional) {
|
|
77
|
+
await transactional.CommitTransaction();
|
|
78
|
+
inTx = false;
|
|
79
|
+
}
|
|
80
|
+
processedEvents.push(event);
|
|
81
|
+
processedCount++;
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (inTx && transactional) {
|
|
85
|
+
await transactional.RollbackTransaction().catch((rbErr) => LogError(`CommsActivityWorker rollback failed: ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`));
|
|
86
|
+
}
|
|
87
|
+
else if (claimedEvent && typeof claimedEvent.Delete === 'function') {
|
|
88
|
+
if (!(await claimedEvent.Delete().catch(() => false))) {
|
|
89
|
+
LogError(`CommsActivityWorker failed to release claimed provider event ${claimedEvent.ID}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
errorCount++;
|
|
93
|
+
LogError(`CommsActivityWorker failed processing event (${event.EventType}): ${err instanceof Error ? err.message : String(err)}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
await this.dispatchDriverHooks(processedEvents, contextUser);
|
|
97
|
+
return {
|
|
98
|
+
ProcessedCount: processedCount,
|
|
99
|
+
DuplicateCount: duplicateCount + raceDuplicates,
|
|
100
|
+
ErrorCount: errorCount,
|
|
101
|
+
UnmatchedCount: unmatchedCount,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* True for an open or click hit from MJ's own routes whose tracking token matches no message
|
|
106
|
+
* log. Those routes accept a hit on its signature alone and leave the lookup to this worker, so
|
|
107
|
+
* a hit for a message that no longer exists arrives here. There is nothing to record it
|
|
108
|
+
* against, and it must not count as an error: an error makes the queue retry it for good.
|
|
109
|
+
*/
|
|
110
|
+
isUnmatchedTrackingHit(event, log) {
|
|
111
|
+
return !log && !event.CommunicationProviderID && Boolean(event.TrackingToken);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* GDPR erasure routine: marks the endpoint `Erased`, clears `NormalizedValue`
|
|
115
|
+
* while preserving `ValueHash` and all `CommunicationSuppression` rows, clears
|
|
116
|
+
* `RecipientAddress` on the endpoint's logs, and clears `IPAddress`, `UserAgent` and
|
|
117
|
+
* `RawPayload` on its activity rows. Consent audit log rows are append-only and are not changed.
|
|
118
|
+
*
|
|
119
|
+
* @param endpointIdOrAddress - An `MJ: Communication Endpoints` ID, or a raw address.
|
|
120
|
+
* @param channelID - `MJ: Communication Base Message Types` ID, used when matching by address.
|
|
121
|
+
*/
|
|
122
|
+
async EraseEndpointPII(endpointIdOrAddress, channelID, contextUser) {
|
|
123
|
+
const endpoint = await this.findEndpointForErasure(endpointIdOrAddress, channelID, contextUser);
|
|
124
|
+
if (!endpoint) {
|
|
125
|
+
return {
|
|
126
|
+
Found: false,
|
|
127
|
+
ScrubbedLogs: 0,
|
|
128
|
+
ScrubbedActivities: 0,
|
|
129
|
+
ScrubbedAuditLogs: 0,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
endpoint.Status = 'Erased';
|
|
133
|
+
endpoint.NormalizedValue = null;
|
|
134
|
+
if (!(await endpoint.Save())) {
|
|
135
|
+
throw new Error(`Erasure could not update endpoint ${endpoint.ID}: ${endpoint.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
136
|
+
}
|
|
137
|
+
const { scrubbedCount: scrubbedLogs } = await this.scrubLogsForEndpoint(endpoint.ID, contextUser);
|
|
138
|
+
const scrubbedActivities = await this.scrubActivitiesForEndpoint(endpoint.ID, contextUser);
|
|
139
|
+
return {
|
|
140
|
+
Found: true,
|
|
141
|
+
CommunicationEndpointID: endpoint.ID,
|
|
142
|
+
ScrubbedLogs: scrubbedLogs,
|
|
143
|
+
ScrubbedActivities: scrubbedActivities,
|
|
144
|
+
// CommunicationConsentAuditLog is append-only (enforced by trgCommunicationConsentAuditLog_AppendOnly); never mutated on erasure.
|
|
145
|
+
ScrubbedAuditLogs: 0,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Determines whether an Opened/Clicked User-Agent represents an automated proxy
|
|
150
|
+
* or link scanner (Apple MPP, GoogleImageProxy, Microsoft SafeLinks, Proofpoint, Barracuda).
|
|
151
|
+
*/
|
|
152
|
+
IsMachineUserAgent(userAgent) {
|
|
153
|
+
if (!userAgent)
|
|
154
|
+
return false;
|
|
155
|
+
const trimmed = userAgent.trim();
|
|
156
|
+
if (!trimmed)
|
|
157
|
+
return false;
|
|
158
|
+
const lower = trimmed.toLowerCase();
|
|
159
|
+
if (lower === 'mozilla/5.0')
|
|
160
|
+
return true;
|
|
161
|
+
if (/apple\s*mail/.test(lower))
|
|
162
|
+
return true;
|
|
163
|
+
const appleMailIdx = lower.indexOf('applemail');
|
|
164
|
+
if (appleMailIdx !== -1 && lower.includes('proxy', appleMailIdx + 9))
|
|
165
|
+
return true;
|
|
166
|
+
const appleIdx = lower.indexOf('apple');
|
|
167
|
+
if (appleIdx !== -1 && lower.includes('mpp', appleIdx + 5))
|
|
168
|
+
return true;
|
|
169
|
+
if (lower.includes('googleimageproxy'))
|
|
170
|
+
return true;
|
|
171
|
+
if (lower.includes('safelinks'))
|
|
172
|
+
return true;
|
|
173
|
+
if (lower.includes('proofpoint') || lower.includes('urldefense'))
|
|
174
|
+
return true;
|
|
175
|
+
if (lower.includes('barracuda'))
|
|
176
|
+
return true;
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
getProvider() {
|
|
180
|
+
return CommunicationEngineBase.Instance.ProviderToUse;
|
|
181
|
+
}
|
|
182
|
+
getRunView() {
|
|
183
|
+
return RunView.FromMetadataProvider(this.getProvider());
|
|
184
|
+
}
|
|
185
|
+
ensureFirstPartyEventId(event) {
|
|
186
|
+
if (event.ProviderEventID) {
|
|
187
|
+
return event;
|
|
188
|
+
}
|
|
189
|
+
if (event.EventType !== 'Opened' &&
|
|
190
|
+
event.EventType !== 'Clicked' &&
|
|
191
|
+
event.EventType !== 'Unsubscribed') {
|
|
192
|
+
return event;
|
|
193
|
+
}
|
|
194
|
+
const token = event.CommunicationLogID ?? event.UnsubscribeToken ?? event.TrackingToken;
|
|
195
|
+
if (!token) {
|
|
196
|
+
return event;
|
|
197
|
+
}
|
|
198
|
+
// An unsubscribe is a state change, not an engagement: every click of the same token
|
|
199
|
+
// means the same thing, so its identity is token + event type only. Opens and clicks
|
|
200
|
+
// keep the timestamp so each engagement is recorded.
|
|
201
|
+
const identity = event.EventType === 'Unsubscribed'
|
|
202
|
+
? `${event.EventType}:${token}`
|
|
203
|
+
: `${event.EventType}:${token}:${event.TargetURL ?? ''}:${event.OccurredAt instanceof Date
|
|
204
|
+
? event.OccurredAt.toISOString()
|
|
205
|
+
: String(event.OccurredAt ?? '')}`;
|
|
206
|
+
const digest = createHash('sha256')
|
|
207
|
+
.update(identity)
|
|
208
|
+
.digest('hex')
|
|
209
|
+
.slice(0, 32);
|
|
210
|
+
event.ProviderEventID = `firstparty:${event.EventType.toLowerCase()}:${digest}`;
|
|
211
|
+
return event;
|
|
212
|
+
}
|
|
213
|
+
async processSingleEvent(event, persistActivity, contextUser, preCorrelatedLog) {
|
|
214
|
+
const log = preCorrelatedLog ?? (await this.correlateEvent(event, contextUser));
|
|
215
|
+
if ((event.EventType === 'Opened' || event.EventType === 'Clicked') &&
|
|
216
|
+
!event.IsMachineEvent &&
|
|
217
|
+
this.IsMachineUserAgent(event.UserAgent)) {
|
|
218
|
+
event.IsMachineEvent = true;
|
|
219
|
+
}
|
|
220
|
+
const endpoint = await this.resolveOrLoadEndpoint(event, contextUser);
|
|
221
|
+
await this.applyComplianceAndHealth(event, log, endpoint, contextUser);
|
|
222
|
+
if (persistActivity) {
|
|
223
|
+
await this.persistActivityRow(event, contextUser);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async deduplicateEvents(events, contextUser) {
|
|
227
|
+
// An event with no provider yet (open, click and unsubscribe hits from MJ's own routes) takes
|
|
228
|
+
// its provider from the log it is correlated to, later, per event. It cannot be looked up
|
|
229
|
+
// here: an empty provider ID is not a valid key. The database claim made after correlation
|
|
230
|
+
// still rejects a redelivery.
|
|
231
|
+
const withProviderEventId = events.filter((e) => Boolean(e.ProviderEventID) && Boolean(e.CommunicationProviderID));
|
|
232
|
+
const existingKeys = await this.loadExistingProviderEventKeys(withProviderEventId, contextUser);
|
|
233
|
+
const seenInBatch = new Set();
|
|
234
|
+
const accepted = [];
|
|
235
|
+
for (const event of events) {
|
|
236
|
+
if (!event.ProviderEventID) {
|
|
237
|
+
accepted.push(event);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const key = this.providerEventKey(event.CommunicationProviderID, event.ProviderEventID);
|
|
241
|
+
if (existingKeys.has(key) || seenInBatch.has(key)) {
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
seenInBatch.add(key);
|
|
245
|
+
accepted.push(event);
|
|
246
|
+
}
|
|
247
|
+
return accepted;
|
|
248
|
+
}
|
|
249
|
+
providerEventKey(providerID, providerEventID) {
|
|
250
|
+
return `${providerID.toLowerCase()}:${providerEventID}`;
|
|
251
|
+
}
|
|
252
|
+
async loadExistingProviderEventKeys(events, contextUser) {
|
|
253
|
+
const keys = new Set();
|
|
254
|
+
if (events.length === 0)
|
|
255
|
+
return keys;
|
|
256
|
+
const byProvider = new UUIDMap();
|
|
257
|
+
for (const ev of events) {
|
|
258
|
+
const list = byProvider.Get(ev.CommunicationProviderID) ?? [];
|
|
259
|
+
list.push(ev.ProviderEventID);
|
|
260
|
+
byProvider.Set(ev.CommunicationProviderID, list);
|
|
261
|
+
}
|
|
262
|
+
const rv = this.getRunView();
|
|
263
|
+
for (const [providerID, eventIDs] of byProvider) {
|
|
264
|
+
const uniqueIds = Array.from(new Set(eventIDs));
|
|
265
|
+
const quoted = uniqueIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
266
|
+
const res = await rv.RunView({
|
|
267
|
+
EntityName: 'MJ: Communication Provider Events',
|
|
268
|
+
Fields: ['CommunicationProviderID', 'ProviderEventID'],
|
|
269
|
+
ExtraFilter: `CommunicationProviderID='${EscapeSQLString(providerID)}' AND ProviderEventID IN (${quoted})`,
|
|
270
|
+
ResultType: 'simple',
|
|
271
|
+
}, contextUser);
|
|
272
|
+
if (!res.Success) {
|
|
273
|
+
throw new Error(`Failed querying Communication Provider Events for deduplication: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
274
|
+
}
|
|
275
|
+
if (res.Results) {
|
|
276
|
+
for (const row of res.Results) {
|
|
277
|
+
keys.add(this.providerEventKey(row.CommunicationProviderID, row.ProviderEventID));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return keys;
|
|
282
|
+
}
|
|
283
|
+
async claimProviderEvent(providerID, providerEventID, contextUser) {
|
|
284
|
+
const md = this.getProvider();
|
|
285
|
+
const entity = await md.GetEntityObject('MJ: Communication Provider Events', contextUser);
|
|
286
|
+
entity.CommunicationProviderID = providerID;
|
|
287
|
+
entity.ProviderEventID = providerEventID;
|
|
288
|
+
entity.ReceivedAt = new Date();
|
|
289
|
+
if (await entity.Save()) {
|
|
290
|
+
return { Entity: entity, Duplicate: false };
|
|
291
|
+
}
|
|
292
|
+
const saveErr = entity.LatestResult?.CompleteMessage ?? 'unknown error';
|
|
293
|
+
const rv = this.getRunView();
|
|
294
|
+
const existing = await rv.RunView({
|
|
295
|
+
EntityName: 'MJ: Communication Provider Events',
|
|
296
|
+
Fields: ['ID'],
|
|
297
|
+
ExtraFilter: `CommunicationProviderID='${EscapeSQLString(providerID)}' AND ProviderEventID='${EscapeSQLString(providerEventID)}'`,
|
|
298
|
+
MaxRows: 1,
|
|
299
|
+
ResultType: 'simple',
|
|
300
|
+
}, contextUser);
|
|
301
|
+
if (existing.Success && existing.Results.length > 0) {
|
|
302
|
+
return { Duplicate: true };
|
|
303
|
+
}
|
|
304
|
+
throw new Error(`Failed to claim Communication Provider Event (${providerEventID}): ${saveErr}`);
|
|
305
|
+
}
|
|
306
|
+
async correlateEvent(event, contextUser) {
|
|
307
|
+
const filter = this.buildLogCorrelationFilter(event);
|
|
308
|
+
if (!filter)
|
|
309
|
+
return undefined;
|
|
310
|
+
const rv = this.getRunView();
|
|
311
|
+
const res = await rv.RunView({
|
|
312
|
+
EntityName: 'MJ: Communication Logs',
|
|
313
|
+
ExtraFilter: filter,
|
|
314
|
+
ResultType: 'entity_object',
|
|
315
|
+
}, contextUser);
|
|
316
|
+
if (!res.Success) {
|
|
317
|
+
throw new Error(`Failed correlating activity event with CommunicationLog: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
318
|
+
}
|
|
319
|
+
if (!res.Results || res.Results.length === 0) {
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
322
|
+
const log = res.Results[0];
|
|
323
|
+
this.hydrateEventFromLog(event, log);
|
|
324
|
+
return log;
|
|
325
|
+
}
|
|
326
|
+
buildLogCorrelationFilter(event) {
|
|
327
|
+
if (event.CommunicationLogID) {
|
|
328
|
+
return `ID='${EscapeSQLString(event.CommunicationLogID)}'`;
|
|
329
|
+
}
|
|
330
|
+
if (event.UnsubscribeToken) {
|
|
331
|
+
return `UnsubscribeToken='${EscapeSQLString(event.UnsubscribeToken)}'`;
|
|
332
|
+
}
|
|
333
|
+
if (event.TrackingToken) {
|
|
334
|
+
return `TrackingToken='${EscapeSQLString(event.TrackingToken)}'`;
|
|
335
|
+
}
|
|
336
|
+
if (event.ProviderMessageID && event.CommunicationProviderID) {
|
|
337
|
+
const filterIdx = event.ProviderMessageID.indexOf('.filter');
|
|
338
|
+
if (filterIdx > 0) {
|
|
339
|
+
const baseId = event.ProviderMessageID.slice(0, filterIdx);
|
|
340
|
+
return `CommunicationProviderID='${EscapeSQLString(event.CommunicationProviderID)}' AND (ProviderMessageID='${EscapeSQLString(event.ProviderMessageID)}' OR ProviderMessageID='${EscapeSQLString(baseId)}')`;
|
|
341
|
+
}
|
|
342
|
+
return `CommunicationProviderID='${EscapeSQLString(event.CommunicationProviderID)}' AND ProviderMessageID='${EscapeSQLString(event.ProviderMessageID)}'`;
|
|
343
|
+
}
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
hydrateEventFromLog(event, log) {
|
|
347
|
+
event.CommunicationLogID = event.CommunicationLogID ?? log.ID;
|
|
348
|
+
// CommunicationProviderID is required on the event type; only overwrite it when the log
|
|
349
|
+
// has a value, so a missing provider stays falsy and is skipped downstream.
|
|
350
|
+
const providerID = event.CommunicationProviderID || log.CommunicationProviderID;
|
|
351
|
+
if (providerID) {
|
|
352
|
+
event.CommunicationProviderID = providerID;
|
|
353
|
+
}
|
|
354
|
+
event.CommunicationSenderID =
|
|
355
|
+
event.CommunicationSenderID ?? log.CommunicationSenderID ?? undefined;
|
|
356
|
+
event.CommunicationEndpointID =
|
|
357
|
+
event.CommunicationEndpointID ?? log.CommunicationEndpointID ?? undefined;
|
|
358
|
+
if (!event.Principal && log.EntityID && log.RecordID) {
|
|
359
|
+
event.Principal = { EntityID: log.EntityID, RecordID: log.RecordID };
|
|
360
|
+
}
|
|
361
|
+
if (log.CorrelationData) {
|
|
362
|
+
try {
|
|
363
|
+
const parsed = JSON.parse(log.CorrelationData);
|
|
364
|
+
if (parsed && typeof parsed === 'object' && Object.keys(parsed).length > 0) {
|
|
365
|
+
event.CorrelationData = {
|
|
366
|
+
...parsed,
|
|
367
|
+
...(event.CorrelationData ?? {}),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
// Ignore malformed CorrelationData JSON on log
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async resolveOrLoadEndpoint(event, contextUser) {
|
|
377
|
+
const rv = this.getRunView();
|
|
378
|
+
if (event.CommunicationEndpointID) {
|
|
379
|
+
const res = await rv.RunView({
|
|
380
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
381
|
+
ExtraFilter: `ID='${EscapeSQLString(event.CommunicationEndpointID)}'`,
|
|
382
|
+
ResultType: 'entity_object',
|
|
383
|
+
}, contextUser);
|
|
384
|
+
if (!res.Success) {
|
|
385
|
+
throw new Error(`Failed loading CommunicationEndpoint ${event.CommunicationEndpointID}: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
386
|
+
}
|
|
387
|
+
return res.Results.length > 0 ? res.Results[0] : undefined;
|
|
388
|
+
}
|
|
389
|
+
const hash = event.ValueHash ??
|
|
390
|
+
(event.NormalizedAddress
|
|
391
|
+
? ComputeEndpointHash(event.NormalizedAddress.trim().toLowerCase())
|
|
392
|
+
: undefined);
|
|
393
|
+
if (!hash)
|
|
394
|
+
return undefined;
|
|
395
|
+
const res = await rv.RunView({
|
|
396
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
397
|
+
ExtraFilter: `ValueHash='${EscapeSQLString(hash)}'`,
|
|
398
|
+
ResultType: 'entity_object',
|
|
399
|
+
}, contextUser);
|
|
400
|
+
if (!res.Success) {
|
|
401
|
+
throw new Error(`Failed resolving CommunicationEndpoint by hash: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
402
|
+
}
|
|
403
|
+
if (res.Results.length > 0) {
|
|
404
|
+
event.CommunicationEndpointID = res.Results[0].ID;
|
|
405
|
+
return res.Results[0];
|
|
406
|
+
}
|
|
407
|
+
return undefined;
|
|
408
|
+
}
|
|
409
|
+
async applyComplianceAndHealth(event, log, endpoint, contextUser) {
|
|
410
|
+
switch (event.EventType) {
|
|
411
|
+
case 'Delivered':
|
|
412
|
+
await this.handleDelivered(event, endpoint);
|
|
413
|
+
break;
|
|
414
|
+
case 'Soft Bounce':
|
|
415
|
+
await this.handleSoftBounce(event, endpoint, contextUser);
|
|
416
|
+
break;
|
|
417
|
+
case 'Hard Bounce':
|
|
418
|
+
await this.handleHardBounce(event, endpoint, contextUser);
|
|
419
|
+
break;
|
|
420
|
+
case 'Dropped':
|
|
421
|
+
await this.handleDropped(event, endpoint, contextUser);
|
|
422
|
+
break;
|
|
423
|
+
case 'Spam Complaint':
|
|
424
|
+
await this.handleSpamComplaint(event, endpoint, contextUser);
|
|
425
|
+
break;
|
|
426
|
+
case 'Unsubscribed':
|
|
427
|
+
await this.handleUnsubscribed(event, log, endpoint, contextUser);
|
|
428
|
+
break;
|
|
429
|
+
case 'Opened':
|
|
430
|
+
case 'Clicked':
|
|
431
|
+
await this.handleEngagement(event, endpoint);
|
|
432
|
+
break;
|
|
433
|
+
default:
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async handleDelivered(event, endpoint) {
|
|
438
|
+
if (!endpoint)
|
|
439
|
+
return;
|
|
440
|
+
if (!endpoint.LastDeliveredAt || event.OccurredAt > endpoint.LastDeliveredAt) {
|
|
441
|
+
endpoint.LastDeliveredAt = event.OccurredAt;
|
|
442
|
+
}
|
|
443
|
+
if (!endpoint.LastBouncedAt || event.OccurredAt > endpoint.LastBouncedAt) {
|
|
444
|
+
endpoint.SoftBounceCount = 0;
|
|
445
|
+
if (endpoint.Status === 'Soft Bouncing') {
|
|
446
|
+
endpoint.Status = 'Active';
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
await this.saveEndpoint(endpoint);
|
|
450
|
+
}
|
|
451
|
+
async handleSoftBounce(event, endpoint, contextUser) {
|
|
452
|
+
if (!endpoint)
|
|
453
|
+
return;
|
|
454
|
+
if (!endpoint.LastBouncedAt || event.OccurredAt > endpoint.LastBouncedAt) {
|
|
455
|
+
endpoint.LastBouncedAt = event.OccurredAt;
|
|
456
|
+
}
|
|
457
|
+
endpoint.SoftBounceCount = (endpoint.SoftBounceCount ?? 0) + 1;
|
|
458
|
+
if (endpoint.Status === 'Active') {
|
|
459
|
+
endpoint.Status = 'Soft Bouncing';
|
|
460
|
+
}
|
|
461
|
+
await this.saveEndpoint(endpoint);
|
|
462
|
+
}
|
|
463
|
+
resolveSoftBouncePolicyConfig() {
|
|
464
|
+
const policy = CommunicationEngineBase.Instance.SuppressionPolicies.find((p) => p.Status === 'Active' &&
|
|
465
|
+
(p.DriverClass === 'SoftBounceThresholdPolicy' ||
|
|
466
|
+
p.Name === 'SoftBounceThresholdPolicy'));
|
|
467
|
+
let threshold = DEFAULT_SOFT_BOUNCE_THRESHOLD;
|
|
468
|
+
let expiryDays = DEFAULT_SOFT_BOUNCE_EXPIRY_DAYS;
|
|
469
|
+
if (policy?.Parameters) {
|
|
470
|
+
try {
|
|
471
|
+
const parsed = JSON.parse(policy.Parameters);
|
|
472
|
+
const thresholdCandidate = parsed.threshold ?? parsed.Threshold;
|
|
473
|
+
if (typeof thresholdCandidate === 'number' && thresholdCandidate > 0) {
|
|
474
|
+
threshold = thresholdCandidate;
|
|
475
|
+
}
|
|
476
|
+
const expiryCandidate = parsed.cooldownDays ?? parsed.ExpiryDays;
|
|
477
|
+
if (typeof expiryCandidate === 'number' && expiryCandidate > 0) {
|
|
478
|
+
expiryDays = expiryCandidate;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
// Use defaults if Parameters JSON is malformed
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return {
|
|
486
|
+
PolicyID: policy?.ID,
|
|
487
|
+
Threshold: threshold,
|
|
488
|
+
ExpiryDays: expiryDays,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
async handleHardBounce(event, endpoint, contextUser) {
|
|
492
|
+
if (endpoint) {
|
|
493
|
+
if (!endpoint.LastBouncedAt || event.OccurredAt > endpoint.LastBouncedAt) {
|
|
494
|
+
endpoint.LastBouncedAt = event.OccurredAt;
|
|
495
|
+
}
|
|
496
|
+
endpoint.Status = 'Hard Bounced';
|
|
497
|
+
await this.saveEndpoint(endpoint);
|
|
498
|
+
}
|
|
499
|
+
if (endpoint || event.Principal) {
|
|
500
|
+
await this.createSuppression({
|
|
501
|
+
CommunicationEndpointID: endpoint?.ID ?? null,
|
|
502
|
+
EntityID: endpoint ? null : event.Principal?.EntityID ?? null,
|
|
503
|
+
RecordID: endpoint ? null : event.Principal?.RecordID ?? null,
|
|
504
|
+
CommunicationSenderID: null,
|
|
505
|
+
BaseMessageTypeID: endpoint?.BaseMessageTypeID ?? null,
|
|
506
|
+
Reason: 'Hard Bounce',
|
|
507
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
508
|
+
EffectiveAt: event.OccurredAt,
|
|
509
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
510
|
+
Notes: event.BounceReason ?? null,
|
|
511
|
+
}, contextUser);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async handleDropped(event, endpoint, contextUser) {
|
|
515
|
+
const mapped = this.mapDropReason(event.DropReason);
|
|
516
|
+
if (!mapped)
|
|
517
|
+
return;
|
|
518
|
+
if (endpoint && mapped.EndpointStatus) {
|
|
519
|
+
endpoint.Status = mapped.EndpointStatus;
|
|
520
|
+
await this.saveEndpoint(endpoint);
|
|
521
|
+
}
|
|
522
|
+
if (endpoint || event.Principal) {
|
|
523
|
+
await this.createSuppression({
|
|
524
|
+
CommunicationEndpointID: endpoint?.ID ?? null,
|
|
525
|
+
EntityID: endpoint ? null : event.Principal?.EntityID ?? null,
|
|
526
|
+
RecordID: endpoint ? null : event.Principal?.RecordID ?? null,
|
|
527
|
+
CommunicationSenderID: mapped.Global
|
|
528
|
+
? null
|
|
529
|
+
: event.CommunicationSenderID ?? null,
|
|
530
|
+
BaseMessageTypeID: endpoint?.BaseMessageTypeID ?? null,
|
|
531
|
+
Reason: mapped.Reason,
|
|
532
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
533
|
+
EffectiveAt: event.OccurredAt,
|
|
534
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
535
|
+
Notes: event.DropReason ?? null,
|
|
536
|
+
}, contextUser);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
mapDropReason(dropReason) {
|
|
540
|
+
const lower = (dropReason ?? '').toLowerCase();
|
|
541
|
+
if (lower.includes('invalid')) {
|
|
542
|
+
return { Reason: 'Invalid Address', Global: true, EndpointStatus: 'Invalid' };
|
|
543
|
+
}
|
|
544
|
+
if (lower.includes('bounced')) {
|
|
545
|
+
return { Reason: 'Hard Bounce', Global: true, EndpointStatus: 'Hard Bounced' };
|
|
546
|
+
}
|
|
547
|
+
if (lower.includes('unsubscribed')) {
|
|
548
|
+
return { Reason: 'User Unsubscribe', Global: false };
|
|
549
|
+
}
|
|
550
|
+
if (lower.includes('spam')) {
|
|
551
|
+
return { Reason: 'Spam Complaint', Global: false, EndpointStatus: 'Complained' };
|
|
552
|
+
}
|
|
553
|
+
return undefined;
|
|
554
|
+
}
|
|
555
|
+
async handleSpamComplaint(event, endpoint, contextUser) {
|
|
556
|
+
if (endpoint) {
|
|
557
|
+
endpoint.Status = 'Complained';
|
|
558
|
+
await this.saveEndpoint(endpoint);
|
|
559
|
+
}
|
|
560
|
+
if (endpoint || event.Principal) {
|
|
561
|
+
await this.createSuppression({
|
|
562
|
+
CommunicationEndpointID: endpoint?.ID ?? null,
|
|
563
|
+
EntityID: endpoint ? null : event.Principal?.EntityID ?? null,
|
|
564
|
+
RecordID: endpoint ? null : event.Principal?.RecordID ?? null,
|
|
565
|
+
CommunicationSenderID: event.CommunicationSenderID ?? null,
|
|
566
|
+
BaseMessageTypeID: endpoint?.BaseMessageTypeID ?? null,
|
|
567
|
+
Reason: 'Spam Complaint',
|
|
568
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
569
|
+
EffectiveAt: event.OccurredAt,
|
|
570
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
571
|
+
}, contextUser);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
async handleUnsubscribed(event, log, endpoint, contextUser) {
|
|
575
|
+
const preferenceID = log?.CommunicationPreferenceID ?? null;
|
|
576
|
+
const senderID = event.CommunicationSenderID ?? null;
|
|
577
|
+
if (event.Principal && preferenceID) {
|
|
578
|
+
// Rule 1: Principal + Preference -> PrincipalPreference Opted Out + scoped suppression
|
|
579
|
+
await this.upsertPrincipalPreferenceOptOut(event, preferenceID, senderID, contextUser);
|
|
580
|
+
await this.createSuppressionIfAbsent({
|
|
581
|
+
CommunicationEndpointID: endpoint?.ID ?? null,
|
|
582
|
+
EntityID: event.Principal.EntityID,
|
|
583
|
+
RecordID: event.Principal.RecordID,
|
|
584
|
+
CommunicationSenderID: senderID,
|
|
585
|
+
CommunicationPreferenceID: preferenceID,
|
|
586
|
+
BaseMessageTypeID: endpoint?.BaseMessageTypeID ?? null,
|
|
587
|
+
Reason: 'User Unsubscribe',
|
|
588
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
589
|
+
EffectiveAt: event.OccurredAt,
|
|
590
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
591
|
+
IPAddress: event.IPAddress ?? null,
|
|
592
|
+
UserAgent: event.UserAgent ?? null,
|
|
593
|
+
}, contextUser);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (event.Principal) {
|
|
597
|
+
// Rule 2: Principal + No Preference -> sender-scoped unsubscribe-all
|
|
598
|
+
await this.createSuppressionIfAbsent({
|
|
599
|
+
CommunicationEndpointID: endpoint?.ID ?? null,
|
|
600
|
+
EntityID: event.Principal.EntityID,
|
|
601
|
+
RecordID: event.Principal.RecordID,
|
|
602
|
+
CommunicationSenderID: senderID,
|
|
603
|
+
CommunicationPreferenceID: null,
|
|
604
|
+
BaseMessageTypeID: endpoint?.BaseMessageTypeID ?? null,
|
|
605
|
+
Reason: 'User Unsubscribe',
|
|
606
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
607
|
+
EffectiveAt: event.OccurredAt,
|
|
608
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
609
|
+
IPAddress: event.IPAddress ?? null,
|
|
610
|
+
UserAgent: event.UserAgent ?? null,
|
|
611
|
+
}, contextUser);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
// Rule 3: No Principal -> endpoint suppression only
|
|
615
|
+
if (endpoint) {
|
|
616
|
+
await this.createSuppressionIfAbsent({
|
|
617
|
+
CommunicationEndpointID: endpoint.ID,
|
|
618
|
+
EntityID: null,
|
|
619
|
+
RecordID: null,
|
|
620
|
+
CommunicationSenderID: senderID,
|
|
621
|
+
CommunicationPreferenceID: preferenceID,
|
|
622
|
+
BaseMessageTypeID: endpoint.BaseMessageTypeID,
|
|
623
|
+
Reason: 'User Unsubscribe',
|
|
624
|
+
Source: event.Source ?? 'Provider Webhook',
|
|
625
|
+
EffectiveAt: event.OccurredAt,
|
|
626
|
+
CommunicationLogID: event.CommunicationLogID ?? null,
|
|
627
|
+
IPAddress: event.IPAddress ?? null,
|
|
628
|
+
UserAgent: event.UserAgent ?? null,
|
|
629
|
+
}, contextUser);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
async upsertPrincipalPreferenceOptOut(event, preferenceID, senderID, contextUser) {
|
|
633
|
+
if (!event.Principal)
|
|
634
|
+
return;
|
|
635
|
+
const senderClause = senderID
|
|
636
|
+
? `CommunicationSenderID='${EscapeSQLString(senderID)}'`
|
|
637
|
+
: `CommunicationSenderID IS NULL`;
|
|
638
|
+
const rv = this.getRunView();
|
|
639
|
+
const res = await rv.RunView({
|
|
640
|
+
EntityName: 'MJ: Communication Principal Preferences',
|
|
641
|
+
ExtraFilter: `EntityID='${EscapeSQLString(event.Principal.EntityID)}' AND RecordID='${EscapeSQLString(event.Principal.RecordID)}' AND CommunicationPreferenceID='${EscapeSQLString(preferenceID)}' AND ${senderClause}`,
|
|
642
|
+
ResultType: 'entity_object',
|
|
643
|
+
}, contextUser);
|
|
644
|
+
const existing = res.Success && res.Results && res.Results.length > 0 ? res.Results[0] : undefined;
|
|
645
|
+
// fls-guard: system-only audit log snapshot persisted internally, never egressed to a caller
|
|
646
|
+
const previousValue = existing ? JSON.stringify(existing.GetAll()) : null;
|
|
647
|
+
const md = this.getProvider();
|
|
648
|
+
const pref = existing ??
|
|
649
|
+
(await md.GetEntityObject('MJ: Communication Principal Preferences', contextUser));
|
|
650
|
+
if (!existing) {
|
|
651
|
+
pref.EntityID = event.Principal.EntityID;
|
|
652
|
+
pref.RecordID = event.Principal.RecordID;
|
|
653
|
+
pref.CommunicationPreferenceID = preferenceID;
|
|
654
|
+
pref.CommunicationSenderID = senderID;
|
|
655
|
+
}
|
|
656
|
+
pref.State = 'Opted Out';
|
|
657
|
+
pref.ConsentSource = event.Source ?? 'Provider Webhook';
|
|
658
|
+
pref.ConsentAt = event.OccurredAt;
|
|
659
|
+
pref.CommunicationLogID = event.CommunicationLogID ?? null;
|
|
660
|
+
pref.IPAddress = event.IPAddress ?? null;
|
|
661
|
+
pref.UserAgent = event.UserAgent ?? null;
|
|
662
|
+
if (!(await pref.Save())) {
|
|
663
|
+
throw new Error(`Failed to save Principal Preference opt-out: ${pref.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
664
|
+
}
|
|
665
|
+
await this.appendConsentAuditLog({
|
|
666
|
+
CommunicationPrincipalPreferenceID: pref.ID,
|
|
667
|
+
Action: existing ? 'Updated' : 'Created',
|
|
668
|
+
PreviousValue: previousValue,
|
|
669
|
+
// fls-guard: system-only audit log snapshot persisted internally, never egressed to a caller
|
|
670
|
+
NewValue: JSON.stringify(pref.GetAll()),
|
|
671
|
+
event,
|
|
672
|
+
}, contextUser);
|
|
673
|
+
}
|
|
674
|
+
async appendConsentAuditLog(params, contextUser) {
|
|
675
|
+
const md = this.getProvider();
|
|
676
|
+
const audit = await md.GetEntityObject('MJ: Communication Consent Audit Logs', contextUser);
|
|
677
|
+
audit.CommunicationSuppressionID = params.CommunicationSuppressionID ?? null;
|
|
678
|
+
audit.CommunicationPrincipalPreferenceID =
|
|
679
|
+
params.CommunicationPrincipalPreferenceID ?? null;
|
|
680
|
+
audit.Action = params.Action;
|
|
681
|
+
audit.PreviousValue = params.PreviousValue;
|
|
682
|
+
audit.NewValue = params.NewValue;
|
|
683
|
+
audit.Source = params.event.Source ?? 'Provider Webhook';
|
|
684
|
+
audit.CommunicationLogID = params.event.CommunicationLogID ?? null;
|
|
685
|
+
audit.IPAddress = params.event.IPAddress ?? null;
|
|
686
|
+
audit.UserAgent = params.event.UserAgent ?? null;
|
|
687
|
+
audit.ChangedAt = params.event.OccurredAt;
|
|
688
|
+
if (!(await audit.Save())) {
|
|
689
|
+
throw new Error(`Failed to save Consent Audit Log: ${audit.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
async handleEngagement(event, endpoint) {
|
|
693
|
+
if (!endpoint || event.IsMachineEvent)
|
|
694
|
+
return;
|
|
695
|
+
if (!endpoint.LastEngagedAt || event.OccurredAt > endpoint.LastEngagedAt) {
|
|
696
|
+
endpoint.LastEngagedAt = event.OccurredAt;
|
|
697
|
+
await this.saveEndpoint(endpoint);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
async saveEndpoint(endpoint) {
|
|
701
|
+
if (!(await endpoint.Save())) {
|
|
702
|
+
throw new Error(`Failed to save Communication Endpoint ${endpoint.ID}: ${endpoint.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Creates an active suppression and its consent audit entry, unless an Active suppression with
|
|
707
|
+
* the same scope, reason and policy already exists (then that one is returned and nothing is
|
|
708
|
+
* written). For use by suppression policy drivers, which re-evaluate on every batch.
|
|
709
|
+
*
|
|
710
|
+
* @param fields - The suppression's scope (endpoint and/or principal, sender, preference,
|
|
711
|
+
* channel), reason, source and dates.
|
|
712
|
+
* @returns The saved or existing suppression. Throws when the lookup or the save fails.
|
|
713
|
+
*/
|
|
714
|
+
async CreatePolicySuppression(fields, contextUser) {
|
|
715
|
+
return this.createSuppressionIfAbsent(fields, contextUser);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Creates a suppression unless an Active one with exactly the same scope and reason already
|
|
719
|
+
* exists. Used for state-change events (unsubscribe, policy cooldown) that can arrive more than
|
|
720
|
+
* once for the same recipient, so repeats add no suppression or consent-audit row. A failed
|
|
721
|
+
* lookup throws: the batch is retried rather than guessing.
|
|
722
|
+
*/
|
|
723
|
+
async createSuppressionIfAbsent(fields, contextUser) {
|
|
724
|
+
const existing = await this.findActiveSuppression(fields, contextUser);
|
|
725
|
+
if (existing) {
|
|
726
|
+
return existing;
|
|
727
|
+
}
|
|
728
|
+
return this.createSuppression(fields, contextUser);
|
|
729
|
+
}
|
|
730
|
+
async findActiveSuppression(fields, contextUser) {
|
|
731
|
+
const eq = (column, value) => value ? `${column}='${EscapeSQLString(value)}'` : `${column} IS NULL`;
|
|
732
|
+
const filter = [
|
|
733
|
+
`Status='Active'`,
|
|
734
|
+
`Reason='${EscapeSQLString(fields.Reason)}'`,
|
|
735
|
+
eq('CommunicationEndpointID', fields.CommunicationEndpointID),
|
|
736
|
+
eq('EntityID', fields.EntityID),
|
|
737
|
+
eq('RecordID', fields.RecordID),
|
|
738
|
+
eq('CommunicationSenderID', fields.CommunicationSenderID),
|
|
739
|
+
eq('CommunicationPreferenceID', fields.CommunicationPreferenceID),
|
|
740
|
+
eq('CommunicationSuppressionPolicyID', fields.CommunicationSuppressionPolicyID),
|
|
741
|
+
].join(' AND ');
|
|
742
|
+
const res = await this.getRunView().RunView({
|
|
743
|
+
EntityName: 'MJ: Communication Suppressions',
|
|
744
|
+
ExtraFilter: filter,
|
|
745
|
+
// Exact-scope matches are a handful of rows at most; expiry is checked below.
|
|
746
|
+
MaxRows: 50,
|
|
747
|
+
ResultType: 'entity_object',
|
|
748
|
+
}, contextUser);
|
|
749
|
+
if (!res.Success) {
|
|
750
|
+
throw new Error(`Failed to check for an existing Communication Suppression: ${res.ErrorMessage ?? 'unknown error'}`);
|
|
751
|
+
}
|
|
752
|
+
// An expired suppression no longer blocks, so it does not count as existing.
|
|
753
|
+
const now = Date.now();
|
|
754
|
+
return (res.Results ?? []).find((r) => !r.ExpiresAt || r.ExpiresAt.getTime() > now);
|
|
755
|
+
}
|
|
756
|
+
async createSuppression(fields, contextUser) {
|
|
757
|
+
const md = this.getProvider();
|
|
758
|
+
const suppression = await md.GetEntityObject('MJ: Communication Suppressions', contextUser);
|
|
759
|
+
suppression.CommunicationEndpointID = fields.CommunicationEndpointID ?? null;
|
|
760
|
+
suppression.EntityID = fields.EntityID ?? null;
|
|
761
|
+
suppression.RecordID = fields.RecordID ?? null;
|
|
762
|
+
suppression.CommunicationSenderID = fields.CommunicationSenderID ?? null;
|
|
763
|
+
suppression.CommunicationPreferenceID = fields.CommunicationPreferenceID ?? null;
|
|
764
|
+
suppression.BaseMessageTypeID = fields.BaseMessageTypeID ?? null;
|
|
765
|
+
suppression.Reason = fields.Reason;
|
|
766
|
+
suppression.Source = fields.Source;
|
|
767
|
+
suppression.Status = 'Active';
|
|
768
|
+
suppression.EffectiveAt = fields.EffectiveAt;
|
|
769
|
+
suppression.ExpiresAt = fields.ExpiresAt ?? null;
|
|
770
|
+
suppression.CommunicationLogID = fields.CommunicationLogID ?? null;
|
|
771
|
+
suppression.CommunicationSuppressionPolicyID =
|
|
772
|
+
fields.CommunicationSuppressionPolicyID ?? null;
|
|
773
|
+
suppression.IPAddress = fields.IPAddress ?? null;
|
|
774
|
+
suppression.UserAgent = fields.UserAgent ?? null;
|
|
775
|
+
suppression.Notes = fields.Notes ?? null;
|
|
776
|
+
if (!(await suppression.Save())) {
|
|
777
|
+
throw new Error(`Failed to save Communication Suppression: ${suppression.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
778
|
+
}
|
|
779
|
+
await this.appendConsentAuditLog({
|
|
780
|
+
CommunicationSuppressionID: suppression.ID,
|
|
781
|
+
Action: 'Created',
|
|
782
|
+
PreviousValue: null,
|
|
783
|
+
// fls-guard: system-only audit log snapshot persisted internally, never egressed to a caller
|
|
784
|
+
NewValue: JSON.stringify(suppression.GetAll()),
|
|
785
|
+
event: {
|
|
786
|
+
Source: fields.Source,
|
|
787
|
+
CommunicationLogID: fields.CommunicationLogID ?? undefined,
|
|
788
|
+
IPAddress: fields.IPAddress ?? undefined,
|
|
789
|
+
UserAgent: fields.UserAgent ?? undefined,
|
|
790
|
+
OccurredAt: fields.EffectiveAt,
|
|
791
|
+
},
|
|
792
|
+
}, contextUser);
|
|
793
|
+
return suppression;
|
|
794
|
+
}
|
|
795
|
+
async persistActivityRow(event, contextUser) {
|
|
796
|
+
const md = this.getProvider();
|
|
797
|
+
const activity = await md.GetEntityObject('MJ: Communication Activities', contextUser);
|
|
798
|
+
activity.CommunicationLogID = event.CommunicationLogID ?? null;
|
|
799
|
+
activity.CommunicationEndpointID = event.CommunicationEndpointID ?? null;
|
|
800
|
+
activity.CommunicationSenderID = event.CommunicationSenderID ?? null;
|
|
801
|
+
activity.CommunicationProviderID = event.CommunicationProviderID;
|
|
802
|
+
activity.EventType = event.EventType;
|
|
803
|
+
activity.OccurredAt = event.OccurredAt;
|
|
804
|
+
activity.ReceivedAt = new Date();
|
|
805
|
+
activity.ProviderEventID = event.ProviderEventID ?? null;
|
|
806
|
+
activity.ProviderMessageID = event.ProviderMessageID ?? null;
|
|
807
|
+
// A provider can report a clicked URL longer than the column holds. Keep the event and
|
|
808
|
+
// shorten the URL, so the save does not fail and the work item is not retried for good.
|
|
809
|
+
activity.TargetURL = event.TargetURL ? event.TargetURL.slice(0, ACTIVITY_TARGET_URL_MAX_LENGTH) : null;
|
|
810
|
+
activity.BounceCode = event.BounceCode ?? null;
|
|
811
|
+
activity.BounceReason = event.BounceReason ?? null;
|
|
812
|
+
activity.IsMachineEvent = event.IsMachineEvent;
|
|
813
|
+
activity.IPAddress = event.IPAddress ?? null;
|
|
814
|
+
activity.UserAgent = event.UserAgent ?? null;
|
|
815
|
+
activity.CorrelationData = event.CorrelationData
|
|
816
|
+
? JSON.stringify(event.CorrelationData)
|
|
817
|
+
: null;
|
|
818
|
+
activity.RawPayload = event.RawPayload ? JSON.stringify(event.RawPayload) : null;
|
|
819
|
+
if (!(await activity.Save())) {
|
|
820
|
+
LogError(`Failed to save Communication Activity: ${activity.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
async dispatchDriverHooks(events, contextUser) {
|
|
824
|
+
if (events.length === 0)
|
|
825
|
+
return;
|
|
826
|
+
const byEntity = new UUIDMap();
|
|
827
|
+
for (const ev of events) {
|
|
828
|
+
if (!ev.Principal?.EntityID)
|
|
829
|
+
continue;
|
|
830
|
+
const list = byEntity.Get(ev.Principal.EntityID) ?? [];
|
|
831
|
+
list.push(ev);
|
|
832
|
+
byEntity.Set(ev.Principal.EntityID, list);
|
|
833
|
+
}
|
|
834
|
+
for (const [entityID, entityEvents] of byEntity) {
|
|
835
|
+
const driver = this.getPrincipalDriver(entityID);
|
|
836
|
+
if (driver) {
|
|
837
|
+
try {
|
|
838
|
+
await driver.OnActivity(entityEvents, contextUser);
|
|
839
|
+
}
|
|
840
|
+
catch (err) {
|
|
841
|
+
LogError(`CommsActivityWorker principal driver hook failed (${entityID}): ${err instanceof Error ? err.message : String(err)}`);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
const activePolicies = CommunicationEngineBase.Instance.SuppressionPolicies.filter((p) => p.Status === 'Active');
|
|
846
|
+
let ranSoftBouncePolicy = false;
|
|
847
|
+
for (const policy of activePolicies) {
|
|
848
|
+
if (policy.DriverClass === 'SoftBounceThresholdPolicy' || policy.Name === 'SoftBounceThresholdPolicy') {
|
|
849
|
+
ranSoftBouncePolicy = true;
|
|
850
|
+
}
|
|
851
|
+
let driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseCommunicationSuppressionPolicy, policy.DriverClass);
|
|
852
|
+
if (!driver && policy.DriverClass === 'SoftBounceThresholdPolicy') {
|
|
853
|
+
driver = new SoftBounceThresholdPolicy();
|
|
854
|
+
}
|
|
855
|
+
if (!driver || typeof driver.Evaluate !== 'function')
|
|
856
|
+
continue;
|
|
857
|
+
let params = {};
|
|
858
|
+
if (policy.Parameters) {
|
|
859
|
+
try {
|
|
860
|
+
params = JSON.parse(policy.Parameters);
|
|
861
|
+
}
|
|
862
|
+
catch {
|
|
863
|
+
params = {};
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
try {
|
|
867
|
+
await driver.Evaluate(events, params, contextUser);
|
|
868
|
+
}
|
|
869
|
+
catch (err) {
|
|
870
|
+
LogError(`CommsActivityWorker policy driver '${policy.DriverClass}' failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
if (!ranSoftBouncePolicy && events.some((e) => e.EventType === 'Soft Bounce')) {
|
|
874
|
+
try {
|
|
875
|
+
await new SoftBounceThresholdPolicy().Evaluate(events, {}, contextUser);
|
|
876
|
+
}
|
|
877
|
+
catch (err) {
|
|
878
|
+
LogError(`CommsActivityWorker default SoftBounceThresholdPolicy failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
getPrincipalDriver(entityID) {
|
|
883
|
+
const principal = CommunicationEngineBase.Instance.Principals.find((p) => p.Status === 'Active' && UUIDsEqual(p.EntityID, entityID));
|
|
884
|
+
const driverClass = principal?.DriverClass ?? 'DefaultCommunicationPrincipal';
|
|
885
|
+
return MJGlobal.Instance.ClassFactory.CreateInstance(BaseCommunicationPrincipal, driverClass);
|
|
886
|
+
}
|
|
887
|
+
async findEndpointForErasure(endpointIdOrAddress, channelID, contextUser) {
|
|
888
|
+
const trimmed = endpointIdOrAddress.trim();
|
|
889
|
+
if (!trimmed)
|
|
890
|
+
return undefined;
|
|
891
|
+
const rv = this.getRunView();
|
|
892
|
+
if (UUID_REGEX.test(trimmed)) {
|
|
893
|
+
const byId = await rv.RunView({
|
|
894
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
895
|
+
ExtraFilter: `ID='${EscapeSQLString(trimmed)}'`,
|
|
896
|
+
ResultType: 'entity_object',
|
|
897
|
+
}, contextUser);
|
|
898
|
+
if (byId.Success && byId.Results.length > 0) {
|
|
899
|
+
return byId.Results[0];
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const norm = NormalizeEndpointAddress(trimmed);
|
|
903
|
+
const hash = norm?.ValueHash ?? ComputeEndpointHash(trimmed.toLowerCase());
|
|
904
|
+
const byHash = await rv.RunView({
|
|
905
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
906
|
+
ExtraFilter: `BaseMessageTypeID='${EscapeSQLString(channelID)}' AND ValueHash='${EscapeSQLString(hash)}'`,
|
|
907
|
+
ResultType: 'entity_object',
|
|
908
|
+
}, contextUser);
|
|
909
|
+
return byHash.Success && byHash.Results.length > 0 ? byHash.Results[0] : undefined;
|
|
910
|
+
}
|
|
911
|
+
async scrubLogsForEndpoint(endpointID, contextUser) {
|
|
912
|
+
const rv = this.getRunView();
|
|
913
|
+
const res = await rv.RunView({
|
|
914
|
+
EntityName: 'MJ: Communication Logs',
|
|
915
|
+
ExtraFilter: `CommunicationEndpointID='${EscapeSQLString(endpointID)}'`,
|
|
916
|
+
ResultType: 'entity_object',
|
|
917
|
+
}, contextUser);
|
|
918
|
+
if (!res.Success) {
|
|
919
|
+
throw new Error(`Erasure could not read the endpoint's communication logs: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
920
|
+
}
|
|
921
|
+
let scrubbedCount = 0;
|
|
922
|
+
const logIDs = [];
|
|
923
|
+
for (const log of res.Results) {
|
|
924
|
+
logIDs.push(log.ID);
|
|
925
|
+
if (log.RecipientAddress !== null || log.CorrelationData !== null || log.DeferredPayload !== null) {
|
|
926
|
+
log.RecipientAddress = null;
|
|
927
|
+
log.CorrelationData = null;
|
|
928
|
+
// A deferred message not yet sent holds its rendered body, which can carry personal data.
|
|
929
|
+
log.DeferredPayload = null;
|
|
930
|
+
if (await log.Save()) {
|
|
931
|
+
scrubbedCount++;
|
|
932
|
+
}
|
|
933
|
+
else {
|
|
934
|
+
throw new Error(`Erasure could not scrub communication log ${log.ID}: ${log.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return { scrubbedCount, logIDs };
|
|
939
|
+
}
|
|
940
|
+
async scrubActivitiesForEndpoint(endpointID, contextUser) {
|
|
941
|
+
const rv = this.getRunView();
|
|
942
|
+
const res = await rv.RunView({
|
|
943
|
+
EntityName: 'MJ: Communication Activities',
|
|
944
|
+
ExtraFilter: `CommunicationEndpointID='${EscapeSQLString(endpointID)}'`,
|
|
945
|
+
ResultType: 'entity_object',
|
|
946
|
+
}, contextUser);
|
|
947
|
+
if (!res.Success) {
|
|
948
|
+
throw new Error(`Erasure could not read the endpoint's communication activities: ${res.ErrorMessage ?? 'RunView failed'}`);
|
|
949
|
+
}
|
|
950
|
+
let scrubbedCount = 0;
|
|
951
|
+
for (const activity of res.Results) {
|
|
952
|
+
if (activity.IPAddress !== null ||
|
|
953
|
+
activity.UserAgent !== null ||
|
|
954
|
+
activity.RawPayload !== null ||
|
|
955
|
+
activity.CorrelationData !== null) {
|
|
956
|
+
activity.IPAddress = null;
|
|
957
|
+
activity.UserAgent = null;
|
|
958
|
+
activity.RawPayload = null;
|
|
959
|
+
activity.CorrelationData = null;
|
|
960
|
+
if (await activity.Save()) {
|
|
961
|
+
scrubbedCount++;
|
|
962
|
+
}
|
|
963
|
+
else {
|
|
964
|
+
throw new Error(`Erasure could not scrub communication activity ${activity.ID}: ${activity.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return scrubbedCount;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
function isTransactionalProvider(provider) {
|
|
972
|
+
return (typeof provider === 'object' &&
|
|
973
|
+
provider !== null &&
|
|
974
|
+
'BeginTransaction' in provider &&
|
|
975
|
+
typeof provider.BeginTransaction === 'function' &&
|
|
976
|
+
'CommitTransaction' in provider &&
|
|
977
|
+
typeof provider.CommitTransaction === 'function' &&
|
|
978
|
+
'RollbackTransaction' in provider &&
|
|
979
|
+
typeof provider.RollbackTransaction === 'function');
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Built-in policy driver for `SoftBounceThresholdPolicy`: evaluates soft-bounce
|
|
983
|
+
* counts against the configured threshold and creates a cooldown `Policy` suppression.
|
|
984
|
+
*/
|
|
985
|
+
let SoftBounceThresholdPolicy = class SoftBounceThresholdPolicy extends BaseCommunicationSuppressionPolicy {
|
|
986
|
+
async Evaluate(events, parameters, contextUser) {
|
|
987
|
+
const softBounces = events.filter((e) => e.EventType === 'Soft Bounce' && e.CommunicationEndpointID);
|
|
988
|
+
if (softBounces.length === 0)
|
|
989
|
+
return;
|
|
990
|
+
const thresholdCandidate = parameters.threshold ?? parameters.Threshold;
|
|
991
|
+
const threshold = typeof thresholdCandidate === 'number' && thresholdCandidate > 0
|
|
992
|
+
? thresholdCandidate
|
|
993
|
+
: DEFAULT_SOFT_BOUNCE_THRESHOLD;
|
|
994
|
+
const expiryCandidate = parameters.cooldownDays ?? parameters.ExpiryDays;
|
|
995
|
+
const expiryDays = typeof expiryCandidate === 'number' && expiryCandidate > 0
|
|
996
|
+
? expiryCandidate
|
|
997
|
+
: DEFAULT_SOFT_BOUNCE_EXPIRY_DAYS;
|
|
998
|
+
const policyId = CommunicationEngineBase.Instance.SuppressionPolicies.find((p) => p.Status === 'Active' &&
|
|
999
|
+
(p.DriverClass === 'SoftBounceThresholdPolicy' || p.Name === 'SoftBounceThresholdPolicy'))?.ID ?? null;
|
|
1000
|
+
if (!policyId) {
|
|
1001
|
+
// CK_CommunicationSuppression_PolicyLink requires a PolicyID when Reason = 'Policy', so
|
|
1002
|
+
// without an Active policy row there is nothing to link to. Say so once per batch rather
|
|
1003
|
+
// than dropping the cooldown silently.
|
|
1004
|
+
LogStatus(`SoftBounceThresholdPolicy: ${softBounces.length} soft bounce(s) in this batch, but no Active ` +
|
|
1005
|
+
`'SoftBounceThresholdPolicy' row exists in MJ: Communication Suppression Policies, so ` +
|
|
1006
|
+
`soft-bounce cooldown suppression is disabled.`);
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
const endpointIds = Array.from(new Set(softBounces.map((e) => e.CommunicationEndpointID)));
|
|
1010
|
+
const rv = RunView.FromMetadataProvider(CommunicationEngineBase.Instance.ProviderToUse);
|
|
1011
|
+
const quoted = endpointIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
1012
|
+
const epRes = await rv.RunView({
|
|
1013
|
+
EntityName: 'MJ: Communication Endpoints',
|
|
1014
|
+
ExtraFilter: `ID IN (${quoted})`,
|
|
1015
|
+
ResultType: 'entity_object',
|
|
1016
|
+
}, contextUser);
|
|
1017
|
+
if (!epRes.Success) {
|
|
1018
|
+
throw new Error(`SoftBounceThresholdPolicy could not load endpoints: ${epRes.ErrorMessage ?? 'unknown error'}`);
|
|
1019
|
+
}
|
|
1020
|
+
const epMap = new UUIDMap();
|
|
1021
|
+
for (const ep of epRes.Results) {
|
|
1022
|
+
epMap.Set(ep.ID, ep);
|
|
1023
|
+
}
|
|
1024
|
+
const seenEndpoints = new Set();
|
|
1025
|
+
const worker = new CommsActivityWorker();
|
|
1026
|
+
for (const ev of softBounces) {
|
|
1027
|
+
const epId = ev.CommunicationEndpointID;
|
|
1028
|
+
const key = epId.toLowerCase();
|
|
1029
|
+
if (seenEndpoints.has(key))
|
|
1030
|
+
continue;
|
|
1031
|
+
const endpoint = epMap.Get(epId);
|
|
1032
|
+
if (!endpoint || endpoint.SoftBounceCount < threshold)
|
|
1033
|
+
continue;
|
|
1034
|
+
seenEndpoints.add(key);
|
|
1035
|
+
const expiresAt = new Date(ev.OccurredAt.getTime() + expiryDays * MS_PER_DAY);
|
|
1036
|
+
await worker.CreatePolicySuppression({
|
|
1037
|
+
CommunicationEndpointID: endpoint.ID,
|
|
1038
|
+
BaseMessageTypeID: endpoint.BaseMessageTypeID,
|
|
1039
|
+
Reason: 'Policy',
|
|
1040
|
+
Source: 'Policy',
|
|
1041
|
+
EffectiveAt: ev.OccurredAt,
|
|
1042
|
+
ExpiresAt: expiresAt,
|
|
1043
|
+
CommunicationLogID: ev.CommunicationLogID ?? null,
|
|
1044
|
+
CommunicationSuppressionPolicyID: policyId,
|
|
1045
|
+
Notes: `Auto-suppressed after ${endpoint.SoftBounceCount} soft bounces`,
|
|
1046
|
+
}, contextUser);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
SoftBounceThresholdPolicy = __decorate([
|
|
1051
|
+
RegisterClass(BaseCommunicationSuppressionPolicy, 'SoftBounceThresholdPolicy')
|
|
1052
|
+
], SoftBounceThresholdPolicy);
|
|
1053
|
+
export { SoftBounceThresholdPolicy };
|
|
1054
|
+
//# sourceMappingURL=CommsActivityWorker.js.map
|