@peopl-health/nexus 5.77.0-dev.16448 → 5.77.0-dev.16506
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 +26 -0
- package/lib/clinical/helpers/chemoContextHelper.js +6 -3
- package/lib/controllers/messageController.js +1 -0
- package/lib/core/NexusMessaging.js +12 -1
- package/lib/index.d.ts +18 -0
- package/lib/index.js +2 -0
- package/lib/jobs/ScheduledMessageJob.js +9 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/services/contactGateService.js +188 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -241,6 +241,32 @@ You can configure Nexus via environment variables or at runtime using simple inj
|
|
|
241
241
|
A custom service can be injected with `messaging.llmMonitor.service`. Use an
|
|
242
242
|
explicit `reconcile({ from, to })` range for intentional historical backfills.
|
|
243
243
|
|
|
244
|
+
- Contact gate
|
|
245
|
+
- `CONTACT_GATE_MODE`: `off` (default), `shadow` records every send, `enforce` also holds back the categories below
|
|
246
|
+
- `CONTACT_GATE_ENFORCE`: comma-separated categories to hold back in `enforce` mode, e.g. `invitations`
|
|
247
|
+
|
|
248
|
+
A patient gets at most 2 counted contacts a day and 6 an ISO week, between
|
|
249
|
+
08:00 and 21:00 Mexico City. Clinical, triage and session sends, operator
|
|
250
|
+
messages and replies to a patient who wrote in the last 30 minutes are never
|
|
251
|
+
counted or held. Register the category of each template and `triggeredBy`
|
|
252
|
+
value once at startup; anything unregistered is `unclassified`.
|
|
253
|
+
|
|
254
|
+
```js
|
|
255
|
+
const { registerContactCategories } = require('@peopl-health/nexus');
|
|
256
|
+
registerContactCategories({
|
|
257
|
+
contentSids: { HXinvitationSid: 'invitations' },
|
|
258
|
+
triggeredBy: { charla_invitation: 'invitations', invitation_engaged: 'sessions' },
|
|
259
|
+
});
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Categories: `clinical`, `triage`, `sessions`, `followup`, `invitations`,
|
|
263
|
+
`unclassified`. A held send returns
|
|
264
|
+
`{ success: false, status: 'contact_capped', reason, category, delivered: false }`
|
|
265
|
+
with `reason` one of `outside_hours`, `daily_cap`, `weekly_cap`; nothing is
|
|
266
|
+
sent or stored as a message. `POST /api/message/send` answers it with 200 and
|
|
267
|
+
the `reason`, and a scheduled message held back is cancelled. The gate fails
|
|
268
|
+
open: if it cannot decide within 2 s, the send goes out.
|
|
269
|
+
|
|
244
270
|
- AWS (S3)
|
|
245
271
|
- AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION (default: us-east-1)
|
|
246
272
|
- AWS_S3_BUCKET_NAME (or inject via `configureMediaController`)
|
|
@@ -14,6 +14,9 @@ const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
|
|
|
14
14
|
|
|
15
15
|
const isDay = (value) => typeof value === 'string' && ISO_DAY.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
|
|
16
16
|
const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
|
|
17
|
+
// a weekday with the date: the model miscounts the day of the week from a bare date ("el viernes" for a Saturday)
|
|
18
|
+
const WEEKDAYS = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
|
|
19
|
+
const weekdayDmy = (iso) => `${WEEKDAYS[new Date(`${iso}T00:00:00Z`).getUTCDay()]} ${dmy(iso)}`;
|
|
17
20
|
const addDays = (iso, days) => new Date(Date.parse(`${iso}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
|
|
18
21
|
const fold = (value) => foldAccents(String(value || '')).toLowerCase().trim();
|
|
19
22
|
const text = (value) => (typeof value === 'string' ? value.trim() : '');
|
|
@@ -132,13 +135,13 @@ function chemoLines(context, today) {
|
|
|
132
135
|
}
|
|
133
136
|
if (context.proximaSesion && context.proximaSesion.fecha >= today) {
|
|
134
137
|
lines.push(context.proximaSesion.tipo === 'agendada'
|
|
135
|
-
? `Próxima sesión de quimioterapia: ${
|
|
136
|
-
: `Próxima sesión de quimioterapia: ${
|
|
138
|
+
? `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
|
|
139
|
+
: `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
|
|
137
140
|
}
|
|
138
141
|
const support = context.proximaVisitaSoporte;
|
|
139
142
|
if (support && support.fecha >= today) {
|
|
140
143
|
const care = texts(support.detalle);
|
|
141
|
-
lines.push(`Próxima visita a la unidad sin quimioterapia: ${
|
|
144
|
+
lines.push(`Próxima visita a la unidad sin quimioterapia: ${weekdayDmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
|
|
142
145
|
}
|
|
143
146
|
if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
|
|
144
147
|
if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
|
|
@@ -125,6 +125,7 @@ const sendMessageController = async (req, res) => {
|
|
|
125
125
|
success: result?.success ?? true,
|
|
126
126
|
messageId: _pickMessageId(result, null),
|
|
127
127
|
status: result?.status || null,
|
|
128
|
+
...(result?.reason && { reason: result.reason }),
|
|
128
129
|
...(result?.preemptive && {
|
|
129
130
|
preemptive: true,
|
|
130
131
|
note: 'Recipient outside 24h window; template approval in progress, delivery not guaranteed within the next 15 min'
|
|
@@ -26,6 +26,7 @@ const { isStaffSend } = require('../helpers/staffSendHelper');
|
|
|
26
26
|
|
|
27
27
|
const { createMessagingProvider } = require('../adapters/registry');
|
|
28
28
|
const { ensureThreadExists } = require('../services/threadService');
|
|
29
|
+
const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
|
|
29
30
|
|
|
30
31
|
const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
|
|
31
32
|
const { getMessages, updateMessage } = require('../services/messageService');
|
|
@@ -243,6 +244,7 @@ class NexusMessaging {
|
|
|
243
244
|
}
|
|
244
245
|
|
|
245
246
|
if (messageData.code) ensureThreadExists(messageData.code);
|
|
247
|
+
if (result?.success === true) observeSend(messageData);
|
|
246
248
|
|
|
247
249
|
return result;
|
|
248
250
|
}
|
|
@@ -388,8 +390,16 @@ class NexusMessaging {
|
|
|
388
390
|
return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
|
|
389
391
|
}
|
|
390
392
|
|
|
393
|
+
let gate = null;
|
|
391
394
|
try {
|
|
392
|
-
|
|
395
|
+
gate = await reserveSend(messageData);
|
|
396
|
+
if (gate?.blocked) {
|
|
397
|
+
await releaseSendClaim(claim.claimId);
|
|
398
|
+
return { success: false, messageId: null, status: 'contact_capped', reason: gate.reason, category: gate.category, delivered: false, deferred: false };
|
|
399
|
+
}
|
|
400
|
+
const result = await this._sendMessage(gate ? { ...messageData, contactGateDecisionId: gate.decisionId } : messageData);
|
|
401
|
+
// A deferred send is recorded when it actually leaves, so its reservation must not also count.
|
|
402
|
+
if (result?.success !== true || result?.deferred === true) await releaseSend(gate?.decisionId);
|
|
393
403
|
if (result?.success === true && result?.deferred !== true && !await completeSendClaim(claim.claimId)) {
|
|
394
404
|
logger.error('[NexusMessaging] send claim completion failed; a retry after the claim expires may send again', {
|
|
395
405
|
code: messageData.code,
|
|
@@ -398,6 +408,7 @@ class NexusMessaging {
|
|
|
398
408
|
}
|
|
399
409
|
return result;
|
|
400
410
|
} catch (error) {
|
|
411
|
+
await releaseSend(gate?.decisionId);
|
|
401
412
|
await releaseSendClaim(claim.claimId);
|
|
402
413
|
throw error;
|
|
403
414
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -942,6 +942,24 @@ declare module '@peopl-health/nexus' {
|
|
|
942
942
|
provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
|
|
943
943
|
): void;
|
|
944
944
|
|
|
945
|
+
export type ContactCategory = 'clinical' | 'triage' | 'sessions' | 'followup' | 'invitations' | 'unclassified';
|
|
946
|
+
|
|
947
|
+
/** What sendMessage returns when the contact gate holds a send back; it never reached the provider. */
|
|
948
|
+
export interface ContactCappedSendResult {
|
|
949
|
+
success: false;
|
|
950
|
+
messageId: null;
|
|
951
|
+
status: 'contact_capped';
|
|
952
|
+
reason: 'outside_hours' | 'daily_cap' | 'weekly_cap';
|
|
953
|
+
category: ContactCategory;
|
|
954
|
+
delivered: false;
|
|
955
|
+
deferred: false;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
export function registerContactCategories(categories: {
|
|
959
|
+
contentSids?: Record<string, ContactCategory>;
|
|
960
|
+
triggeredBy?: Record<string, ContactCategory>;
|
|
961
|
+
}): void;
|
|
962
|
+
|
|
945
963
|
export const supportCandidateService: {
|
|
946
964
|
updateSupportOperationalReview(request: {
|
|
947
965
|
patientId: string;
|
package/lib/index.js
CHANGED
|
@@ -54,6 +54,7 @@ const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./serv
|
|
|
54
54
|
const { MapCache } = require('./utils/MapCache');
|
|
55
55
|
const supportCandidateService = require('./clinical/services/supportCandidateService');
|
|
56
56
|
const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
|
|
57
|
+
const { registerContactCategories } = require('./services/contactGateService');
|
|
57
58
|
const supportActionService = require('./clinical/services/supportActionService');
|
|
58
59
|
const supportLightService = require('./clinical/services/supportLightService');
|
|
59
60
|
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
@@ -395,6 +396,7 @@ module.exports = {
|
|
|
395
396
|
MapCache,
|
|
396
397
|
supportCandidateService,
|
|
397
398
|
registerDashboardProvider,
|
|
399
|
+
registerContactCategories,
|
|
398
400
|
supportActionService,
|
|
399
401
|
supportLightService,
|
|
400
402
|
supportInvitability,
|
|
@@ -144,6 +144,15 @@ class ScheduledMessageJob extends BaseJob {
|
|
|
144
144
|
return { success: false, reason: result.status };
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
if (result?.status === 'contact_capped') {
|
|
148
|
+
await ScheduledMessage.updateOne(
|
|
149
|
+
{ _id: scheduledMessageId },
|
|
150
|
+
{ $set: { status: 'cancelled', errorCode: result.status, errorMessage: `Contact limit reached: ${result.reason}` } }
|
|
151
|
+
);
|
|
152
|
+
logger.info('[ScheduledMessageJob] Not sent, the patient reached her contact limit', { scheduledMessageId, reason: result.reason });
|
|
153
|
+
return { success: false, reason: result.status };
|
|
154
|
+
}
|
|
155
|
+
|
|
147
156
|
const messageId = result?.messageId || result?.sid || null;
|
|
148
157
|
|
|
149
158
|
await ScheduledMessage.updateOne(
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const CONTACT_GATE_TTL_SECONDS = 90 * 24 * 60 * 60;
|
|
4
|
+
|
|
5
|
+
const contactGateDecisionSchema = new mongoose.Schema({
|
|
6
|
+
code: { type: String, required: true },
|
|
7
|
+
contactCode: { type: String, default: null },
|
|
8
|
+
kind: { type: String, enum: ['operator', 'reply', 'proactive'], required: true },
|
|
9
|
+
category: { type: String, default: null },
|
|
10
|
+
mode: { type: String, enum: ['shadow', 'enforce'], required: true },
|
|
11
|
+
status: { type: String, enum: ['reserved', 'sent', 'blocked', 'failed', null], default: null },
|
|
12
|
+
wouldAllow: { type: Boolean, required: true },
|
|
13
|
+
reason: { type: String, default: null },
|
|
14
|
+
dayCount: { type: Number, default: 0 },
|
|
15
|
+
weekCount: { type: Number, default: 0 },
|
|
16
|
+
sendKind: { type: String, default: null },
|
|
17
|
+
triggeredBy: { type: String, default: null },
|
|
18
|
+
contentSid: { type: String, default: null },
|
|
19
|
+
createdAt: { type: Date, default: Date.now }
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
contactGateDecisionSchema.index({ code: 1, kind: 1, createdAt: -1 }, { name: 'contact_gate_code_kind_idx' });
|
|
23
|
+
contactGateDecisionSchema.index({ createdAt: 1 }, { name: 'contact_gate_ttl_idx', expireAfterSeconds: CONTACT_GATE_TTL_SECONDS });
|
|
24
|
+
|
|
25
|
+
const ContactGateDecision = mongoose.model('ContactGateDecision', contactGateDecisionSchema);
|
|
26
|
+
|
|
27
|
+
module.exports = { ContactGateDecision, CONTACT_GATE_TTL_SECONDS };
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
const moment = require('moment-timezone');
|
|
2
|
+
|
|
3
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
|
+
const { logger } = require('../utils/logger');
|
|
5
|
+
|
|
6
|
+
const { ContactGateDecision } = require('../models/contactGateDecisionModel');
|
|
7
|
+
const { isStaffSend } = require('../helpers/staffSendHelper');
|
|
8
|
+
const { getMessages } = require('./messageService');
|
|
9
|
+
|
|
10
|
+
const CATEGORIES = ['clinical', 'triage', 'sessions', 'followup', 'invitations', 'unclassified'];
|
|
11
|
+
const EXEMPT_CATEGORIES = ['clinical', 'triage', 'sessions'];
|
|
12
|
+
const DAILY_CAP = 2;
|
|
13
|
+
const WEEKLY_CAP = 6;
|
|
14
|
+
const CONTACT_TIMEZONE = 'America/Mexico_City';
|
|
15
|
+
const CONTACT_HOURS = { start: 8, end: 21 };
|
|
16
|
+
const REPLY_WINDOW_MS = 30 * 60 * 1000;
|
|
17
|
+
const MODES = ['shadow', 'enforce'];
|
|
18
|
+
const NOT_COUNTED_STATUSES = ['blocked', 'failed'];
|
|
19
|
+
const CHECK_TIMEOUT_MS = 2000;
|
|
20
|
+
const NEXUS_TRIGGER_CATEGORIES = {
|
|
21
|
+
paused_safety_net: 'clinical',
|
|
22
|
+
seguimiento: 'followup',
|
|
23
|
+
followup: 'followup',
|
|
24
|
+
send_reminder: 'followup'
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const registered = { contentSids: {}, triggeredBy: {} };
|
|
28
|
+
|
|
29
|
+
function registerContactCategories({ contentSids = {}, triggeredBy = {} } = {}) {
|
|
30
|
+
const unknown = [...Object.values(contentSids), ...Object.values(triggeredBy)].find(value => !CATEGORIES.includes(value));
|
|
31
|
+
if (unknown !== undefined) throw new Error(`Unknown contact category: ${unknown}`);
|
|
32
|
+
Object.assign(registered.contentSids, contentSids);
|
|
33
|
+
Object.assign(registered.triggeredBy, triggeredBy);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function contactGateMode() {
|
|
37
|
+
const mode = runtimeConfig.get('CONTACT_GATE_MODE');
|
|
38
|
+
return MODES.includes(mode) ? mode : 'off';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Only an explicit list blocks; an exempt category in it is still never counted, so never blocked.
|
|
42
|
+
function enforcedCategories() {
|
|
43
|
+
if (contactGateMode() !== 'enforce') return [];
|
|
44
|
+
return String(runtimeConfig.get('CONTACT_GATE_ENFORCE') || '').split(',').map(value => value.trim()).filter(Boolean);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function triggerSource(triggeredBy) {
|
|
48
|
+
const trigger = String(triggeredBy || '');
|
|
49
|
+
return trigger.startsWith('followup_') ? 'followup' : trigger.split(':')[0];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function categoryOf({ contentSid, triggeredBy }) {
|
|
53
|
+
const source = triggerSource(triggeredBy);
|
|
54
|
+
return registered.triggeredBy[source] || registered.contentSids[contentSid] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A released or recovery send carries no trigger of its own; it inherits the one of the message it delivers.
|
|
58
|
+
async function triggerOf({ triggeredBy, parentMessageId }) {
|
|
59
|
+
if (triggeredBy || !parentMessageId) return triggeredBy || null;
|
|
60
|
+
const [parent] = await getMessages({ _id: parentMessageId }, { select: 'triggeredBy', limit: 1 });
|
|
61
|
+
return parent?.triggeredBy || null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function classify(messageData, now) {
|
|
65
|
+
if (isStaffSend(messageData.triggeredBy)) return { kind: 'operator', category: null };
|
|
66
|
+
const [inbound] = await getMessages(
|
|
67
|
+
{
|
|
68
|
+
numero: messageData.code,
|
|
69
|
+
contact_code: messageData.contactCode || null,
|
|
70
|
+
from_me: false,
|
|
71
|
+
createdAt: { $gte: new Date(now.getTime() - REPLY_WINDOW_MS) }
|
|
72
|
+
},
|
|
73
|
+
{ select: '_id', limit: 1 }
|
|
74
|
+
);
|
|
75
|
+
return { kind: inbound ? 'reply' : 'proactive', category: categoryOf(messageData) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const isCounted = ({ kind, category }) => kind === 'proactive' && !EXEMPT_CATEGORIES.includes(category);
|
|
79
|
+
|
|
80
|
+
async function priorCounts(code, now, ownId = null) {
|
|
81
|
+
const local = moment(now).tz(CONTACT_TIMEZONE);
|
|
82
|
+
const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES }, status: { $nin: NOT_COUNTED_STATUSES } };
|
|
83
|
+
if (ownId) counted._id = { $ne: ownId };
|
|
84
|
+
const [dayCount, weekCount] = await Promise.all([
|
|
85
|
+
ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('day').toDate() } }),
|
|
86
|
+
ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('isoWeek').toDate() } })
|
|
87
|
+
]);
|
|
88
|
+
return { dayCount, weekCount };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function verdict(classified, { dayCount, weekCount }, now) {
|
|
92
|
+
if (!isCounted(classified)) return { wouldAllow: true, reason: null };
|
|
93
|
+
const hour = moment(now).tz(CONTACT_TIMEZONE).hour();
|
|
94
|
+
if (hour < CONTACT_HOURS.start || hour >= CONTACT_HOURS.end) return { wouldAllow: false, reason: 'outside_hours' };
|
|
95
|
+
if (dayCount >= DAILY_CAP) return { wouldAllow: false, reason: 'daily_cap' };
|
|
96
|
+
if (weekCount >= WEEKLY_CAP) return { wouldAllow: false, reason: 'weekly_cap' };
|
|
97
|
+
return { wouldAllow: true, reason: null };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function decisionRow(messageData, classified, triggeredBy, now) {
|
|
101
|
+
return {
|
|
102
|
+
code: messageData.code,
|
|
103
|
+
...classified,
|
|
104
|
+
mode: contactGateMode(),
|
|
105
|
+
contactCode: messageData.contactCode || null,
|
|
106
|
+
sendKind: messageData.kind || null,
|
|
107
|
+
triggeredBy,
|
|
108
|
+
contentSid: messageData.contentSid || null,
|
|
109
|
+
createdAt: now
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function withTimeout(promise) {
|
|
114
|
+
let timer;
|
|
115
|
+
const timeout = new Promise((resolve, reject) => {
|
|
116
|
+
timer = setTimeout(() => reject(new Error('contact gate check timed out')), CHECK_TIMEOUT_MS);
|
|
117
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
118
|
+
});
|
|
119
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The reservation is written before counting, so of two concurrent sends at the last slot at most one goes out.
|
|
123
|
+
async function reserve(messageData, enforced, now) {
|
|
124
|
+
const triggeredBy = await triggerOf(messageData);
|
|
125
|
+
const classified = await classify({ ...messageData, triggeredBy }, now);
|
|
126
|
+
if (!isCounted(classified) || !enforced.includes(classified.category)) return null;
|
|
127
|
+
const row = await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), wouldAllow: true, status: 'reserved' });
|
|
128
|
+
let decided;
|
|
129
|
+
try {
|
|
130
|
+
const counts = await priorCounts(messageData.code, now, row._id);
|
|
131
|
+
decided = verdict(classified, counts, now);
|
|
132
|
+
await ContactGateDecision.updateOne({ _id: row._id }, { $set: { ...decided, ...counts, status: decided.wouldAllow ? 'reserved' : 'blocked' } });
|
|
133
|
+
} catch (error) {
|
|
134
|
+
await releaseSend(row._id);
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
return decided.wouldAllow
|
|
138
|
+
? { decisionId: row._id }
|
|
139
|
+
: { blocked: true, decisionId: row._id, reason: decided.reason, category: classified.category };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Decides before the send whether an enforced category may go out; any failure lets the send through.
|
|
143
|
+
async function reserveSend(messageData, now = new Date()) {
|
|
144
|
+
const code = messageData?.code;
|
|
145
|
+
try {
|
|
146
|
+
const enforced = enforcedCategories();
|
|
147
|
+
if (!enforced.length || !code) return null;
|
|
148
|
+
const pending = reserve(messageData, enforced, now);
|
|
149
|
+
// A check that finishes after the send went out frees its slot; that send is recorded when it leaves.
|
|
150
|
+
return await withTimeout(pending).catch(error => {
|
|
151
|
+
pending.then(late => releaseSend(late?.decisionId), () => {});
|
|
152
|
+
throw error;
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
logger.warn('[contactGate] Send was not checked and goes out', { code, error: error.message });
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// A reservation whose send never left frees its slot.
|
|
161
|
+
async function releaseSend(decisionId) {
|
|
162
|
+
if (!decisionId) return;
|
|
163
|
+
try {
|
|
164
|
+
await ContactGateDecision.updateOne({ _id: decisionId, status: 'reserved' }, { $set: { status: 'failed' } });
|
|
165
|
+
} catch (error) {
|
|
166
|
+
logger.warn('[contactGate] Reservation was not released', { decisionId: String(decisionId), error: error.message });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Records every send that left; a send the gate reserved only confirms its row.
|
|
171
|
+
async function observeSend(messageData, now = new Date()) {
|
|
172
|
+
const code = messageData?.code;
|
|
173
|
+
try {
|
|
174
|
+
if (contactGateMode() === 'off' || !code) return null;
|
|
175
|
+
if (messageData.contactGateDecisionId) {
|
|
176
|
+
return await ContactGateDecision.findOneAndUpdate({ _id: messageData.contactGateDecisionId }, { $set: { status: 'sent' } }, { new: true });
|
|
177
|
+
}
|
|
178
|
+
const triggeredBy = await triggerOf(messageData);
|
|
179
|
+
const classified = await classify({ ...messageData, triggeredBy }, now);
|
|
180
|
+
const counts = isCounted(classified) ? await priorCounts(code, now) : { dayCount: 0, weekCount: 0 };
|
|
181
|
+
return await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), ...verdict(classified, counts, now), ...counts });
|
|
182
|
+
} catch (error) {
|
|
183
|
+
logger.warn('[contactGate] Send was not recorded', { code, error: error.message });
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
module.exports = { registerContactCategories, reserveSend, releaseSend, observeSend };
|