@peopl-health/nexus 6.0.0-dev.16505 → 6.0.0-dev.16560
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/doctorReviewMessageHelper.js +1 -0
- package/lib/clinical/services/escalationDraftService.js +26 -4
- 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/models/escalationReviewModel.js +1 -0
- package/lib/services/characterizationOutcomeService.js +20 -5
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/escalationReviewService.js +3 -0
- package/lib/services/untakenAlertService.js +1 -1
- 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`)
|
|
@@ -31,6 +31,7 @@ function flagsByStatus(sections) {
|
|
|
31
31
|
unassessed: pending.map((flag) => inlineOf(flag.flag)),
|
|
32
32
|
drugSafety: pending.filter((flag) => flag.blocksDrug !== false).map((flag) => inlineOf(flag.flag)),
|
|
33
33
|
urgent: pending.filter((flag) => flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
|
|
34
|
+
urgentPresent: flags.filter((flag) => flag.present === true && flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
|
|
34
35
|
unobtainable: pending.filter((flag) => flag.present === UNOBTAINABLE).map((flag) => inlineOf(flag.flag)),
|
|
35
36
|
};
|
|
36
37
|
}
|
|
@@ -89,8 +89,25 @@ function draftProvider() {
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
const MAX_URGENT_FLAGS = 2;
|
|
93
|
+
const flagKey = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
|
|
94
|
+
|
|
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) {
|
|
98
|
+
const urgent = (Array.isArray(block?.redFlags) ? block.redFlags : []).filter((flag) => flag?.urgentIfPositive === true);
|
|
99
|
+
if (urgent.length <= MAX_URGENT_FLAGS) return block;
|
|
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));
|
|
106
|
+
return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
|
|
107
|
+
}
|
|
108
|
+
|
|
92
109
|
async function generateEscalationDraft({
|
|
93
|
-
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(),
|
|
94
111
|
} = {}) {
|
|
95
112
|
const { presetId } = await getEscalationDraft();
|
|
96
113
|
const llm = provider ?? draftProvider();
|
|
@@ -131,7 +148,8 @@ async function generateEscalationDraft({
|
|
|
131
148
|
const parsed = safeParse(readStructuredText(result), null);
|
|
132
149
|
const patientMessage = trimmed(parsed?.patientMessage);
|
|
133
150
|
// The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
|
|
134
|
-
const
|
|
151
|
+
const held = new Set(heldUrgentFlags.map(flagKey));
|
|
152
|
+
const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(block, held));
|
|
135
153
|
if (!blocks.length) {
|
|
136
154
|
const shape = parsed.symptoms;
|
|
137
155
|
logger.warn('[escalationDraft] generation returned a malformed symptom list', {
|
|
@@ -186,6 +204,9 @@ async function generateEscalationDraft({
|
|
|
186
204
|
return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
|
|
187
205
|
}
|
|
188
206
|
|
|
207
|
+
const urgentPresent = [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgentPresent))];
|
|
208
|
+
// A grave flag the patient confirmed is enough for the doctor, whatever else is still pending.
|
|
209
|
+
const sufficientForDoctor = urgentPresent.length ? true : (typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null);
|
|
189
210
|
return {
|
|
190
211
|
completed: true,
|
|
191
212
|
attempted: true,
|
|
@@ -196,9 +217,10 @@ async function generateEscalationDraft({
|
|
|
196
217
|
unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
|
|
197
218
|
urgentUnassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgent))],
|
|
198
219
|
unobtainableRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unobtainable))],
|
|
220
|
+
urgentPresentRedFlags: urgentPresent,
|
|
199
221
|
missingCharacterization: textList(parsed?.missingCharacterization),
|
|
200
|
-
sufficientForDoctor
|
|
201
|
-
blockingQuestion:
|
|
222
|
+
sufficientForDoctor,
|
|
223
|
+
blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
|
|
202
224
|
suggestCall: suggestCallOf(parsed?.suggestCall),
|
|
203
225
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
204
226
|
};
|
|
@@ -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 };
|
|
@@ -133,6 +133,7 @@ const draftSchema = new mongoose.Schema({
|
|
|
133
133
|
unassessedRedFlags: { type: [String], default: undefined },
|
|
134
134
|
urgentUnassessedRedFlags: { type: [String], default: undefined },
|
|
135
135
|
unobtainableRedFlags: { type: [String], default: undefined },
|
|
136
|
+
urgentPresentRedFlags: { type: [String], default: undefined },
|
|
136
137
|
sufficientForDoctor: { type: Boolean, default: undefined },
|
|
137
138
|
blockingQuestion: { type: String, default: undefined },
|
|
138
139
|
missingCharacterization: { type: [String], default: undefined },
|
|
@@ -7,6 +7,7 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
|
|
|
7
7
|
|
|
8
8
|
const { countMessages } = require('./messageService');
|
|
9
9
|
const { logPatientChange } = require('./patientService');
|
|
10
|
+
const { getThreadInfo } = require('./threadService');
|
|
10
11
|
const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
|
|
11
12
|
const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
|
|
12
13
|
const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
@@ -48,7 +49,11 @@ function outcomeOf(review, clock, now) {
|
|
|
48
49
|
const withUpdate = (note) => (update ? noteOf([UPDATE_NOTE, note].filter(Boolean).join(' · ')) : note);
|
|
49
50
|
|
|
50
51
|
const grave = graveMissingOf(review, clock, now);
|
|
51
|
-
|
|
52
|
+
const present = latest.urgentPresentRedFlags ?? [];
|
|
53
|
+
if (grave.length || present.length) {
|
|
54
|
+
const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`];
|
|
55
|
+
return { grave, update, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
|
|
56
|
+
}
|
|
52
57
|
// A grave question still inside its wait holds the case even when the rest is enough.
|
|
53
58
|
if (pendingFlagsOf(review, clock.since).flags.length) return null;
|
|
54
59
|
if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
|
|
@@ -218,12 +223,19 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
|
|
|
218
223
|
return delivered ? sending.length : 0;
|
|
219
224
|
}
|
|
220
225
|
|
|
226
|
+
const unsentGraveAlerts = (review, clock) => (review.graveAlerts ?? []).filter((entry) => !entry.sentAt && timeOf(entry.since) === clock.since.getTime());
|
|
227
|
+
|
|
228
|
+
// A patient in the hospital is already under care: the doctor still gets the grave datum, the team is not called for it.
|
|
229
|
+
async function skipGraveAlerts(review, clock, now) {
|
|
230
|
+
for (const entry of unsentGraveAlerts(review, clock)) await setOn(review, entry, { sentAt: now, skippedReason: 'patient_hospitalized' }, { sentAt: null });
|
|
231
|
+
}
|
|
232
|
+
|
|
221
233
|
// In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
|
|
222
234
|
async function remindQuietPatient(review, clock, now) {
|
|
223
235
|
if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
|
|
224
236
|
const latest = (review.drafts ?? []).at(-1);
|
|
225
237
|
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
|
|
226
|
-
const pending = latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0;
|
|
238
|
+
const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
|
|
227
239
|
if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
228
240
|
const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
|
|
229
241
|
if (now.getTime() < dueAt.getTime()) return;
|
|
@@ -266,13 +278,16 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
266
278
|
async function settleCharacterization(review, clock, now) {
|
|
267
279
|
if (!clock) return;
|
|
268
280
|
const outcome = outcomeOf(review, clock, now);
|
|
269
|
-
const
|
|
281
|
+
const graveWork = outcome?.grave.length || unsentGraveAlerts(review, clock).length;
|
|
282
|
+
const hospitalized = graveWork ? Boolean((await getThreadInfo(review.patientCode))?.hospitalizedAt) : false;
|
|
283
|
+
const claimed = outcome?.grave.length && !hospitalized ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
|
|
270
284
|
const attempts = attemptsOf(review, clock);
|
|
271
285
|
// Each failure doubles the wait; after the last attempt the team hands the case over by hand.
|
|
272
286
|
const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
|
|
273
287
|
|| (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
|
|
274
|
-
if (outcome && !backingOff && await handOff(review, clock, outcome, now) && !outcome.grave.length) await sendHandoffNotice(review, clock, outcome);
|
|
275
|
-
|
|
288
|
+
if (outcome && !backingOff && await handOff(review, clock, outcome, now) && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome);
|
|
289
|
+
if (hospitalized) await skipGraveAlerts(review, clock, now);
|
|
290
|
+
else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
|
|
276
291
|
await remindQuietPatient(review, clock, now);
|
|
277
292
|
}
|
|
278
293
|
|
|
@@ -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) {
|
|
@@ -1448,6 +1450,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1448
1450
|
unassessedRedFlags: draft.unassessedRedFlags,
|
|
1449
1451
|
urgentUnassessedRedFlags: draft.urgentUnassessedRedFlags,
|
|
1450
1452
|
unobtainableRedFlags: draft.unobtainableRedFlags,
|
|
1453
|
+
urgentPresentRedFlags: draft.urgentPresentRedFlags,
|
|
1451
1454
|
sufficientForDoctor: draft.sufficientForDoctor,
|
|
1452
1455
|
blockingQuestion: draft.blockingQuestion,
|
|
1453
1456
|
missingCharacterization: draft.missingCharacterization,
|
|
@@ -172,7 +172,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
172
172
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
173
173
|
}, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, quietReminders: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
174
174
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
175
|
-
'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
|
|
175
|
+
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
|
|
176
176
|
})
|
|
177
177
|
.sort({ _id: -1 })
|
|
178
178
|
.limit(SWEEP_LIMIT)
|