@peopl-health/nexus 5.61.0-dev.11184 → 5.61.0-dev.11187
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/helpers/reviewUpdateHelper.js +21 -1
- package/lib/clinical/services/escalationDraftService.js +17 -3
- package/lib/clinical/services/treatmentProposalService.js +7 -2
- package/lib/config/lifecycle.js +4 -1
- package/lib/controllers/conversationController.js +2 -2
- package/lib/controllers/escalationReviewController.js +26 -0
- package/lib/controllers/messageController.js +21 -1
- package/lib/index.d.ts +14 -0
- package/lib/index.js +20 -0
- package/lib/models/escalationReviewModel.js +41 -2
- package/lib/routes/index.js +4 -0
- package/lib/services/conversationService.js +40 -13
- package/lib/services/escalationReviewService.js +531 -48
- package/lib/services/patientTaskService.js +1 -0
- package/lib/services/reviewAlertSweepService.js +88 -0
- package/lib/services/reviewBoardService.js +78 -0
- package/lib/services/reviewDraftSweepService.js +79 -0
- package/package.json +1 -1
|
@@ -51,4 +51,24 @@ function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText =
|
|
|
51
51
|
};
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
// The agent's own reading of each case since the escalation, handed to the draft so it builds on it
|
|
55
|
+
// instead of re-deriving it: the latest impression per case, the safety flags and what the patient said.
|
|
56
|
+
function characterizationSeedOf(updates = []) {
|
|
57
|
+
if (!Array.isArray(updates) || !updates.length) return null;
|
|
58
|
+
// Clinical order is the turn time, not the order the writes landed in.
|
|
59
|
+
const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
|
|
60
|
+
const latestByCase = new Map();
|
|
61
|
+
byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
|
|
62
|
+
const key = impression.caseId || impression.ctcaeTerm;
|
|
63
|
+
if (key) latestByCase.set(key, { ...impression, at: update.at });
|
|
64
|
+
}));
|
|
65
|
+
return {
|
|
66
|
+
cases: [...latestByCase.values()],
|
|
67
|
+
safetyFlags: [...new Set(updates.flatMap((update) => update.safetyFlags || []))],
|
|
68
|
+
newSinceEscalation: byTime
|
|
69
|
+
.filter((update) => update.patientText)
|
|
70
|
+
.map((update) => ({ at: update.at, patientText: update.patientText })),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
module.exports = { characterizationSeedOf, reviewUpdateOf };
|
|
@@ -45,7 +45,14 @@ function settleProposal(parsed) {
|
|
|
45
45
|
return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
const textList = (value) => (Array.isArray(value) ? value.map(trimmed).filter(Boolean) : []);
|
|
49
|
+
|
|
50
|
+
function suggestCallOf(value) {
|
|
51
|
+
if (typeof value?.value !== 'boolean') return null;
|
|
52
|
+
return { value: value.value, reason: trimmed(value.reason) || null };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
|
|
49
56
|
const conversation = Array.isArray(context?.conversation)
|
|
50
57
|
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
51
58
|
: context?.conversation ?? null;
|
|
@@ -58,6 +65,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
|
|
|
58
65
|
protocolVersion: FORMULARY_VERSION,
|
|
59
66
|
protocol,
|
|
60
67
|
alarms,
|
|
68
|
+
agentCharacterization,
|
|
61
69
|
patient: {
|
|
62
70
|
clinicalContext: context?.agentContext ?? null,
|
|
63
71
|
conversation,
|
|
@@ -83,7 +91,9 @@ function draftProvider() {
|
|
|
83
91
|
}
|
|
84
92
|
}
|
|
85
93
|
|
|
86
|
-
async function generateEscalationDraft({
|
|
94
|
+
async function generateEscalationDraft({
|
|
95
|
+
code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
|
|
96
|
+
} = {}) {
|
|
87
97
|
const { presetId } = await getEscalationDraft();
|
|
88
98
|
const llm = provider ?? draftProvider();
|
|
89
99
|
|
|
@@ -92,7 +102,7 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
92
102
|
}
|
|
93
103
|
|
|
94
104
|
const context = await getEscalationContext({ code, now });
|
|
95
|
-
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
|
|
105
|
+
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms, agentCharacterization });
|
|
96
106
|
|
|
97
107
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
98
108
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -165,6 +175,10 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
165
175
|
doctorText,
|
|
166
176
|
patientMessage,
|
|
167
177
|
protocolVersion: FORMULARY_VERSION,
|
|
178
|
+
keyQuestions: textList(parsed?.keyQuestions),
|
|
179
|
+
unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
|
|
180
|
+
missingCharacterization: textList(parsed?.missingCharacterization),
|
|
181
|
+
suggestCall: suggestCallOf(parsed?.suggestCall),
|
|
168
182
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
169
183
|
};
|
|
170
184
|
}
|
|
@@ -102,10 +102,14 @@ function resolvedDrugs(proposals) {
|
|
|
102
102
|
});
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
function drugsNamedIn(text) {
|
|
106
|
+
const padded = ` ${key(text)} `;
|
|
107
|
+
return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
|
|
108
|
+
}
|
|
109
|
+
|
|
105
110
|
function unproposedDrugsIn(text, proposals) {
|
|
106
111
|
const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
|
|
107
|
-
|
|
108
|
-
return DRUG_NAMES.filter((name) => !proposed.has(name) && padded.includes(` ${name} `));
|
|
112
|
+
return drugsNamedIn(text).filter((name) => !proposed.has(name));
|
|
109
113
|
}
|
|
110
114
|
|
|
111
115
|
function crossSymptomIssues(proposals) {
|
|
@@ -127,5 +131,6 @@ function crossSymptomIssues(proposals) {
|
|
|
127
131
|
module.exports = {
|
|
128
132
|
validateProposal,
|
|
129
133
|
unproposedDrugsIn,
|
|
134
|
+
drugsNamedIn,
|
|
130
135
|
crossSymptomIssues,
|
|
131
136
|
};
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -6,6 +6,7 @@ const { _clearClinicalContextCache } = require('../helpers/patientInformationHel
|
|
|
6
6
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
7
7
|
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
8
8
|
const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
|
|
9
|
+
const { stopReviewDraftSweep } = require('../services/reviewDraftSweepService');
|
|
9
10
|
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
10
11
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
11
12
|
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
@@ -20,7 +21,9 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
|
20
21
|
const SWEEP_STOP_MS = 2000;
|
|
21
22
|
|
|
22
23
|
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
23
|
-
const stopped = Promise.allSettled([
|
|
24
|
+
const stopped = Promise.allSettled([
|
|
25
|
+
stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(),
|
|
26
|
+
]);
|
|
24
27
|
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
25
28
|
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
26
29
|
}
|
|
@@ -34,7 +34,7 @@ const getConversationController = async (req, res) => {
|
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const { threads, total, airtableNameMap, openTaskMap } = await fetchConversationData(filter, skip, limit);
|
|
37
|
+
const { threads, total, airtableNameMap, openTaskMap, reviewMap } = await fetchConversationData(filter, skip, limit);
|
|
38
38
|
|
|
39
39
|
if (!threads?.length) {
|
|
40
40
|
return res.status(200).json({
|
|
@@ -44,7 +44,7 @@ const getConversationController = async (req, res) => {
|
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
const processedConversations = await processConversations(threads, airtableNameMap, openTaskMap);
|
|
47
|
+
const processedConversations = await processConversations(threads, airtableNameMap, openTaskMap, reviewMap);
|
|
48
48
|
const totalPages = Math.ceil(total / limit);
|
|
49
49
|
|
|
50
50
|
res.status(200).json({
|
|
@@ -7,6 +7,7 @@ const {
|
|
|
7
7
|
cancelEscalationReview,
|
|
8
8
|
closeEscalationReview,
|
|
9
9
|
getEscalationReviewById,
|
|
10
|
+
getReviewTimeline,
|
|
10
11
|
handOffToDoctor,
|
|
11
12
|
listEscalationReviews,
|
|
12
13
|
openEscalationReview,
|
|
@@ -18,6 +19,7 @@ const {
|
|
|
18
19
|
confirmNoteFacts,
|
|
19
20
|
syncEscalationReviewCase,
|
|
20
21
|
} = require('../services/escalationReviewService');
|
|
22
|
+
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
21
23
|
|
|
22
24
|
const respondWithError = (res, error, action, context) => {
|
|
23
25
|
logger.error(`Error ${action}:`, {
|
|
@@ -53,6 +55,15 @@ const getEscalationReviewController = async (req, res) => {
|
|
|
53
55
|
}
|
|
54
56
|
};
|
|
55
57
|
|
|
58
|
+
const getReviewTimelineController = async (req, res) => {
|
|
59
|
+
try {
|
|
60
|
+
const timeline = await getReviewTimeline({ id: req.params.id });
|
|
61
|
+
res.status(200).json({ success: true, timeline });
|
|
62
|
+
} catch (error) {
|
|
63
|
+
respondWithError(res, error, 'reading the escalation review timeline', { reviewId: req.params?.id });
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
56
67
|
const listEscalationReviewsController = async (req, res) => {
|
|
57
68
|
try {
|
|
58
69
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
@@ -62,6 +73,15 @@ const listEscalationReviewsController = async (req, res) => {
|
|
|
62
73
|
}
|
|
63
74
|
};
|
|
64
75
|
|
|
76
|
+
const listReviewBoardController = async (req, res) => {
|
|
77
|
+
try {
|
|
78
|
+
const rows = await listReviewBoard({ bucket: req.query.bucket });
|
|
79
|
+
res.status(200).json({ success: true, rows });
|
|
80
|
+
} catch (error) {
|
|
81
|
+
respondWithError(res, error, 'listing the review board', { bucket: String(req.query?.bucket || '') });
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
65
85
|
const setEscalationReviewCasesController = async (req, res) => {
|
|
66
86
|
try {
|
|
67
87
|
const { patientCaseRecordIds, triggeredBy } = req.body || {};
|
|
@@ -143,6 +163,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
143
163
|
comment = null,
|
|
144
164
|
doctorName = null,
|
|
145
165
|
doctorReply = null,
|
|
166
|
+
reason = null,
|
|
167
|
+
draftNumber = null,
|
|
146
168
|
triggeredBy,
|
|
147
169
|
} = req.body || {};
|
|
148
170
|
const review = await recordDoctorDecision({
|
|
@@ -153,6 +175,8 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
153
175
|
comment,
|
|
154
176
|
doctorName,
|
|
155
177
|
doctorReply,
|
|
178
|
+
reason,
|
|
179
|
+
draftNumber,
|
|
156
180
|
recordedBy: triggeredBy,
|
|
157
181
|
requestId: req.requestId,
|
|
158
182
|
});
|
|
@@ -224,8 +248,10 @@ module.exports = {
|
|
|
224
248
|
cancelEscalationReviewController,
|
|
225
249
|
closeEscalationReviewController,
|
|
226
250
|
getEscalationReviewController,
|
|
251
|
+
getReviewTimelineController,
|
|
227
252
|
handOffEscalationReviewController,
|
|
228
253
|
listEscalationReviewsController,
|
|
254
|
+
listReviewBoardController,
|
|
229
255
|
openEscalationReviewController,
|
|
230
256
|
recordEscalationReviewDecisionController,
|
|
231
257
|
sendEscalationReviewIndicationsController,
|
|
@@ -2,6 +2,7 @@ const moment = require('moment-timezone');
|
|
|
2
2
|
const mongoose = require('mongoose');
|
|
3
3
|
|
|
4
4
|
const { logger } = require('../utils/logger');
|
|
5
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
5
6
|
|
|
6
7
|
const { ScheduledMessage } = require('../models/agendaMessageModel.js');
|
|
7
8
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
|
|
@@ -13,6 +14,9 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
|
|
|
13
14
|
|
|
14
15
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
15
16
|
const { getMessages } = require('../services/messageService');
|
|
17
|
+
const { recordDirectIndication } = require('../services/escalationReviewService');
|
|
18
|
+
|
|
19
|
+
const INDICATION_WAIT_MS = 5000;
|
|
16
20
|
|
|
17
21
|
const { sendMessage, sendScheduledMessage, getDefaultInstance } = require('../core/NexusMessaging');
|
|
18
22
|
|
|
@@ -69,7 +73,8 @@ const sendMessageController = async (req, res) => {
|
|
|
69
73
|
frontendId = null,
|
|
70
74
|
triggeredBy = null,
|
|
71
75
|
idempotencyKey = null,
|
|
72
|
-
contactCode = null
|
|
76
|
+
contactCode = null,
|
|
77
|
+
asIndication = false
|
|
73
78
|
} = req.body || {};
|
|
74
79
|
|
|
75
80
|
const formattedCode = ensureWhatsAppFormat(code);
|
|
@@ -100,6 +105,21 @@ const sendMessageController = async (req, res) => {
|
|
|
100
105
|
variables: finalVariables, code: formattedCode,
|
|
101
106
|
frontendId, triggeredBy, idempotencyKey, ...contact
|
|
102
107
|
});
|
|
108
|
+
// Only a message the approver explicitly sent as the indication resolves the clinical review.
|
|
109
|
+
if (asIndication === true && result?.success && triggeredBy && message && !contentSid && !contact.contactCode) {
|
|
110
|
+
// Awaited so the review is usually settled before the reply returns, but never for long: the
|
|
111
|
+
// message already went out, and a slow lookup finishes in the background. It never throws.
|
|
112
|
+
await withTimeout(recordDirectIndication({
|
|
113
|
+
code: formattedCode,
|
|
114
|
+
triggeredBy,
|
|
115
|
+
body: message,
|
|
116
|
+
messageId: _pickMessageId(result, null),
|
|
117
|
+
status: result?.status ?? null,
|
|
118
|
+
deferred: result?.deferred === true || result?.preemptive === true,
|
|
119
|
+
}), INDICATION_WAIT_MS, 'clinical review resolution').catch((error) => {
|
|
120
|
+
logger.warn('[sendMessageController] The clinical review is still resolving in the background', { error: error.message });
|
|
121
|
+
});
|
|
122
|
+
}
|
|
103
123
|
return res.status(200).json({
|
|
104
124
|
success: result?.success ?? true,
|
|
105
125
|
messageId: _pickMessageId(result, null),
|
package/lib/index.d.ts
CHANGED
|
@@ -355,6 +355,8 @@ declare module '@peopl-health/nexus' {
|
|
|
355
355
|
ner?: NerOptions;
|
|
356
356
|
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
357
357
|
inboundRecovery?: InboundRecoveryOptions;
|
|
358
|
+
reviewDrafts?: ReviewDraftsOptions;
|
|
359
|
+
reviewAlerts?: ReviewAlertsOptions;
|
|
358
360
|
}
|
|
359
361
|
|
|
360
362
|
export interface RecommendationRecoveryOptions {
|
|
@@ -362,6 +364,18 @@ declare module '@peopl-health/nexus' {
|
|
|
362
364
|
intervalMs?: number;
|
|
363
365
|
}
|
|
364
366
|
|
|
367
|
+
export interface ReviewDraftsOptions {
|
|
368
|
+
/** Writes the clinical review draft automatically after each alarm or agent update. */
|
|
369
|
+
enabled?: boolean;
|
|
370
|
+
intervalMs?: number;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export interface ReviewAlertsOptions {
|
|
374
|
+
/** WhatsApps the approver on stat/asap reviews and re-alerts an unanswered stat review. */
|
|
375
|
+
enabled?: boolean;
|
|
376
|
+
intervalMs?: number;
|
|
377
|
+
}
|
|
378
|
+
|
|
365
379
|
export interface InboundRecoveryOptions {
|
|
366
380
|
enabled: boolean;
|
|
367
381
|
intervalMs?: number;
|
package/lib/index.js
CHANGED
|
@@ -32,6 +32,8 @@ const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNet
|
|
|
32
32
|
const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
33
|
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
34
|
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
35
|
+
const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
|
|
36
|
+
const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
|
|
35
37
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
36
38
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
37
39
|
const { DrainingError } = require('./core/BatchingManager');
|
|
@@ -203,6 +205,24 @@ class Nexus {
|
|
|
203
205
|
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
204
206
|
}
|
|
205
207
|
|
|
208
|
+
try {
|
|
209
|
+
if (options.reviewDrafts?.enabled === true) {
|
|
210
|
+
startReviewDraftSweep({ intervalMs: options.reviewDrafts.intervalMs });
|
|
211
|
+
logger.info('[Nexus] clinical review draft sweep armed');
|
|
212
|
+
}
|
|
213
|
+
} catch (e) {
|
|
214
|
+
logger.warn('Warning: failed to arm the clinical review draft sweep:', e?.message || e);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
if (options.reviewAlerts?.enabled === true) {
|
|
219
|
+
startReviewAlertSweep({ intervalMs: options.reviewAlerts.intervalMs });
|
|
220
|
+
logger.info('[Nexus] clinical review doctor alert sweep armed');
|
|
221
|
+
}
|
|
222
|
+
} catch (e) {
|
|
223
|
+
logger.warn('Warning: failed to arm the clinical review doctor alert sweep:', e?.message || e);
|
|
224
|
+
}
|
|
225
|
+
|
|
206
226
|
try {
|
|
207
227
|
if (options.inboundRecovery?.enabled === true) {
|
|
208
228
|
startInboundRecoverySweep({
|
|
@@ -10,8 +10,9 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
|
10
10
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
11
11
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
12
12
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
13
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
|
|
14
|
-
const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
|
|
13
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'direct_chat'];
|
|
14
|
+
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
15
|
+
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
15
16
|
|
|
16
17
|
const alarmSchema = new mongoose.Schema({
|
|
17
18
|
urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
|
|
@@ -36,6 +37,17 @@ const impressionUpdateSchema = new mongoose.Schema({
|
|
|
36
37
|
checkInQuestion: { type: String, default: null },
|
|
37
38
|
}, { _id: false });
|
|
38
39
|
|
|
40
|
+
const doctorAlertSchema = new mongoose.Schema({
|
|
41
|
+
kind: { type: String, enum: ['initial', 'realert'], required: true },
|
|
42
|
+
urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
|
|
43
|
+
physicianEmail: { type: String, default: null },
|
|
44
|
+
transport: { type: String, default: null },
|
|
45
|
+
messageId: { type: String, default: null },
|
|
46
|
+
error: { type: String, default: null },
|
|
47
|
+
teamAlerted: { type: Boolean, default: false },
|
|
48
|
+
sentAt: { type: Date, required: true },
|
|
49
|
+
}, { _id: false });
|
|
50
|
+
|
|
39
51
|
const reviewUpdateSchema = new mongoose.Schema({
|
|
40
52
|
turnId: { type: String, required: true },
|
|
41
53
|
tools: { type: [String], default: [] },
|
|
@@ -65,10 +77,21 @@ const callLogSchema = new mongoose.Schema({
|
|
|
65
77
|
loggedBy: { type: String, required: true },
|
|
66
78
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
67
79
|
|
|
80
|
+
const suggestCallSchema = new mongoose.Schema({
|
|
81
|
+
value: { type: Boolean, required: true },
|
|
82
|
+
reason: { type: String, default: null },
|
|
83
|
+
}, { _id: false });
|
|
84
|
+
|
|
68
85
|
const draftSchema = new mongoose.Schema({
|
|
69
86
|
doctorText: { type: String, required: true },
|
|
70
87
|
patientMessage: { type: String, required: true },
|
|
71
88
|
writtenBy: { type: String, required: true },
|
|
89
|
+
protocolVersion: { type: String, default: null },
|
|
90
|
+
keyQuestions: { type: [String], default: undefined },
|
|
91
|
+
unassessedRedFlags: { type: [String], default: undefined },
|
|
92
|
+
missingCharacterization: { type: [String], default: undefined },
|
|
93
|
+
suggestCall: { type: suggestCallSchema, default: undefined },
|
|
94
|
+
sectionsUnavailable: { type: [String], default: undefined },
|
|
72
95
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
73
96
|
|
|
74
97
|
const doctorHandoffSchema = new mongoose.Schema({
|
|
@@ -89,6 +112,8 @@ const decisionSchema = new mongoose.Schema({
|
|
|
89
112
|
finalText: { type: String, default: null },
|
|
90
113
|
comment: { type: String, default: null },
|
|
91
114
|
doctorReply: { type: String, default: null },
|
|
115
|
+
returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
|
|
116
|
+
warnings: { type: [String], default: undefined },
|
|
92
117
|
decidedBy: { type: String, required: true },
|
|
93
118
|
recordedBy: { type: String, required: true },
|
|
94
119
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
@@ -149,6 +174,16 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
149
174
|
alarms: { type: [alarmSchema], default: [] },
|
|
150
175
|
updates: { type: [reviewUpdateSchema], default: [] },
|
|
151
176
|
updatedSinceSeen: { type: Boolean, default: false },
|
|
177
|
+
followUpCases: { type: [String], default: undefined },
|
|
178
|
+
// The decision the follow-up cases were fixed for; a later indication extends them.
|
|
179
|
+
followUpDecision: { type: Number, default: null },
|
|
180
|
+
draftDueAt: { type: Date, default: null },
|
|
181
|
+
draftAttempts: { type: Number, default: 0 },
|
|
182
|
+
doctorAlerts: { type: [doctorAlertSchema], default: [] },
|
|
183
|
+
doctorAlertDueAt: { type: Date, default: null },
|
|
184
|
+
doctorAlertKind: { type: String, enum: ['initial', 'realert', null], default: null },
|
|
185
|
+
doctorAlertAttempts: { type: Number, default: 0 },
|
|
186
|
+
approverViewedAt: { type: Date, default: null },
|
|
152
187
|
previousReviewId: { type: String, default: null },
|
|
153
188
|
callLogs: { type: [callLogSchema], default: [] },
|
|
154
189
|
noteFacts: { type: [noteFactSchema], default: [] },
|
|
@@ -165,6 +200,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
165
200
|
}, { timestamps: true });
|
|
166
201
|
|
|
167
202
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
203
|
+
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
204
|
+
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
205
|
+
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
168
206
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
169
207
|
|
|
170
208
|
const getEscalationReview = () => {
|
|
@@ -182,6 +220,7 @@ module.exports = {
|
|
|
182
220
|
DOCTOR_DECISIONS,
|
|
183
221
|
HANDOFF_MODES,
|
|
184
222
|
INTERRUPTED_STATUSES,
|
|
223
|
+
RETURN_REASONS,
|
|
185
224
|
getEscalationReview,
|
|
186
225
|
escalationReviewSchema,
|
|
187
226
|
};
|
package/lib/routes/index.js
CHANGED
|
@@ -120,8 +120,10 @@ const traceRouteDefinitions = {
|
|
|
120
120
|
|
|
121
121
|
const escalationReviewRouteDefinitions = {
|
|
122
122
|
'POST /': 'openEscalationReviewController',
|
|
123
|
+
'GET /': 'listReviewBoardController',
|
|
123
124
|
'GET /by-patient/:code': 'listEscalationReviewsController',
|
|
124
125
|
'GET /:id': 'getEscalationReviewController',
|
|
126
|
+
'GET /:id/timeline': 'getReviewTimelineController',
|
|
125
127
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
126
128
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
127
129
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
@@ -294,7 +296,9 @@ const builtInControllers = {
|
|
|
294
296
|
// Escalation review controllers
|
|
295
297
|
openEscalationReviewController: escalationReviewController.openEscalationReviewController,
|
|
296
298
|
listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
|
|
299
|
+
listReviewBoardController: escalationReviewController.listReviewBoardController,
|
|
297
300
|
getEscalationReviewController: escalationReviewController.getEscalationReviewController,
|
|
301
|
+
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
298
302
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
299
303
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
300
304
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|
|
@@ -6,6 +6,7 @@ const { Thread } = require('../models/threadModel');
|
|
|
6
6
|
|
|
7
7
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
8
8
|
const { getOpenTaskSummary } = require('../services/patientTaskSummaryService');
|
|
9
|
+
const { boardBucketOfFilter, listReviewBoard } = require('../services/reviewBoardService');
|
|
9
10
|
|
|
10
11
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
11
12
|
const { ensurePatientResource } = require('./patientResourceService');
|
|
@@ -40,6 +41,37 @@ const buildThreadFilter = (filter, { taskCodes }) => {
|
|
|
40
41
|
}
|
|
41
42
|
};
|
|
42
43
|
|
|
44
|
+
const fetchFilteredThreads = async (threadFilter, skip, limit) => {
|
|
45
|
+
const [threads, total] = await Promise.all([
|
|
46
|
+
Thread.find(threadFilter)
|
|
47
|
+
.sort({ lastMessageAt: -1 })
|
|
48
|
+
.skip(skip)
|
|
49
|
+
.limit(limit)
|
|
50
|
+
.lean(),
|
|
51
|
+
Thread.countDocuments(threadFilter)
|
|
52
|
+
]);
|
|
53
|
+
return { threads, total, reviewMap: null };
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// The board decides the order; only the requested page's threads are read in full.
|
|
57
|
+
const fetchBoardThreads = async (bucket, skip, limit) => {
|
|
58
|
+
const rows = await listReviewBoard({ bucket });
|
|
59
|
+
const reviewMap = new Map(rows.map(({ patientCode, ...row }) => [patientCode, row]));
|
|
60
|
+
const withThread = new Set((await Thread.find(
|
|
61
|
+
{ code: { $in: [...reviewMap.keys()] }, lastMessageAt: { $ne: null } },
|
|
62
|
+
{ code: 1 },
|
|
63
|
+
).lean()).map((thread) => thread.code));
|
|
64
|
+
const ordered = rows.map((row) => row.patientCode).filter((code) => withThread.has(code));
|
|
65
|
+
const page = ordered.slice(skip, skip + limit);
|
|
66
|
+
const threads = page.length
|
|
67
|
+
? await Thread.find({ code: { $in: page }, lastMessageAt: { $ne: null } }).sort({ lastMessageAt: -1 }).lean()
|
|
68
|
+
: [];
|
|
69
|
+
// A patient can hold more than one thread; the most recently active one represents them.
|
|
70
|
+
const threadByCode = new Map();
|
|
71
|
+
threads.forEach((thread) => { if (!threadByCode.has(thread.code)) threadByCode.set(thread.code, thread); });
|
|
72
|
+
return { threads: page.map((code) => threadByCode.get(code)).filter(Boolean), total: ordered.length, reviewMap };
|
|
73
|
+
};
|
|
74
|
+
|
|
43
75
|
const fetchConversationData = async (filter, skip, limit) => {
|
|
44
76
|
const openTaskMap = PENDING_TASK_FILTERS.includes(filter)
|
|
45
77
|
? await getOpenTaskSummary()
|
|
@@ -54,19 +86,13 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
54
86
|
requests: taskEntries.filter(([, entry]) => entry.requests > 0).map(([code]) => code),
|
|
55
87
|
};
|
|
56
88
|
|
|
57
|
-
const threadFilter = buildThreadFilter(filter, { taskCodes });
|
|
58
|
-
|
|
59
89
|
logger.info('[fetchConversationData] Applying filter', { filter });
|
|
60
90
|
const startTime = Date.now();
|
|
61
91
|
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
.limit(limit)
|
|
67
|
-
.lean(),
|
|
68
|
-
Thread.countDocuments(threadFilter)
|
|
69
|
-
]);
|
|
92
|
+
const bucket = boardBucketOfFilter(filter);
|
|
93
|
+
const { threads, total, reviewMap } = bucket
|
|
94
|
+
? await fetchBoardThreads(bucket, skip, limit)
|
|
95
|
+
: await fetchFilteredThreads(buildThreadFilter(filter, { taskCodes }), skip, limit);
|
|
70
96
|
|
|
71
97
|
logger.info('[fetchConversationData] Completed', { duration: Date.now() - startTime, count: threads.length });
|
|
72
98
|
|
|
@@ -82,7 +108,7 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
82
108
|
}
|
|
83
109
|
}
|
|
84
110
|
|
|
85
|
-
return { threads, total, airtableNameMap, openTaskMap };
|
|
111
|
+
return { threads, total, airtableNameMap, openTaskMap, reviewMap };
|
|
86
112
|
};
|
|
87
113
|
|
|
88
114
|
const getMediaType = (media) => {
|
|
@@ -93,7 +119,7 @@ const getMediaType = (media) => {
|
|
|
93
119
|
return type === 'application' ? 'document' : subtype === 'webp' ? 'sticker' : type;
|
|
94
120
|
};
|
|
95
121
|
|
|
96
|
-
const processConversations = async (threads, airtableNameMap, openTaskMap) => {
|
|
122
|
+
const processConversations = async (threads, airtableNameMap, openTaskMap, reviewMap = null) => {
|
|
97
123
|
const createConversation = (thread, index) => {
|
|
98
124
|
const code = thread?.code || `error_${index}`;
|
|
99
125
|
return {
|
|
@@ -119,7 +145,8 @@ const processConversations = async (threads, airtableNameMap, openTaskMap) => {
|
|
|
119
145
|
lastMessageFromMe: thread?.lastMessageFromMe || false,
|
|
120
146
|
isLastMessageMedia: !!thread?.lastMessageMedia,
|
|
121
147
|
lastMessageType: getMediaType(thread?.lastMessageMedia),
|
|
122
|
-
openTasks: openTaskMap?.get(code) || null
|
|
148
|
+
openTasks: openTaskMap?.get(code) || null,
|
|
149
|
+
clinicalReview: reviewMap?.get(code) || null
|
|
123
150
|
};
|
|
124
151
|
};
|
|
125
152
|
|