@peopl-health/nexus 5.77.0-dev.16342 → 5.77.0-dev.16439
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/lib/clinical/services/triageRecommendationService.js +8 -1
- package/lib/controllers/messageController.js +0 -1
- package/lib/core/NexusMessaging.js +1 -12
- package/lib/index.d.ts +0 -18
- package/lib/index.js +0 -2
- package/lib/jobs/ScheduledMessageJob.js +0 -9
- package/package.json +1 -1
- package/lib/models/contactGateDecisionModel.js +0 -27
- package/lib/services/contactGateService.js +0 -188
|
@@ -880,6 +880,13 @@ function issuePaths(issues) {
|
|
|
880
880
|
return [...new Set(issues.map((issue) => String(issue.path || '').replace(/\[[^\]]*\]/g, '[]')).filter(Boolean))];
|
|
881
881
|
}
|
|
882
882
|
|
|
883
|
+
// Zod issue paths in dotted form with indices collapsed; keys are the DTO's camelCase, not the model's snake_case.
|
|
884
|
+
function dtoIssues(err) {
|
|
885
|
+
const issues = Array.isArray(err?.issues) ? err.issues : [];
|
|
886
|
+
const paths = issues.map((issue) => ({ path: arr(issue.path).map((key) => (typeof key === 'number' ? '[]' : `.${String(key)}`)).join('').replace(/^\./, '') }));
|
|
887
|
+
return paths.some((issue) => issue.path) ? paths : null;
|
|
888
|
+
}
|
|
889
|
+
|
|
883
890
|
function truncateToCardLimit(elements, repairs) {
|
|
884
891
|
const excess = elements.length - MAX_TRIAGE_CARDS;
|
|
885
892
|
if (excess <= 0) return 0;
|
|
@@ -992,7 +999,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
992
999
|
plan = buildPlan(takeaways, elements);
|
|
993
1000
|
} catch (err) {
|
|
994
1001
|
lastIssues = [{ path: 'plan', problem: err?.message || 'DTO inválido' }];
|
|
995
|
-
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_dto_invalid'); continue; }
|
|
1002
|
+
if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_dto_invalid', dtoIssues(err)); continue; }
|
|
996
1003
|
return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
|
|
997
1004
|
}
|
|
998
1005
|
return outcome({
|
|
@@ -125,7 +125,6 @@ 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 }),
|
|
129
128
|
...(result?.preemptive && {
|
|
130
129
|
preemptive: true,
|
|
131
130
|
note: 'Recipient outside 24h window; template approval in progress, delivery not guaranteed within the next 15 min'
|
|
@@ -26,7 +26,6 @@ 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');
|
|
30
29
|
|
|
31
30
|
const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
|
|
32
31
|
const { getMessages, updateMessage } = require('../services/messageService');
|
|
@@ -244,7 +243,6 @@ class NexusMessaging {
|
|
|
244
243
|
}
|
|
245
244
|
|
|
246
245
|
if (messageData.code) ensureThreadExists(messageData.code);
|
|
247
|
-
if (result?.success === true) observeSend(messageData);
|
|
248
246
|
|
|
249
247
|
return result;
|
|
250
248
|
}
|
|
@@ -390,16 +388,8 @@ class NexusMessaging {
|
|
|
390
388
|
return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
|
|
391
389
|
}
|
|
392
390
|
|
|
393
|
-
let gate = null;
|
|
394
391
|
try {
|
|
395
|
-
|
|
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);
|
|
392
|
+
const result = await this._sendMessage(messageData);
|
|
403
393
|
if (result?.success === true && result?.deferred !== true && !await completeSendClaim(claim.claimId)) {
|
|
404
394
|
logger.error('[NexusMessaging] send claim completion failed; a retry after the claim expires may send again', {
|
|
405
395
|
code: messageData.code,
|
|
@@ -408,7 +398,6 @@ class NexusMessaging {
|
|
|
408
398
|
}
|
|
409
399
|
return result;
|
|
410
400
|
} catch (error) {
|
|
411
|
-
await releaseSend(gate?.decisionId);
|
|
412
401
|
await releaseSendClaim(claim.claimId);
|
|
413
402
|
throw error;
|
|
414
403
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -942,24 +942,6 @@ 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
|
-
|
|
963
945
|
export const supportCandidateService: {
|
|
964
946
|
updateSupportOperationalReview(request: {
|
|
965
947
|
patientId: string;
|
package/lib/index.js
CHANGED
|
@@ -54,7 +54,6 @@ 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');
|
|
58
57
|
const supportActionService = require('./clinical/services/supportActionService');
|
|
59
58
|
const supportLightService = require('./clinical/services/supportLightService');
|
|
60
59
|
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
@@ -396,7 +395,6 @@ module.exports = {
|
|
|
396
395
|
MapCache,
|
|
397
396
|
supportCandidateService,
|
|
398
397
|
registerDashboardProvider,
|
|
399
|
-
registerContactCategories,
|
|
400
398
|
supportActionService,
|
|
401
399
|
supportLightService,
|
|
402
400
|
supportInvitability,
|
|
@@ -144,15 +144,6 @@ 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
|
-
|
|
156
147
|
const messageId = result?.messageId || result?.sid || null;
|
|
157
148
|
|
|
158
149
|
await ScheduledMessage.updateOne(
|
package/package.json
CHANGED
|
@@ -1,27 +0,0 @@
|
|
|
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 };
|
|
@@ -1,188 +0,0 @@
|
|
|
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 };
|