@peopl-health/nexus 6.0.0-dev.16335 → 6.0.0-dev.16336
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/clinicalAirtableService.js +3 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +4 -2
- package/lib/services/escalationReviewService.js +16 -10
- package/lib/services/teamAlertService.js +2 -1
- package/lib/services/untakenAlertService.js +7 -29
- package/lib/utils/coercionUtils.js +2 -1
- package/package.json +1 -1
|
@@ -254,7 +254,7 @@ function recordEmergency(params) {
|
|
|
254
254
|
return serializedEmergencyWrite(params.code, () => recordEmergencyNow(params));
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
-
async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null }) {
|
|
257
|
+
async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null, onMerging = null }) {
|
|
258
258
|
const level = urgencyLevel || MEDICAL_URGENCY_TO_EMERGENCY_LEVEL[urgencyFhir] || 'Alta';
|
|
259
259
|
const prior = anchor?.recordId ? anchor : (mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null);
|
|
260
260
|
const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
|
|
@@ -281,6 +281,7 @@ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '
|
|
|
281
281
|
|
|
282
282
|
const open = mergeable ? await readEmergencyRow(prior.recordId, code) : null;
|
|
283
283
|
if (open) {
|
|
284
|
+
onMerging?.(true);
|
|
284
285
|
const incoming = belowPrior
|
|
285
286
|
? [symptom && `Síntoma: ${symptom}`, suspectedCondition && `Sospecha: ${suspectedCondition}`, recommendedAction && `Acción recomendada: ${recommendedAction}`]
|
|
286
287
|
.filter(Boolean).join(' · ')
|
|
@@ -301,6 +302,7 @@ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '
|
|
|
301
302
|
}
|
|
302
303
|
}
|
|
303
304
|
|
|
305
|
+
onMerging?.(false);
|
|
304
306
|
if (documentation) fields['Documentación_emergencia'] = documentation;
|
|
305
307
|
const created = await airtableService.addRecord(Monitoreo_ID, 'emergencies', [{ fields }], code);
|
|
306
308
|
const record = Array.isArray(created) ? created[0] : created;
|
|
@@ -392,6 +392,7 @@ async function handler(args, context = {}) {
|
|
|
392
392
|
queued = written || duplicate;
|
|
393
393
|
} else {
|
|
394
394
|
let emergencyRecordId = null;
|
|
395
|
+
let merging = false;
|
|
395
396
|
queued = await recordEmergency({
|
|
396
397
|
code: runtime.patientCode,
|
|
397
398
|
trace,
|
|
@@ -408,10 +409,11 @@ async function handler(args, context = {}) {
|
|
|
408
409
|
anchor: anchor?.emergencyRecordId ? { recordId: anchor.emergencyRecordId, urgencyFhir: anchor.urgencyLevel } : null,
|
|
409
410
|
keepOpenRow: keptOpenLevel,
|
|
410
411
|
onRecorded: (recordId) => { emergencyRecordId = recordId; },
|
|
412
|
+
onMerging: (into) => { merging = into; },
|
|
411
413
|
});
|
|
412
414
|
if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
|
|
413
|
-
// A merge into an
|
|
414
|
-
if (review && !queued &&
|
|
415
|
+
// A merge into an open row never alerts; any other failed write may have left the team without one.
|
|
416
|
+
if (review && !queued && !merging) {
|
|
415
417
|
alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
|
|
416
418
|
}
|
|
417
419
|
if (urgencyLevel !== 'routine') {
|
|
@@ -2,7 +2,7 @@ const mongoose = require('mongoose');
|
|
|
2
2
|
|
|
3
3
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
4
|
const { httpError, requiredText } = require('../utils/httpErrorUtils');
|
|
5
|
-
const { inlineOf } = require('../utils/coercionUtils');
|
|
5
|
+
const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
8
|
const { isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
@@ -1253,22 +1253,26 @@ async function fallbackRecipient() {
|
|
|
1253
1253
|
return phone ? { name: null, email: null, phone } : soleApprover();
|
|
1254
1254
|
}
|
|
1255
1255
|
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
// A brief notice for the whole team; a patient record that cannot be read never holds it back.
|
|
1259
|
-
async function teamFallbackNotice(review, urgencyLevel, alarmId) {
|
|
1256
|
+
// Who and where for a team alert; a patient record that cannot be read never holds the alert back.
|
|
1257
|
+
async function teamAlertIdentity(review) {
|
|
1260
1258
|
let identity = { patientName: '', treatingDoctor: '' };
|
|
1261
1259
|
try {
|
|
1262
1260
|
identity = doctorIdentity(await getPatientInformation(review.patientCode));
|
|
1263
1261
|
} catch (error) {
|
|
1264
|
-
logger.error('[EscalationReview] The patient record could not be read
|
|
1262
|
+
logger.error('[EscalationReview] The patient record could not be read; the team alert goes out without the name', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
1265
1263
|
}
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1264
|
+
return {
|
|
1265
|
+
patient: oneLineOf(identity.patientName) || 'sin nombre registrado',
|
|
1266
|
+
doctor: oneLineOf(identity.treatingDoctor) || 'sin médico registrado',
|
|
1267
|
+
link: conversationLink(review.patientCode) || 'abrir el chat en la plataforma',
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
async function teamFallbackNotice(review, urgencyLevel, alarmId) {
|
|
1272
|
+
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
1269
1273
|
const alarm = (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
|
|
1270
1274
|
?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
|
|
1271
|
-
const what = [urgencyLevel.toUpperCase(),
|
|
1275
|
+
const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
|
|
1272
1276
|
return {
|
|
1273
1277
|
body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
|
|
1274
1278
|
template: { 1: what, 2: patient, 3: doctor, 4: link },
|
|
@@ -2146,6 +2150,7 @@ module.exports = {
|
|
|
2146
2150
|
BOOKKEEPING,
|
|
2147
2151
|
DOCUMENTING_STATUSES,
|
|
2148
2152
|
FEVER_CATEGORY,
|
|
2153
|
+
appliedLevelOf,
|
|
2149
2154
|
MAX_ALERT_ATTEMPTS,
|
|
2150
2155
|
PRE_DECISION_STATUSES,
|
|
2151
2156
|
_resetEscalationReviewIndexes,
|
|
@@ -2153,6 +2158,7 @@ module.exports = {
|
|
|
2153
2158
|
caseTakenReason,
|
|
2154
2159
|
currentAlarms,
|
|
2155
2160
|
doctorIdentity,
|
|
2161
|
+
teamAlertIdentity,
|
|
2156
2162
|
addDraft,
|
|
2157
2163
|
alertWithoutEmergencyRow,
|
|
2158
2164
|
attachEmergencyRow,
|
|
@@ -93,7 +93,8 @@ async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
|
93
93
|
|
|
94
94
|
const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
// Phones alone count only once the notice template exists, or a notice outside the 24-hour window reaches no one.
|
|
97
|
+
const teamChannelConfigured = async () => groupConfigured() || (Boolean(runtimeConfig.get(NOTICE_TEMPLATE_KEY)) && (await teamPhones()).length > 0);
|
|
97
98
|
|
|
98
99
|
async function postToGroup(body, quoted) {
|
|
99
100
|
const res = await axios({
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
const {
|
|
1
|
+
const { oneLineOf } = require('../utils/coercionUtils');
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
4
|
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
|
-
const {
|
|
5
|
+
const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
6
6
|
const { escalationGravePendingShadow, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
7
7
|
|
|
8
|
-
const {
|
|
8
|
+
const { logPatientChange } = require('./patientService');
|
|
9
9
|
const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
|
|
10
|
-
const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms,
|
|
10
|
+
const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
|
|
11
11
|
const { recordGraveMissing } = require('./gravePendingService');
|
|
12
12
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
13
13
|
|
|
@@ -24,16 +24,8 @@ const ACTIONS = {
|
|
|
24
24
|
asap: 'Tomar el caso: escribir o llamar y registrar la llamada',
|
|
25
25
|
urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
|
|
26
26
|
};
|
|
27
|
-
const NO_NAME = 'sin nombre registrado';
|
|
28
|
-
const NO_DOCTOR = 'sin médico registrado';
|
|
29
|
-
const NO_LINK = 'abrir el chat en la plataforma';
|
|
30
27
|
const MAX_QUESTION_LENGTH = 200;
|
|
31
28
|
|
|
32
|
-
const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
|
|
33
|
-
|
|
34
|
-
// A WhatsApp template variable cannot hold a line break.
|
|
35
|
-
const oneLine = (value) => inlineOf(value).replace(/\s+/g, ' ');
|
|
36
|
-
|
|
37
29
|
const duration = (minutes) => {
|
|
38
30
|
const hours = Math.floor(minutes / 60);
|
|
39
31
|
const rest = Math.round(minutes % 60);
|
|
@@ -53,7 +45,7 @@ function untakenClockOf(review, policy) {
|
|
|
53
45
|
return {
|
|
54
46
|
level,
|
|
55
47
|
since,
|
|
56
|
-
symptom:
|
|
48
|
+
symptom: oneLineOf(atLevel.at(-1).symptom),
|
|
57
49
|
emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
|
|
58
50
|
stages: untakenStagesOf(level, since, policy),
|
|
59
51
|
};
|
|
@@ -80,7 +72,7 @@ function deadlineText(clock, stage) {
|
|
|
80
72
|
function pendingQuestionOf(review, clock) {
|
|
81
73
|
const draft = (review.drafts ?? []).at(-1);
|
|
82
74
|
if (!draft || new Date(draft.createdAt).getTime() < clock.since.getTime()) return null;
|
|
83
|
-
const question =
|
|
75
|
+
const question = oneLineOf(draft.keyQuestions?.[0]);
|
|
84
76
|
return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
|
|
85
77
|
}
|
|
86
78
|
|
|
@@ -94,22 +86,8 @@ function patientPromptNote(review, stage, now) {
|
|
|
94
86
|
return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
|
|
95
87
|
}
|
|
96
88
|
|
|
97
|
-
async function identityOf(review) {
|
|
98
|
-
try {
|
|
99
|
-
return doctorIdentity(await getPatientInformation(review.patientCode));
|
|
100
|
-
} catch (error) {
|
|
101
|
-
logger.error('[UntakenAlert] The patient record could not be read; the alert goes out without the name', {
|
|
102
|
-
escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
|
|
103
|
-
});
|
|
104
|
-
return { patientName: '', treatingDoctor: '' };
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
89
|
async function untakenMessage(review, clock, stage, now) {
|
|
109
|
-
const {
|
|
110
|
-
const patient = patientName || NO_NAME;
|
|
111
|
-
const doctor = treatingDoctor || NO_DOCTOR;
|
|
112
|
-
const link = conversationLink(review.patientCode) || NO_LINK;
|
|
90
|
+
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
113
91
|
const deadline = deadlineText(clock, stage);
|
|
114
92
|
const level = LEVEL_LABELS[clock.level];
|
|
115
93
|
const action = ACTIONS[clock.level];
|
|
@@ -3,7 +3,8 @@ const arr = (value) => (Array.isArray(value) ? value : []);
|
|
|
3
3
|
const strList = (value) => arr(value).map(str).map((item) => item.trim()).filter(Boolean);
|
|
4
4
|
const firstOf = (value) => (Array.isArray(value) ? value[0] : value);
|
|
5
5
|
const inlineOf = (value) => String(firstOf(value) ?? '').trim();
|
|
6
|
+
const oneLineOf = (value) => inlineOf(value).replace(/\s+/g, ' ');
|
|
6
7
|
|
|
7
8
|
module.exports = {
|
|
8
|
-
str, arr, strList, firstOf, inlineOf,
|
|
9
|
+
str, arr, strList, firstOf, inlineOf, oneLineOf,
|
|
9
10
|
};
|