@peopl-health/nexus 5.72.6 → 5.72.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clinical/services/escalationDraftService.js +5 -3
- package/lib/controllers/escalationReviewController.js +11 -0
- package/lib/helpers/reviewCaseCandidateHelper.js +51 -0
- package/lib/routes/index.js +2 -0
- package/lib/services/escalationReviewService.js +14 -4
- package/lib/services/patientTaskService.js +4 -1
- package/package.json +1 -1
|
@@ -186,9 +186,11 @@ async function generateEscalationDraft({
|
|
|
186
186
|
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
187
187
|
return { completed: false, attempted: true, rejected: true, reason: 'the model returned no usable text' };
|
|
188
188
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
189
|
+
// The token goes into the reason because the audit log keeps the reason: it says which prompt rule leaked.
|
|
190
|
+
const leaked = TECHNICAL_TOKEN.exec(`${composeDoctorBody({ ...draft, alarm: null })}\n${patientMessage}`)?.[0].slice(0, 40);
|
|
191
|
+
if (leaked) {
|
|
192
|
+
logger.warn('[escalationDraft] generation leaked a technical token into the text', { reviewId, token: leaked });
|
|
193
|
+
return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
|
|
192
194
|
}
|
|
193
195
|
|
|
194
196
|
return {
|
|
@@ -16,6 +16,7 @@ const {
|
|
|
16
16
|
requestBotDraft,
|
|
17
17
|
sendApprovedIndications,
|
|
18
18
|
setReviewCases,
|
|
19
|
+
listReviewCaseCandidates,
|
|
19
20
|
suggestDraft,
|
|
20
21
|
suggestKeyQuestions,
|
|
21
22
|
confirmNoteFacts,
|
|
@@ -97,6 +98,15 @@ const setEscalationReviewCasesController = async (req, res) => {
|
|
|
97
98
|
}
|
|
98
99
|
};
|
|
99
100
|
|
|
101
|
+
const listEscalationReviewCaseCandidatesController = async (req, res) => {
|
|
102
|
+
try {
|
|
103
|
+
const candidates = await listReviewCaseCandidates({ id: req.params.id });
|
|
104
|
+
res.status(200).json({ success: true, candidates });
|
|
105
|
+
} catch (error) {
|
|
106
|
+
respondWithError(res, error, 'listing escalation review case candidates', { reviewId: req.params?.id });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
100
110
|
const addEscalationReviewCallLogController = async (req, res) => {
|
|
101
111
|
try {
|
|
102
112
|
const { outcome, notes, calledAt, triggeredBy } = req.body || {};
|
|
@@ -289,6 +299,7 @@ module.exports = {
|
|
|
289
299
|
recordEscalationReviewDecisionController,
|
|
290
300
|
sendEscalationReviewIndicationsController,
|
|
291
301
|
setEscalationReviewCasesController,
|
|
302
|
+
listEscalationReviewCaseCandidatesController,
|
|
292
303
|
suggestEscalationReviewDraftController,
|
|
293
304
|
suggestEscalationReviewQuestionsController,
|
|
294
305
|
syncEscalationReviewCaseController,
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Triage cases a review can cover: the patient's cases raised from a day before the review opened, plus
|
|
2
|
+
// the ones it already covers. A case is only suggested; the team decides which ones the review covers.
|
|
3
|
+
const LOOKBACK_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
const NEAR_ALARM_MS = 2 * 60 * 60 * 1000;
|
|
5
|
+
const STEM_LENGTH = 5;
|
|
6
|
+
// Stems too common in symptom names and alarm text to tell two symptoms apart.
|
|
7
|
+
const GENERIC_STEMS = new Set(['dolor', 'grado', 'sinto', 'para', 'del', 'con', 'las', 'los', 'una', 'que', 'por', 'sin', 'dific', 'frecu']);
|
|
8
|
+
|
|
9
|
+
const words = (text) => String(text ?? '')
|
|
10
|
+
.toLowerCase()
|
|
11
|
+
.normalize('NFD')
|
|
12
|
+
.replace(/[̀-ͯ]/g, '')
|
|
13
|
+
.split(/[^a-z]+/)
|
|
14
|
+
.filter((word) => word.length >= 3)
|
|
15
|
+
.map((word) => word.slice(0, STEM_LENGTH))
|
|
16
|
+
.filter((stem) => !GENERIC_STEMS.has(stem));
|
|
17
|
+
|
|
18
|
+
const symptomOf = (description) => String(description ?? '').replace(/\s*Grado\s*-\s*\d+\s*$/i, '');
|
|
19
|
+
|
|
20
|
+
// Suggested when an alarm of the review came within two hours of the case and names the same symptom.
|
|
21
|
+
function isSuggested(patientCase, alarms) {
|
|
22
|
+
const caseWords = words(symptomOf(patientCase.description));
|
|
23
|
+
const createdAt = Date.parse(patientCase.createdAt);
|
|
24
|
+
if (!caseWords.length || !Number.isFinite(createdAt)) return false;
|
|
25
|
+
return alarms.some((alarm) => {
|
|
26
|
+
if (!(Math.abs(new Date(alarm.raisedAt).getTime() - createdAt) <= NEAR_ALARM_MS)) return false;
|
|
27
|
+
const alarmWords = new Set(words(`${alarm.symptom ?? ''} ${alarm.suspectedCondition ?? ''}`));
|
|
28
|
+
return caseWords.some((word) => alarmWords.has(word));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function caseCandidates({ review, cases, linkedIds }) {
|
|
33
|
+
const since = new Date(review.createdAt).getTime() - LOOKBACK_MS;
|
|
34
|
+
const linked = new Set(linkedIds);
|
|
35
|
+
return cases
|
|
36
|
+
.filter((patientCase) => linked.has(patientCase.recordId) || Date.parse(patientCase.createdAt) >= since)
|
|
37
|
+
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
38
|
+
.map((patientCase) => ({
|
|
39
|
+
recordId: patientCase.recordId,
|
|
40
|
+
number: patientCase.number,
|
|
41
|
+
createdAt: patientCase.createdAt,
|
|
42
|
+
description: patientCase.description,
|
|
43
|
+
grade: patientCase.grade,
|
|
44
|
+
status: patientCase.status,
|
|
45
|
+
operationsStatus: patientCase.operationsStatus,
|
|
46
|
+
isLinked: linked.has(patientCase.recordId),
|
|
47
|
+
isSuggested: !linked.has(patientCase.recordId) && isSuggested(patientCase, review.alarms ?? []),
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = { caseCandidates };
|
package/lib/routes/index.js
CHANGED
|
@@ -128,6 +128,7 @@ const escalationReviewRouteDefinitions = {
|
|
|
128
128
|
'GET /by-patient/:code': 'listEscalationReviewsController',
|
|
129
129
|
'GET /:id': 'getEscalationReviewController',
|
|
130
130
|
'GET /:id/timeline': 'getReviewTimelineController',
|
|
131
|
+
'GET /:id/case-candidates': 'listEscalationReviewCaseCandidatesController',
|
|
131
132
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
132
133
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
133
134
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
@@ -311,6 +312,7 @@ const builtInControllers = {
|
|
|
311
312
|
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
312
313
|
requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
|
|
313
314
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
315
|
+
listEscalationReviewCaseCandidatesController: escalationReviewController.listEscalationReviewCaseCandidatesController,
|
|
314
316
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
315
317
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|
|
316
318
|
suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
|
|
@@ -24,6 +24,7 @@ const {
|
|
|
24
24
|
} = require('../models/escalationReviewModel');
|
|
25
25
|
const { getPatientAuditLog } = require('../models/patientAuditLogModel');
|
|
26
26
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
27
|
+
const { caseCandidates } = require('../helpers/reviewCaseCandidateHelper');
|
|
27
28
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
28
29
|
const { DrainingError } = require('../core/BatchingManager');
|
|
29
30
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
@@ -45,7 +46,7 @@ const { composePrompt } = require('../clinical/services/promptComposerService');
|
|
|
45
46
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
46
47
|
|
|
47
48
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
48
|
-
const { MAX_NOTE_LENGTH,
|
|
49
|
+
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
49
50
|
const { countMessages } = require('./messageService');
|
|
50
51
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
51
52
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
@@ -68,6 +69,8 @@ const BOOKKEEPING = { timestamps: false };
|
|
|
68
69
|
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
69
70
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
70
71
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
72
|
+
// The cases a review covers can change while it is open and no operation is in flight.
|
|
73
|
+
const CASE_SELECTABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor', 'approved', 'needs_intervention', ...FOLLOWUP_STATUSES];
|
|
71
74
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
72
75
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
73
76
|
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
|
|
@@ -450,7 +453,7 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
|
|
|
450
453
|
const recordIds = [...new Set(requested.map((recordId) => String(recordId ?? '').trim()).filter(Boolean))];
|
|
451
454
|
if (!recordIds.length) return [];
|
|
452
455
|
|
|
453
|
-
const
|
|
456
|
+
const cases = await readPatientCases(patientCode);
|
|
454
457
|
const known = new Set(cases.map((patientCase) => patientCase.recordId));
|
|
455
458
|
const stranger = recordIds.find((recordId) => !known.has(recordId));
|
|
456
459
|
if (stranger) throw httpError(404, 'Patient case not found for this patient');
|
|
@@ -796,7 +799,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
796
799
|
const operator = requiredText(updatedBy, 'updatedBy');
|
|
797
800
|
if (!Array.isArray(patientCaseRecordIds)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
|
|
798
801
|
const current = await loadReview(reviewId);
|
|
799
|
-
if (!
|
|
802
|
+
if (!CASE_SELECTABLE_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
|
|
800
803
|
|
|
801
804
|
const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
|
|
802
805
|
const casesChanged = {
|
|
@@ -814,7 +817,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
814
817
|
};
|
|
815
818
|
const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
|
|
816
819
|
|
|
817
|
-
const review = await updateReview(reviewId,
|
|
820
|
+
const review = await updateReview(reviewId, CASE_SELECTABLE_STATUSES, [{
|
|
818
821
|
$set: {
|
|
819
822
|
patientCaseRecordIds: recordIds,
|
|
820
823
|
status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
|
|
@@ -835,6 +838,12 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
835
838
|
return review;
|
|
836
839
|
}
|
|
837
840
|
|
|
841
|
+
async function listReviewCaseCandidates({ id } = {}) {
|
|
842
|
+
const review = await loadReview(reviewIdOf(id));
|
|
843
|
+
const cases = await readPatientCases(review.patientCode);
|
|
844
|
+
return caseCandidates({ review, cases, linkedIds: caseIdsOf(review) });
|
|
845
|
+
}
|
|
846
|
+
|
|
838
847
|
async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
|
|
839
848
|
const reviewId = reviewIdOf(id);
|
|
840
849
|
const operator = requiredText(loggedBy, 'loggedBy');
|
|
@@ -2089,6 +2098,7 @@ module.exports = {
|
|
|
2089
2098
|
sendApprovedIndications,
|
|
2090
2099
|
setAlarmAppliedLevel,
|
|
2091
2100
|
setReviewCases,
|
|
2101
|
+
listReviewCaseCandidates,
|
|
2092
2102
|
suggestDraft,
|
|
2093
2103
|
suggestKeyQuestions,
|
|
2094
2104
|
confirmNoteFacts,
|
|
@@ -158,8 +158,10 @@ async function readTasks(kind, whatsappId) {
|
|
|
158
158
|
};
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
+
const readPatientCases = (code) => readAllTasks('cases', validWhatsappId(code));
|
|
162
|
+
|
|
161
163
|
async function openCaseIds(code) {
|
|
162
|
-
const cases = await
|
|
164
|
+
const cases = await readPatientCases(code);
|
|
163
165
|
return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
|
|
164
166
|
}
|
|
165
167
|
|
|
@@ -212,6 +214,7 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
|
|
|
212
214
|
module.exports = {
|
|
213
215
|
MAX_NOTE_LENGTH,
|
|
214
216
|
openCaseIds,
|
|
217
|
+
readPatientCases,
|
|
215
218
|
getPatientTasks,
|
|
216
219
|
updatePatientTask,
|
|
217
220
|
};
|