@peopl-health/nexus 6.1.0-dev.18134 → 6.1.0-dev.18137
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.
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
2
|
const { inlineOf, oneLineOf } = require('../../utils/coercionUtils');
|
|
3
|
-
const { mexicoStamp } = require('../../utils/dateUtils');
|
|
4
3
|
|
|
5
4
|
const URGENCY_LABELS = {
|
|
6
5
|
stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
|
|
@@ -82,13 +81,20 @@ function proposalLine({ proposal, conduct, sections }) {
|
|
|
82
81
|
].filter(Boolean).join(' ');
|
|
83
82
|
}
|
|
84
83
|
|
|
84
|
+
const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
85
|
+
// The part as a whole phrase of the text, so «no» is not found inside «ibuprofeno».
|
|
86
|
+
const includesText = (text, part) => Boolean(text && part) && new RegExp(`(^|[^\\p{L}\\d/])${escaped(part)}($|[^\\p{L}\\d/])`, 'iu').test(text);
|
|
87
|
+
|
|
85
88
|
function symptomParagraph(entry, fallbackSymptom) {
|
|
86
89
|
const sections = entry.sections ?? {};
|
|
87
|
-
const
|
|
90
|
+
const label = inlineOf(sections.symptom) || fallbackSymptom || 'Síntoma no especificado';
|
|
91
|
+
const graded = [1, 2, 3, 4, 5].includes(sections.grade);
|
|
92
|
+
const grade = graded ? `G${sections.grade}` : 'grado no establecido';
|
|
88
93
|
const { present, absent, unassessed } = flagsByStatus(sections);
|
|
89
94
|
const summary = inlineOf(sections.characterizationSummary);
|
|
90
95
|
return [
|
|
91
|
-
|
|
96
|
+
// An ungraded symptom whose label already names a grade is not called ungraded.
|
|
97
|
+
!graded && /\bG[1-5]\b/.test(label) ? `${label}:` : `${label} (${grade}):`,
|
|
92
98
|
summary && sentence(summary),
|
|
93
99
|
present.length && `${present.length > 1 ? 'Banderas rojas presentes' : 'Bandera roja presente'}: ${sentence(present.join(', '))}`,
|
|
94
100
|
!present.length && !unassessed.length && absent.length && 'Sin banderas rojas.',
|
|
@@ -102,12 +108,15 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
|
|
|
102
108
|
const lastDose = inlineOf(context?.lastDose);
|
|
103
109
|
const priorManagement = inlineOf(context?.priorManagement);
|
|
104
110
|
const response = inlineOf(context?.response);
|
|
105
|
-
const urgency = [URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel), alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null].filter(Boolean);
|
|
106
111
|
const priorities = inlineOf(shared?.doctorPriorities);
|
|
112
|
+
// The last dose is said once, so not again when the treatment text already gives it.
|
|
113
|
+
const dose = includesText(treatment, lastDose) ? null : `última dosis: ${lastDose || 'no disponible'}`;
|
|
114
|
+
// A response that already reads as one («sin respuesta», «respuesta parcial») is not prefixed again; «no aplica» says nothing.
|
|
115
|
+
const answer = response && !/^no aplica\b/i.test(response) && !includesText(priorManagement, response)
|
|
116
|
+
&& (/^(respuesta\b|(sin|no)\s)/i.test(response) ? response : `respuesta ${response}`);
|
|
107
117
|
return [
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
priorManagement || response ? `Manejo previo: ${sentence([priorManagement, response && `respuesta ${response}`].filter(Boolean).join('; '))}` : null,
|
|
118
|
+
treatment || lastDose ? `Tratamiento: ${[treatment || 'no disponible', dose].filter(Boolean).join('; ')}.` : 'Tratamiento y última dosis: no disponibles.',
|
|
119
|
+
priorManagement || answer ? `Manejo previo: ${sentence([priorManagement, answer].filter(Boolean).join('; '))}` : null,
|
|
111
120
|
vitalsLine(shared?.vitals),
|
|
112
121
|
inlineOf(shared?.objectiveData) ? `Datos objetivos: ${sentence(inlineOf(shared.objectiveData))}` : null,
|
|
113
122
|
'',
|
|
@@ -120,7 +129,8 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
|
|
|
120
129
|
|
|
121
130
|
function identityLines({ identity, review }) {
|
|
122
131
|
const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
|
|
123
|
-
|
|
132
|
+
const patient = identity.age ? `${identity.patientName}, ${identity.age} años` : identity.patientName;
|
|
133
|
+
return [`Paciente: ${patient} · ${phone}`, `Médico tratante: ${withTitle(identity.treatingDoctor)}`];
|
|
124
134
|
}
|
|
125
135
|
|
|
126
136
|
function withIdentity({ identity, review, doctorText }) {
|
|
@@ -144,9 +144,18 @@ async function handOff(review, clock, outcome, now) {
|
|
|
144
144
|
try {
|
|
145
145
|
if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
|
|
146
146
|
const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
|
|
147
|
-
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
|
|
147
|
+
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
|
|
148
148
|
} catch (error) {
|
|
149
|
-
|
|
149
|
+
// Someone handed the case off since the sweep read it: nothing failed, and the next sweep reads the new handoff.
|
|
150
|
+
const next = `doctorHandoffs.${(review.doctorHandoffs ?? []).length}`;
|
|
151
|
+
const overtaken = error?.statusCode === 409
|
|
152
|
+
&& Boolean(await getEscalationReview().exists({ _id: review._id, [next]: { $exists: true } }).catch(() => null));
|
|
153
|
+
// The digest stays queued for a handoff still being sent or one that did not ring the doctor, as another sweep's may rely on it.
|
|
154
|
+
const unqueue = overtaken
|
|
155
|
+
? { [`${next}.transport`]: { $exists: true, $ne: null } }
|
|
156
|
+
: { status: { $nin: ['awaiting_doctor', 'handing_off'] } };
|
|
157
|
+
if (digest) await getEscalationReview().updateOne({ _id: review._id, ...unqueue }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
|
|
158
|
+
if (overtaken) return false;
|
|
150
159
|
const attempt = attemptsOf(review, clock) + 1;
|
|
151
160
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
|
|
152
161
|
// A 409 is mostly another sweep or a person who moved the case first.
|
|
@@ -229,8 +238,8 @@ async function graveMessage(review, clock, entries) {
|
|
|
229
238
|
}
|
|
230
239
|
|
|
231
240
|
const sameEntry = (entry) => ({ flag: entry.flag, since: entry.since });
|
|
232
|
-
const setOn = (review, entry, fields, filter = {}) => getEscalationReview().updateOne(
|
|
233
|
-
{ _id: review._id, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
|
|
241
|
+
const setOn = (review, entry, fields, filter = {}, guard = {}) => getEscalationReview().updateOne(
|
|
242
|
+
{ _id: review._id, ...guard, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
|
|
234
243
|
{ $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`graveAlerts.$.${key}`, value])) },
|
|
235
244
|
BOOKKEEPING,
|
|
236
245
|
);
|
|
@@ -251,7 +260,9 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
|
|
|
251
260
|
const message = await graveMessage(review, clock, pending);
|
|
252
261
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
253
262
|
const sending = [];
|
|
254
|
-
|
|
263
|
+
// A decision or a closing since the sweep read the case means the alert is no longer due.
|
|
264
|
+
const undecided = { closedAt: null, status: { $in: PRE_DECISION_STATUSES }, decisions: { $size: (review.decisions ?? []).length } };
|
|
265
|
+
for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null }, undecided)).modifiedCount) sending.push(entry);
|
|
255
266
|
if (!sending.length) return 0;
|
|
256
267
|
let delivered = 0;
|
|
257
268
|
try {
|
|
@@ -5,7 +5,8 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
|
|
|
5
5
|
const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
|
-
const { isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
8
|
+
const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
9
|
+
const { safeParse } = require('../utils/jsonUtils');
|
|
9
10
|
const {
|
|
10
11
|
CALL_OUTCOMES,
|
|
11
12
|
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
@@ -45,6 +46,7 @@ const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/hel
|
|
|
45
46
|
const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
|
|
46
47
|
const { composePrompt } = require('../clinical/services/promptComposerService');
|
|
47
48
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
49
|
+
const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
|
|
48
50
|
|
|
49
51
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
50
52
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
@@ -72,6 +74,7 @@ const MAX_ALERT_ATTEMPTS = 3;
|
|
|
72
74
|
const BOOKKEEPING = { timestamps: false };
|
|
73
75
|
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
74
76
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
77
|
+
const HANDING_OFF_WAIT_MS = 3000;
|
|
75
78
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
76
79
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
77
80
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
@@ -348,7 +351,10 @@ function doctorIdentity(patient) {
|
|
|
348
351
|
const missing = [];
|
|
349
352
|
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
350
353
|
if (!treatingDoctor) missing.push('médico tratante');
|
|
351
|
-
|
|
354
|
+
const demografia = safeParse(patient?.['clinical-context-json'], null)?.demografia;
|
|
355
|
+
const born = ageInYears(birthDateFrom(demografia?.fecha_nacimiento));
|
|
356
|
+
const age = born > 0 && born < 130 ? born : ageFrom(demografia?.edad);
|
|
357
|
+
return { patientName, treatingDoctor, age, missing };
|
|
352
358
|
}
|
|
353
359
|
|
|
354
360
|
async function readDoctorIdentity(review) {
|
|
@@ -792,6 +798,21 @@ async function appendKeepingDraft(id, entry) {
|
|
|
792
798
|
throw httpError(409, STATUS_CONFLICT);
|
|
793
799
|
}
|
|
794
800
|
|
|
801
|
+
// With the doctor the case keeps its status; a bot handoff redrafts it as an update, so the call reaches the draft the doctor reads.
|
|
802
|
+
async function appendWithDoctor(id, entry) {
|
|
803
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
804
|
+
const review = await loadReview(id);
|
|
805
|
+
// The bot's own update passes through handing_off while it sends; the call waits for it once.
|
|
806
|
+
if (review.status === 'handing_off' && attempt === 0) {
|
|
807
|
+
await new Promise((resolve) => { setTimeout(resolve, HANDING_OFF_WAIT_MS); });
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (review.status !== 'awaiting_doctor') break;
|
|
811
|
+
return updateReview(id, ['awaiting_doctor'], { $push: { callLogs: entry }, ...(updatesDoctor(review) && { $set: redraftAfterCall() }) });
|
|
812
|
+
}
|
|
813
|
+
throw httpError(409, STATUS_CONFLICT);
|
|
814
|
+
}
|
|
815
|
+
|
|
795
816
|
async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
|
|
796
817
|
const reviewId = reviewIdOf(id);
|
|
797
818
|
const operator = requiredText(updatedBy, 'updatedBy');
|
|
@@ -844,11 +865,13 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
|
|
|
844
865
|
if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
|
|
845
866
|
|
|
846
867
|
const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
|
|
847
|
-
const review = outcome === 'contacted'
|
|
848
|
-
?
|
|
849
|
-
:
|
|
868
|
+
const review = await (outcome === 'contacted'
|
|
869
|
+
? updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
|
|
870
|
+
: appendKeepingDraft(reviewId, entry))
|
|
871
|
+
.catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)));
|
|
850
872
|
await audit(review, operator, requestId, { action: 'call_logged', outcome });
|
|
851
|
-
|
|
873
|
+
// Note facts are confirmed only while the case is documented, so none are proposed while it is with the doctor.
|
|
874
|
+
if (outcome !== 'contacted' || review.status === 'awaiting_doctor') return review;
|
|
852
875
|
return proposeNoteFacts(review, operator, requestId);
|
|
853
876
|
}
|
|
854
877
|
|
|
@@ -1681,7 +1704,7 @@ async function soleApprover() {
|
|
|
1681
1704
|
}
|
|
1682
1705
|
|
|
1683
1706
|
// With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
|
|
1684
|
-
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1707
|
+
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1685
1708
|
const reviewId = reviewIdOf(id);
|
|
1686
1709
|
const operator = requiredText(sentBy, 'sentBy');
|
|
1687
1710
|
if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
|
|
@@ -1724,7 +1747,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note =
|
|
|
1724
1747
|
reviewId,
|
|
1725
1748
|
[review.status],
|
|
1726
1749
|
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
1727
|
-
|
|
1750
|
+
// A caller that read the case earlier passes how many handoffs it saw, so one made since is not repeated.
|
|
1751
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt, ...(handoffs != null && { doctorHandoffs: { $size: handoffs } }) },
|
|
1728
1752
|
);
|
|
1729
1753
|
let delivery = {};
|
|
1730
1754
|
let updated;
|