@peopl-health/nexus 5.58.0-dev.10495 → 5.58.0-dev.10496
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/helpers/doctorReviewMessageHelper.js +147 -0
- package/lib/clinical/protocols/treatmentFormulary.js +1 -0
- package/lib/clinical/services/escalationDraftService.js +35 -5
- package/lib/models/escalationReviewModel.js +8 -0
- package/lib/services/escalationReviewService.js +66 -32
- package/package.json +1 -1
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
|
+
const { inlineOf } = require('../../utils/coercionUtils');
|
|
3
|
+
const { mexicoStamp } = require('../../utils/dateUtils');
|
|
4
|
+
|
|
5
|
+
const URGENCY_LABELS = {
|
|
6
|
+
stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const PROPOSAL_HEADING = 'Propuesta de tratamiento (sugerencia para su aprobación, no es una indicación):';
|
|
10
|
+
const REQUESTED_ACTION = 'Acción solicitada: ¿aprueba la propuesta, la modifica o prefiere una valoración presencial?';
|
|
11
|
+
const ASSESSMENT_ACTION = 'Acción solicitada: valoración médica prioritaria. ¿La valora en persona, la envía a urgencias o indica otra conducta?';
|
|
12
|
+
const DOCTOR_TITLE = /^(dr|dra)\.?\s/i;
|
|
13
|
+
|
|
14
|
+
const clean = (value) => inlineOf(value);
|
|
15
|
+
|
|
16
|
+
const withTitle = (name) => (DOCTOR_TITLE.test(name) ? name : `Dr./Dra. ${name}`);
|
|
17
|
+
|
|
18
|
+
function doctorIdentity(patient) {
|
|
19
|
+
const patientName = clean(patient?.name);
|
|
20
|
+
const treatingDoctor = clean(patient?.doctor) || clean(patient?.doctor_auna);
|
|
21
|
+
const missing = [];
|
|
22
|
+
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
23
|
+
if (!treatingDoctor) missing.push('médico tratante');
|
|
24
|
+
return { patientName, treatingDoctor, missing };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function latestAlarm(review) {
|
|
28
|
+
const alarms = Array.isArray(review?.alarms) ? review.alarms : [];
|
|
29
|
+
return alarms[alarms.length - 1] ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function presentRedFlags(sections) {
|
|
33
|
+
return (Array.isArray(sections?.redFlags) ? sections.redFlags : [])
|
|
34
|
+
.filter((flag) => flag?.present === true)
|
|
35
|
+
.map((flag) => clean(flag.flag))
|
|
36
|
+
.filter(Boolean);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function withholdReason(sections) {
|
|
40
|
+
const present = presentRedFlags(sections);
|
|
41
|
+
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(clean).filter(Boolean);
|
|
42
|
+
const reasons = [];
|
|
43
|
+
if (present.length) reasons.push(`bandera roja presente (${present.join(', ')})`);
|
|
44
|
+
if (modifiers.length) reasons.push(`condición que cambia el algoritmo (${modifiers.join(', ')})`);
|
|
45
|
+
return reasons.join('; ') || null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function symptomLines(alarm, sections) {
|
|
49
|
+
const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
|
|
50
|
+
const said = [
|
|
51
|
+
clean(alarm?.symptom) || clean(sections?.symptom),
|
|
52
|
+
grade,
|
|
53
|
+
clean(alarm?.suspectedCondition),
|
|
54
|
+
URGENCY_LABELS[alarm?.urgencyLevel] ?? clean(alarm?.urgencyLevel),
|
|
55
|
+
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
56
|
+
].filter(Boolean);
|
|
57
|
+
const flags = Array.isArray(sections?.redFlags) ? sections.redFlags : [];
|
|
58
|
+
if (!flags.length) return [`Síntoma: ${said.join(' · ')}`, 'Banderas rojas: no documentadas.'];
|
|
59
|
+
const present = presentRedFlags(sections);
|
|
60
|
+
const absent = flags.filter((flag) => flag?.present !== true).map((flag) => clean(flag?.flag)).filter(Boolean);
|
|
61
|
+
return [
|
|
62
|
+
`Síntoma: ${said.join(' · ')}`,
|
|
63
|
+
`Banderas rojas presentes: ${present.length ? present.join(', ') : 'ninguna'}.`,
|
|
64
|
+
`Banderas rojas ausentes: ${absent.length ? absent.join(', ') : 'ninguna revisada'}.`,
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function vitalsLine(vitals) {
|
|
69
|
+
const parts = [];
|
|
70
|
+
if (vitals?.temperatureC != null) parts.push(`T ${vitals.temperatureC} °C`);
|
|
71
|
+
if (vitals?.heartRate != null) parts.push(`FC ${vitals.heartRate} lpm`);
|
|
72
|
+
if (vitals?.systolic != null || vitals?.diastolic != null) parts.push(`PA ${vitals.systolic ?? '?'}/${vitals.diastolic ?? '?'} mmHg`);
|
|
73
|
+
if (vitals?.spo2 != null) parts.push(`SpO2 ${vitals.spo2}%`);
|
|
74
|
+
if (vitals?.respiratoryRate != null) parts.push(`FR ${vitals.respiratoryRate} rpm`);
|
|
75
|
+
return parts.length ? `Signos vitales: ${parts.join(' · ')}.` : 'Signos vitales: no reportados.';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function proposalItemLine(symptom, item) {
|
|
79
|
+
const entry = formularyFor(symptom);
|
|
80
|
+
const drug = entry ? findDrug(entry, item) : null;
|
|
81
|
+
if (!drug) return null;
|
|
82
|
+
const name = [drug.drug, drug.brand ? `(${drug.brand})` : null, drug.strength].filter(Boolean).join(' ');
|
|
83
|
+
const parts = [`- ${name}`];
|
|
84
|
+
if (drug.instructions) parts.push(drug.instructions);
|
|
85
|
+
parts.push(`posición en la tabla: ${drug.tableLabel}`);
|
|
86
|
+
const why = clean(item?.justification?.text);
|
|
87
|
+
if (why) parts.push(`motivo: ${why}`);
|
|
88
|
+
return parts.join(' — ');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function proposalLines({ proposal, withheldReason }) {
|
|
92
|
+
if (!proposal?.items?.length) {
|
|
93
|
+
const reason = clean(withheldReason) || 'sin propuesta farmacológica';
|
|
94
|
+
return [PROPOSAL_HEADING, `No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
|
|
95
|
+
}
|
|
96
|
+
const lines = proposal.items.map((item) => proposalItemLine(proposal.symptom, item)).filter(Boolean);
|
|
97
|
+
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(clean).filter(Boolean);
|
|
98
|
+
if (declared.length) lines.push(`Condiciones que se declararon para esta propuesta (verificar): ${declared.join(', ')}.`);
|
|
99
|
+
return [PROPOSAL_HEADING, ...lines];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
|
|
103
|
+
const context = sections?.oncologyContext;
|
|
104
|
+
const value = (text) => clean(text) || 'no disponible';
|
|
105
|
+
return [
|
|
106
|
+
...symptomLines(alarm, sections),
|
|
107
|
+
'',
|
|
108
|
+
`Caracterización: ${clean(sections?.characterizationSummary) || 'no disponible'}`,
|
|
109
|
+
vitalsLine(sections?.vitals),
|
|
110
|
+
`Datos objetivos: ${clean(sections?.objectiveData) || 'no disponibles'}`,
|
|
111
|
+
'',
|
|
112
|
+
`Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
|
|
113
|
+
`Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
|
|
114
|
+
'',
|
|
115
|
+
...proposalLines({ proposal, withheldReason }),
|
|
116
|
+
'',
|
|
117
|
+
proposal?.items?.length ? REQUESTED_ACTION : ASSESSMENT_ACTION,
|
|
118
|
+
].join('\n');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderDoctorMessage({ identity, review, doctorText, link }) {
|
|
122
|
+
const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
|
|
123
|
+
return [
|
|
124
|
+
`Paciente: ${identity.patientName} · ${phone}`,
|
|
125
|
+
`Médico tratante: ${withTitle(identity.treatingDoctor)}`,
|
|
126
|
+
String(doctorText ?? '').trim(),
|
|
127
|
+
'',
|
|
128
|
+
link,
|
|
129
|
+
].join('\n');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function templateSummary(review) {
|
|
133
|
+
const alarm = latestAlarm(review);
|
|
134
|
+
if (!alarm) return 'sin alarma registrada';
|
|
135
|
+
return [clean(alarm.symptom), URGENCY_LABELS[alarm.urgencyLevel] ?? clean(alarm.urgencyLevel)].filter(Boolean).join(' · ');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = {
|
|
139
|
+
REQUESTED_ACTION,
|
|
140
|
+
ASSESSMENT_ACTION,
|
|
141
|
+
doctorIdentity,
|
|
142
|
+
withholdReason,
|
|
143
|
+
latestAlarm,
|
|
144
|
+
composeDoctorBody,
|
|
145
|
+
renderDoctorMessage,
|
|
146
|
+
templateSummary,
|
|
147
|
+
};
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
const { getEscalationDraft } = require('../config/subAgentsConfig');
|
|
2
2
|
|
|
3
|
-
const { FORMULARY_VERSION, TREATMENT_FORMULARY } = require('../protocols/treatmentFormulary');
|
|
3
|
+
const { FORMULARY_VERSION, TREATMENT_FORMULARY, validateProposal } = require('../protocols/treatmentFormulary');
|
|
4
4
|
|
|
5
5
|
const { createLLMProvider } = require('../providers/createLLMProvider');
|
|
6
6
|
|
|
7
|
+
const { composeDoctorBody, withholdReason } = require('../helpers/doctorReviewMessageHelper');
|
|
7
8
|
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
8
9
|
|
|
9
10
|
const { getEscalationContext } = require('../../services/escalationContextService');
|
|
@@ -18,7 +19,21 @@ const CALL_LOG_LIMIT = 10;
|
|
|
18
19
|
|
|
19
20
|
const trimmed = (value) => String(value ?? '').trim();
|
|
20
21
|
|
|
21
|
-
function
|
|
22
|
+
function settleProposal(parsed) {
|
|
23
|
+
const withheld = withholdReason(parsed);
|
|
24
|
+
const raw = parsed?.treatmentProposal;
|
|
25
|
+
const items = Array.isArray(raw?.items) ? raw.items : [];
|
|
26
|
+
if (withheld) return { proposal: null, withheldReason: withheld, strippedItems: items.length };
|
|
27
|
+
if (!items.length) return { proposal: null, withheldReason: trimmed(parsed?.proposalWithheldReason) || null, strippedItems: 0 };
|
|
28
|
+
|
|
29
|
+
const conditions = Array.isArray(raw.conditions) ? raw.conditions : [];
|
|
30
|
+
const ruledOut = Array.isArray(raw.ruledOut) ? raw.ruledOut : [];
|
|
31
|
+
const proposal = { symptom: raw.symptom, items, conditions, ruledOut };
|
|
32
|
+
const { valid, issues } = validateProposal(proposal, { conditions, ruledOut });
|
|
33
|
+
return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
|
|
22
37
|
const conversation = Array.isArray(context?.conversation)
|
|
23
38
|
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
24
39
|
: context?.conversation ?? null;
|
|
@@ -30,6 +45,7 @@ function buildDraftInput({ context, callLogs, protocol }) {
|
|
|
30
45
|
return {
|
|
31
46
|
protocolVersion: FORMULARY_VERSION,
|
|
32
47
|
protocol,
|
|
48
|
+
alarms,
|
|
33
49
|
patient: {
|
|
34
50
|
clinicalContext: context?.agentContext ?? null,
|
|
35
51
|
conversation,
|
|
@@ -55,7 +71,7 @@ function draftProvider() {
|
|
|
55
71
|
}
|
|
56
72
|
}
|
|
57
73
|
|
|
58
|
-
async function generateEscalationDraft({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
|
|
74
|
+
async function generateEscalationDraft({ code, callLogs = [], alarms = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
|
|
59
75
|
const { presetId } = await getEscalationDraft();
|
|
60
76
|
const llm = provider ?? draftProvider();
|
|
61
77
|
|
|
@@ -64,7 +80,7 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
64
80
|
}
|
|
65
81
|
|
|
66
82
|
const context = await getEscalationContext({ code, now });
|
|
67
|
-
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY });
|
|
83
|
+
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
|
|
68
84
|
|
|
69
85
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
70
86
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -91,8 +107,19 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
91
107
|
}
|
|
92
108
|
|
|
93
109
|
const parsed = safeParse(readStructuredText(result), null);
|
|
94
|
-
const doctorText = trimmed(parsed?.doctorText);
|
|
95
110
|
const patientMessage = trimmed(parsed?.patientMessage);
|
|
111
|
+
if (!trimmed(parsed?.characterizationSummary)) {
|
|
112
|
+
logger.warn('[escalationDraft] generation did not return the sectioned doctor draft', { reviewId });
|
|
113
|
+
return { completed: false, attempted: true, reason: 'the model did not return the sectioned doctor draft (characterizationSummary missing)' };
|
|
114
|
+
}
|
|
115
|
+
const settled = settleProposal(parsed);
|
|
116
|
+
|
|
117
|
+
if (settled.invalid) {
|
|
118
|
+
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues: settled.invalid });
|
|
119
|
+
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${settled.invalid.join('; ')}` };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const doctorText = composeDoctorBody({ alarm: alarms[alarms.length - 1] ?? null, sections: parsed, proposal: settled.proposal, withheldReason: settled.withheldReason });
|
|
96
123
|
|
|
97
124
|
if (!doctorText || !patientMessage) {
|
|
98
125
|
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
@@ -104,6 +131,9 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
104
131
|
attempted: true,
|
|
105
132
|
doctorText,
|
|
106
133
|
patientMessage,
|
|
134
|
+
proposal: settled.proposal,
|
|
135
|
+
proposalWithheldReason: settled.withheldReason,
|
|
136
|
+
...(settled.strippedItems ? { proposalStripped: settled.strippedItems } : {}),
|
|
107
137
|
protocolVersion: FORMULARY_VERSION,
|
|
108
138
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
109
139
|
};
|
|
@@ -56,6 +56,7 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
56
56
|
physicianEmail: { type: String, default: null },
|
|
57
57
|
transport: { type: String, enum: [null, 'text', 'template'], default: null },
|
|
58
58
|
messageId: { type: String, default: null },
|
|
59
|
+
message: { type: String, default: null },
|
|
59
60
|
sentBy: { type: String, required: true },
|
|
60
61
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
61
62
|
|
|
@@ -91,6 +92,12 @@ const interruptionResolutionSchema = new mongoose.Schema({
|
|
|
91
92
|
notes: { type: String, required: true },
|
|
92
93
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
93
94
|
|
|
95
|
+
const identityBlockSchema = new mongoose.Schema({
|
|
96
|
+
missing: { type: [String], default: [] },
|
|
97
|
+
blockedAt: { type: Date, required: true },
|
|
98
|
+
blockedBy: { type: String, required: true },
|
|
99
|
+
}, { _id: false });
|
|
100
|
+
|
|
94
101
|
const escalationReviewSchema = new mongoose.Schema({
|
|
95
102
|
patientCode: { type: String, required: true },
|
|
96
103
|
patientCaseRecordId: { type: String, default: null },
|
|
@@ -126,6 +133,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
126
133
|
patientDelivery: { type: patientDeliverySchema, default: null },
|
|
127
134
|
pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
|
|
128
135
|
interruptionResolution: { type: interruptionResolutionSchema, default: null },
|
|
136
|
+
identityBlock: { type: identityBlockSchema, default: null },
|
|
129
137
|
closedBy: { type: String, default: null },
|
|
130
138
|
closedAt: { type: Date, default: null },
|
|
131
139
|
cancellationReason: { type: String, default: null },
|
|
@@ -5,7 +5,6 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
|
|
|
5
5
|
const { inlineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
|
-
const { mexicoStamp } = require('../utils/dateUtils');
|
|
9
8
|
const { isoDay } = require('../utils/dateUtils');
|
|
10
9
|
const {
|
|
11
10
|
CALL_OUTCOMES,
|
|
@@ -21,6 +20,8 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
|
21
20
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
22
21
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
23
22
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
23
|
+
const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
24
|
+
const { doctorIdentity, renderDoctorMessage, templateSummary } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
24
25
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
25
26
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
26
27
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
@@ -296,42 +297,53 @@ async function syncCase(review, operator, requestId) {
|
|
|
296
297
|
}
|
|
297
298
|
}
|
|
298
299
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function doctorHeader(review, patient) {
|
|
304
|
-
const name = inlineOf(patient?.name);
|
|
305
|
-
const phone = review.patientCode.replace(/^whatsapp:/, '');
|
|
306
|
-
const treating = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
|
|
300
|
+
function doctorLink(review) {
|
|
301
|
+
return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
302
|
+
}
|
|
307
303
|
|
|
308
|
-
|
|
309
|
-
|
|
304
|
+
async function readDoctorIdentity(review) {
|
|
305
|
+
let patient;
|
|
306
|
+
try {
|
|
307
|
+
patient = await getPatientInformation(review.patientCode);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
logger.error('[EscalationReview] The patient record could not be read for the doctor message', {
|
|
310
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
311
|
+
});
|
|
312
|
+
throw httpError(503, 'The patient record could not be read; the doctor message needs the patient name and the treating doctor');
|
|
313
|
+
}
|
|
314
|
+
return doctorIdentity(patient);
|
|
315
|
+
}
|
|
310
316
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
317
|
+
async function blockForMissingIdentity({ review, missing, operator }) {
|
|
318
|
+
const blocked = `El mensaje al médico no se envió: falta ${missing.join(' y ')} en el expediente`;
|
|
319
|
+
await getEscalationReview().updateOne(
|
|
320
|
+
{ _id: review._id },
|
|
321
|
+
{ $set: { identityBlock: { missing, blockedAt: new Date(), blockedBy: operator } } },
|
|
322
|
+
);
|
|
323
|
+
const { written, duplicate } = await writeUnresolvedRequest({
|
|
324
|
+
code: review.patientCode,
|
|
325
|
+
trace: null,
|
|
326
|
+
question: blocked,
|
|
327
|
+
details: `Revisión de escalación ${review._id}: completa ${missing.join(' y ')} en estado_general y vuelve a enviar al médico.`,
|
|
328
|
+
category: 'contact_team_member',
|
|
329
|
+
urgency: 'soon',
|
|
330
|
+
});
|
|
331
|
+
if (!written && !duplicate) {
|
|
332
|
+
logger.error('[EscalationReview] A doctor message was blocked for missing identity and the team ticket was not written', {
|
|
333
|
+
escalationReviewId: String(review._id), missing,
|
|
334
|
+
});
|
|
320
335
|
}
|
|
321
|
-
|
|
336
|
+
throw httpError(422, blocked);
|
|
322
337
|
}
|
|
323
338
|
|
|
324
|
-
async function sendDoctorAlert({
|
|
339
|
+
async function sendDoctorAlert({ message, approver, operator }) {
|
|
325
340
|
const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
|
|
326
341
|
if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
|
|
327
|
-
const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
328
342
|
const inWindow = await isWithin24HourWindow(doctorCode);
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
|
|
334
|
-
const result = await sendMessage(message);
|
|
343
|
+
const outgoing = inWindow
|
|
344
|
+
? { code: doctorCode, body: message.body, triggeredBy: operator }
|
|
345
|
+
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
|
|
346
|
+
const result = await sendMessage(outgoing);
|
|
335
347
|
if (!result?.success && !result?.completed) {
|
|
336
348
|
throw httpError(502, 'The WhatsApp message to the physician could not be sent');
|
|
337
349
|
}
|
|
@@ -636,6 +648,7 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
|
|
|
636
648
|
const draft = await generateEscalationDraft({
|
|
637
649
|
code: review.patientCode,
|
|
638
650
|
callLogs: review.callLogs ?? [],
|
|
651
|
+
alarms: review.alarms ?? [],
|
|
639
652
|
reviewId: String(review._id),
|
|
640
653
|
});
|
|
641
654
|
// A generation run sends the patient's context to a model. That is what the audit exists to
|
|
@@ -866,13 +879,34 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
866
879
|
if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
|
|
867
880
|
}
|
|
868
881
|
|
|
882
|
+
const draftedAt = draft.createdAt ? new Date(draft.createdAt).getTime() : null;
|
|
883
|
+
if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
|
|
884
|
+
throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
885
|
+
}
|
|
886
|
+
const identity = await readDoctorIdentity(review);
|
|
887
|
+
if (identity.missing.length) await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
888
|
+
const link = doctorLink(review);
|
|
889
|
+
const message = {
|
|
890
|
+
body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
|
|
891
|
+
template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
|
|
892
|
+
};
|
|
893
|
+
|
|
869
894
|
const claim = newOperationClaim();
|
|
870
|
-
await updateReview(
|
|
895
|
+
await updateReview(
|
|
896
|
+
reviewId,
|
|
897
|
+
[review.status],
|
|
898
|
+
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
899
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
|
|
900
|
+
);
|
|
871
901
|
let delivery = {};
|
|
872
902
|
let updated;
|
|
873
903
|
try {
|
|
874
|
-
if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({
|
|
875
|
-
const
|
|
904
|
+
if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
|
|
905
|
+
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
|
|
906
|
+
const handoff = {
|
|
907
|
+
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, sentBy: operator } },
|
|
908
|
+
$unset: { identityBlock: '' },
|
|
909
|
+
};
|
|
876
910
|
const recordUpdate = withCaseMirror(review, handoff, { status: 'en revision_medica' });
|
|
877
911
|
updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
|
|
878
912
|
} catch (error) {
|