@peopl-health/nexus 6.0.22 → 6.0.24
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/models/escalationReviewModel.js +3 -0
- package/lib/services/characterizationOutcomeService.js +16 -8
- package/lib/services/doctorDigestService.js +150 -0
- package/lib/services/escalationReviewService.js +1 -0
- package/lib/services/patientCodeMigrationService.js +4 -2
- package/lib/services/untakenAlertService.js +4 -0
- package/package.json +1 -1
|
@@ -253,6 +253,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
253
253
|
graveAlerts: { type: [graveAlertSchema], default: [] },
|
|
254
254
|
autoHandoffFailedAt: { type: Date, default: null },
|
|
255
255
|
autoHandoffAttempts: { type: Number, default: 0 },
|
|
256
|
+
digestQueuedAt: { type: Date, default: null },
|
|
257
|
+
digestClaimedAt: { type: Date, default: null },
|
|
258
|
+
digestSentAt: { type: Date, default: null },
|
|
256
259
|
quietReminders: { type: [quietReminderSchema], default: [] },
|
|
257
260
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
258
261
|
feverPromptStartedAt: { type: Date, default: null },
|
|
@@ -13,6 +13,7 @@ const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES,
|
|
|
13
13
|
const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
|
|
14
14
|
const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
15
15
|
const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
|
|
16
|
+
const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
|
|
16
17
|
|
|
17
18
|
const OPERATOR = AUTO_HANDOFF_OPERATOR;
|
|
18
19
|
const AUDIT_SOURCE = 'escalation_review';
|
|
@@ -116,9 +117,14 @@ const takenOf = async (review, clock) => {
|
|
|
116
117
|
const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clock.since.getTime() ? review.autoHandoffAttempts ?? 0 : 0);
|
|
117
118
|
|
|
118
119
|
async function handOff(review, clock, outcome, now) {
|
|
120
|
+
// An urgent case ready to decide waits for the doctor's digest, queued before the handoff so a failed write never strands it.
|
|
121
|
+
const digest = !outcome.update && clock.level === 'urgent' && !review.drafts.at(-1)?.urgentPresentRedFlags?.length && urgentDigestLive()
|
|
122
|
+
&& Boolean(await digestRecipient().catch(() => null));
|
|
119
123
|
try {
|
|
120
|
-
await
|
|
124
|
+
if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
|
|
125
|
+
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify && !digest });
|
|
121
126
|
} catch (error) {
|
|
127
|
+
if (digest) await getEscalationReview().updateOne({ _id: review._id, status: { $ne: 'awaiting_doctor' } }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
|
|
122
128
|
const attempt = attemptsOf(review, clock) + 1;
|
|
123
129
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
|
|
124
130
|
// A 409 is mostly another sweep or a person who moved the case first.
|
|
@@ -130,15 +136,15 @@ async function handOff(review, clock, outcome, now) {
|
|
|
130
136
|
return false;
|
|
131
137
|
}
|
|
132
138
|
if (review.autoHandoffAttempts) await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffAttempts: 0 } }, BOOKKEEPING);
|
|
133
|
-
await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note), notified: outcome.notify });
|
|
134
|
-
return true;
|
|
139
|
+
await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note), notified: outcome.notify && !digest, digest });
|
|
140
|
+
return digest ? 'digest' : true;
|
|
135
141
|
}
|
|
136
142
|
|
|
137
143
|
// Only the first handoff reaches the group; a later update to the doctor shows in the platform.
|
|
138
|
-
async function sendHandoffNotice(review, clock, outcome) {
|
|
144
|
+
async function sendHandoffNotice(review, clock, outcome, queuedAt = null) {
|
|
139
145
|
if (outcome.update) return;
|
|
140
146
|
try {
|
|
141
|
-
await postHandoffNotice(review, clock, outcome);
|
|
147
|
+
await postHandoffNotice(review, clock, outcome, queuedAt);
|
|
142
148
|
} catch (error) {
|
|
143
149
|
logger.error('[CharacterizationOutcome] The handoff notice was not sent', {
|
|
144
150
|
escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
|
|
@@ -165,10 +171,11 @@ async function sendGaveUpNotice(review, clock) {
|
|
|
165
171
|
}
|
|
166
172
|
}
|
|
167
173
|
|
|
168
|
-
async function postHandoffNotice(review, clock, { note }) {
|
|
174
|
+
async function postHandoffNotice(review, clock, { note }, queuedAt) {
|
|
169
175
|
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
170
176
|
const taken = await takenOf(review, clock);
|
|
171
|
-
const
|
|
177
|
+
const passed = queuedAt ? `📋 Va al médico en el resumen de urgentes (a más tardar ${digestTimeOf(review, queuedAt)})` : '📋 Pasó al médico';
|
|
178
|
+
const header = taken ? passed : `${passed} · todavía sin tomar`;
|
|
172
179
|
const action = !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho';
|
|
173
180
|
const body = [
|
|
174
181
|
header,
|
|
@@ -365,7 +372,8 @@ async function settleCharacterization(review, clock, now) {
|
|
|
365
372
|
const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
|
|
366
373
|
|| (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
|
|
367
374
|
// A patient in the hospital gets no team call, so nothing holds the doctor's handoff.
|
|
368
|
-
|
|
375
|
+
const handed = outcome && (!outcome.held || hospitalized) && !backingOff ? await handOff(review, clock, outcome, now) : false;
|
|
376
|
+
if (handed && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome, handed === 'digest' ? now : null);
|
|
369
377
|
if (hospitalized) await skipGraveAlerts(review, clock, now);
|
|
370
378
|
else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
|
|
371
379
|
await remindQuietPatient(review, clock, now);
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { oneLineOf } = require('../utils/coercionUtils');
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
5
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
6
|
+
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
8
|
+
|
|
9
|
+
const { logPatientChange } = require('./patientService');
|
|
10
|
+
const { listEscalationApprovers } = require('./physicianService');
|
|
11
|
+
const { responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
12
|
+
const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
|
+
|
|
14
|
+
const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
|
|
15
|
+
const DEFAULT_WINDOW_MINUTES = 60;
|
|
16
|
+
const DEFAULT_LEAD_MINUTES = 120;
|
|
17
|
+
const MAX_CASES_PER_MESSAGE = 5;
|
|
18
|
+
// The template's fixed text plus the cases stay under WhatsApp's 1024 characters.
|
|
19
|
+
const MAX_LINES_LENGTH = 800;
|
|
20
|
+
const MAX_FIELD_LENGTH = 60;
|
|
21
|
+
const STALE_CLAIM_MS = 10 * 60 * 1000;
|
|
22
|
+
const OPERATOR = 'bot:doctorDigest';
|
|
23
|
+
const getMessaging = () => require('../core/NexusMessaging');
|
|
24
|
+
|
|
25
|
+
const minutesOf = (key, fallback) => {
|
|
26
|
+
const minutes = Number(runtimeConfig.get(key, fallback));
|
|
27
|
+
return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
|
|
28
|
+
};
|
|
29
|
+
const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
|
|
30
|
+
|
|
31
|
+
// Urgent cases ready for the doctor go in a digest only once its template exists.
|
|
32
|
+
const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
|
|
33
|
+
|
|
34
|
+
// The approving doctor's WhatsApp, or null when there is none to send the digest to.
|
|
35
|
+
async function digestRecipient() {
|
|
36
|
+
const [approver] = await listEscalationApprovers();
|
|
37
|
+
const code = ensureWhatsAppFormat(String(approver?.phone ?? '').replace(/[^\d+]/g, ''));
|
|
38
|
+
return PATIENT_CODE.test(code) ? code : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The time a case queued now reaches the doctor at the latest, in the team's clock, for the group notice.
|
|
42
|
+
function digestTimeOf(review, now) {
|
|
43
|
+
const policy = responseDeadlinePolicy();
|
|
44
|
+
const dueAt = Math.max(now.getTime(), digestDueAt([{ ...review, digestQueuedAt: now }], policy).getTime());
|
|
45
|
+
return new Date(dueAt).toLocaleTimeString('es-MX', { timeZone: policy.teamHours.timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The digest goes when the oldest queued case has waited the window, or earlier so every case keeps the lead before its deadline; at night, when the team day opens.
|
|
49
|
+
function digestDueAt(reviews, policy) {
|
|
50
|
+
const window = minutesOf('ESCALATION_DOCTOR_DIGEST_WINDOW_MINUTES', DEFAULT_WINDOW_MINUTES) * 60000;
|
|
51
|
+
const lead = minutesOf('ESCALATION_DOCTOR_DIGEST_LEAD_MINUTES', DEFAULT_LEAD_MINUTES) * 60000;
|
|
52
|
+
const times = reviews.flatMap((review) => {
|
|
53
|
+
const deadline = responseDeadlineOf(review, policy)?.dueAt;
|
|
54
|
+
return [new Date(review.digestQueuedAt).getTime() + window, ...(deadline ? [deadline.getTime() - lead] : [])];
|
|
55
|
+
});
|
|
56
|
+
return teamOpenAt(new Date(Math.min(...times)), policy);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function digestLines(reviews) {
|
|
60
|
+
const lines = [];
|
|
61
|
+
for (const review of reviews) {
|
|
62
|
+
const { patient } = await teamAlertIdentity(review);
|
|
63
|
+
const label = [patient, review.alarms?.at(-1)?.symptom].map((text) => oneLineOf(text).slice(0, MAX_FIELD_LENGTH).trim()).filter(Boolean).join(' · ');
|
|
64
|
+
lines.push(`${label}: ${doctorLink(review)}`);
|
|
65
|
+
}
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Cases go in order, five at most per message and within the length the template allows.
|
|
70
|
+
function chunksOf(entries) {
|
|
71
|
+
const chunks = [];
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
const last = chunks.at(-1);
|
|
74
|
+
const length = last ? [...last, entry].map(({ line }) => line).join(' | ').length : 0;
|
|
75
|
+
if (last && last.length < MAX_CASES_PER_MESSAGE && length <= MAX_LINES_LENGTH) last.push(entry);
|
|
76
|
+
else chunks.push([entry]);
|
|
77
|
+
}
|
|
78
|
+
return chunks;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function sendDigest(code, entries) {
|
|
82
|
+
const lines = entries.map(({ line }) => line);
|
|
83
|
+
const count = String(entries.length);
|
|
84
|
+
const outgoing = await isWithin24HourWindow(code)
|
|
85
|
+
? { code, body: [`🟡 Casos urgentes listos para decidir: ${count}`, '', ...lines].join('\n'), triggeredBy: OPERATOR }
|
|
86
|
+
: { code, contentSid: runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: count, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
|
|
87
|
+
const result = await getMessaging().sendMessage(outgoing);
|
|
88
|
+
if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
|
|
89
|
+
if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const audit = (review, delivered) => logPatientChange({
|
|
93
|
+
code: review.patientCode,
|
|
94
|
+
updatedBy: OPERATOR,
|
|
95
|
+
source: 'escalation_review',
|
|
96
|
+
requestId: null,
|
|
97
|
+
changes: { escalationReviewId: String(review._id), action: delivered ? 'doctor_digest_sent' : 'doctor_digest_failed' },
|
|
98
|
+
}).catch((error) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(error) }));
|
|
99
|
+
|
|
100
|
+
// Sends the queued urgent cases still waiting for the doctor in one message per few cases, once the digest is due.
|
|
101
|
+
async function sendDueDoctorDigests({ now = new Date() } = {}) {
|
|
102
|
+
if (!urgentDigestLive()) return 0;
|
|
103
|
+
const unclaimed = { $or: [{ digestClaimedAt: null }, { digestClaimedAt: { $lt: new Date(now.getTime() - STALE_CLAIM_MS) } }] };
|
|
104
|
+
const found = await getEscalationReview()
|
|
105
|
+
.find({ closedAt: null, status: 'awaiting_doctor', digestQueuedAt: { $ne: null }, digestSentAt: null, ...unclaimed })
|
|
106
|
+
.sort({ digestQueuedAt: 1 })
|
|
107
|
+
.lean();
|
|
108
|
+
// A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
|
|
109
|
+
const queued = found.filter((review) => !(review.doctorHandoffs ?? [])
|
|
110
|
+
.some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime()));
|
|
111
|
+
if (!queued.length) return 0;
|
|
112
|
+
const policy = responseDeadlinePolicy();
|
|
113
|
+
if (now.getTime() < digestDueAt(queued, policy).getTime()) return 0;
|
|
114
|
+
|
|
115
|
+
const code = await digestRecipient();
|
|
116
|
+
if (!code) {
|
|
117
|
+
logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
const lines = await digestLines(queued);
|
|
121
|
+
let sent = 0;
|
|
122
|
+
// Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
|
|
123
|
+
for (const chunk of chunksOf(queued.map((review, index) => ({ review, line: lines[index] })))) {
|
|
124
|
+
const claimed = [];
|
|
125
|
+
for (const entry of chunk) {
|
|
126
|
+
const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
|
|
127
|
+
if ((await getEscalationReview().updateOne(filter, { $set: { digestClaimedAt: now } }, BOOKKEEPING)).modifiedCount) claimed.push(entry);
|
|
128
|
+
}
|
|
129
|
+
if (!claimed.length) continue;
|
|
130
|
+
const ids = claimed.map(({ review }) => review._id);
|
|
131
|
+
let delivered = false;
|
|
132
|
+
try {
|
|
133
|
+
await sendDigest(code, claimed);
|
|
134
|
+
delivered = true;
|
|
135
|
+
sent += claimed.length;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
logger.error('[DoctorDigest] The digest was not sent; it goes again on the next sweep', { cases: claimed.length, error: redacted(error) });
|
|
138
|
+
await getEscalationReview().updateMany({ _id: { $in: ids }, digestClaimedAt: now }, { $set: { digestClaimedAt: null } }, BOOKKEEPING);
|
|
139
|
+
}
|
|
140
|
+
// A sent digest keeps its claim even when this write fails, so it is not sent again before the claim goes stale.
|
|
141
|
+
if (delivered) {
|
|
142
|
+
await getEscalationReview().updateMany({ _id: { $in: ids }, digestClaimedAt: now }, { $set: { digestSentAt: now } }, BOOKKEEPING)
|
|
143
|
+
.catch((error) => logger.error('[DoctorDigest] The digest went out but was not marked as sent', { cases: claimed.length, error: redacted(error) }));
|
|
144
|
+
}
|
|
145
|
+
for (const { review } of claimed) await audit(review, delivered);
|
|
146
|
+
}
|
|
147
|
+
return sent;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
|
|
@@ -193,8 +193,10 @@ async function moveThreads(source, target, state, migrationId) {
|
|
|
193
193
|
async function countMovedMessages(target, messages) {
|
|
194
194
|
const counted = messages.filter((doc) => !INTERNAL_ORIGINS.has(doc.origin));
|
|
195
195
|
if (!counted.length) return;
|
|
196
|
-
const
|
|
197
|
-
const
|
|
196
|
+
const ids = counted.map((doc) => doc._id);
|
|
197
|
+
const latest = await Message.findOne({ _id: { $in: ids } }, null, { sort: { createdAt: -1 } }).lean();
|
|
198
|
+
// Staff can mark the chat read mid-move, so count what is stored now, not the snapshot.
|
|
199
|
+
const unread = await Message.countDocuments({ _id: { $in: ids }, from_me: false, read: { $ne: true } });
|
|
198
200
|
await Thread.updateOne({ code: target }, { $inc: { messageCount: counted.length, unreadCount: unread } });
|
|
199
201
|
await Thread.updateOne(
|
|
200
202
|
{ code: target, $or: [{ lastMessageAt: null }, { lastMessageAt: { $lt: latest.createdAt } }] },
|
|
@@ -10,6 +10,7 @@ const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = requi
|
|
|
10
10
|
const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
|
|
11
11
|
const { settleCharacterization } = require('./characterizationOutcomeService');
|
|
12
12
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
13
|
+
const { sendDueDoctorDigests } = require('./doctorDigestService');
|
|
13
14
|
|
|
14
15
|
const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
|
|
15
16
|
const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -205,6 +206,9 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
205
206
|
failed('[UntakenAlert] Could not settle the characterization of a review', review, error);
|
|
206
207
|
}
|
|
207
208
|
}
|
|
209
|
+
if (autoHandoff) {
|
|
210
|
+
await sendDueDoctorDigests({ now }).catch((error) => logger.error('[UntakenAlert] Could not send the doctor digest', { error: redactDirectIdentifiers(String(error?.message || error)) }));
|
|
211
|
+
}
|
|
208
212
|
return sent;
|
|
209
213
|
}
|
|
210
214
|
|