@peopl-health/nexus 6.4.0-dev.18956 → 6.4.0-dev.18959

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,107 +0,0 @@
1
- const { oneLineOf } = require('../../utils/coercionUtils');
2
- const { normalizeForAnchor } = require('../../utils/textMatchUtils');
3
- const { DURATION_SOURCE, durationDays, isRouteOnly } = require('./planTextHelper');
4
-
5
- const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
6
- // «1 tableta» «cada 8 horas | c/8h» «por 5 días», then «, …» what else the formulary says.
7
- const DOSING = new RegExp(`^(.*?)\\s+((?:cada|c\\/)\\s*[^,;]+?)(?:\\s+(${DURATION_SOURCE}))?(?:\\s*[,;]\\s*(.*))?$`, 'i');
8
- // Only a clause of its own: «…, y tragar, por 7 días» gives the days, «…, no manejar durante 2 días» does not.
9
- const LATE_DURATION = new RegExp(`(?:^|[,;]\\s*)(${DURATION_SOURCE})\\s*$`, 'i');
10
-
11
- const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
12
-
13
- const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
14
- const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${item.dose} ${item.frequency} por ${daysText(item.days)}.`;
15
- const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
16
- const PRESCRIPTION_LINE = 'Justo después de tu mensaje le llega aparte la receta del médico en PDF; dile que la va a recibir.';
17
-
18
- const FOLLOW_UP_LINES = {
19
- check_in: (hours) => `Seguimiento: le escribiremos en unas ${hours} horas para ver cómo va.`,
20
- vigilancia: (hours) => `Seguimiento: queda en vigilancia las próximas ${hours} horas; le escribiremos para ver cómo va.`,
21
- };
22
- const followUpLineOf = (plan) => FOLLOW_UP_LINES[plan.followUp?.kind]?.(plan.followUp.hours) ?? null;
23
-
24
- function planInstructions(plan) {
25
- const lines = ['Transmítele al paciente lo que indicó el médico, con tus palabras: no cambies dosis, frecuencia ni días, y no agregues otros medicamentos ni estudios. Escribe dosis, horas y días con números, como vienen aquí, sin repetirlos con letra, y no agregues avisos de urgencia que el médico no dio.'];
26
- if (plan.items.length) {
27
- lines.push('Medicamentos:', ...plan.items.map((item) => `- ${itemLine(item)}`));
28
- }
29
- if (plan.studies.length) {
30
- lines.push('Estudios:', ...plan.studies.map((study) => `- ${studyLine(study)}`));
31
- }
32
- if (plan.homeCare.length) lines.push('Cuidados en casa:', ...plan.homeCare.map((entry) => `- ${entry}`));
33
- if (plan.note) lines.push(`Nota del médico: «${plan.note}».`);
34
- const followUp = followUpLineOf(plan);
35
- if (followUp) lines.push(followUp);
36
- if (needsPrescriber(plan)) lines.push(PRESCRIPTION_LINE);
37
- return lines.join('\n');
38
- }
39
-
40
- // An edit can drop or reword the receta line; the PDF goes out anyway, so the assistant is still told.
41
- function assistantInstructionsOf(plan) {
42
- if (!needsPrescriber(plan) || normalizeForAnchor(plan.instructions).includes(normalizeForAnchor(PRESCRIPTION_LINE))) return plan.instructions;
43
- return `${plan.instructions}\n${PRESCRIPTION_LINE}`;
44
- }
45
-
46
- function planSummary(plan) {
47
- const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
48
- if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
49
- if (plan.note) lines.push(`Nota: ${plan.note}`);
50
- return lines.join('\n');
51
- }
52
-
53
- function prescriptionText(plan) {
54
- const lines = plan.items.map(itemLine);
55
- if (plan.studies.length) lines.push('Estudios:', ...plan.studies.map(studyLine));
56
- return lines.join('\n');
57
- }
58
-
59
- function dosingOf(instructions) {
60
- const text = oneLineOf(instructions);
61
- const match = text.match(DOSING);
62
- if (!match) return { dose: text || null, frequency: null, days: null, rest: null };
63
- const [, dose, frequency, duration, , , , rest] = match;
64
- const late = !duration ? rest?.match(LATE_DURATION) : null;
65
- const said = duration ?? late?.[1];
66
- const days = durationDays(said);
67
- const others = late ? rest.slice(0, late.index).replace(/[,;\s]+$/, '') : rest;
68
- // A range («por 3 a 5 días») is the doctor's to settle, so it stays in the note.
69
- const left = [others, said && !days ? said : null].filter(Boolean).join(', ');
70
- return { dose: isRouteOnly(dose) ? null : dose, frequency, days, rest: left || null };
71
- }
72
-
73
- // What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
74
- function proposedPlanOf(draft) {
75
- const seen = new Set();
76
- const rests = [];
77
- const items = (draft?.symptoms ?? [])
78
- .filter((entry) => entry?.proposal?.confirmed)
79
- .flatMap((entry) => (entry.proposal.items ?? []).map((item) => ({ item, formularyKey: entry.proposal.formularyKey })))
80
- .filter(({ item }) => !seen.has(normalizeForAnchor(item.drug)) && seen.add(normalizeForAnchor(item.drug)))
81
- .map(({ item, formularyKey }) => {
82
- const { rest, ...dosing } = dosingOf(item.instructions);
83
- if (rest) rests.push(`${item.drug}: ${rest}`);
84
- return { drug: item.drug, strength: item.strength ?? null, ...dosing, position: item.position ?? null, reason: null, formularyKey };
85
- });
86
- return { items, studies: [], homeCare: [], note: rests.join('. ') || null, followUp: { kind: 'check_in', hours: DEFAULT_FOLLOW_UP_HOURS.check_in } };
87
- }
88
-
89
- // The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
90
- const plannedTextOf = (plan) => [
91
- ...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item.days && `por ${item.days} dias`]),
92
- ...plan.studies.flatMap((study) => [study.name, study.instructions]),
93
- ...plan.homeCare,
94
- plan.note,
95
- followUpLineOf(plan),
96
- ].filter(Boolean).join('\n');
97
-
98
- module.exports = {
99
- DEFAULT_FOLLOW_UP_HOURS,
100
- assistantInstructionsOf,
101
- needsPrescriber,
102
- planInstructions,
103
- planSummary,
104
- plannedTextOf,
105
- prescriptionText,
106
- proposedPlanOf,
107
- };
@@ -1,131 +0,0 @@
1
- const { foldAccents } = require('../../utils/formatUtils');
2
- const { normalizeForAnchor } = require('../../utils/textMatchUtils');
3
-
4
- const UNITS = ['', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
5
- const TEENS = ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciseis', 'diecisiete', 'dieciocho', 'diecinueve'];
6
- const TENS = ['', '', 'veinte', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa'];
7
- // 1 to 99 as written without accents: «veintiuno», «veintiun», «treinta y seis»; «un» and «una» are 1.
8
- const NUMBER_WORDS = Object.freeze(Object.fromEntries([
9
- ['un', 1], ['una', 1], ['veintiun', 21],
10
- ...UNITS.slice(1).map((word, index) => [word, index + 1]),
11
- ...TEENS.map((word, index) => [word, index + 10]),
12
- ...UNITS.slice(1).map((word, index) => [`veinti${word}`, index + 21]),
13
- ...TENS.slice(2).map((word, index) => [word, (index + 2) * 10]),
14
- ...TENS.slice(3).flatMap((word, tens) => UNITS.slice(1).map((unit, index) => [`${word} y ${unit}`, (tens + 3) * 10 + index + 1])),
15
- ]));
16
- const WORDS = Object.keys(NUMBER_WORDS).sort((a, b) => b.length - a.length).join('|');
17
- const COUNT = `(?:\\d+|${WORDS})`;
18
- // «y» is left out: «treinta y cinco» is one number, not a range.
19
- const TO = '\\s*(?:a|-|o|u)\\s*';
20
- const DAYS_PER = Object.freeze({ d: 1, dia: 1, dias: 1, semana: 7, semanas: 7, mes: 30, meses: 30 });
21
- const DAY_UNITS = 'd[ií]as?|semanas?|mes(?:es)?|d\\b';
22
-
23
- const UNIT_SCALE = Object.freeze({
24
- microgramo: ['mg', 0.001], microgramos: ['mg', 0.001], mcg: ['mg', 0.001], µg: ['mg', 0.001], ug: ['mg', 0.001],
25
- miligramo: ['mg', 1], miligramos: ['mg', 1], mg: ['mg', 1],
26
- gramo: ['mg', 1000], gramos: ['mg', 1000], g: ['mg', 1000], gr: ['mg', 1000],
27
- ml: ['ml', 1], ui: ['ui', 1],
28
- });
29
- const UNITS_SOURCE = Object.keys(UNIT_SCALE).sort((a, b) => b.length - a.length).join('|');
30
- // Forms a dose is counted in («media tableta», «1/2 tableta»), then forms that only name the preparation.
31
- const COUNTED_FORMS = 'tabletas?|tab|capsulas?|caps|comprimidos?|pastillas?|sobres?|ampolletas?|ampulas?|ampollas?|cucharadas?|cucharaditas?|gotas|supositorios?|ovulos?|parches?';
32
- const OTHER_FORMS = 'jarabe|crema|pomada|gel|unguento|locion|solucion|suspension|inyectable|inyeccion|spray|colirio';
33
- // «por 5 días», «durante una semana», «x 7 días», «por unos 5 días», «por 3 a 5 días»
34
- const DURATION_SOURCE = `(?:por|durante|x)\\s+(?:(?:unos|unas|los|las|pr[oó]ximos|otros)\\s+)*(${COUNT})(?:${TO}(${COUNT}))?\\s*(${DAY_UNITS})`;
35
- const DURATION = new RegExp(`^${DURATION_SOURCE}$`, 'i');
36
-
37
- const ROUTES = new Set(['vo', 'po', 'oral', 'iv', 'ev', 'intravenosa', 'im', 'intramuscular', 'sc', 'subcutanea', 'sl', 'sublingual', 'topica', 'topico', 'cutanea', 'transdermica', 'rectal', 'vaginal', 'nasal', 'intranasal', 'inhalada', 'inhalado', 'oftalmica', 'otica']);
38
- // What a drug's name may carry that does not name it: «Ondansetrón 8 mg», «Metoclopramida gotas»; a spelled-out route («transdérmica») stays.
39
- const NOT_A_NAME = new RegExp(`^(?:\\d+(?:${UNITS_SOURCE})?|${UNITS_SOURCE}|vo|iv|im|sc|sl|oral|${COUNTED_FORMS}|${OTHER_FORMS})$`);
40
-
41
- const URGENCY_WORDS = /\b(urgencias?|urgente|de inmediato|inmediata|inmediatamente|emergencias?|911|ambulancia|hospital|guardia|lo antes posible|cuanto antes|no esperes)\b/g;
42
- // Only filler may sit between: «no necesitas ir a urgencias» calms, «no es normal, ve a urgencias» does not.
43
- const CALMING_BEFORE = /\b(?:no\s+(?:es|son|parece|hay|hace\s+falta|necesitas?|requiere|requieres|tienes\s+(?:que|por\s+que))|sin\s+necesidad\s+de)(?:\s+(?:necesario|ir|acudir|a|al|una|un|de|la|que))*\s*$/;
44
-
45
- const folded = (text) => foldAccents(text).toLowerCase();
46
-
47
- const countOf = (word) => (/^\d+$/.test(word) ? Number(word) : NUMBER_WORDS[folded(word).replace(/\s+/g, ' ')] ?? null);
48
- const daysPer = (unit) => DAYS_PER[folded(unit)];
49
-
50
- const isRouteOnly = (text) => ROUTES.has(folded(text).replace(/\./g, '').replace(/^(?:por\s+)?(?:via\s+)?/, '').trim());
51
-
52
- const drugNameOf = (text) => normalizeForAnchor(text).split(' ').filter((word) => word && !NOT_A_NAME.test(word)).join(' ');
53
-
54
- // Null for a range or an unknown count: the doctor settles those.
55
- function durationDays(phrase) {
56
- const match = folded(String(phrase ?? '')).trim().match(DURATION);
57
- if (!match || match[2]) return null;
58
- const count = countOf(match[1]);
59
- return count ? count * daysPer(match[3]) : null;
60
- }
61
-
62
- const NUMBER_WORD = new RegExp(`\\b(${WORDS})\\b`, 'g');
63
- const IN_DAYS = new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s*(semanas?|mes(?:es)?|d)\\b`, 'g');
64
- const DAYS_IN_UNIT = (_, from, to, unit) => [from, to].filter(Boolean).map((value) => value * daysPer(unit)).join(' a ').concat(' dias');
65
- const TIMES_A_DAY = (written, ...counts) => {
66
- const times = counts.slice(0, 2).filter(Boolean).map(Number);
67
- return times.every((count) => count > 0 && 24 % count === 0) ? times.map((count) => `cada ${24 / count} horas`).join(' o ') : written;
68
- };
69
-
70
- // A dot stays decimal, as written in Mexico.
71
- function dosingTextOf(text) {
72
- return folded(text)
73
- .replace(/\b[1-9]\d{0,2}(?:,\d{3})+\b/g, (thousands) => thousands.replace(/,/g, ''))
74
- .replace(/(\d),(\d)/g, '$1.$2')
75
- .replace(NUMBER_WORD, (word) => String(countOf(word)))
76
- .replace(/(\d+(?:\.\d+)?)\s*\((\d+(?:\.\d+)?)\)/g, (written, number, again) => (number === again ? number : written))
77
- .replace(/(?<![\d/])([1-3])\/([2-4])(?![\d/])/g, (written, top, bottom) => (Number(top) < Number(bottom) ? String(Math.round((top / bottom) * 1000) / 1000) : written))
78
- .replace(new RegExp(`\\b(?:media|medio)\\s+(?=(?:${COUNTED_FORMS}|horas?)\\b)`, 'g'), '0.5 ')
79
- .replace(/\bcada\s+(\d+(?:\.\d+)?)\s*min(?:utos?)?\b/g, (_, minutes) => `cada ${Math.round((minutes / 60) * 1000) / 1000} horas`)
80
- .replace(/\bc\/\s*(\d+)\s*(?:h|hs|hrs?|horas?)\b/g, 'cada $1 horas')
81
- .replace(new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s+ve(?:z|ces)\\s+(?:al|por|cada)\\s+dia\\b`, 'g'), TIMES_A_DAY)
82
- .replace(/\bcada\s+hora\s+y\s+media\b/g, 'cada 1.5 horas')
83
- .replace(/\b(\d+)\s+(dias?|horas?)\s+y\s+medi[oa]\b/g, (_, count, unit) => `${Number(count) + 0.5} ${unit}`)
84
- .replace(/\bcada\s+hora\b/g, 'cada 1 horas')
85
- .replace(/\bcada\s+dia\b/g, 'cada 24 horas')
86
- .replace(/\b(?:(?:por|durante|x)\s+(?:(?:unos|unas|los|las|proximos|otros)\s+)*|(?:los|las)\s+proxim[oa]s\s+)(?=\d)/g, 'por ')
87
- .replace(IN_DAYS, DAYS_IN_UNIT)
88
- .replace(/\s+/g, ' ');
89
- }
90
-
91
- const AMOUNTS = new RegExp(`\\b(\\d+(?:\\.\\d+)?)\\s*(${UNITS_SOURCE})(?![a-z])`, 'g');
92
- const RANGE = `(\\d+(?:\\.\\d+)?)(?:${TO}(\\d+(?:\\.\\d+)?))?`;
93
- const HOURS = new RegExp(`cada\\s+${RANGE}\\s*h(?:s|rs?|oras?)?\\b`, 'g');
94
- const DAYS = new RegExp(`por\\s+${RANGE}\\s+dias?\\b`, 'g');
95
-
96
- const valuesIn = (text, pattern) => new Set([...text.matchAll(pattern)].flatMap((match) => [match[1], match[2]]).filter(Boolean).map(Number));
97
-
98
- // Amounts are keyed in mg, ml or UI, so «1 g» and «1000 mg» meet.
99
- function dosingFactsOf(text) {
100
- const dosing = dosingTextOf(text);
101
- const amounts = new Map([...dosing.matchAll(AMOUNTS)].map(([written, value, unit]) => {
102
- const [base, scale] = UNIT_SCALE[unit];
103
- return [`${Math.round(Number(value) * scale * 1000) / 1000} ${base}`, written];
104
- }));
105
- return { hours: valuesIn(dosing, HOURS), days: valuesIn(dosing, DAYS), amounts };
106
- }
107
-
108
- // List markers («1.», «2)») number lines, not doses.
109
- const LIST_MARKER = /(^|\n)[ \t]*\d+[.)][ \t]+|(?<!\([^)\n]*)(^|\s)\d+\)[ \t]+/g;
110
- // Clock times, dates, phone numbers and temperatures are not doses.
111
- const NOT_DOSING = [/\b\d{1,2}:\d{2}\b/g, new RegExp(`\\b\\d{1,2}\\/\\d{1,2}(?:\\/\\d{2,4})?\\b(?!\\s*(?:${COUNTED_FORMS}|${UNITS_SOURCE})\\b)`, 'g'), /\b(?=(?:\d[ -]?){8,})\d{2,4}(?:[ -]?\d{2,4}){2,}\b/g, /\b\d+(?:\.\d+)?\s*(?:°\s*c?|grados)/g, /\b(?:fiebre|temperatura)\s+(?:(?:de|es|sea|esta|mayor|menor|a|mas|que|pasa|sube|llega|arriba|encima|del|por)\s+)*\d+(?:\.\d+)?/g];
112
- const NUMBER = /\d+(?:\.\d+)?/g;
113
- const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) => Number(number)));
114
-
115
- // Every number in the text, after the same spelling as dosingFactsOf.
116
- const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
117
-
118
- // The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
119
- function looseNumbersOf(text) {
120
- const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
121
- return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
122
- }
123
-
124
- function urgencyWordsIn(text) {
125
- const plain = folded(text);
126
- return new Set([...plain.matchAll(URGENCY_WORDS)]
127
- .filter((match) => !CALMING_BEFORE.test(plain.slice(0, match.index)))
128
- .map((match) => match[1]));
129
- }
130
-
131
- module.exports = { DURATION_SOURCE, allNumbersOf, dosingFactsOf, drugNameOf, durationDays, isRouteOnly, looseNumbersOf, urgencyWordsIn };
@@ -1,120 +0,0 @@
1
- const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
2
- const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
3
- const { httpError } = require('../../utils/httpErrorUtils');
4
- const { oneLineOf } = require('../../utils/coercionUtils');
5
- const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
6
- const { isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
7
-
8
- const FIRST_LINE = '1L';
9
- const MAX_ENTRIES = 10;
10
- const MAX_FIELD_LENGTH = 300;
11
- const MAX_NOTE_LENGTH = 1000;
12
- const MAX_INSTRUCTIONS_LENGTH = 4000;
13
- const MAX_DAYS = 90;
14
- const MAX_FOLLOW_UP_HOURS = 168;
15
-
16
- const textOf = (value, name, max = MAX_FIELD_LENGTH) => {
17
- if (value != null && typeof value !== 'string') throw httpError(400, `${name} must be text`);
18
- const text = oneLineOf(value);
19
- if (text.length > max) throw httpError(400, `${name} exceeds ${max} characters`);
20
- return text || null;
21
- };
22
-
23
- const neededText = (value, name) => {
24
- const text = textOf(value, name);
25
- if (!text) throw httpError(400, `${name} is required`);
26
- return text;
27
- };
28
-
29
- const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
30
-
31
- // Only a number or a string of digits: `true`, `[5]` and `'1e1'` are not days.
32
- const wholeNumber = (value, name, max) => {
33
- const number = typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value.trim())) ? Number(value) : NaN;
34
- if (!Number.isInteger(number) || number < 1 || number > max) throw httpError(400, `${name} must be a whole number from 1 to ${max}`);
35
- return number;
36
- };
37
-
38
- const listOf = (value, name) => {
39
- if (value == null) return [];
40
- if (!Array.isArray(value)) throw httpError(400, `${name} must be a list`);
41
- if (value.length > MAX_ENTRIES) throw httpError(400, `${name} allows at most ${MAX_ENTRIES} entries`);
42
- return value;
43
- };
44
-
45
- function itemOf(item, index) {
46
- const name = `plan.items[${index}]`;
47
- const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
48
- const reason = textOf(item?.reason, `${name}.reason`);
49
- if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
50
- return {
51
- drug: neededText(item?.drug, `${name}.drug`),
52
- strength: textOf(item?.strength, `${name}.strength`),
53
- dose: neededText(item?.dose, `${name}.dose`),
54
- frequency: neededText(item?.frequency, `${name}.frequency`),
55
- days: wholeNumber(item?.days, `${name}.days`, MAX_DAYS),
56
- position,
57
- reason,
58
- formularyKey: textOf(item?.formularyKey, `${name}.formularyKey`),
59
- };
60
- }
61
-
62
- function followUpOf(value) {
63
- if (value != null && !isPlainObject(value)) throw httpError(400, 'plan.followUp must be an object with a kind');
64
- const kind = value?.kind ?? 'none';
65
- if (!PLAN_FOLLOW_UPS.includes(kind)) throw httpError(400, `plan.followUp.kind must be one of: ${PLAN_FOLLOW_UPS.join(', ')}`);
66
- if (kind === 'none') return { kind, hours: null };
67
- return { kind, hours: wholeNumber(value?.hours ?? DEFAULT_FOLLOW_UP_HOURS[kind], 'plan.followUp.hours', MAX_FOLLOW_UP_HOURS) };
68
- }
69
-
70
- function planOf(input) {
71
- if (!isPlainObject(input)) throw httpError(400, 'plan is required');
72
- const plan = {
73
- items: listOf(input.items, 'plan.items').map((item, index) => {
74
- if (!isPlainObject(item)) throw httpError(400, `plan.items[${index}] must be an object`);
75
- return itemOf(item, index);
76
- }),
77
- studies: listOf(input.studies, 'plan.studies').map((study, index) => ({
78
- name: neededText(study?.name, `plan.studies[${index}].name`),
79
- instructions: textOf(study?.instructions, `plan.studies[${index}].instructions`),
80
- })),
81
- homeCare: listOf(input.homeCare, 'plan.homeCare').map((entry, index) => neededText(entry, `plan.homeCare[${index}]`)),
82
- note: textOf(input.note, 'plan.note', MAX_NOTE_LENGTH),
83
- followUp: followUpOf(input.followUp),
84
- };
85
- if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note) {
86
- throw httpError(400, 'plan needs a drug, a study, a home care measure or a note');
87
- }
88
- return plan;
89
- }
90
-
91
- function approvedInstructions(plan, edited) {
92
- if (edited != null && typeof edited !== 'string') throw httpError(400, 'instructions must be text');
93
- if (!edited?.trim()) return { instructions: planInstructions(plan), instructionsEdited: false };
94
- const instructions = edited.trim();
95
- if (instructions.length > MAX_INSTRUCTIONS_LENGTH) throw httpError(400, `instructions exceed ${MAX_INSTRUCTIONS_LENGTH} characters`);
96
- return { instructions, instructionsEdited: instructions !== planInstructions(plan) };
97
- }
98
-
99
- const strays = (said, planned) => [...said].filter((value) => !planned.has(value));
100
- const everyOf = (hours) => (hours < 1 ? `cada ${Math.round(hours * 60)} minutos` : `cada ${hours} horas`);
101
-
102
- function replyIssues(plan, reply) {
103
- if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
104
- const planned = plannedTextOf(plan);
105
- const said = dosingFactsOf(reply);
106
- const allowed = dosingFactsOf(planned);
107
- const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
108
- for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
109
- for (const days of strays(said.days, allowed.days)) issues.push(`dice «por ${days} días», que no está en el plan`);
110
- for (const [amount, written] of said.amounts) {
111
- if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
112
- }
113
- // 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(reply), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
115
- for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
116
- for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
117
- return issues;
118
- }
119
-
120
- module.exports = { approvedInstructions, planOf, replyIssues };
@@ -1,30 +0,0 @@
1
- const { Monitoreo_ID } = require('../config/airtableConfig');
2
-
3
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
4
-
5
- const { addLinkedRecord } = require('./airtableService');
6
-
7
- // physicianId links the receta to a physicians row; the Airtable automation picks the PDF template from that physician's specialty.
8
- async function createPrescription({ code, prescription, authorEmail, creationSource = 'other', physicianId }) {
9
- const patientCode = ensureWhatsAppFormat(code);
10
- const record = await addLinkedRecord(
11
- Monitoreo_ID,
12
- 'patient_prescriptions',
13
- {
14
- prescription,
15
- author_email: authorEmail,
16
- creation_source: creationSource,
17
- created: new Date().toISOString(),
18
- ...(physicianId && { physician: [physicianId] })
19
- },
20
- {
21
- referenceTable: 'estado_general',
22
- referenceFilter: `{whatsapp_id}='${patientCode}'`,
23
- linkFieldName: 'patient_id'
24
- },
25
- patientCode
26
- );
27
- return record?.id || null;
28
- }
29
-
30
- module.exports = { createPrescription };