@peopl-health/nexus 6.5.2 → 6.5.4
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/AssistantProcessor.js +2 -1
- package/lib/clinical/flags/escalationFlags.js +5 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +14 -0
- package/lib/models/escalationReviewModel.js +9 -0
- package/lib/services/characterizationOutcomeService.js +19 -9
- package/lib/services/doctorDigestService.js +11 -5
- package/lib/services/escalationReviewService.js +12 -7
- package/lib/services/stillNeededService.js +35 -0
- package/lib/services/untakenAlertService.js +5 -5
- package/package.json +1 -1
|
@@ -149,7 +149,8 @@ class AssistantProcessor {
|
|
|
149
149
|
|
|
150
150
|
maybeWarmPatientRisk({ code: thread.code, turnId: runOptions.runId || null });
|
|
151
151
|
|
|
152
|
-
|
|
152
|
+
// Only the live patient turn may take the review's pending question; shadows, replays and staff reads build context too.
|
|
153
|
+
const runConfig = { ...runOptions, phiProcessor: this.phiProcessor, contingencySnapshot, followUpSnapshot, claimStillNeeded: !runOptions.shadow && isPatientTurn };
|
|
153
154
|
const bridgeArmed = Boolean(!runOptions.shadow && message?.body && this.sendMessage);
|
|
154
155
|
let bridgeDecision = null;
|
|
155
156
|
let bridgeReasoning = null;
|
|
@@ -28,6 +28,10 @@ function escalationAutoHandoffLive() {
|
|
|
28
28
|
return flagNotOff('ESCALATION_AUTO_HANDOFF_LIVE');
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
function escalationInTurnAskLive() {
|
|
32
|
+
return flagNotOff('ESCALATION_IN_TURN_ASK_LIVE');
|
|
33
|
+
}
|
|
34
|
+
|
|
31
35
|
function escalationUntakenAlertsLive() {
|
|
32
36
|
return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
|
|
33
37
|
}
|
|
@@ -49,6 +53,7 @@ module.exports = {
|
|
|
49
53
|
escalationApproverAlertLive,
|
|
50
54
|
escalationAssessmentLive,
|
|
51
55
|
escalationAutoHandoffLive,
|
|
56
|
+
escalationInTurnAskLive,
|
|
52
57
|
escalationPatientTimerLive,
|
|
53
58
|
escalationUntakenAlertsLive,
|
|
54
59
|
escalationUpdateModeLive,
|
|
@@ -52,6 +52,9 @@ const PENDING_INSTRUCTION_NOTE = `${OPERATOR_TURN_PREFIX} Hay un mensaje del sis
|
|
|
52
52
|
const deliveredWhileWaitingNote = (text) =>
|
|
53
53
|
`${OPERATOR_TURN_PREFIX} Mientras este turno esperaba, ya le enviaste al paciente: "${text}". No repitas ese contenido. Responde con normalidad y por completo a todo lo demás que escribió el paciente.`;
|
|
54
54
|
|
|
55
|
+
const stillNeededNote = (question) =>
|
|
56
|
+
`${OPERATOR_TURN_PREFIX} La revisión del equipo médico todavía necesita saber: "${question}". Si el paciente no lo contestó en este mensaje, pregúntalo con tus palabras al final de tu respuesta, como tu única pregunta, y no digas que el equipo ya tiene todo. Si ya lo contestó, no lo preguntes.`;
|
|
57
|
+
|
|
55
58
|
function readComorbidities(value) {
|
|
56
59
|
const parsed = typeof value === 'string' ? safeParse(value, null) : value;
|
|
57
60
|
if (!isPlainObject(parsed)) return inline(value);
|
|
@@ -130,6 +133,8 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
130
133
|
content: formatPatientMessage(turnLines),
|
|
131
134
|
type: 'message'
|
|
132
135
|
});
|
|
136
|
+
const question = config.claimStillNeeded ? await this._stillNeeded(thread.code, config.runId) : null;
|
|
137
|
+
if (question) context.push({ [CURRENT_TURN]: true, role: 'user', content: stillNeededNote(inline(question)), type: 'message' });
|
|
133
138
|
}
|
|
134
139
|
|
|
135
140
|
for (const msg of await this._outboundTail(thread.code, beforeCheckpoint, config)) {
|
|
@@ -152,6 +157,15 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
152
157
|
}
|
|
153
158
|
}
|
|
154
159
|
|
|
160
|
+
async _stillNeeded(code, turnId) {
|
|
161
|
+
try {
|
|
162
|
+
return await require('../../services/stillNeededService').claimStillNeeded(code, turnId);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
logger.warn('[DefaultMemoryManager] still-needed datum unavailable', { error: error.message });
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
155
169
|
_hasPendingInstruction(code, beforeCheckpoint, config) {
|
|
156
170
|
return Boolean(beforeCheckpoint) && !config.beforeCheckpoint && hasInstructionInFlight(code);
|
|
157
171
|
}
|
|
@@ -112,6 +112,14 @@ const blockingAskSchema = new mongoose.Schema({
|
|
|
112
112
|
outcome: { type: String, default: null },
|
|
113
113
|
}, { _id: false });
|
|
114
114
|
|
|
115
|
+
const inTurnAskSchema = new mongoose.Schema({
|
|
116
|
+
draftAt: { type: Date, required: true },
|
|
117
|
+
key: { type: String, required: true },
|
|
118
|
+
question: { type: String, required: true },
|
|
119
|
+
turnId: { type: String, default: null },
|
|
120
|
+
at: { type: Date, required: true },
|
|
121
|
+
}, { _id: false });
|
|
122
|
+
|
|
115
123
|
const reviewUpdateSchema = new mongoose.Schema({
|
|
116
124
|
turnId: { type: String, required: true },
|
|
117
125
|
tools: { type: [String], default: [] },
|
|
@@ -362,6 +370,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
362
370
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
363
371
|
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
364
372
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
373
|
+
inTurnAsks: { type: [inTurnAskSchema], default: [] },
|
|
365
374
|
feverPromptStartedAt: { type: Date, default: null },
|
|
366
375
|
approverViewedAt: { type: Date, default: null },
|
|
367
376
|
previousReviewId: { type: String, default: null },
|
|
@@ -117,14 +117,17 @@ function outcomeOf(review, clock, now) {
|
|
|
117
117
|
if (latest.sufficientForDoctor !== false) return null;
|
|
118
118
|
// The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
|
|
119
119
|
const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
120
|
+
// The bot asked this draft's question in its own reply when no redraft followed that reply.
|
|
121
|
+
const inTurn = (review.inTurnAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
120
122
|
const sent = ask && !ask.skippedReason;
|
|
123
|
+
const askedAt = sent ? ask.sentAt : inTurn?.at ?? latest.createdAt;
|
|
121
124
|
// A first handoff with a question waits for its ask (recorded once the bot's reply is in), or in flight, up to twice the wait.
|
|
122
|
-
if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(
|
|
123
|
-
if (minutesSince(
|
|
125
|
+
if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(askedAt, now) < 2 * wait) return null;
|
|
126
|
+
if (minutesSince(askedAt, now) < wait) return null;
|
|
124
127
|
const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
|
|
125
128
|
// An update's draft is never asked about, so it says only what is missing.
|
|
126
129
|
if (update) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(noteOf(missing)) };
|
|
127
|
-
const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open';
|
|
130
|
+
const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open' || Boolean(inTurn);
|
|
128
131
|
return { grave: [], update, notify, note: noteOf(`${missing} (${asked ? 'no contestó' : 'no se le preguntó'})`) };
|
|
129
132
|
}
|
|
130
133
|
|
|
@@ -385,13 +388,12 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
385
388
|
await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
|
|
386
389
|
}
|
|
387
390
|
|
|
388
|
-
|
|
389
|
-
async function askBlockingQuestion(review, clock, now) {
|
|
391
|
+
function pendingAskOf(review, clock) {
|
|
390
392
|
// With the doctor, only a case the bot handed over is still asked, and only its grave data.
|
|
391
393
|
const withDoctor = review.status === 'awaiting_doctor';
|
|
392
|
-
if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
|
|
394
|
+
if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return null;
|
|
393
395
|
const latest = (review.drafts ?? []).at(-1);
|
|
394
|
-
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
|
|
396
|
+
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return null;
|
|
395
397
|
// A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
|
|
396
398
|
const settled = new Set([
|
|
397
399
|
...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
|
|
@@ -401,8 +403,16 @@ async function askBlockingQuestion(review, clock, now) {
|
|
|
401
403
|
: pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
|
|
402
404
|
const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
|
|
403
405
|
const question = graveFlags.join('; ') || blocking || null;
|
|
406
|
+
if (!question) return null;
|
|
404
407
|
const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
|
|
405
|
-
|
|
408
|
+
return { latest, withDoctor, graveFlags, blocking, question, flags };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
|
|
412
|
+
async function askBlockingQuestion(review, clock, now) {
|
|
413
|
+
const pending = pendingAskOf(review, clock);
|
|
414
|
+
if (!pending) return;
|
|
415
|
+
const { latest, withDoctor, graveFlags, blocking, question, flags } = pending;
|
|
406
416
|
const asks = review.blockingAsks ?? [];
|
|
407
417
|
if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
408
418
|
const last = await lastChatMessage(review.patientCode);
|
|
@@ -470,4 +480,4 @@ async function settleCharacterization(review, clock, now) {
|
|
|
470
480
|
await askBlockingQuestion(review, clock, now);
|
|
471
481
|
}
|
|
472
482
|
|
|
473
|
-
module.exports = { outcomeOf, settleCharacterization };
|
|
483
|
+
module.exports = { outcomeOf, pendingAskOf, settleCharacterization };
|
|
@@ -59,11 +59,10 @@ function digestDueAt(reviews, policy) {
|
|
|
59
59
|
return teamOpenAt(new Date(Math.min(...times)), policy);
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
function digestLines(cases, now, policy) {
|
|
63
63
|
const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
|
|
64
64
|
const lines = [];
|
|
65
|
-
for (const review of
|
|
66
|
-
const { patient, identity } = await teamAlertIdentity(review);
|
|
65
|
+
for (const { review, who: { patient, identity } } of cases) {
|
|
67
66
|
if (brief) {
|
|
68
67
|
lines.push(doctorDigestLine({
|
|
69
68
|
identity: { ...identity, patientName: identity.patientName || patient },
|
|
@@ -128,17 +127,24 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
|
|
|
128
127
|
.some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime()));
|
|
129
128
|
if (!queued.length) return 0;
|
|
130
129
|
const policy = responseDeadlinePolicy();
|
|
130
|
+
// Dropping cases only delays the digest, so nothing is read from the patient records before any of them is due.
|
|
131
131
|
if (now.getTime() < digestDueAt(queued, policy).getTime()) return 0;
|
|
132
|
+
const cases = [];
|
|
133
|
+
for (const review of queued) {
|
|
134
|
+
const who = await teamAlertIdentity(review);
|
|
135
|
+
if (!who.identity.testPatient) cases.push({ review, who });
|
|
136
|
+
}
|
|
137
|
+
if (!cases.length || now.getTime() < digestDueAt(cases.map(({ review }) => review), policy).getTime()) return 0;
|
|
132
138
|
|
|
133
139
|
const code = await digestRecipient();
|
|
134
140
|
if (!code) {
|
|
135
141
|
logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
|
|
136
142
|
return 0;
|
|
137
143
|
}
|
|
138
|
-
const lines =
|
|
144
|
+
const lines = digestLines(cases, now, policy);
|
|
139
145
|
let sent = 0;
|
|
140
146
|
// Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
|
|
141
|
-
for (const chunk of chunksOf(
|
|
147
|
+
for (const chunk of chunksOf(cases.map(({ review }, index) => ({ review, line: lines[index] })))) {
|
|
142
148
|
const claimed = [];
|
|
143
149
|
for (const entry of chunk) {
|
|
144
150
|
const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
|
|
@@ -361,8 +361,12 @@ function doctorLink(review) {
|
|
|
361
361
|
return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
362
362
|
}
|
|
363
363
|
|
|
364
|
+
// A test record, by its tipo or a name starting with «test» (the rule of Airtable's notifyEmergency), alerts the team but not the doctors.
|
|
365
|
+
const TEST_NAME = /^test\b/i;
|
|
366
|
+
|
|
364
367
|
function doctorIdentity(patient) {
|
|
365
368
|
const patientName = inlineOf(patient?.name);
|
|
369
|
+
const testPatient = inlineOf(patient?.tipo).toLowerCase() === 'test' || TEST_NAME.test(patientName);
|
|
366
370
|
const treatingDoctor = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
|
|
367
371
|
const missing = [];
|
|
368
372
|
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
@@ -370,7 +374,7 @@ function doctorIdentity(patient) {
|
|
|
370
374
|
const demografia = safeParse(patient?.['clinical-context-json'], null)?.demografia;
|
|
371
375
|
const born = ageInYears(birthDateFrom(demografia?.fecha_nacimiento));
|
|
372
376
|
const age = born > 0 && born < 130 ? born : ageFrom(demografia?.edad);
|
|
373
|
-
return { patientName, treatingDoctor, age, missing };
|
|
377
|
+
return { patientName, treatingDoctor, age, missing, testPatient };
|
|
374
378
|
}
|
|
375
379
|
|
|
376
380
|
async function readDoctorIdentity(review) {
|
|
@@ -1368,7 +1372,7 @@ async function fallbackRecipient() {
|
|
|
1368
1372
|
|
|
1369
1373
|
// Who and where for a team alert; a patient record that cannot be read never holds the alert back.
|
|
1370
1374
|
async function teamAlertIdentity(review) {
|
|
1371
|
-
let identity = { patientName: '', treatingDoctor: '' };
|
|
1375
|
+
let identity = { patientName: '', treatingDoctor: '', testPatient: false };
|
|
1372
1376
|
try {
|
|
1373
1377
|
identity = doctorIdentity(await getPatientInformation(review.patientCode));
|
|
1374
1378
|
} catch (error) {
|
|
@@ -1382,8 +1386,7 @@ async function teamAlertIdentity(review) {
|
|
|
1382
1386
|
};
|
|
1383
1387
|
}
|
|
1384
1388
|
|
|
1385
|
-
|
|
1386
|
-
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
1389
|
+
function teamFallbackNotice(review, urgencyLevel, alarmId, { patient, doctor, link }) {
|
|
1387
1390
|
const alarm = alarmFor(review, urgencyLevel, alarmId);
|
|
1388
1391
|
const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
|
|
1389
1392
|
return {
|
|
@@ -1394,7 +1397,8 @@ async function teamFallbackNotice(review, urgencyLevel, alarmId) {
|
|
|
1394
1397
|
|
|
1395
1398
|
async function alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId) {
|
|
1396
1399
|
try {
|
|
1397
|
-
const
|
|
1400
|
+
const who = await teamAlertIdentity(review);
|
|
1401
|
+
const result = await sendTeamAlert({ message: teamFallbackNotice(review, urgencyLevel, alarmId, who), operator: ALERT_OPERATOR, notice: true, ...(who.identity.testPatient && { withDoctors: false }) });
|
|
1398
1402
|
const missed = result.phones.filter((phone) => !phone.delivered).length + (groupConfigured() && !result.group.delivered ? 1 : 0);
|
|
1399
1403
|
if (result.delivered && missed) logger.warn('[EscalationReview] The team notice missed some recipients', { escalationReviewId: String(review._id), delivered: result.delivered, missed });
|
|
1400
1404
|
return result.delivered ? { transport: 'team' } : null;
|
|
@@ -1866,8 +1870,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
1866
1870
|
let delivery = {};
|
|
1867
1871
|
let updated;
|
|
1868
1872
|
try {
|
|
1869
|
-
|
|
1870
|
-
|
|
1873
|
+
const rings = notify && !identity.testPatient;
|
|
1874
|
+
if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
|
|
1875
|
+
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
|
|
1871
1876
|
const handoff = {
|
|
1872
1877
|
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
|
|
1873
1878
|
$addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const { normalizedKeyOf } = require('../utils/coercionUtils');
|
|
2
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
4
|
+
const { escalationInTurnAskLive } = require('../clinical/flags/escalationFlags');
|
|
5
|
+
|
|
6
|
+
const { BOOKKEEPING, caseTakenReason } = require('./escalationReviewService');
|
|
7
|
+
const { pendingAskOf } = require('./characterizationOutcomeService');
|
|
8
|
+
const { responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
9
|
+
const { UNTAKEN_PROJECTION, untakenClockOf } = require('./untakenAlertService');
|
|
10
|
+
|
|
11
|
+
// The review's blocking question the bot asks in its own reply: not grave, and served once per episode.
|
|
12
|
+
async function claimStillNeeded(code, turnId = null, now = new Date()) {
|
|
13
|
+
if (!escalationInTurnAskLive()) return null;
|
|
14
|
+
const review = await getEscalationReview().findOne({ patientCode: ensureWhatsAppFormat(code), closedAt: null, status: 'draft_ready' }, UNTAKEN_PROJECTION).lean();
|
|
15
|
+
if (!review) return null;
|
|
16
|
+
const clock = untakenClockOf(review, responseDeadlinePolicy());
|
|
17
|
+
const pending = clock && pendingAskOf(review, clock);
|
|
18
|
+
if (!pending?.blocking) return null;
|
|
19
|
+
const key = normalizedKeyOf(pending.latest.blockingFlag || pending.blocking);
|
|
20
|
+
const served = { key, draftAt: { $gte: clock.since } };
|
|
21
|
+
const earlier = (review.inTurnAsks ?? []).find((entry) => entry.key === key && new Date(entry.draftAt) >= clock.since);
|
|
22
|
+
// A retry of the same turn rebuilds its context, so it gets the question its first attempt claimed.
|
|
23
|
+
if (earlier) return turnId && earlier.turnId === turnId ? earlier.question : null;
|
|
24
|
+
// A case the team already took is theirs to ask; a missing thread does not count as taken.
|
|
25
|
+
const taken = await caseTakenReason(review, clock.since, clock.level);
|
|
26
|
+
if (taken && taken !== 'thread_missing') return null;
|
|
27
|
+
const claimed = await getEscalationReview().updateOne(
|
|
28
|
+
{ _id: review._id, closedAt: null, inTurnAsks: { $not: { $elemMatch: served } } },
|
|
29
|
+
{ $push: { inTurnAsks: { draftAt: pending.latest.createdAt, key, question: pending.blocking, turnId, at: now } } },
|
|
30
|
+
BOOKKEEPING,
|
|
31
|
+
);
|
|
32
|
+
return claimed.modifiedCount ? pending.blocking : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { claimStillNeeded };
|
|
@@ -27,7 +27,7 @@ const ACTIONS = {
|
|
|
27
27
|
};
|
|
28
28
|
const MAX_QUESTION_LENGTH = 200;
|
|
29
29
|
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
30
|
-
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
30
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
31
31
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
32
32
|
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
33
33
|
};
|
|
@@ -98,8 +98,7 @@ function patientPromptNote(review, stage, now) {
|
|
|
98
98
|
return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
|
|
102
|
-
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
101
|
+
function untakenMessage(review, clock, stage, now, { patient, doctor, link }) {
|
|
103
102
|
const deadline = deadlineText(clock, stage);
|
|
104
103
|
const level = LEVEL_LABELS[clock.level];
|
|
105
104
|
const action = ACTIONS[clock.level];
|
|
@@ -150,11 +149,12 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
150
149
|
await claimStage(review, clock, stage, now, taken);
|
|
151
150
|
return false;
|
|
152
151
|
}
|
|
153
|
-
const
|
|
152
|
+
const who = await teamAlertIdentity(review);
|
|
153
|
+
const message = untakenMessage(review, clock, stage, now, who);
|
|
154
154
|
// Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
|
|
155
155
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
156
156
|
if (!await claimStage(review, clock, stage, now)) return false;
|
|
157
|
-
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' });
|
|
157
|
+
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' && !who.identity.testPatient });
|
|
158
158
|
const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
|
|
159
159
|
await getEscalationReview().updateOne(
|
|
160
160
|
{ _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
|