@peopl-health/nexus 6.6.0-dev.21349 → 6.6.0
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/flags/escalationFlags.js +5 -0
- package/lib/clinical/services/escalationDraftService.js +4 -3
- package/lib/core/NexusMessaging.js +1 -0
- package/lib/models/escalationReviewModel.js +2 -0
- package/lib/services/caseFollowUpSweepService.js +72 -5
- package/lib/services/characterizationOutcomeService.js +1 -1
- package/lib/services/escalationReviewService.js +51 -9
- package/lib/services/reviewAlertSweepService.js +2 -2
- package/lib/services/reviewDeadlineService.js +8 -7
- package/lib/services/reviewDraftSweepService.js +2 -2
- package/package.json +1 -1
|
@@ -44,6 +44,10 @@ function escalationWatchTeamNoticeLive() {
|
|
|
44
44
|
return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
function escalationStaleQueueNoticeLive() {
|
|
48
|
+
return flagOn('ESCALATION_STALE_QUEUE_NOTICE_LIVE');
|
|
49
|
+
}
|
|
50
|
+
|
|
47
51
|
function escalationCaseFollowUpLive() {
|
|
48
52
|
return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
|
|
49
53
|
}
|
|
@@ -58,6 +62,7 @@ module.exports = {
|
|
|
58
62
|
escalationUntakenAlertsLive,
|
|
59
63
|
escalationUpdateModeLive,
|
|
60
64
|
escalationWatchExpiryLive,
|
|
65
|
+
escalationStaleQueueNoticeLive,
|
|
61
66
|
escalationWatchTeamNoticeLive,
|
|
62
67
|
feverPatientTimerLive,
|
|
63
68
|
};
|
|
@@ -88,7 +88,7 @@ function suggestCallOf(value) {
|
|
|
88
88
|
|
|
89
89
|
const localStampOf = (at) => (at ? getCurrentMexicoDateTime(at) : null);
|
|
90
90
|
|
|
91
|
-
function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null, now = Date.now() }) {
|
|
91
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null, previousQuestions = null, now = Date.now() }) {
|
|
92
92
|
const conversation = Array.isArray(context?.conversation)
|
|
93
93
|
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
94
94
|
: context?.conversation ?? null;
|
|
@@ -103,6 +103,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
|
|
|
103
103
|
protocol,
|
|
104
104
|
alarms: alarms.map((alarm) => ({ ...alarm, raisedAtLocal: localStampOf(alarm.raisedAt) })),
|
|
105
105
|
agentCharacterization,
|
|
106
|
+
previousQuestions,
|
|
106
107
|
patient: {
|
|
107
108
|
clinicalContext: context?.agentContext ?? null,
|
|
108
109
|
conversation,
|
|
@@ -153,7 +154,7 @@ function reopenBlockingFlag(block, blockingFlag) {
|
|
|
153
154
|
}
|
|
154
155
|
|
|
155
156
|
async function generateEscalationDraft({
|
|
156
|
-
code, callLogs = [], alarms = [], agentCharacterization = null, heldUrgentFlags = [], provider, trace = null, reviewId = null, now = Date.now(),
|
|
157
|
+
code, callLogs = [], alarms = [], agentCharacterization = null, previousQuestions = null, heldUrgentFlags = [], provider, trace = null, reviewId = null, now = Date.now(),
|
|
157
158
|
} = {}) {
|
|
158
159
|
const { presetId } = await getEscalationDraft();
|
|
159
160
|
const llm = provider ?? draftProvider();
|
|
@@ -163,7 +164,7 @@ async function generateEscalationDraft({
|
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
const context = await getEscalationContext({ code, now });
|
|
166
|
-
const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization, now });
|
|
167
|
+
const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization, previousQuestions, now });
|
|
167
168
|
|
|
168
169
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
169
170
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -664,6 +664,7 @@ class NexusMessaging {
|
|
|
664
664
|
await releaseHeldMessages(chatId, { contactCode: messageData.contactCode || null }).catch(error =>
|
|
665
665
|
logger.error('[processIncomingMessage] Held message release failed', { code: chatId, error: error.message })
|
|
666
666
|
);
|
|
667
|
+
await require('../services/escalationReviewService').noteIncomingPatientMessage({ code: chatId });
|
|
667
668
|
}
|
|
668
669
|
if (chatId && hasPreprocessingHandler()) {
|
|
669
670
|
const claim = await runPreprocessingHandler({ code: chatId, context: 'incomingMessage', message: messageData });
|
|
@@ -320,6 +320,7 @@ const caseFollowUpSchema = new mongoose.Schema({
|
|
|
320
320
|
firstDueAt: { type: Date, required: true },
|
|
321
321
|
nextCheckAt: { type: Date, default: null },
|
|
322
322
|
unansweredAt: { type: Date, default: null },
|
|
323
|
+
unsettledAt: { type: Date, default: null },
|
|
323
324
|
}, { _id: false });
|
|
324
325
|
|
|
325
326
|
const escalationReviewSchema = new mongoose.Schema({
|
|
@@ -373,6 +374,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
373
374
|
monitoringUntil: { type: Date, default: null },
|
|
374
375
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
375
376
|
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
377
|
+
staleQueueNoticeAt: { type: Date, default: null },
|
|
376
378
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
377
379
|
inTurnAsks: { type: [inTurnAskSchema], default: [] },
|
|
378
380
|
feverPromptStartedAt: { type: Date, default: null },
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
2
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
3
3
|
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
4
|
-
const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
|
|
4
|
+
const { escalationCaseFollowUpLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
|
|
5
5
|
|
|
6
6
|
const { logPatientChange } = require('./patientService');
|
|
7
7
|
const { getThreadInfo } = require('./threadService');
|
|
8
|
-
const { BOOKKEEPING, closeEscalationReview } = require('./escalationReviewService');
|
|
9
|
-
const { effectiveUrgencyOf } = require('./reviewDeadlineService');
|
|
8
|
+
const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread } = require('./escalationReviewService');
|
|
9
|
+
const { effectiveUrgencyOf, positiveSetting } = require('./reviewDeadlineService');
|
|
10
10
|
const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
|
|
11
11
|
|
|
12
12
|
const OPERATOR = 'bot:caseFollowUp';
|
|
@@ -15,6 +15,14 @@ const SWEEP_LIMIT = 50;
|
|
|
15
15
|
const SETTLE_MS = 24 * 60 * 60 * 1000;
|
|
16
16
|
const RECHECK_MS = 60 * 60 * 1000;
|
|
17
17
|
const KEPT_OPEN_URGENCIES = ['stat', 'asap'];
|
|
18
|
+
const STALE_QUEUE_STATUSES = ['indications_queued', 'needs_intervention'];
|
|
19
|
+
const DEFAULT_STALE_QUEUE_HOURS = 72;
|
|
20
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
21
|
+
const STALE_QUEUE_LOOKBACK_MS = 7 * 24 * HOUR_MS;
|
|
22
|
+
const STALE_QUEUE_HEADERS = {
|
|
23
|
+
indications_queued: '⏳ Indicación en cola sin enviar desde hace días',
|
|
24
|
+
needs_intervention: '⏳ Caso que requiere intervención sin movimiento desde hace días',
|
|
25
|
+
};
|
|
18
26
|
|
|
19
27
|
const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
|
|
20
28
|
|
|
@@ -46,6 +54,23 @@ async function keepUnanswered(review, now) {
|
|
|
46
54
|
if (kept.modifiedCount) await audit(review, { action: 'followup_result', result: 'unanswered' });
|
|
47
55
|
}
|
|
48
56
|
|
|
57
|
+
async function settleAnswer(review, now) {
|
|
58
|
+
const { review: current, reading } = await followUpReadingOf(review);
|
|
59
|
+
if (reading === 'settled') return close(current, 'answered');
|
|
60
|
+
const held = await getEscalationReview().updateOne(
|
|
61
|
+
{ _id: review._id, closedAt: null, status: { $in: FOLLOW_UP_STATUSES }, 'caseFollowUp.reminderId': review.caseFollowUp.reminderId, 'caseFollowUp.unsettledAt': null },
|
|
62
|
+
{ $set: { 'caseFollowUp.unsettledAt': now, 'caseFollowUp.nextCheckAt': null, updatedSinceSeen: true } },
|
|
63
|
+
BOOKKEEPING,
|
|
64
|
+
);
|
|
65
|
+
if (!held.modifiedCount) return null;
|
|
66
|
+
await audit(review, { action: 'followup_result', result: 'answered_unsettled', reading });
|
|
67
|
+
return noticeCaseThread(review, {
|
|
68
|
+
header: '💬 La paciente contestó el seguimiento sin mejoría registrada',
|
|
69
|
+
action: 'Qué hacer: leer su respuesta y cerrar el caso o pedir una nueva indicación',
|
|
70
|
+
kind: 'followup_unsettled',
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
49
74
|
async function settle(review, now) {
|
|
50
75
|
const followUp = review.caseFollowUp;
|
|
51
76
|
if ((await getThreadInfo(review.patientCode))?.stopped === true) return checkAgainAt(review, new Date(now.getTime() + RECHECK_MS));
|
|
@@ -54,7 +79,7 @@ async function settle(review, now) {
|
|
|
54
79
|
const repliedAt = asked && await lastReplyAt(review.patientCode, asked, now);
|
|
55
80
|
if (repliedAt) {
|
|
56
81
|
const settleAt = new Date(repliedAt.getTime() + SETTLE_MS);
|
|
57
|
-
return now < settleAt ? checkAgainAt(review, settleAt) :
|
|
82
|
+
return now < settleAt ? checkAgainAt(review, settleAt) : settleAnswer(review, now);
|
|
58
83
|
}
|
|
59
84
|
const giveUpAt = new Date(new Date(followUp.dueAt).getTime() + SECOND_TRY_MS);
|
|
60
85
|
if (now < giveUpAt) return checkAgainAt(review, giveUpAt);
|
|
@@ -86,4 +111,46 @@ async function sweepCaseFollowUps({ now = new Date() } = {}) {
|
|
|
86
111
|
return settled;
|
|
87
112
|
}
|
|
88
113
|
|
|
89
|
-
|
|
114
|
+
const LAST_DECISION_AT = { $arrayElemAt: ['$decisions.createdAt', -1] };
|
|
115
|
+
|
|
116
|
+
async function sweepStaleQueues({ now = new Date() } = {}) {
|
|
117
|
+
if (!escalationStaleQueueNoticeLive()) return 0;
|
|
118
|
+
const hours = positiveSetting('ESCALATION_STALE_QUEUE_HOURS', DEFAULT_STALE_QUEUE_HOURS);
|
|
119
|
+
const cutoff = new Date(now.getTime() - (hours * HOUR_MS < STALE_QUEUE_LOOKBACK_MS ? hours : DEFAULT_STALE_QUEUE_HOURS) * HOUR_MS);
|
|
120
|
+
const reviews = await getEscalationReview()
|
|
121
|
+
.find({
|
|
122
|
+
closedAt: null,
|
|
123
|
+
status: { $in: STALE_QUEUE_STATUSES },
|
|
124
|
+
'decisions.0': { $exists: true },
|
|
125
|
+
$expr: { $and: [
|
|
126
|
+
{ $lte: [LAST_DECISION_AT, cutoff] },
|
|
127
|
+
{ $gt: [LAST_DECISION_AT, new Date(now.getTime() - STALE_QUEUE_LOOKBACK_MS)] },
|
|
128
|
+
{ $or: [{ $eq: [{ $ifNull: ['$staleQueueNoticeAt', null] }, null] }, { $lt: ['$staleQueueNoticeAt', LAST_DECISION_AT] }] },
|
|
129
|
+
] },
|
|
130
|
+
})
|
|
131
|
+
.limit(SWEEP_LIMIT)
|
|
132
|
+
.lean();
|
|
133
|
+
let noticed = 0;
|
|
134
|
+
for (const review of reviews) {
|
|
135
|
+
try {
|
|
136
|
+
const claimed = await getEscalationReview().updateOne(
|
|
137
|
+
{ _id: review._id, closedAt: null, status: { $in: STALE_QUEUE_STATUSES }, staleQueueNoticeAt: review.staleQueueNoticeAt ?? null },
|
|
138
|
+
{ $set: { staleQueueNoticeAt: now } },
|
|
139
|
+
BOOKKEEPING,
|
|
140
|
+
);
|
|
141
|
+
if (!claimed.modifiedCount) continue;
|
|
142
|
+
await noticeCaseThread(review, {
|
|
143
|
+
header: STALE_QUEUE_HEADERS[review.status],
|
|
144
|
+
action: 'Qué hacer: enviar la indicación o cerrar el caso desde el panel',
|
|
145
|
+
kind: 'stale_queue',
|
|
146
|
+
});
|
|
147
|
+
await audit(review, { action: 'stale_queue_noticed', status: review.status });
|
|
148
|
+
noticed += 1;
|
|
149
|
+
} catch (error) {
|
|
150
|
+
logger.error('[CaseFollowUpSweep] Could not notice a stale queued case', { escalationReviewId: String(review._id), error: errorOf(error) });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return noticed;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = { sweepCaseFollowUps, sweepStaleQueues };
|
|
@@ -355,7 +355,7 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
355
355
|
const latest = (review.drafts ?? []).at(-1);
|
|
356
356
|
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
|
|
357
357
|
const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
|
|
358
|
-
if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
358
|
+
if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt) || (!entry.skippedReason && timeOf(entry.draftAt) >= clock.since.getTime()))) return;
|
|
359
359
|
const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
|
|
360
360
|
if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
|
|
361
361
|
// A short reply records no clinical update, so the patient's own messages decide whether she answered.
|
|
@@ -72,6 +72,8 @@ const RECENT_REVIEW_LIMIT = 20;
|
|
|
72
72
|
const TIMELINE_LIMIT = 500;
|
|
73
73
|
const MAX_REVIEW_UPDATES = 50;
|
|
74
74
|
const DRAFT_DEBOUNCE_MS = 20 * 1000;
|
|
75
|
+
// Long enough for the agent's own turn to finish, so a patient reply is drafted once.
|
|
76
|
+
const INBOUND_DRAFT_DELAY_MS = 90 * 1000;
|
|
75
77
|
const DRAFT_OPERATOR = 'bot:escalationDraft';
|
|
76
78
|
const AUTO_HANDOFF_OPERATOR = 'bot:characterizationOutcome';
|
|
77
79
|
const MAX_DOCTOR_UPDATES = 3;
|
|
@@ -87,6 +89,7 @@ const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
|
87
89
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
88
90
|
const HANDING_OFF_WAIT_MS = 3000;
|
|
89
91
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
92
|
+
const REFRESHABLE_STATUSES = [...FOLLOWUP_STATUSES, 'needs_intervention'];
|
|
90
93
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
91
94
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
92
95
|
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
|
|
@@ -1523,12 +1526,12 @@ async function closeSettled(review) {
|
|
|
1523
1526
|
}
|
|
1524
1527
|
}
|
|
1525
1528
|
|
|
1526
|
-
async function
|
|
1529
|
+
async function followUpReadingOf(snapshot) {
|
|
1527
1530
|
const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
|
|
1528
|
-
if (!since) return snapshot;
|
|
1531
|
+
if (!since) return { review: snapshot, reading: null };
|
|
1529
1532
|
const sinceMs = new Date(since).getTime();
|
|
1530
1533
|
const { review, known } = await followUpCasesOf(snapshot, sinceMs);
|
|
1531
|
-
if (!known.size) return review;
|
|
1534
|
+
if (!known.size) return { review, reading: null };
|
|
1532
1535
|
|
|
1533
1536
|
const latest = new Map();
|
|
1534
1537
|
(review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
|
|
@@ -1537,9 +1540,16 @@ async function settleFollowUp(snapshot, { background = true, canClose = true } =
|
|
|
1537
1540
|
.filter((impression) => known.has(impression.caseId) && readingOf(impression))
|
|
1538
1541
|
.forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
|
|
1539
1542
|
|
|
1540
|
-
if ([...latest.values()].includes('worsening')) return
|
|
1543
|
+
if ([...latest.values()].includes('worsening')) return { review, reading: 'worsening' };
|
|
1541
1544
|
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1542
|
-
|
|
1545
|
+
return { review, reading: settled ? 'settled' : 'unsettled' };
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
|
|
1549
|
+
const { review, reading } = await followUpReadingOf(snapshot);
|
|
1550
|
+
if (!reading) return review;
|
|
1551
|
+
if (reading === 'worsening') return reopenFromFollowUp(review, 'worsening', { background });
|
|
1552
|
+
if (reading !== 'settled' || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1543
1553
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1544
1554
|
return review;
|
|
1545
1555
|
}
|
|
@@ -1561,13 +1571,14 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1561
1571
|
const startedAt = new Date();
|
|
1562
1572
|
const review = await loadReview(reviewIdOf(id));
|
|
1563
1573
|
const updating = updatesDoctor(review);
|
|
1564
|
-
|
|
1574
|
+
const refreshing = REFRESHABLE_STATUSES.includes(review.status);
|
|
1575
|
+
if (review.closedAt || (!DOCUMENTING_STATUSES.includes(review.status) && !updating && !refreshing)) return { review: null, retry: false };
|
|
1565
1576
|
const latest = (review.drafts ?? []).at(-1);
|
|
1566
1577
|
if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
|
|
1567
1578
|
|
|
1568
1579
|
const identity = await readDoctorIdentity(review);
|
|
1569
1580
|
if (identity.missing.length) {
|
|
1570
|
-
if (!review.identityBlock) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
|
|
1581
|
+
if (!review.identityBlock && !refreshing) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
|
|
1571
1582
|
return { review: null, retry: false };
|
|
1572
1583
|
}
|
|
1573
1584
|
|
|
@@ -1577,6 +1588,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1577
1588
|
alarms: review.alarms ?? [],
|
|
1578
1589
|
agentCharacterization: characterizationSeedOf(review.updates),
|
|
1579
1590
|
heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
|
|
1591
|
+
previousQuestions: latest ? { keyQuestions: latest.keyQuestions ?? [], missingCharacterization: latest.missingCharacterization ?? [], urgentUnassessedRedFlags: latest.urgentUnassessedRedFlags ?? [] } : null,
|
|
1580
1592
|
reviewId: String(review._id),
|
|
1581
1593
|
});
|
|
1582
1594
|
if (draft.attempted) {
|
|
@@ -1609,14 +1621,17 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1609
1621
|
...(draft.symptoms?.length && { symptoms: draft.symptoms }),
|
|
1610
1622
|
};
|
|
1611
1623
|
const EscalationReview = getEscalationReview();
|
|
1624
|
+
const stage = (updating && { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } })
|
|
1625
|
+
|| (refreshing && { status: review.status })
|
|
1626
|
+
|| { status: { $in: DOCUMENTING_STATUSES } };
|
|
1612
1627
|
const saved = await EscalationReview.findOneAndUpdate(
|
|
1613
1628
|
{
|
|
1614
1629
|
_id: review._id,
|
|
1615
|
-
...
|
|
1630
|
+
...stage,
|
|
1616
1631
|
draftDueAt: { $lte: lease },
|
|
1617
1632
|
drafts: { $size: (review.drafts ?? []).length },
|
|
1618
1633
|
},
|
|
1619
|
-
{ $push: { drafts: entry }, $set: { status: updating ?
|
|
1634
|
+
{ $push: { drafts: entry }, $set: { status: updating || refreshing ? review.status : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
|
|
1620
1635
|
{ new: true },
|
|
1621
1636
|
).lean();
|
|
1622
1637
|
if (!saved) return { review: null, retry: false };
|
|
@@ -2168,6 +2183,29 @@ async function recordPatientSend({ code, channel, sentBy, text, messageId = null
|
|
|
2168
2183
|
}
|
|
2169
2184
|
}
|
|
2170
2185
|
|
|
2186
|
+
async function noteIncomingPatientMessage({ code, now = new Date() } = {}) {
|
|
2187
|
+
try {
|
|
2188
|
+
if (!PATIENT_CODE.test(String(code ?? ''))) return false;
|
|
2189
|
+
const due = new Date(now.getTime() + INBOUND_DRAFT_DELAY_MS);
|
|
2190
|
+
const { modifiedCount } = await getEscalationReview().updateOne(
|
|
2191
|
+
{
|
|
2192
|
+
patientCode: patientCodeOf(code),
|
|
2193
|
+
closedAt: null,
|
|
2194
|
+
status: { $in: [...DOCUMENTING_STATUSES, ...REFRESHABLE_STATUSES] },
|
|
2195
|
+
draftDueAt: { $not: { $lte: due } },
|
|
2196
|
+
},
|
|
2197
|
+
{ $set: { draftDueAt: due, draftAttempts: 0, updatedSinceSeen: true } },
|
|
2198
|
+
BOOKKEEPING,
|
|
2199
|
+
);
|
|
2200
|
+
return modifiedCount > 0;
|
|
2201
|
+
} catch (error) {
|
|
2202
|
+
logger.error('[EscalationReview] A patient reply could not arm a redraft of the open review', {
|
|
2203
|
+
error: redactedError(error), stack: redactedStack(error),
|
|
2204
|
+
});
|
|
2205
|
+
return false;
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2171
2209
|
const latestUpdateGuard = (review) => {
|
|
2172
2210
|
const updates = review.updates ?? [];
|
|
2173
2211
|
if (!updates.length) return { 'updates.0': { $exists: false } };
|
|
@@ -2583,6 +2621,7 @@ module.exports = {
|
|
|
2583
2621
|
attachEmergencyRow,
|
|
2584
2622
|
cancelEscalationReview,
|
|
2585
2623
|
closeEscalationReview,
|
|
2624
|
+
followUpReadingOf,
|
|
2586
2625
|
escalationAnchorOf,
|
|
2587
2626
|
generateBotDraft,
|
|
2588
2627
|
getEscalationReviewById,
|
|
@@ -2590,11 +2629,14 @@ module.exports = {
|
|
|
2590
2629
|
previewPlanInstructions,
|
|
2591
2630
|
handOffToDoctor,
|
|
2592
2631
|
listEscalationReviews,
|
|
2632
|
+
noticeCaseThread,
|
|
2593
2633
|
openEscalationReview,
|
|
2594
2634
|
reclassifyUrgency,
|
|
2595
2635
|
recordEscalationAlarm,
|
|
2596
2636
|
recordDirectIndication,
|
|
2597
2637
|
recordPatientSend,
|
|
2638
|
+
noteIncomingPatientMessage,
|
|
2639
|
+
REFRESHABLE_STATUSES,
|
|
2598
2640
|
recordDoctorDecision,
|
|
2599
2641
|
sendScheduledDoctorAlert,
|
|
2600
2642
|
recordReviewUpdate,
|
|
@@ -6,7 +6,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
|
6
6
|
const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
|
|
7
7
|
const { sweepUntakenAlerts } = require('./untakenAlertService');
|
|
8
8
|
const { sweepExpiredWatches } = require('./watchExpiryService');
|
|
9
|
-
const { sweepCaseFollowUps } = require('./caseFollowUpSweepService');
|
|
9
|
+
const { sweepCaseFollowUps, sweepStaleQueues } = require('./caseFollowUpSweepService');
|
|
10
10
|
|
|
11
11
|
const SWEEP_LIMIT = 10;
|
|
12
12
|
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
@@ -101,7 +101,7 @@ const watchSweeper = createIntervalSweeper({
|
|
|
101
101
|
|
|
102
102
|
const caseFollowUpSweeper = createIntervalSweeper({
|
|
103
103
|
label: '[CaseFollowUpSweep]',
|
|
104
|
-
sweep: () => sweepCaseFollowUps(),
|
|
104
|
+
sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
|
|
105
105
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
106
106
|
});
|
|
107
107
|
|
|
@@ -75,18 +75,18 @@ function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level])
|
|
|
75
75
|
return new Date(timeOf(from) + minutes * 60 * 1000);
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
const
|
|
79
|
-
const
|
|
80
|
-
return Number.isFinite(
|
|
78
|
+
const positiveSetting = (key, fallback) => {
|
|
79
|
+
const value = Number(runtimeConfig.get(key, fallback));
|
|
80
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
81
81
|
};
|
|
82
82
|
|
|
83
83
|
// asap leaves the team its early alert before the patient gets the numbers to call.
|
|
84
|
-
const patientTimerMinutes = (level) =>
|
|
85
|
-
const untakenEarlyMinutes = () =>
|
|
84
|
+
const patientTimerMinutes = (level) => positiveSetting(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
|
|
85
|
+
const untakenEarlyMinutes = () => positiveSetting('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
|
|
86
86
|
// How long a question the patient left unanswered waits before the case goes to the doctor without the answer.
|
|
87
|
-
const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ?
|
|
87
|
+
const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveSetting(PENDING_WAIT_KEYS[level], DEFAULT_PENDING_WAIT_MINUTES[level]) : null);
|
|
88
88
|
const teamOpenAt = (now, policy) => addWorkingMinutes(now, 0, policy.teamHours);
|
|
89
|
-
const quietReminderMinutes = () =>
|
|
89
|
+
const quietReminderMinutes = () => positiveSetting('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
|
|
90
90
|
|
|
91
91
|
function untakenStagesOf(level, since, policy, { fever = false } = {}) {
|
|
92
92
|
const total = policy.responseMinutes[level];
|
|
@@ -127,6 +127,7 @@ module.exports = {
|
|
|
127
127
|
responseDeadlineOf,
|
|
128
128
|
patientTimerMinutes,
|
|
129
129
|
pendingWaitMinutes,
|
|
130
|
+
positiveSetting,
|
|
130
131
|
quietReminderMinutes,
|
|
131
132
|
responseDeadlinePolicy,
|
|
132
133
|
teamOpenAt,
|
|
@@ -3,7 +3,7 @@ const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
|
3
3
|
const { withTimeout } = require('../utils/timeoutUtils');
|
|
4
4
|
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
5
|
|
|
6
|
-
const { BOOKKEEPING, DOCUMENTING_STATUSES, generateBotDraft } = require('./escalationReviewService');
|
|
6
|
+
const { BOOKKEEPING, DOCUMENTING_STATUSES, REFRESHABLE_STATUSES, generateBotDraft } = require('./escalationReviewService');
|
|
7
7
|
|
|
8
8
|
const SWEEP_LIMIT = 1;
|
|
9
9
|
const DEFAULT_SWEEP_INTERVAL_MS = 10 * 1000;
|
|
@@ -38,7 +38,7 @@ async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts =
|
|
|
38
38
|
}
|
|
39
39
|
if (retry && !willRetry) {
|
|
40
40
|
const marked = await EscalationReview.updateOne(
|
|
41
|
-
{ _id, draftDueAt: lease, closedAt: null, status: { $in: DOCUMENTING_STATUSES } },
|
|
41
|
+
{ _id, draftDueAt: lease, closedAt: null, status: { $in: [...DOCUMENTING_STATUSES, ...REFRESHABLE_STATUSES] } },
|
|
42
42
|
{ $set: { draftDueAt: null, draftFailedAt: new Date() } },
|
|
43
43
|
BOOKKEEPING,
|
|
44
44
|
);
|