@peopl-health/nexus 6.0.0-dev.16508 → 6.0.0-dev.16614
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/flags/escalationFlags.js +7 -5
- package/lib/clinical/services/escalationDraftService.js +13 -6
- package/lib/clinical/services/triageRecommendationService.js +15 -2
- 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 +178 -0
- package/lib/services/escalationReviewService.js +2 -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`)
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
2
2
|
|
|
3
3
|
const flagOn = (key) => String(runtimeConfig.get(key, 'false')).trim().toLowerCase() === 'true';
|
|
4
|
+
// Launched behaviour stays on unless the variable is set to 'false'.
|
|
5
|
+
const flagNotOff = (key) => String(runtimeConfig.get(key, 'true')).trim().toLowerCase() !== 'false';
|
|
4
6
|
|
|
5
7
|
function escalationUpdateModeLive() {
|
|
6
|
-
return
|
|
8
|
+
return flagNotOff('ESCALATION_UPDATE_MODE_LIVE');
|
|
7
9
|
}
|
|
8
10
|
|
|
9
11
|
function escalationAssessmentLive() {
|
|
@@ -11,7 +13,7 @@ function escalationAssessmentLive() {
|
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
function feverPatientTimerLive() {
|
|
14
|
-
return
|
|
16
|
+
return flagNotOff('FEVER_PATIENT_TIMER_LIVE');
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
function escalationApproverAlertLive() {
|
|
@@ -19,15 +21,15 @@ function escalationApproverAlertLive() {
|
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
function escalationPatientTimerLive() {
|
|
22
|
-
return
|
|
24
|
+
return flagNotOff('ESCALATION_PATIENT_TIMER_LIVE');
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
function escalationAutoHandoffLive() {
|
|
26
|
-
return
|
|
28
|
+
return flagNotOff('ESCALATION_AUTO_HANDOFF_LIVE');
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
function escalationUntakenAlertsLive() {
|
|
30
|
-
return
|
|
32
|
+
return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
module.exports = {
|
|
@@ -90,18 +90,24 @@ function draftProvider() {
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
const MAX_URGENT_FLAGS = 2;
|
|
93
|
-
const
|
|
93
|
+
const flagKey = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
|
|
94
94
|
|
|
95
|
-
// The model does not always keep to two grave flags per symptom
|
|
96
|
-
|
|
95
|
+
// The model does not always keep to two grave flags per symptom. Confirmed flags keep the mark first, then the pending ones the
|
|
96
|
+
// previous draft already held (so their wait keeps running when the model reorders them), then the rest in its order.
|
|
97
|
+
function capUrgentFlags(block, held) {
|
|
97
98
|
const urgent = (Array.isArray(block?.redFlags) ? block.redFlags : []).filter((flag) => flag?.urgentIfPositive === true);
|
|
98
99
|
if (urgent.length <= MAX_URGENT_FLAGS) return block;
|
|
99
|
-
const
|
|
100
|
+
const rank = (flag) => {
|
|
101
|
+
if (flag.present === true) return 0;
|
|
102
|
+
if (flag.present === false) return 3;
|
|
103
|
+
return held.has(flagKey(flag.flag)) ? 1 : 2;
|
|
104
|
+
};
|
|
105
|
+
const kept = new Set([...urgent].sort((a, b) => rank(a) - rank(b)).slice(0, MAX_URGENT_FLAGS));
|
|
100
106
|
return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
|
|
101
107
|
}
|
|
102
108
|
|
|
103
109
|
async function generateEscalationDraft({
|
|
104
|
-
code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
|
|
110
|
+
code, callLogs = [], alarms = [], agentCharacterization = null, heldUrgentFlags = [], provider, trace = null, reviewId = null, now = Date.now(),
|
|
105
111
|
} = {}) {
|
|
106
112
|
const { presetId } = await getEscalationDraft();
|
|
107
113
|
const llm = provider ?? draftProvider();
|
|
@@ -142,7 +148,8 @@ async function generateEscalationDraft({
|
|
|
142
148
|
const parsed = safeParse(readStructuredText(result), null);
|
|
143
149
|
const patientMessage = trimmed(parsed?.patientMessage);
|
|
144
150
|
// The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
|
|
145
|
-
const
|
|
151
|
+
const held = new Set(heldUrgentFlags.map(flagKey));
|
|
152
|
+
const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(block, held));
|
|
146
153
|
if (!blocks.length) {
|
|
147
154
|
const shape = parsed.symptoms;
|
|
148
155
|
logger.warn('[escalationDraft] generation returned a malformed symptom list', {
|
|
@@ -44,6 +44,7 @@ const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper'
|
|
|
44
44
|
const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
|
|
45
45
|
const { getCatalog } = require('../../fhir/services/terminologyService');
|
|
46
46
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
47
|
+
const { findArchivedByRecordIds } = require('../../services/airtableArchiveReadService');
|
|
47
48
|
const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
|
|
48
49
|
const { recommendationId } = require('../../fhir/helpers/recommendationIds');
|
|
49
50
|
const { RecommendationSafetyGate } = require('../../shared/dtos/RecommendationSafetyGate');
|
|
@@ -1130,8 +1131,9 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1130
1131
|
.filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
|
|
1131
1132
|
if (!ids.length) return [];
|
|
1132
1133
|
const formula = `OR(${ids.map((id) => `{recordID}='${id}'`).join(',')})`;
|
|
1133
|
-
const
|
|
1134
|
-
if (!
|
|
1134
|
+
const live = await getRecordByFilter(Symptoms_ID, 'cluster_resolutions', formula).catch(() => null);
|
|
1135
|
+
if (!live) return [];
|
|
1136
|
+
const rows = [...live, ...await readArchivedResolutions(ids.filter((id) => !live.some((row) => row.recordID === id)))];
|
|
1135
1137
|
if (!patientRecordId && rows.length) {
|
|
1136
1138
|
logger.warn('[triageRecommendation] prior resolutions unverified: payload carries no patientRecordId', { count: rows.length });
|
|
1137
1139
|
}
|
|
@@ -1145,6 +1147,17 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1145
1147
|
.filter(Boolean);
|
|
1146
1148
|
}
|
|
1147
1149
|
|
|
1150
|
+
// A resolution deleted from Airtable is read from its archived copy; an unreadable archive only loses that context.
|
|
1151
|
+
async function readArchivedResolutions(ids) {
|
|
1152
|
+
if (!ids.length) return [];
|
|
1153
|
+
try {
|
|
1154
|
+
return await findArchivedByRecordIds({ baseId: Symptoms_ID, tableName: 'cluster_resolutions', recordIds: ids });
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
logger.warn('[triageRecommendation] archived prior resolutions unreadable', { count: ids.length, error: error?.message });
|
|
1157
|
+
return [];
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1148
1161
|
function ownedByPatient(row, patientRecordId) {
|
|
1149
1162
|
const owners = Array.isArray(row[PATIENT_LOOKUP_FIELD]) ? row[PATIENT_LOOKUP_FIELD] : [];
|
|
1150
1163
|
if (owners.includes(patientRecordId)) return true;
|
|
@@ -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 };
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
const moment = require('moment-timezone');
|
|
2
|
+
|
|
3
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
|
+
const { logger } = require('../utils/logger');
|
|
5
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
|
+
const { isWithinHourWindow } = require('../utils/scheduleUtils');
|
|
7
|
+
|
|
8
|
+
const { ContactGateDecision } = require('../models/contactGateDecisionModel');
|
|
9
|
+
const { isStaffSend } = require('../helpers/staffSendHelper');
|
|
10
|
+
const { CONTACT_WINDOW } = require('../clinical/config/safetyNetConfig');
|
|
11
|
+
const { getMessages } = require('./messageService');
|
|
12
|
+
|
|
13
|
+
const CATEGORIES = ['clinical', 'triage', 'sessions', 'followup', 'invitations', 'unclassified'];
|
|
14
|
+
const EXEMPT_CATEGORIES = ['clinical', 'triage', 'sessions'];
|
|
15
|
+
const DAILY_CAP = 2;
|
|
16
|
+
const WEEKLY_CAP = 6;
|
|
17
|
+
const REPLY_WINDOW_MS = 30 * 60 * 1000;
|
|
18
|
+
const MODES = ['shadow', 'enforce'];
|
|
19
|
+
const NOT_COUNTED_STATUSES = ['blocked', 'failed'];
|
|
20
|
+
const CHECK_TIMEOUT_MS = 2000;
|
|
21
|
+
const NEXUS_TRIGGER_CATEGORIES = {
|
|
22
|
+
paused_safety_net: 'clinical',
|
|
23
|
+
seguimiento: 'followup',
|
|
24
|
+
followup: 'followup',
|
|
25
|
+
send_reminder: 'followup'
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const registered = { contentSids: {}, triggeredBy: {} };
|
|
29
|
+
|
|
30
|
+
function registerContactCategories({ contentSids = {}, triggeredBy = {} } = {}) {
|
|
31
|
+
const unknown = [...Object.values(contentSids), ...Object.values(triggeredBy)].find(value => !CATEGORIES.includes(value));
|
|
32
|
+
if (unknown !== undefined) throw new Error(`Unknown contact category: ${unknown}`);
|
|
33
|
+
Object.assign(registered.contentSids, contentSids);
|
|
34
|
+
Object.assign(registered.triggeredBy, triggeredBy);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function contactGateMode() {
|
|
38
|
+
const mode = runtimeConfig.get('CONTACT_GATE_MODE');
|
|
39
|
+
return MODES.includes(mode) ? mode : 'off';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Only an explicit list blocks; an exempt category in it is still never counted, so never blocked.
|
|
43
|
+
function enforcedCategories() {
|
|
44
|
+
if (contactGateMode() !== 'enforce') return [];
|
|
45
|
+
return String(runtimeConfig.get('CONTACT_GATE_ENFORCE') || '').split(',').map(value => value.trim()).filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function triggerSource(triggeredBy) {
|
|
49
|
+
const trigger = String(triggeredBy || '');
|
|
50
|
+
return trigger.startsWith('followup_') ? 'followup' : trigger.split(':')[0];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function categoryOf({ contentSid, triggeredBy }) {
|
|
54
|
+
const source = triggerSource(triggeredBy);
|
|
55
|
+
return registered.triggeredBy[source] || registered.contentSids[contentSid] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A released or recovery send carries no trigger of its own; it inherits the one of the message it delivers.
|
|
59
|
+
async function triggerOf({ triggeredBy, parentMessageId }) {
|
|
60
|
+
if (triggeredBy || !parentMessageId) return triggeredBy || null;
|
|
61
|
+
const [parent] = await getMessages({ _id: parentMessageId }, { select: 'triggeredBy', limit: 1 });
|
|
62
|
+
return parent?.triggeredBy || null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function classify(messageData, now) {
|
|
66
|
+
if (isStaffSend(messageData.triggeredBy)) return { kind: 'operator', category: null };
|
|
67
|
+
const [inbound] = await getMessages(
|
|
68
|
+
{
|
|
69
|
+
numero: messageData.code,
|
|
70
|
+
contact_code: messageData.contactCode || null,
|
|
71
|
+
from_me: false,
|
|
72
|
+
createdAt: { $gte: new Date(now.getTime() - REPLY_WINDOW_MS) }
|
|
73
|
+
},
|
|
74
|
+
{ select: '_id', limit: 1 }
|
|
75
|
+
);
|
|
76
|
+
return { kind: inbound ? 'reply' : 'proactive', category: categoryOf(messageData) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const isCounted = ({ kind, category }) => kind === 'proactive' && !EXEMPT_CATEGORIES.includes(category);
|
|
80
|
+
|
|
81
|
+
async function priorCounts(code, now, ownId = null) {
|
|
82
|
+
const local = moment(now).tz(CONTACT_WINDOW.timeZone);
|
|
83
|
+
const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES }, status: { $nin: NOT_COUNTED_STATUSES } };
|
|
84
|
+
if (ownId) counted._id = { $ne: ownId };
|
|
85
|
+
const [dayCount, weekCount] = await Promise.all([
|
|
86
|
+
ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('day').toDate() } }),
|
|
87
|
+
ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('isoWeek').toDate() } })
|
|
88
|
+
]);
|
|
89
|
+
return { dayCount, weekCount };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function verdict(classified, { dayCount, weekCount }, now) {
|
|
93
|
+
if (!isCounted(classified)) return { wouldAllow: true, reason: null };
|
|
94
|
+
if (!isWithinHourWindow(now, CONTACT_WINDOW)) 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
|
+
// The reservation is written before counting, so of two concurrent sends at the last slot at most one goes out.
|
|
114
|
+
async function reserve(messageData, enforced, now) {
|
|
115
|
+
const triggeredBy = await triggerOf(messageData);
|
|
116
|
+
const classified = await classify({ ...messageData, triggeredBy }, now);
|
|
117
|
+
if (!isCounted(classified) || !enforced.includes(classified.category)) return null;
|
|
118
|
+
const row = await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), wouldAllow: true, status: 'reserved' });
|
|
119
|
+
let decided;
|
|
120
|
+
try {
|
|
121
|
+
const counts = await priorCounts(messageData.code, now, row._id);
|
|
122
|
+
decided = verdict(classified, counts, now);
|
|
123
|
+
await ContactGateDecision.updateOne({ _id: row._id }, { $set: { ...decided, ...counts, status: decided.wouldAllow ? 'reserved' : 'blocked' } });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
await releaseSend(row._id);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
return decided.wouldAllow
|
|
129
|
+
? { decisionId: row._id }
|
|
130
|
+
: { blocked: true, decisionId: row._id, reason: decided.reason, category: classified.category };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Decides before the send whether an enforced category may go out; any failure lets the send through.
|
|
134
|
+
async function reserveSend(messageData, now = new Date()) {
|
|
135
|
+
const code = messageData?.code;
|
|
136
|
+
try {
|
|
137
|
+
const enforced = enforcedCategories();
|
|
138
|
+
if (!enforced.length || !code) return null;
|
|
139
|
+
const pending = reserve(messageData, enforced, now);
|
|
140
|
+
// A check that finishes after the send went out frees its slot; that send is recorded when it leaves.
|
|
141
|
+
return await withTimeout(pending, CHECK_TIMEOUT_MS, 'contact gate check').catch(error => {
|
|
142
|
+
pending.then(late => releaseSend(late?.decisionId), () => {});
|
|
143
|
+
throw error;
|
|
144
|
+
});
|
|
145
|
+
} catch (error) {
|
|
146
|
+
logger.warn('[contactGate] Send was not checked and goes out', { code, error: error.message });
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function releaseSend(decisionId) {
|
|
152
|
+
if (!decisionId) return;
|
|
153
|
+
try {
|
|
154
|
+
await ContactGateDecision.updateOne({ _id: decisionId, status: 'reserved' }, { $set: { status: 'failed' } });
|
|
155
|
+
} catch (error) {
|
|
156
|
+
logger.warn('[contactGate] Reservation was not released', { decisionId: String(decisionId), error: error.message });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Records every send that left; a send the gate reserved only confirms its row.
|
|
161
|
+
async function observeSend(messageData, now = new Date()) {
|
|
162
|
+
const code = messageData?.code;
|
|
163
|
+
try {
|
|
164
|
+
if (contactGateMode() === 'off' || !code) return null;
|
|
165
|
+
if (messageData.contactGateDecisionId) {
|
|
166
|
+
return await ContactGateDecision.findOneAndUpdate({ _id: messageData.contactGateDecisionId }, { $set: { status: 'sent' } }, { new: true });
|
|
167
|
+
}
|
|
168
|
+
const triggeredBy = await triggerOf(messageData);
|
|
169
|
+
const classified = await classify({ ...messageData, triggeredBy }, now);
|
|
170
|
+
const counts = isCounted(classified) ? await priorCounts(code, now) : { dayCount: 0, weekCount: 0 };
|
|
171
|
+
return await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), ...verdict(classified, counts, now), ...counts });
|
|
172
|
+
} catch (error) {
|
|
173
|
+
logger.warn('[contactGate] Send was not recorded', { code, error: error.message });
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
module.exports = { registerContactCategories, reserveSend, releaseSend, observeSend };
|
|
@@ -865,6 +865,7 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
|
|
|
865
865
|
code: review.patientCode,
|
|
866
866
|
callLogs: review.callLogs ?? [],
|
|
867
867
|
alarms: review.alarms ?? [],
|
|
868
|
+
heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
|
|
868
869
|
reviewId: String(review._id),
|
|
869
870
|
});
|
|
870
871
|
// A generation run sends the patient's context to a model. That is what the audit exists to
|
|
@@ -1426,6 +1427,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1426
1427
|
callLogs: review.callLogs ?? [],
|
|
1427
1428
|
alarms: review.alarms ?? [],
|
|
1428
1429
|
agentCharacterization: characterizationSeedOf(review.updates),
|
|
1430
|
+
heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
|
|
1429
1431
|
reviewId: String(review._id),
|
|
1430
1432
|
});
|
|
1431
1433
|
if (draft.attempted) {
|