@peopl-health/nexus 6.4.15 → 6.4.17
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/doctorPlanHelper.js +15 -4
- package/lib/clinical/services/doctorPlanService.js +6 -2
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
- package/lib/models/escalationReviewModel.js +5 -1
- package/lib/services/escalationReviewService.js +28 -6
- package/lib/services/reviewDeadlineService.js +1 -1
- package/lib/services/untakenAlertService.js +1 -1
- package/package.json +1 -1
|
@@ -6,8 +6,10 @@ const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ auto: 24, check_in: 24, vigilanc
|
|
|
6
6
|
|
|
7
7
|
const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
|
|
8
8
|
|
|
9
|
+
const DURATION_TEXTS = Object.freeze({ as_needed: 'solo si lo necesita', continuous: 'de forma continua, hasta nuevo aviso', unspecified: null });
|
|
9
10
|
const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
|
|
10
|
-
const
|
|
11
|
+
const durationTextOf = (item) => (!item.duration || item.duration === 'days' ? `por ${daysText(item.days)}` : DURATION_TEXTS[item.duration]);
|
|
12
|
+
const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${[item.dose, item.frequency, durationTextOf(item)].filter(Boolean).join(' ')}.`;
|
|
11
13
|
const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
|
|
12
14
|
// The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours.
|
|
13
15
|
const PLAN_TEXTS = Object.freeze({
|
|
@@ -54,12 +56,21 @@ function prescriptionText(plan) {
|
|
|
54
56
|
return lines.join('\n');
|
|
55
57
|
}
|
|
56
58
|
|
|
59
|
+
const FREQUENCY_DURATIONS = Object.freeze([[/\s*por raz[oó]n necesaria$/i, 'as_needed'], [/\s*de forma continua$/i, 'continuous']]);
|
|
60
|
+
|
|
61
|
+
// A formulary frequency that already names the duration gives it up, so the line does not say it twice.
|
|
62
|
+
function frequencyDurationOf(frequency) {
|
|
63
|
+
const [pattern, duration] = FREQUENCY_DURATIONS.find(([candidate]) => candidate.test(frequency ?? '')) ?? [];
|
|
64
|
+
return duration ? { frequency: frequency.replace(pattern, ''), duration } : { frequency, duration: 'days' };
|
|
65
|
+
}
|
|
66
|
+
|
|
57
67
|
// The formulary's own fields; a drug it no longer lists keeps its old text as the dose, for the doctor to split.
|
|
58
68
|
function dosingOf(item, formularyKey) {
|
|
59
69
|
const entry = formularyFor(formularyKey);
|
|
60
70
|
const dosing = entry && findDrug(entry, item)?.dosing;
|
|
61
|
-
if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, days: null, note: null };
|
|
62
|
-
|
|
71
|
+
if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, duration: 'days', days: null, note: null };
|
|
72
|
+
const { frequency, duration } = frequencyDurationOf(dosing.frequency ?? null);
|
|
73
|
+
return { dose: dosing.dose ?? null, frequency, duration, days: duration === 'days' ? dosing.days ?? null : null, note: dosing.note ?? null };
|
|
63
74
|
}
|
|
64
75
|
|
|
65
76
|
// What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
|
|
@@ -80,7 +91,7 @@ function proposedPlanOf(draft) {
|
|
|
80
91
|
|
|
81
92
|
// The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
|
|
82
93
|
const plannedTextOf = (plan) => [
|
|
83
|
-
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item
|
|
94
|
+
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, durationTextOf(item)]),
|
|
84
95
|
...plan.studies.flatMap((study) => [study.name, study.instructions]),
|
|
85
96
|
...plan.homeCare,
|
|
86
97
|
plan.note,
|
|
@@ -2,7 +2,7 @@ const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('..
|
|
|
2
2
|
const { allNumbersOf, dosingFactsOf, isDosingSentence, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
3
3
|
const { httpError } = require('../../utils/httpErrorUtils');
|
|
4
4
|
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
5
|
-
const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
5
|
+
const { PLAN_DURATIONS, PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
6
6
|
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
7
7
|
const { drugsNamedIn, isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
|
|
8
8
|
|
|
@@ -48,12 +48,16 @@ function itemOf(item, index) {
|
|
|
48
48
|
const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
|
|
49
49
|
const reason = textOf(item?.reason, `${name}.reason`);
|
|
50
50
|
if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
|
|
51
|
+
const duration = item?.duration ?? 'days';
|
|
52
|
+
if (!PLAN_DURATIONS.includes(duration)) throw httpError(400, `${name}.duration must be one of: ${PLAN_DURATIONS.join(', ')}`);
|
|
53
|
+
if (duration !== 'days' && item?.days != null) throw httpError(400, `${name}.days must be empty when the duration is ${duration}`);
|
|
51
54
|
return {
|
|
52
55
|
drug: neededText(item?.drug, `${name}.drug`),
|
|
53
56
|
strength: textOf(item?.strength, `${name}.strength`),
|
|
54
57
|
dose: neededText(item?.dose, `${name}.dose`),
|
|
55
58
|
frequency: neededText(item?.frequency, `${name}.frequency`),
|
|
56
|
-
|
|
59
|
+
duration,
|
|
60
|
+
days: duration === 'days' ? wholeNumber(item?.days, `${name}.days`, MAX_DAYS) : null,
|
|
57
61
|
position,
|
|
58
62
|
reason,
|
|
59
63
|
formularyKey: textOf(item?.formularyKey, `${name}.formularyKey`),
|
|
@@ -14,6 +14,7 @@ const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'retu
|
|
|
14
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
15
15
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
16
16
|
const PLAN_FOLLOW_UPS = ['none', 'auto', 'check_in', 'vigilancia'];
|
|
17
|
+
const PLAN_DURATIONS = Object.freeze(['days', 'as_needed', 'continuous', 'unspecified']);
|
|
17
18
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
18
19
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
19
20
|
|
|
@@ -31,6 +32,7 @@ const alarmSchema = new mongoose.Schema({
|
|
|
31
32
|
clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
32
33
|
emergencyRecordId: { type: String, default: null },
|
|
33
34
|
appliedLevel: { type: String, default: null },
|
|
35
|
+
isHeldInFollowUp: { type: Boolean, default: undefined },
|
|
34
36
|
raisedAt: { type: Date, required: true },
|
|
35
37
|
}, { _id: false });
|
|
36
38
|
|
|
@@ -209,7 +211,8 @@ const planItemSchema = new mongoose.Schema({
|
|
|
209
211
|
strength: { type: String, default: null },
|
|
210
212
|
dose: { type: String, required: true },
|
|
211
213
|
frequency: { type: String, required: true },
|
|
212
|
-
|
|
214
|
+
duration: { type: String, enum: PLAN_DURATIONS, default: 'days' },
|
|
215
|
+
days: { type: Number, default: null },
|
|
213
216
|
position: { type: String, default: null },
|
|
214
217
|
reason: { type: String, default: null },
|
|
215
218
|
formularyKey: { type: String, default: null },
|
|
@@ -442,6 +445,7 @@ module.exports = {
|
|
|
442
445
|
DOCTOR_DECISIONS,
|
|
443
446
|
HANDOFF_MODES,
|
|
444
447
|
INTERRUPTED_STATUSES,
|
|
448
|
+
PLAN_DURATIONS,
|
|
445
449
|
PLAN_FOLLOW_UPS,
|
|
446
450
|
FOLLOWUP_STATUSES,
|
|
447
451
|
RETURN_REASONS,
|
|
@@ -525,7 +525,8 @@ async function recordReviewUpdate({ code, update, now = new Date(), settleInBack
|
|
|
525
525
|
|
|
526
526
|
if (FOLLOWUP_STATUSES.includes(pushed.status)) {
|
|
527
527
|
await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
|
|
528
|
-
|
|
528
|
+
const canClose = !(pushed.alarms ?? []).some((alarm) => alarm.isHeldInFollowUp && alarm.turnId === update.turnId);
|
|
529
|
+
return await settleFollowUp(pushed, { background: settleInBackground, canClose });
|
|
529
530
|
}
|
|
530
531
|
|
|
531
532
|
const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
|
|
@@ -571,7 +572,26 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
|
|
|
571
572
|
}
|
|
572
573
|
}
|
|
573
574
|
|
|
574
|
-
|
|
575
|
+
function shouldHoldInFollowUp(review, alarm, mode) {
|
|
576
|
+
if (mode !== 'update' || ALERTED_URGENCIES.includes(alarm.urgencyLevel)) return false;
|
|
577
|
+
const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
|
|
578
|
+
return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
async function holdInFollowUp(review, alarm) {
|
|
582
|
+
const held = await getEscalationReview()
|
|
583
|
+
.findOneAndUpdate(
|
|
584
|
+
{ _id: review._id, status: review.status, 'alarms.alarmId': alarm.alarmId },
|
|
585
|
+
{ $set: { 'alarms.$.isHeldInFollowUp': true, updatedSinceSeen: true } },
|
|
586
|
+
{ new: true },
|
|
587
|
+
)
|
|
588
|
+
.lean();
|
|
589
|
+
if (!held) return review;
|
|
590
|
+
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result: 'update_held', statusFrom: review.status });
|
|
591
|
+
return held;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date() } = {}) {
|
|
575
595
|
try {
|
|
576
596
|
const patientCode = patientCodeOf(code);
|
|
577
597
|
const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
|
|
@@ -587,7 +607,9 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
587
607
|
if (joined) {
|
|
588
608
|
await scheduleDoctorAlert(joined, entry, now);
|
|
589
609
|
await armPatientTimerOnJoin(joined, entry, now);
|
|
590
|
-
if (FOLLOWUP_STATUSES.includes(joined.status))
|
|
610
|
+
if (FOLLOWUP_STATUSES.includes(joined.status)) {
|
|
611
|
+
return shouldHoldInFollowUp(joined, entry, mode) ? await holdInFollowUp(joined, entry) : await reopenFromFollowUp(joined, 'new_alarm');
|
|
612
|
+
}
|
|
591
613
|
if (!DOCUMENTING_STATUSES.includes(joined.status)) {
|
|
592
614
|
logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
|
|
593
615
|
escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
|
|
@@ -619,7 +641,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
619
641
|
}
|
|
620
642
|
|
|
621
643
|
function escalationAnchorOf(review, alarmId) {
|
|
622
|
-
const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
|
|
644
|
+
const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId && !alarm.isHeldInFollowUp);
|
|
623
645
|
if (!prior.length) return null;
|
|
624
646
|
const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
|
|
625
647
|
const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
|
|
@@ -1468,7 +1490,7 @@ async function closeSettled(review) {
|
|
|
1468
1490
|
}
|
|
1469
1491
|
}
|
|
1470
1492
|
|
|
1471
|
-
async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
1493
|
+
async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
|
|
1472
1494
|
const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
|
|
1473
1495
|
if (!since) return snapshot;
|
|
1474
1496
|
const sinceMs = new Date(since).getTime();
|
|
@@ -1484,7 +1506,7 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
|
1484
1506
|
|
|
1485
1507
|
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening', { background });
|
|
1486
1508
|
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1487
|
-
if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1509
|
+
if (!settled || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1488
1510
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1489
1511
|
return review;
|
|
1490
1512
|
}
|
|
@@ -98,7 +98,7 @@ function responseDeadlineOf(review, policy) {
|
|
|
98
98
|
if (review.closedAt || FOLLOWUP_STATUSES.includes(review.status)) return null;
|
|
99
99
|
const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
|
|
100
100
|
const waiting = alarmLevelsOf(review)
|
|
101
|
-
.filter(({ alarm }) => Number.isNaN(decidedAt) || timeOf(alarm.raisedAt) > decidedAt)
|
|
101
|
+
.filter(({ alarm }) => !alarm.isHeldInFollowUp && (Number.isNaN(decidedAt) || timeOf(alarm.raisedAt) > decidedAt))
|
|
102
102
|
.map(({ level, clockFrom }) => ({ urgency: level, dueAt: dueAtFor(clockFrom, level, policy) }))
|
|
103
103
|
.filter(({ dueAt }) => dueAt);
|
|
104
104
|
if (!waiting.length) return null;
|
|
@@ -46,7 +46,7 @@ function episodeStartOf(alarms) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
function untakenClockOf(review, policy) {
|
|
49
|
-
const entries = levelsOf(currentAlarms(review), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
|
|
49
|
+
const entries = levelsOf(currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
|
|
50
50
|
const level = entries.reduce((top, entry) => (URGENCY_RANK[entry.level] > (URGENCY_RANK[top] || 0) ? entry.level : top), null);
|
|
51
51
|
if (!level) return null;
|
|
52
52
|
const atLevel = entries.filter((entry) => entry.level === level);
|