@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20074
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 +3 -1
- package/lib/clinical/config/planTextsConfig.js +41 -0
- package/lib/clinical/flags/escalationFlags.js +15 -0
- package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +72 -2
- package/lib/clinical/helpers/legacyContextHelper.js +6 -2
- package/lib/clinical/helpers/planTextHelper.js +9 -2
- package/lib/clinical/protocols/treatmentFormulary.js +3 -3
- package/lib/clinical/services/bridgeService.js +2 -2
- package/lib/clinical/services/checkInDueService.js +3 -2
- package/lib/clinical/services/clinicalAirtableService.js +3 -2
- package/lib/clinical/services/clinicalExtractionService.js +9 -2
- package/lib/clinical/services/contingencyDispatchService.js +8 -4
- package/lib/clinical/services/doctorPlanService.js +27 -11
- package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
- package/lib/config/awsConfig.js +1 -1
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/escalationReviewController.js +16 -3
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +16 -18
- package/lib/fhir/constants/escalationCaseStatus.js +1 -1
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/helpers/templateFlowControllerHelper.js +9 -48
- package/lib/index.d.ts +3 -3
- package/lib/models/escalationReviewModel.js +32 -2
- package/lib/services/assistantMessageService.js +11 -6
- package/lib/services/caseFollowUpService.js +226 -0
- package/lib/services/caseFollowUpSweepService.js +89 -0
- package/lib/services/characterizationOutcomeService.js +27 -15
- package/lib/services/escalationCaseStateService.js +68 -0
- package/lib/services/escalationReviewService.js +123 -37
- package/lib/services/flowDataExchangeService.js +6 -35
- package/lib/services/reviewAlertSweepService.js +19 -1
- package/lib/services/reviewBoardService.js +24 -6
- package/lib/services/reviewDeadlineService.js +1 -1
- package/lib/services/untakenAlertService.js +9 -7
- package/lib/services/watchExpiryService.js +162 -0
- package/lib/utils/coercionUtils.js +5 -1
- package/lib/utils/textMatchUtils.js +52 -18
- package/package.json +1 -1
|
@@ -163,6 +163,7 @@ class AssistantProcessor {
|
|
|
163
163
|
traceId: ctx?.trace?._id ? String(ctx.trace._id) : null,
|
|
164
164
|
shouldContinue: runOptions.shouldContinue,
|
|
165
165
|
sendMessage: this.sendMessage,
|
|
166
|
+
...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
|
|
166
167
|
});
|
|
167
168
|
return bridgeDecision;
|
|
168
169
|
};
|
|
@@ -294,6 +295,7 @@ class AssistantProcessor {
|
|
|
294
295
|
outreachCarrier: runOptions.outreachCarrier || null,
|
|
295
296
|
outreachStartedAt: runOptions.outreachStartedAt || null,
|
|
296
297
|
triggeredBy: runOptions.triggeredBy || null,
|
|
298
|
+
...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
|
|
297
299
|
run,
|
|
298
300
|
predictionTimeMs,
|
|
299
301
|
retries: runResult?.retries || 0,
|
|
@@ -395,7 +397,7 @@ class AssistantProcessor {
|
|
|
395
397
|
const outreachCarrier = result.outreachCarrier
|
|
396
398
|
? { ...result.outreachCarrier, utilityBasis: result.signals?.outreachDecision?.utilityBasis || result.outreachCarrier.utilityBasis || null }
|
|
397
399
|
: null;
|
|
398
|
-
sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt });
|
|
400
|
+
sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt, ...(result.contactCode && { contactCode: result.contactCode, contactRole: result.contactRole }) });
|
|
399
401
|
result.delivery = sent || null;
|
|
400
402
|
} catch (error) {
|
|
401
403
|
if (directive) {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const { PLAN_TEXTS } = require('../helpers/doctorPlanHelper');
|
|
2
|
+
const { Config_ID } = require('../../config/airtableConfig');
|
|
3
|
+
|
|
4
|
+
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
|
+
|
|
6
|
+
const { logger } = require('../../utils/logger');
|
|
7
|
+
const { MapCache } = require('../../utils/MapCache');
|
|
8
|
+
|
|
9
|
+
const PLAN_TEXTS_TABLE = 'plan_instructions';
|
|
10
|
+
const CACHE_TTL = 5 * 60 * 1000;
|
|
11
|
+
const CACHE_KEY = 'planTexts';
|
|
12
|
+
const NEEDS_HOURS = ['FOLLOW_UP_CHECK_IN', 'FOLLOW_UP_VIGILANCIA'];
|
|
13
|
+
|
|
14
|
+
const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
|
|
15
|
+
|
|
16
|
+
// A missing, empty or broken row keeps the code's text, so an edit in Airtable never stops a plan from going out.
|
|
17
|
+
async function getPlanTexts() {
|
|
18
|
+
const cached = cache.get(CACHE_KEY);
|
|
19
|
+
if (cached) return cached;
|
|
20
|
+
|
|
21
|
+
let records = null;
|
|
22
|
+
try {
|
|
23
|
+
records = await getRecordByFilter(Config_ID, PLAN_TEXTS_TABLE, 'TRUE()');
|
|
24
|
+
} catch (error) {
|
|
25
|
+
logger.error('[planTextsConfig] plan_instructions could not be read; using the default texts', { error: error.message });
|
|
26
|
+
}
|
|
27
|
+
const byKey = Object.fromEntries((records || []).map((record) => [record.config, typeof record.value === 'string' ? record.value.trim() : '']));
|
|
28
|
+
const texts = Object.fromEntries(Object.entries(PLAN_TEXTS).map(([key, fallback]) => {
|
|
29
|
+
const value = byKey[key];
|
|
30
|
+
if (!value) return [key, fallback];
|
|
31
|
+
if (NEEDS_HOURS.includes(key) && !value.includes('{horas}')) {
|
|
32
|
+
logger.error('[planTextsConfig] follow-up text lacks {horas}; using the default', { key });
|
|
33
|
+
return [key, fallback];
|
|
34
|
+
}
|
|
35
|
+
return [key, value];
|
|
36
|
+
}));
|
|
37
|
+
if (records) cache.set(CACHE_KEY, texts);
|
|
38
|
+
return texts;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { getPlanTexts, _clearPlanTextsCache: () => cache.clear() };
|
|
@@ -32,12 +32,27 @@ function escalationUntakenAlertsLive() {
|
|
|
32
32
|
return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
function escalationWatchExpiryLive() {
|
|
36
|
+
return flagNotOff('ESCALATION_WATCH_EXPIRY_LIVE');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function escalationWatchTeamNoticeLive() {
|
|
40
|
+
return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function escalationCaseFollowUpLive() {
|
|
44
|
+
return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
|
|
45
|
+
}
|
|
46
|
+
|
|
35
47
|
module.exports = {
|
|
48
|
+
escalationCaseFollowUpLive,
|
|
36
49
|
escalationApproverAlertLive,
|
|
37
50
|
escalationAssessmentLive,
|
|
38
51
|
escalationAutoHandoffLive,
|
|
39
52
|
escalationPatientTimerLive,
|
|
40
53
|
escalationUntakenAlertsLive,
|
|
41
54
|
escalationUpdateModeLive,
|
|
55
|
+
escalationWatchExpiryLive,
|
|
56
|
+
escalationWatchTeamNoticeLive,
|
|
42
57
|
feverPatientTimerLive,
|
|
43
58
|
};
|
|
@@ -2,47 +2,55 @@ const { oneLineOf } = require('../../utils/coercionUtils');
|
|
|
2
2
|
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
3
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
4
4
|
|
|
5
|
-
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
|
|
5
|
+
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ auto: 24, check_in: 24, vigilancia: 48 });
|
|
6
6
|
|
|
7
7
|
const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
|
|
8
8
|
|
|
9
|
+
const DURATION_TEXTS = Object.freeze({ as_needed: 'solo si lo necesita', continuous: 'de forma continua, hasta nuevo aviso', unspecified: null });
|
|
9
10
|
const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
|
|
10
|
-
const
|
|
11
|
+
const SAID_DURATION = Object.freeze({ as_needed: /raz[oó]n necesaria|si lo necesita/i, continuous: /forma continua/i });
|
|
12
|
+
const durationTextOf = (item) => {
|
|
13
|
+
if (!item.duration || item.duration === 'days') return `por ${daysText(item.days)}`;
|
|
14
|
+
return SAID_DURATION[item.duration]?.test(`${item.dose ?? ''} ${item.frequency ?? ''}`) ? null : DURATION_TEXTS[item.duration];
|
|
15
|
+
};
|
|
16
|
+
const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${[item.dose, item.frequency, durationTextOf(item)].filter(Boolean).join(' ')}.`;
|
|
11
17
|
const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
|
|
12
|
-
|
|
18
|
+
// The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours.
|
|
19
|
+
const PLAN_TEXTS = Object.freeze({
|
|
20
|
+
INTRO: 'Transmítele al paciente lo que indicó el médico, con tus palabras: no agregues medicamentos ni estudios que el médico no indicó, ni avisos de urgencia que no dio.',
|
|
21
|
+
MEDS_HEADER: 'Medicamentos (no cambies dosis, frecuencia ni días; escríbelos con números, como vienen aquí, sin repetirlos con letra):',
|
|
22
|
+
// Written without numbers so the reply check, which flags any amount or hour the plan lacks, stays quiet.
|
|
23
|
+
COMPLEMENTARY: 'Indicaciones complementarias: además de lo anterior, por cada síntoma que contó dale de 2 a 4 cuidados en casa concretos, accionables y de alto valor, diciendo qué hacer y cómo hacerlo, aunque el médico no los haya escrito. Escríbelos con palabras, sin números, cantidades ni frecuencias y sin avisos de urgencia, para que no se confundan con lo que indicó el médico. Solo medidas estándar de enfermería oncológica: sin medicamentos, suplementos, remedios caseros ni dietas restrictivas.',
|
|
24
|
+
FOLLOW_UP_CHECK_IN: 'Seguimiento: le escribiremos en unas {horas} horas para ver cómo va.',
|
|
25
|
+
FOLLOW_UP_VIGILANCIA: 'Seguimiento: queda en vigilancia las próximas {horas} horas; le escribiremos para ver cómo va.',
|
|
26
|
+
});
|
|
13
27
|
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
vigilancia: (hours) => `Seguimiento: queda en vigilancia las próximas ${hours} horas; le escribiremos para ver cómo va.`,
|
|
17
|
-
};
|
|
18
|
-
const followUpLineOf = (plan) => FOLLOW_UP_LINES[plan.followUp?.kind]?.(plan.followUp.hours) ?? null;
|
|
28
|
+
const FOLLOW_UP_KEYS = { auto: 'FOLLOW_UP_CHECK_IN', check_in: 'FOLLOW_UP_CHECK_IN', vigilancia: 'FOLLOW_UP_VIGILANCIA' };
|
|
29
|
+
const followUpLineOf = (plan, texts = PLAN_TEXTS) => texts[FOLLOW_UP_KEYS[plan.followUp?.kind]]?.replaceAll('{horas}', plan.followUp.hours) ?? null;
|
|
19
30
|
|
|
20
|
-
function planInstructions(plan) {
|
|
21
|
-
const lines = [
|
|
31
|
+
function planInstructions(plan, texts = PLAN_TEXTS) {
|
|
32
|
+
const lines = [texts.INTRO];
|
|
22
33
|
if (plan.items.length) {
|
|
23
|
-
lines.push(
|
|
34
|
+
lines.push(texts.MEDS_HEADER, ...plan.items.map((item) => `- ${itemLine(item)}`));
|
|
24
35
|
}
|
|
25
36
|
if (plan.studies.length) {
|
|
26
37
|
lines.push('Estudios:', ...plan.studies.map((study) => `- ${studyLine(study)}`));
|
|
27
38
|
}
|
|
28
39
|
if (plan.homeCare.length) lines.push('Cuidados en casa:', ...plan.homeCare.map((entry) => `- ${entry}`));
|
|
29
40
|
if (plan.note) lines.push(`Nota del médico: «${plan.note}».`);
|
|
30
|
-
|
|
41
|
+
lines.push(texts.COMPLEMENTARY);
|
|
42
|
+
const followUp = followUpLineOf(plan, texts);
|
|
31
43
|
if (followUp) lines.push(followUp);
|
|
32
|
-
if (needsPrescriber(plan)) lines.push(PRESCRIPTION_LINE);
|
|
33
44
|
return lines.join('\n');
|
|
34
45
|
}
|
|
35
46
|
|
|
36
|
-
// An edit can drop or reword the receta line; the PDF goes out anyway, so the assistant is still told.
|
|
37
|
-
function assistantInstructionsOf(plan) {
|
|
38
|
-
if (!needsPrescriber(plan) || normalizeForAnchor(plan.instructions).includes(normalizeForAnchor(PRESCRIPTION_LINE))) return plan.instructions;
|
|
39
|
-
return `${plan.instructions}\n${PRESCRIPTION_LINE}`;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
47
|
function planSummary(plan) {
|
|
43
48
|
const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
|
|
44
49
|
if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
|
|
45
50
|
if (plan.note) lines.push(`Nota: ${plan.note}`);
|
|
51
|
+
if (plan.followUp?.kind === 'auto') lines.push(`Seguimiento: automático, unas ${plan.followUp.hours} h.`);
|
|
52
|
+
if (plan.followUp?.kind === 'check_in') lines.push(`Seguimiento: check-in en ${plan.followUp.hours} h.`);
|
|
53
|
+
if (plan.followUp?.kind === 'vigilancia') lines.push(`Seguimiento: vigilancia ${plan.followUp.hours} h.`);
|
|
46
54
|
return lines.join('\n');
|
|
47
55
|
}
|
|
48
56
|
|
|
@@ -56,8 +64,9 @@ function prescriptionText(plan) {
|
|
|
56
64
|
function dosingOf(item, formularyKey) {
|
|
57
65
|
const entry = formularyFor(formularyKey);
|
|
58
66
|
const dosing = entry && findDrug(entry, item)?.dosing;
|
|
59
|
-
if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, days: null, note: null };
|
|
60
|
-
|
|
67
|
+
if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, duration: 'days', days: null, note: null };
|
|
68
|
+
const duration = dosing.duration ?? 'days';
|
|
69
|
+
return { dose: dosing.dose ?? null, frequency: dosing.frequency ?? null, duration, days: duration === 'days' ? dosing.days ?? null : null, note: dosing.note ?? null };
|
|
61
70
|
}
|
|
62
71
|
|
|
63
72
|
// What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
|
|
@@ -78,7 +87,7 @@ function proposedPlanOf(draft) {
|
|
|
78
87
|
|
|
79
88
|
// The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
|
|
80
89
|
const plannedTextOf = (plan) => [
|
|
81
|
-
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item
|
|
90
|
+
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, durationTextOf(item)]),
|
|
82
91
|
...plan.studies.flatMap((study) => [study.name, study.instructions]),
|
|
83
92
|
...plan.homeCare,
|
|
84
93
|
plan.note,
|
|
@@ -87,7 +96,7 @@ const plannedTextOf = (plan) => [
|
|
|
87
96
|
|
|
88
97
|
module.exports = {
|
|
89
98
|
DEFAULT_FOLLOW_UP_HOURS,
|
|
90
|
-
|
|
99
|
+
PLAN_TEXTS,
|
|
91
100
|
needsPrescriber,
|
|
92
101
|
planInstructions,
|
|
93
102
|
planSummary,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
|
-
const { inlineOf, oneLineOf } = require('../../utils/coercionUtils');
|
|
2
|
+
const { cutOnWord, inlineOf, oneLineOf } = require('../../utils/coercionUtils');
|
|
3
3
|
|
|
4
4
|
const URGENCY_LABELS = {
|
|
5
5
|
stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
|
|
@@ -19,6 +19,7 @@ function latestAlarm(review) {
|
|
|
19
19
|
|
|
20
20
|
// The patient does not know it or cannot check it: still pending, but asking again will not get it.
|
|
21
21
|
const UNOBTAINABLE = 'no_obtenible';
|
|
22
|
+
const askedOf = (flag, unobtainable) => (unobtainable.includes(flag) ? `${flag} (no lo puede dar)` : flag);
|
|
22
23
|
|
|
23
24
|
function flagsByStatus(sections) {
|
|
24
25
|
const flags = (Array.isArray(sections?.redFlags) ? sections.redFlags : []).filter((flag) => inlineOf(flag?.flag));
|
|
@@ -99,7 +100,7 @@ function symptomParagraph(entry, fallbackSymptom) {
|
|
|
99
100
|
present.length && `${present.length > 1 ? 'Banderas rojas presentes' : 'Bandera roja presente'}: ${sentence(present.join(', '))}`,
|
|
100
101
|
!present.length && !unassessed.length && absent.length && 'Sin banderas rojas.',
|
|
101
102
|
// A proposal names its own pending grave flags; without one they would go unsaid.
|
|
102
|
-
!proposedDrugs(entry).length && urgent.length && `Falta descartar: ${sentence(urgent.map((flag) => (
|
|
103
|
+
!proposedDrugs(entry).length && urgent.length && `Falta descartar: ${sentence(urgent.map((flag) => askedOf(flag, unobtainable)).join(', '))}`,
|
|
103
104
|
proposalLine(entry),
|
|
104
105
|
].filter(Boolean).join(' ');
|
|
105
106
|
}
|
|
@@ -167,6 +168,74 @@ function doctorAlertHeadline({ review, kind, note = null, level = null, symptom
|
|
|
167
168
|
|
|
168
169
|
const doctorAlertOpener = (kind, headline) => `${ALERT_OPENERS[kind]}: ${headline}`;
|
|
169
170
|
|
|
171
|
+
const BRIEF_MARKS = { stat: '🔴', ...LEVEL_MARKS };
|
|
172
|
+
const BRIEF_VERBS = { act_now: 'Valorar ahora', proposal: 'Aprobar o modificar tratamiento', indication: 'Entrar y aprobar indicación' };
|
|
173
|
+
const MAX_BRIEF_SYMPTOM = 40;
|
|
174
|
+
const MAX_BRIEF_KEY = 110;
|
|
175
|
+
|
|
176
|
+
const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
177
|
+
const titleCased = (name) => (name === name.toUpperCase() ? name.toLowerCase().replace(/(^|[\s'’-])(\p{L})/gu, (_, gap, letter) => gap + letter.toUpperCase()) : name);
|
|
178
|
+
|
|
179
|
+
const HOUR_FORMAT = { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' };
|
|
180
|
+
|
|
181
|
+
function deadlineLabel(deadline, now, timeZone) {
|
|
182
|
+
if (!deadline) return null;
|
|
183
|
+
const day = (date) => new Date(date).toLocaleDateString('en-CA', { timeZone });
|
|
184
|
+
const time = new Date(deadline).toLocaleTimeString('es-MX', { timeZone, ...HOUR_FORMAT });
|
|
185
|
+
if (new Date(deadline) <= new Date(now)) return day(deadline) === day(now) ? `venció ${time}` : `venció el ${new Date(deadline).toLocaleDateString('es-MX', { timeZone, day: '2-digit', month: '2-digit' })} ${time}`;
|
|
186
|
+
if (day(deadline) === day(now)) return `antes de ${time}`;
|
|
187
|
+
if (day(deadline) === day(new Date(new Date(now).getTime() + 86400000))) return `antes de mañana ${time}`;
|
|
188
|
+
return `antes del ${new Date(deadline).toLocaleDateString('es-MX', { timeZone, day: '2-digit', month: '2-digit' })} ${time}`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function briefSymptomOf(draft, symptom) {
|
|
192
|
+
const symptoms = Array.isArray(draft?.symptoms) ? draft.symptoms : [];
|
|
193
|
+
const wanted = oneLineOf(symptom).toLowerCase();
|
|
194
|
+
const match = symptoms.find((entry) => wanted && oneLineOf(entry.symptom).toLowerCase() === wanted);
|
|
195
|
+
// The alarm's text rarely equals the draft's label: guessing among several symptoms could name and clear the wrong one.
|
|
196
|
+
return match ?? (symptoms.length === 1 ? symptoms[0] : null);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const briefDrugs = (draft) => (draft?.symptoms ?? []).flatMap((entry) => entry.proposal?.items ?? [])
|
|
200
|
+
.map((item) => [item.drug, item.strength].map(oneLineOf).filter(Boolean).join(' ')).filter(Boolean);
|
|
201
|
+
|
|
202
|
+
const namedFlags = (list) => (Array.isArray(list) ? list.map(oneLineOf).filter(Boolean) : []);
|
|
203
|
+
|
|
204
|
+
function briefKeyLine(draft, entry) {
|
|
205
|
+
const grave = namedFlags(draft?.urgentPresentRedFlags);
|
|
206
|
+
const present = namedFlags(entry?.presentRedFlags).filter((flag) => !grave.includes(flag));
|
|
207
|
+
const unknown = (namedFlags(draft?.urgentUnassessedRedFlags).length ? namedFlags(draft.urgentUnassessedRedFlags) : namedFlags(entry?.unassessedRedFlags))
|
|
208
|
+
.map((flag) => askedOf(flag, namedFlags(draft?.unobtainableRedFlags)));
|
|
209
|
+
const absent = namedFlags(entry?.absentRedFlags);
|
|
210
|
+
const drugs = briefDrugs(draft);
|
|
211
|
+
const parts = [
|
|
212
|
+
grave.length && `⚠️ ${capitalized(grave.join(', '))}`,
|
|
213
|
+
present.length && `Presente: ${present.join(', ')}`,
|
|
214
|
+
unknown.length && `Sin dato aún: ${unknown.join(', ')}`,
|
|
215
|
+
!grave.length && !present.length && !unknown.length && (absent.length ? 'Sin banderas rojas' : 'Banderas rojas sin evaluar'),
|
|
216
|
+
drugs.length && `Propuesta: ${drugs.join('; ')}`,
|
|
217
|
+
].filter(Boolean);
|
|
218
|
+
return cutOnWord(parts.join(' · '), MAX_BRIEF_KEY);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// The four lines of the doctor's alert; each is a template variable, so none may be empty.
|
|
222
|
+
function doctorBrief({ kind, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
223
|
+
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
224
|
+
// A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
|
|
225
|
+
const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
|
|
226
|
+
const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
|
|
227
|
+
const mark = actNow ? '🔴' : BRIEF_MARKS[level];
|
|
228
|
+
const label = cutOnWord(entry?.symptom || alarmSymptom || 'Síntoma no especificado', MAX_BRIEF_SYMPTOM);
|
|
229
|
+
const graded = [1, 2, 3, 4, 5].includes(entry?.grade) && !/\bG[1-5]\b/i.test(label) ? `${label} G${entry.grade}` : label;
|
|
230
|
+
const patient = identity.age ? `${titleCased(oneLineOf(identity.patientName))}, ${identity.age}` : titleCased(oneLineOf(identity.patientName));
|
|
231
|
+
return [
|
|
232
|
+
[[mark, verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
|
|
233
|
+
`${patient} · ${graded} (${withTitle(titleCased(oneLineOf(identity.treatingDoctor)))})`,
|
|
234
|
+
briefKeyLine(draft, entry),
|
|
235
|
+
link,
|
|
236
|
+
];
|
|
237
|
+
}
|
|
238
|
+
|
|
170
239
|
module.exports = {
|
|
171
240
|
REQUESTED_ACTION,
|
|
172
241
|
ASSESSMENT_ACTION,
|
|
@@ -178,4 +247,5 @@ module.exports = {
|
|
|
178
247
|
templateSummary,
|
|
179
248
|
doctorAlertHeadline,
|
|
180
249
|
doctorAlertOpener,
|
|
250
|
+
doctorBrief,
|
|
181
251
|
};
|
|
@@ -40,6 +40,9 @@ const SENTINELS = [
|
|
|
40
40
|
/^no (he recibido|tengo) (alguno|ningun[oa])( mas)?$/,
|
|
41
41
|
];
|
|
42
42
|
|
|
43
|
+
// A bare «Sí» to the allergy question says there is one, so it stays as an unnamed allergy.
|
|
44
|
+
const UNNAMED_ALLERGY = 'Alergia a medicamentos referida, sin especificar';
|
|
45
|
+
|
|
43
46
|
const clean = (s) => sanitizeInlineText(s, Infinity);
|
|
44
47
|
const fold = (s) => foldAccents(clean(s)).toLowerCase().replace(/[.;,]+$/, '');
|
|
45
48
|
const isSentinel = (s) => SENTINELS.some((re) => re.test(fold(s)));
|
|
@@ -73,8 +76,9 @@ function candidatesFor(record) {
|
|
|
73
76
|
// 394 patients hold both keys; written separately the second arbitrates the first into `alternates`.
|
|
74
77
|
const perVariable = new Map();
|
|
75
78
|
for (const [key, variableId] of Object.entries(FIELD_MAP)) {
|
|
76
|
-
const
|
|
77
|
-
if (!
|
|
79
|
+
const written = clean(clinical[key]);
|
|
80
|
+
if (!written) continue;
|
|
81
|
+
const value = key === 'alergias_medicamentos' && fold(written) === 'si' ? UNNAMED_ALLERGY : written;
|
|
78
82
|
if (isSentinel(value)) { out.sentinels[key] = (out.sentinels[key] || 0) + 1; continue; }
|
|
79
83
|
const bucket = perVariable.get(variableId) || [];
|
|
80
84
|
if (bucket.some((held) => fold(held) === fold(value))) continue;
|
|
@@ -98,9 +98,16 @@ const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) =>
|
|
|
98
98
|
// Every number in the text, after the same spelling as dosingFactsOf.
|
|
99
99
|
const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
|
|
100
100
|
|
|
101
|
+
// «un»/«una» before a word that is not a dose, a span or a count («una compresa fría») is an article; «toma una cada 8 horas» counts.
|
|
102
|
+
const COUNT_FOLLOWS = `${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|horas?|dias?|semanas?|mes(?:es)?|minutos?|ve(?:z|ces)|dosis|toma|cada|al|a|por|o|u|y|sola|mas|extra|adicional|en|de|diaria|diario`;
|
|
103
|
+
const ARTICLE = new RegExp(`\\b(?:un|una)\\s+(?=[a-z])(?!(?:${COUNT_FOLLOWS})\\b)`, 'g');
|
|
104
|
+
// What makes a sentence about a dose, a study or the follow-up rather than home care.
|
|
105
|
+
const DOSING_WORDS = new RegExp(`\\b(?:${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|dosis|medicamentos?|medicinas?|receta|ayun\\w*|estudios?|analisis|laboratorio|cita|consulta|contact\\w*|escrib\\w*|seguimiento|vigilancia)\\b`);
|
|
106
|
+
const isDosingSentence = (text) => DOSING_WORDS.test(folded(text));
|
|
107
|
+
|
|
101
108
|
// The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
|
|
102
109
|
function looseNumbersOf(text) {
|
|
103
|
-
const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
|
|
110
|
+
const dosing = dosingTextOf(folded(String(text ?? '')).replace(LIST_MARKER, '$1$2').replace(ARTICLE, ''));
|
|
104
111
|
return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
|
|
105
112
|
}
|
|
106
113
|
|
|
@@ -111,4 +118,4 @@ function urgencyWordsIn(text) {
|
|
|
111
118
|
.map((match) => match[1]));
|
|
112
119
|
}
|
|
113
120
|
|
|
114
|
-
module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, looseNumbersOf, urgencyWordsIn };
|
|
121
|
+
module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, isDosingSentence, looseNumbersOf, urgencyWordsIn };
|
|
@@ -96,7 +96,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
96
96
|
{
|
|
97
97
|
drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
|
|
98
98
|
instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
|
|
99
|
-
dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria' },
|
|
99
|
+
dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria', duration: 'as_needed' },
|
|
100
100
|
contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
|
|
101
101
|
},
|
|
102
102
|
],
|
|
@@ -256,12 +256,12 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
256
256
|
{
|
|
257
257
|
drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
|
|
258
258
|
instructions: 'capa fina cada 12 horas de forma continua',
|
|
259
|
-
dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua' },
|
|
259
|
+
dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua', duration: 'continuous' },
|
|
260
260
|
},
|
|
261
261
|
{
|
|
262
262
|
drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
|
|
263
263
|
instructions: '2 a 3 veces al día de forma continua',
|
|
264
|
-
dosing: { dose: '2 a 3 veces al día de forma continua' }, isPharmacological: false,
|
|
264
|
+
dosing: { dose: '2 a 3 veces al día de forma continua', duration: 'continuous' }, isPharmacological: false,
|
|
265
265
|
},
|
|
266
266
|
{ drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
|
|
267
267
|
{ drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
|
|
@@ -32,7 +32,7 @@ function buildDedupNote(bridgeText) {
|
|
|
32
32
|
'clínico. El mensaje final es la SEGUNDA burbuja que verá el paciente, no la primera.';
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage }) {
|
|
35
|
+
function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage, contactCode = null, contactRole = null }) {
|
|
36
36
|
const authored = typeof bridgeText === 'string' && bridgeText.trim() ? bridgeText : null;
|
|
37
37
|
|
|
38
38
|
if (!isBridgeEnabled()) return { sent: false, reason: 'disabled', proposed: Boolean(authored) };
|
|
@@ -67,7 +67,7 @@ function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false
|
|
|
67
67
|
if (entry.clearWhenDelivered && bridgeTimestamps.get(code) === entry) bridgeTimestamps.delete(code);
|
|
68
68
|
};
|
|
69
69
|
try {
|
|
70
|
-
Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId }))
|
|
70
|
+
Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId, ...(contactCode && { contactCode, contactRole }) }))
|
|
71
71
|
.then(delivered)
|
|
72
72
|
.catch(failed);
|
|
73
73
|
} catch (err) {
|
|
@@ -2,13 +2,13 @@ const moment = require('moment-timezone');
|
|
|
2
2
|
|
|
3
3
|
const { TRIAGE_RESULT_MARKER } = require('../helpers/triageResultMessageHelper');
|
|
4
4
|
const { getMessages } = require('../../services/messageService');
|
|
5
|
-
const { replyContactFor } = require('../../helpers/caregiverHelper');
|
|
6
5
|
const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
|
|
7
6
|
const { checkInsPausedUntil } = require('../../services/threadService');
|
|
8
7
|
const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
|
|
9
8
|
const { readRecommendationPlans } = require('../../fhir');
|
|
10
9
|
const { ARMED_BY } = require('../../shared/dtos/ContingencySafetyNet');
|
|
11
10
|
const { logger } = require('../../utils/logger');
|
|
11
|
+
const { isCaseFollowUpId, planCaseCheckIn } = require('../../services/caseFollowUpService');
|
|
12
12
|
const { readActiveNets, escalationUrgencyOf, CHECK_IN_WINDOW } = require('./contingencyDispatchService');
|
|
13
13
|
const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
|
|
14
14
|
|
|
@@ -75,7 +75,7 @@ async function recentExchange(code, now) {
|
|
|
75
75
|
lastMessage(code, now, false),
|
|
76
76
|
lastMessage(code, now, true),
|
|
77
77
|
getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
|
|
78
|
-
|
|
78
|
+
isWithin24HourWindow(code),
|
|
79
79
|
]);
|
|
80
80
|
return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
|
|
81
81
|
}
|
|
@@ -181,6 +181,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
181
181
|
});
|
|
182
182
|
}
|
|
183
183
|
|
|
184
|
+
if (isCaseFollowUpId(reminderId)) return planCaseCheckIn({ code, reminderId, firstName, now });
|
|
184
185
|
const plan = await readPendingReminderForPatient({ code, reminderId });
|
|
185
186
|
if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
|
|
186
187
|
if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
|
|
@@ -50,6 +50,7 @@ const REMINDER_TYPE_TO_AIRTABLE = {
|
|
|
50
50
|
// of pending rows so the predicate cannot drift between them.
|
|
51
51
|
const PENDING_ROW_FILTER = 'IF({is_active}, "true", "false") = "true", IF({is_sent}, "true", "false") = "false"';
|
|
52
52
|
const ROUTINE_OUTREACH_FILTER = 'OR({type} = "seguimiento", LEFT({schedule_id}, 9) = "recovery_")';
|
|
53
|
+
const NOT_CASE_FOLLOW_UP = 'LEFT({schedule_id}, 14) != "case_followup_"';
|
|
53
54
|
const RECOVERY_FILTER = 'LEFT({schedule_id}, 9) = "recovery_"';
|
|
54
55
|
// `reminder` and `contingency` have no `source`; the lookup through the patient link carries it.
|
|
55
56
|
const ROW_PROGRAM_FIELD = 'source (from patient_id)';
|
|
@@ -525,14 +526,14 @@ async function readPendingReminderForPatient({ code, reminderId }) {
|
|
|
525
526
|
} : null;
|
|
526
527
|
}
|
|
527
528
|
|
|
528
|
-
async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false }) {
|
|
529
|
+
async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false, includeCaseFollowUp = false }) {
|
|
529
530
|
return standDownRow({
|
|
530
531
|
code,
|
|
531
532
|
trace,
|
|
532
533
|
table: 'reminder',
|
|
533
534
|
planId: null,
|
|
534
535
|
standDownReason: reason,
|
|
535
|
-
filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
|
|
536
|
+
filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${includeCaseFollowUp ? 'TRUE()' : NOT_CASE_FOLLOW_UP}, ${PENDING_ROW_FILTER})`,
|
|
536
537
|
});
|
|
537
538
|
}
|
|
538
539
|
|
|
@@ -3,7 +3,7 @@ const { getExtractor } = require('../config/subAgentsConfig');
|
|
|
3
3
|
const { detectSafetyFlags } = require('../helpers/safetyFlagsHelper');
|
|
4
4
|
const { buildExtractorInput, toClinicalMention } = require('../helpers/clinicalMentionHelper');
|
|
5
5
|
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
6
|
-
const { isQuoteAnchored } = require('../../utils/textMatchUtils');
|
|
6
|
+
const { isQuoteAnchored, negationNearQuote } = require('../../utils/textMatchUtils');
|
|
7
7
|
const { foldAccents } = require('../../utils/formatUtils');
|
|
8
8
|
const { getClinicalContext } = require('../../helpers/patientInformationHelper');
|
|
9
9
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
@@ -110,6 +110,7 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
110
110
|
let unanchored = 0;
|
|
111
111
|
let unusable = 0;
|
|
112
112
|
let forcedPending = 0;
|
|
113
|
+
let polarityConflicts = 0;
|
|
113
114
|
rawMentions.forEach((raw, index) => {
|
|
114
115
|
if (!raw || typeof raw !== 'object') {
|
|
115
116
|
unusable += 1;
|
|
@@ -126,10 +127,12 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
126
127
|
return;
|
|
127
128
|
}
|
|
128
129
|
const quotes = mention.provenance.verbatimQuotes;
|
|
129
|
-
|
|
130
|
+
const negated = Boolean(mention.fact.assertion?.negated);
|
|
131
|
+
if (!quotes.some((quote) => isQuoteAnchored(quote, text, { negated }))) {
|
|
130
132
|
unanchored += 1;
|
|
131
133
|
return;
|
|
132
134
|
}
|
|
135
|
+
if (!negated && quotes.every((quote) => negationNearQuote(quote, text))) polarityConflicts += 1;
|
|
133
136
|
if (!mention.provenance.needsConfirmation && !endsNamedLine(raw, mention.fact)
|
|
134
137
|
&& namesNothingSpecific(mention.fact.canonicalTerm, vagueWords)) {
|
|
135
138
|
forcedPending += 1;
|
|
@@ -148,10 +151,14 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
148
151
|
if (forcedPending) {
|
|
149
152
|
logger.warn('[clinicalExtraction] mentions held back: the term names no specific clinical entity', { turnId, forcedPending });
|
|
150
153
|
}
|
|
154
|
+
if (polarityConflicts) {
|
|
155
|
+
logger.warn('[clinicalExtraction] mentions read as present despite a nearby negation', { turnId, polarityConflicts });
|
|
156
|
+
}
|
|
151
157
|
trace?.setSignals?.({
|
|
152
158
|
clinicalMentionsUnanchored: unanchored,
|
|
153
159
|
clinicalMentionsPending: pendingMentions.length,
|
|
154
160
|
clinicalMentionsForcedPending: forcedPending,
|
|
161
|
+
clinicalMentionsPolarityConflict: polarityConflicts,
|
|
155
162
|
});
|
|
156
163
|
|
|
157
164
|
const patientMentions = [...clinicalMentions, ...pendingMentions]
|
|
@@ -18,9 +18,9 @@ const MS_PER_HOUR = 60 * MS_PER_MINUTE;
|
|
|
18
18
|
const EXPIRY_WINDOW_MULTIPLIER = 6;
|
|
19
19
|
const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
|
|
20
20
|
const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
|
|
21
|
-
const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent:
|
|
22
|
-
//
|
|
23
|
-
const LEGACY_ESCALATION_SILENCE_MINUTES = {
|
|
21
|
+
const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 120 };
|
|
22
|
+
// Urgent nets armed with the old 4 h window keep their level until they expire (48 h).
|
|
23
|
+
const LEGACY_ESCALATION_SILENCE_MINUTES = { urgent: 240 };
|
|
24
24
|
const OPEN_CEILING_SILENCE_MINUTES = 720;
|
|
25
25
|
const OPEN_CEILING_ORIGIN = 'open_ceiling';
|
|
26
26
|
const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
|
|
@@ -291,6 +291,10 @@ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
|
|
|
291
291
|
patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
|
|
292
292
|
});
|
|
293
293
|
|
|
294
|
+
const retireSilenceNets = ({ patientCode, trace = null }) => retireNets({
|
|
295
|
+
patientCode, trace, isLive: null, select: (active) => active.filter((net) => net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'after the doctor decided',
|
|
296
|
+
});
|
|
297
|
+
|
|
294
298
|
function escalationUrgencyOf(net) {
|
|
295
299
|
if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
|
|
296
300
|
const silence = net?.patientReminder?.firesAfterSilenceMinutes;
|
|
@@ -493,4 +497,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
|
|
|
493
497
|
return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
|
|
494
498
|
}
|
|
495
499
|
|
|
496
|
-
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
500
|
+
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, retireSilenceNets, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
|
|
2
|
-
const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
2
|
+
const { allNumbersOf, dosingFactsOf, isDosingSentence, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
3
3
|
const { httpError } = require('../../utils/httpErrorUtils');
|
|
4
4
|
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
5
|
-
const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
6
|
-
const {
|
|
5
|
+
const { PLAN_DURATIONS, PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
6
|
+
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
7
|
+
const { drugsNamedIn, isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
|
|
7
8
|
|
|
8
9
|
const FIRST_LINE = '1L';
|
|
9
10
|
const MAX_ENTRIES = 10;
|
|
@@ -47,12 +48,16 @@ function itemOf(item, index) {
|
|
|
47
48
|
const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
|
|
48
49
|
const reason = textOf(item?.reason, `${name}.reason`);
|
|
49
50
|
if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
|
|
51
|
+
if (item?.duration != null && !PLAN_DURATIONS.includes(item.duration)) throw httpError(400, `${name}.duration must be one of: ${PLAN_DURATIONS.join(', ')}`);
|
|
52
|
+
// Typed days win: a client that predates the duration field sends the proposal's duration back beside them.
|
|
53
|
+
const duration = item?.days != null ? 'days' : item?.duration ?? 'days';
|
|
50
54
|
return {
|
|
51
55
|
drug: neededText(item?.drug, `${name}.drug`),
|
|
52
56
|
strength: textOf(item?.strength, `${name}.strength`),
|
|
53
57
|
dose: neededText(item?.dose, `${name}.dose`),
|
|
54
58
|
frequency: neededText(item?.frequency, `${name}.frequency`),
|
|
55
|
-
|
|
59
|
+
duration,
|
|
60
|
+
days: duration === 'days' ? wholeNumber(item?.days, `${name}.days`, MAX_DAYS) : null,
|
|
56
61
|
position,
|
|
57
62
|
reason,
|
|
58
63
|
formularyKey: textOf(item?.formularyKey, `${name}.formularyKey`),
|
|
@@ -82,27 +87,38 @@ function planOf(input) {
|
|
|
82
87
|
note: textOf(input.note, 'plan.note', MAX_NOTE_LENGTH),
|
|
83
88
|
followUp: followUpOf(input.followUp),
|
|
84
89
|
};
|
|
85
|
-
|
|
86
|
-
|
|
90
|
+
// A follow-up alone is a plan: the assistant adds its home care and the case stays open until the check-in.
|
|
91
|
+
if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note && plan.followUp.kind === 'none') {
|
|
92
|
+
throw httpError(400, 'plan needs a drug, a study, a home care measure, a note or a follow-up');
|
|
87
93
|
}
|
|
88
94
|
return plan;
|
|
89
95
|
}
|
|
90
96
|
|
|
91
|
-
function approvedInstructions(plan, edited) {
|
|
97
|
+
function approvedInstructions(plan, edited, texts) {
|
|
92
98
|
if (edited != null && typeof edited !== 'string') throw httpError(400, 'instructions must be text');
|
|
93
|
-
if (!edited?.trim()) return { instructions: planInstructions(plan), instructionsEdited: false };
|
|
99
|
+
if (!edited?.trim()) return { instructions: planInstructions(plan, texts), instructionsEdited: false };
|
|
94
100
|
const instructions = edited.trim();
|
|
95
101
|
if (instructions.length > MAX_INSTRUCTIONS_LENGTH) throw httpError(400, `instructions exceed ${MAX_INSTRUCTIONS_LENGTH} characters`);
|
|
96
|
-
return { instructions, instructionsEdited: instructions !== planInstructions(plan) };
|
|
102
|
+
return { instructions, instructionsEdited: instructions !== planInstructions(plan, texts) };
|
|
97
103
|
}
|
|
98
104
|
|
|
99
105
|
const strays = (said, planned) => [...said].filter((value) => !planned.has(value));
|
|
100
106
|
const everyOf = (hours) => (hours < 1 ? `cada ${Math.round(hours * 60)} minutos` : `cada ${hours} horas`);
|
|
101
107
|
|
|
108
|
+
// With no drug in the plan, only sentences about a dose, a study or the follow-up are read for numbers: home care may count gargles.
|
|
109
|
+
function checkedTextOf(plan, reply, planned) {
|
|
110
|
+
if (plan.items.length || drugsNamedIn(planned).length) return reply;
|
|
111
|
+
const studies = plan.studies.map((study) => normalizeForAnchor(study.name)).filter(Boolean);
|
|
112
|
+
return String(reply).split(/(?<=[.!?;:])\s+|\n+/)
|
|
113
|
+
.filter((sentence) => isDosingSentence(sentence) || drugsNamedIn(sentence).length || studies.some((name) => normalizeForAnchor(sentence).includes(name)))
|
|
114
|
+
.join('\n');
|
|
115
|
+
}
|
|
116
|
+
|
|
102
117
|
function replyIssues(plan, reply) {
|
|
103
118
|
if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
|
|
104
119
|
const planned = plannedTextOf(plan);
|
|
105
|
-
const
|
|
120
|
+
const checked = checkedTextOf(plan, reply, planned);
|
|
121
|
+
const said = dosingFactsOf(checked);
|
|
106
122
|
const allowed = dosingFactsOf(planned);
|
|
107
123
|
const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
|
|
108
124
|
for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
|
|
@@ -111,7 +127,7 @@ function replyIssues(plan, reply) {
|
|
|
111
127
|
if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
|
|
112
128
|
}
|
|
113
129
|
// A number no pattern reads («tómalo 5 días», «a las 10») still flags when the plan never names it.
|
|
114
|
-
for (const number of strays(looseNumbersOf(
|
|
130
|
+
for (const number of strays(looseNumbersOf(checked), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
|
|
115
131
|
for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
|
|
116
132
|
for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
|
|
117
133
|
return issues;
|