@peopl-health/nexus 5.76.4 → 5.76.6

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.
@@ -14,6 +14,10 @@ function chemoContextLive() {
14
14
  return flagOn('CHEMO_CONTEXT_LIVE');
15
15
  }
16
16
 
17
+ function rtContextBlockLive() {
18
+ return flagOn('RT_CONTEXT_BLOCK');
19
+ }
20
+
17
21
  function profileFromMongo() {
18
22
  return flagOn('PATIENT_PROFILE_FROM_MONGO');
19
23
  }
@@ -38,4 +42,5 @@ module.exports = {
38
42
  profileFromMongo,
39
43
  profileSyncOn,
40
44
  regimenCloserLive,
45
+ rtContextBlockLive,
41
46
  };
@@ -1,6 +1,8 @@
1
1
  const { isCohortEnabled } = require('../config/cohortConfig');
2
2
  const { isBridgeEnabled } = require('./bridgeConfig');
3
- const { contextReadLive, contextMirrorLive, contextVerifierLive } = require('./clinicalContextFlags');
3
+ const {
4
+ contextReadLive, contextMirrorLive, contextVerifierLive, rtContextBlockLive,
5
+ } = require('./clinicalContextFlags');
4
6
  const { isComposerEnabled, isAgentSelfRenderEnabled } = require('./composerFlags');
5
7
  const { isContingencyCancelOnReplyLive, isArmOnOpenCeilingLive, isContingencyRuleBlockLive } = require('./contingencyFlags');
6
8
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('./escalationFlags');
@@ -20,6 +22,7 @@ const FLAG_READERS = {
20
22
  contextRead: contextReadLive,
21
23
  contextMirror: contextMirrorLive,
22
24
  contextVerifier: contextVerifierLive,
25
+ rtContextBlock: rtContextBlockLive,
23
26
  composer: isComposerEnabled,
24
27
  agentSelfRender: isAgentSelfRenderEnabled,
25
28
  contingencyCancelOnReply: isContingencyCancelOnReplyLive,
@@ -10,6 +10,7 @@ const { composePrompt, resolveTools } = require('../services/promptComposerServi
10
10
  const { resolveSkillCatalog } = require('../services/skillService');
11
11
  const { RISK_HEADLINE_MARKER } = require('../services/riskHeadlineService');
12
12
  const { resolveClinicalContext } = require('../services/clinicalContextReadService');
13
+ const { radiotherapyBlockFor, withRadiotherapyBlock } = require('../services/radiotherapyContextService');
13
14
  const { isContingencyRuleBlockLive } = require('../flags/contingencyFlags');
14
15
  const { snapshotClinicalFlags } = require('../flags/flagSnapshot');
15
16
  const { TURN_KIND } = require('../context/turnContext');
@@ -321,7 +322,7 @@ class BaseLLMProvider {
321
322
  ...this._buildFollowUpPolicyMessage(toolIds),
322
323
  ...this._buildFollowUpMessage(promptVariables),
323
324
  ...this._buildFollowUpCheckMessage(toolIds),
324
- ...this._buildContingencyCheckMessage(promptVariables, toolIds),
325
+ ...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
325
326
  ...this._buildClockMessage(promptVariables, interpolatedVariables),
326
327
  ...messages,
327
328
  ...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
@@ -494,12 +495,16 @@ class BaseLLMProvider {
494
495
  // Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
495
496
  // because an unresolved net later asks the patient a question they had already answered.
496
497
  // Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
497
- _buildContingencyCheckMessage(promptVariables, toolIds = []) {
498
+ // A net is marked fired before its own check-in turn runs, so during that turn its check-in has not reached the patient yet.
499
+ _buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
498
500
  if (!(toolIds || []).includes('setContingencyPlan')) return [];
499
501
  const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
500
502
  if (!active.length) return [];
503
+ const dueNet = outreachBrief?.checkIn?.planId || null;
501
504
  const waiting = active.map(({ carePlan: plan = {} } = {}) => {
502
- const fired = plan.status === 'fired_reminder' ? ' Su check-in ya se envió.' : '';
505
+ let fired = '';
506
+ if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
507
+ else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
503
508
  return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
504
509
  });
505
510
  return [{
@@ -634,6 +639,7 @@ class BaseLLMProvider {
634
639
 
635
640
  logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
636
641
 
642
+ const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
637
643
  const override = config.clinicalData;
638
644
  const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
639
645
  const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
@@ -657,8 +663,9 @@ class BaseLLMProvider {
657
663
  patientId: thread.code,
658
664
  legacyBlock: promptVariables.clinical_context,
659
665
  });
660
- promptVariables.clinical_context = withHospitalization(block, thread?.hospitalizedAt);
661
- assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source });
666
+ const rtBlock = await radiotherapyBlock;
667
+ promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
668
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
662
669
 
663
670
  const result = await this.runConversation({
664
671
  threadId: conversationId,
@@ -101,6 +101,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
101
101
  checkIn = {
102
102
  type,
103
103
  reminderId,
104
+ planId,
104
105
  dueAt: null,
105
106
  question: netQuestion,
106
107
  concern: net.carePlan.concern,
@@ -118,6 +119,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
118
119
  checkIn = {
119
120
  type,
120
121
  reminderId,
122
+ planId: null,
121
123
  dueAt: plan.fireAt || null,
122
124
  question: plan.message || question,
123
125
  concern: plan.windowReasoning,
@@ -0,0 +1,40 @@
1
+ const { rtContextBlockLive } = require('../flags/clinicalContextFlags');
2
+ const { Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
3
+ const { escapeFormulaValue, fieldEquals } = require('../../helpers/airtableFormulaHelper');
4
+ const { getRecordByFilter } = require('../../services/airtableService');
5
+ const { logger } = require('../../utils/logger');
6
+ const { withTimeout } = require('../../utils/timeoutUtils');
7
+ const { latestCourse, renderRadiotherapyBlock } = require('./radiotherapyPhaseService');
8
+
9
+ const ZONE_FIELDS = ['rt_zona', 'rt_zona_confirmada'];
10
+ const FACT_FIELDS = ['value_text', 'normalized_value', 'report_date'];
11
+ const READ_TIMEOUT_MS = 2000;
12
+
13
+ const courseFacts = (code) => getRecordByFilter(
14
+ Estado_General_ID,
15
+ 'facts',
16
+ `AND({variable}='radiotherapy_summary', ARRAYJOIN({whatsapp_id (from patient)})='${escapeFormulaValue(code)}')`,
17
+ null,
18
+ FACT_FIELDS,
19
+ );
20
+
21
+ async function radiotherapyBlockFor(code, now) {
22
+ try {
23
+ if (!rtContextBlockLive() || !code) return '';
24
+ const [zones, facts] = await withTimeout(Promise.all([
25
+ getRecordByFilter(Symptoms_ID, 'estado_general', fieldEquals('whatsapp_id', code), 'Grid view', ZONE_FIELDS),
26
+ courseFacts(code),
27
+ ]), READ_TIMEOUT_MS, 'radiotherapy context read');
28
+ const row = zones?.[0] || {};
29
+ return renderRadiotherapyBlock({
30
+ zona: row.rt_zona || null, confirmada: Boolean(row.rt_zona_confirmada), curso: latestCourse(facts), now,
31
+ });
32
+ } catch (error) {
33
+ logger.warn('[radiotherapyContext] block left out', { error: error?.message });
34
+ return '';
35
+ }
36
+ }
37
+
38
+ const withRadiotherapyBlock = (block, rtBlock) => (rtBlock ? [block, rtBlock].filter(Boolean).join('\n\n') : block);
39
+
40
+ module.exports = { radiotherapyBlockFor, withRadiotherapyBlock };
@@ -0,0 +1,272 @@
1
+ const {
2
+ addDays, daysBetween, formatDmy, mexicoDay,
3
+ } = require('../../utils/dateUtils');
4
+ const { foldAccents } = require('../../utils/formatUtils');
5
+ const { safeParse } = require('../../utils/jsonUtils');
6
+
7
+ const SKIN = 'enrojecimiento que se extiende fuera de la zona tratada, calor o pus';
8
+ const PELVIC_NEVER = Object.freeze(['no poder orinar', SKIN]);
9
+ const PELVIC_LATE = Object.freeze(['dolor nuevo de cadera, ingle o sacro al caminar']);
10
+
11
+ // Recomendaciones aprobadas el 22-oct-2026 (propuesta para firma de radioterapia); pendiente el visto bueno del servicio
12
+ const RT_DRAFT = Object.freeze({
13
+ ACUTE_DAYS: 90,
14
+ STALE_DAYS: 10,
15
+ SRS_EARLY_DAYS: 7,
16
+ SRS_MAX_FRACTIONS: 5,
17
+ GENERAL_EXPECTED: Object.freeze(['fatiga', 'falta de apetito', 'dolor o molestia en la zona tratada']),
18
+ NEVER_EXPECTED: Object.freeze(['fiebre de 38.0 °C o más', 'síntoma neurológico nuevo (debilidad, convulsión, confusión, dolor de cabeza con vómito)']),
19
+ SEVERITY: 'Esperable describe la causa probable, no la gravedad: no poder beber o tragar, más de 7 evacuaciones al día sobre lo habitual, pérdida de 5 % del peso o piel abierta e infectada no son esperables en ninguna fase.',
20
+ SEQUELAE: 'Secuelas persistentes ya conocidas (boca seca, fibrosis, piel más oscura, linfedema ya conocido) pueden seguir presentes.',
21
+ IMMUNOTHERAPY: 'Si recibe inmunoterapia al mismo tiempo, tos, diarrea o erupción en la piel nuevas no se atribuyen a la radioterapia.',
22
+ PELVIC_BLEEDING: 'Sangrado rectal o en la orina: puede ser un efecto tardío conocido, pero la radioterapia no lo explica sin evaluación.',
23
+ ZONES: Object.freeze({
24
+ 'pelvis femenina': {
25
+ expected: ['diarrea o evacuaciones blandas', 'cólicos o dolor abdominal', 'ardor o urgencia al orinar', 'flujo vaginal', 'irritación de la piel en pliegues de la zona'],
26
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
27
+ },
28
+ 'pelvis masculina': {
29
+ expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'chorro débil', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
30
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
31
+ },
32
+ pelvis: {
33
+ expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
34
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
35
+ },
36
+ mama: {
37
+ expected: ['reacción de la piel en la zona tratada (enrojecimiento, comezón, descamación)', 'oscurecimiento de la piel', 'hinchazón o sensibilidad de la mama'],
38
+ never: ['hinchazón súbita y dolorosa del brazo', 'si se irradiaron los ganglios: tos o falta de aire nuevas de 1 a 6 meses después del fin', SKIN],
39
+ },
40
+ 'cabeza y cuello': {
41
+ expected: ['dolor al tragar', 'llagas en la boca', 'boca seca o saliva espesa y flema', 'cambios en el gusto', 'ronquera', 'reacción de la piel del cuello', 'pérdida leve de peso'],
42
+ never: ['sangrado por la boca, el cuello o la traqueostomía', 'ruido al respirar o falta de aire', 'no tolerar líquidos ni la alimentación por sonda',
43
+ 'mareo al pararse u orina escasa (deshidratación)', SKIN],
44
+ },
45
+ torax: {
46
+ expected: ['dolor o ardor al tragar', 'acidez'],
47
+ activeOnly: ['tos leve'],
48
+ never: ['falta de aire en reposo', 'dolor en el pecho o tos con sangre', 'tos o falta de aire nuevas de 1 a 6 meses después del fin (hasta 12 meses con SBRT o inmunoterapia)'],
49
+ },
50
+ abdomen: { expected: ['náuseas', 'diarrea'], never: [] },
51
+ 'cerebro holocraneal': {
52
+ expected: ['somnolencia', 'náuseas leves', 'caída del cabello'],
53
+ never: [],
54
+ lateEffects: 'Problemas de memoria o de concentración pueden ser un efecto tardío de la radioterapia al cerebro.',
55
+ },
56
+ radiocirugia: {
57
+ earlyExpected: ['dolor de cabeza leve y náuseas los primeros ~7 días'],
58
+ expected: [],
59
+ never: ['dolor de cabeza nuevo o que empeora después de los primeros ~7 días'],
60
+ },
61
+ 'cerebro sin tecnica': { expected: [], never: [] },
62
+ 'hueso u otra': {
63
+ expected: ['aumento pasajero del dolor en el sitio tratado los primeros días'],
64
+ never: ['debilidad en las piernas, pérdida de control de esfínteres o de sensibilidad (posible compresión medular)', 'fractura del hueso tratado', SKIN],
65
+ },
66
+ }),
67
+ ZONE_ALIASES: Object.freeze({
68
+ prostata: 'pelvis masculina',
69
+ recto: 'pelvis',
70
+ vejiga: 'pelvis',
71
+ cervix: 'pelvis femenina',
72
+ cervicouterino: 'pelvis femenina',
73
+ endometrio: 'pelvis femenina',
74
+ utero: 'pelvis femenina',
75
+ vulva: 'pelvis femenina',
76
+ vagina: 'pelvis femenina',
77
+ laringe: 'cabeza y cuello',
78
+ orofaringe: 'cabeza y cuello',
79
+ nasofaringe: 'cabeza y cuello',
80
+ 'cavidad oral': 'cabeza y cuello',
81
+ esofago: 'torax',
82
+ pulmon: 'torax',
83
+ cerebro: 'cerebro holocraneal',
84
+ holocraneal: 'cerebro holocraneal',
85
+ }),
86
+ });
87
+
88
+ const PHASE = Object.freeze({
89
+ PLANNED: 'planeada',
90
+ START_UNCONFIRMED: 'inicio_por_confirmar',
91
+ ACTIVE: 'en_curso',
92
+ RECENT: 'terminada',
93
+ HISTORY: 'antecedente',
94
+ UNCONFIRMED: 'por_confirmar',
95
+ UNKNOWN: 'sin_fechas',
96
+ });
97
+ const SERVICE_ORIGIN = 'servicio_radioterapia';
98
+ const WORKDAYS_PER_WEEK = 5;
99
+ const STATUS_ALIASES = Object.freeze({
100
+ completed: 'completed', completado: 'completed', terminada: 'completed',
101
+ active: 'active', ongoing: 'active', 'en curso': 'active',
102
+ planned: 'planned', planificado: 'planned', planeada: 'planned',
103
+ });
104
+ const SRS_TECHNIQUE = /radiocirug|\bsrs\b|\bsbrt\b|estereot/i;
105
+ const HEADER = 'Radioterapia';
106
+ const BRAIN_KIND = Object.freeze({
107
+ radiocirugia: ' (radiocirugía)',
108
+ 'cerebro sin tecnica': ` (tipo de tratamiento no registrado; con ${RT_DRAFT.SRS_MAX_FRACTIONS} sesiones o menos puede ser radiocirugía u holocraneal)`,
109
+ });
110
+
111
+ const fold = (text) => foldAccents(text).trim().toLowerCase();
112
+ const isDay = (value) => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
113
+ const isWorkday = (day) => ![0, 6].includes(new Date(`${day}T00:00:00Z`).getUTCDay());
114
+
115
+ function shiftWorkdays(day, count) {
116
+ const step = count < 0 ? -1 : 1;
117
+ let at = day;
118
+ for (let left = Math.abs(count); left > 0;) {
119
+ at = addDays(at, step);
120
+ if (isWorkday(at)) left -= 1;
121
+ }
122
+ return at;
123
+ }
124
+
125
+ function workdaysThrough(from, to) {
126
+ let count = 0;
127
+ for (let at = from; at <= to; at = addDays(at, 1)) if (isWorkday(at)) count += 1;
128
+ return count;
129
+ }
130
+
131
+ const normalizeStatus = (status) => STATUS_ALIASES[fold(status)] || null;
132
+
133
+ function courseFromEntry(entry) {
134
+ const sesiones = Number(entry.sessions_planned ?? entry.fractions_planned);
135
+ return {
136
+ inicio: isDay(entry.start_date) ? entry.start_date : null,
137
+ fin: isDay(entry.end_date) ? entry.end_date : null,
138
+ sesiones: Number.isInteger(sesiones) && sesiones > 0 ? sesiones : null,
139
+ estado: normalizeStatus(entry.status),
140
+ tecnica: typeof entry.technique === 'string' ? entry.technique : null,
141
+ };
142
+ }
143
+
144
+ function courseFromFact(fact) {
145
+ const normalized = safeParse(fact?.normalized_value) || {};
146
+ const entry = (Array.isArray(normalized.add) ? normalized.add : []).find((item) => item?.start_date || item?.end_date || item?.status);
147
+ return entry ? courseFromEntry(entry) : null;
148
+ }
149
+
150
+ const originOf = (fact) => safeParse(fact?.normalized_value)?.origin || null;
151
+
152
+ // the unit's register wins over facts extracted from conversation; newest report first within each
153
+ function latestCourse(facts) {
154
+ const rows = (Array.isArray(facts) ? facts : []).filter(Boolean);
155
+ if (!rows.length) return null;
156
+ const newest = (a, b) => String(b.report_date ?? '').localeCompare(String(a.report_date ?? ''));
157
+ const service = rows.filter((fact) => originOf(fact) === SERVICE_ORIGIN).sort(newest);
158
+ return courseFromFact((service.length ? service : [...rows].sort(newest))[0]);
159
+ }
160
+
161
+ function zoneProfile(zona, curso) {
162
+ if (!zona) return null;
163
+ const key = fold(zona);
164
+ let canonical = RT_DRAFT.ZONES[key] ? key : RT_DRAFT.ZONE_ALIASES[key] || null;
165
+ if (canonical === 'cerebro holocraneal' && SRS_TECHNIQUE.test(curso?.tecnica || '')) canonical = 'radiocirugia';
166
+ else if (canonical === 'cerebro holocraneal' && curso?.sesiones && curso.sesiones <= RT_DRAFT.SRS_MAX_FRACTIONS) canonical = 'cerebro sin tecnica';
167
+ return canonical ? { key: canonical, ...RT_DRAFT.ZONES[canonical] } : { key: null, unrecognized: true };
168
+ }
169
+
170
+ function phaseOf(curso, today) {
171
+ const { sesiones, estado } = curso;
172
+ let { inicio } = curso;
173
+ const { fin } = curso;
174
+ if (!inicio && fin && sesiones) inicio = shiftWorkdays(fin, -(sesiones - 1));
175
+ if (inicio && today < inicio) return { phase: PHASE.PLANNED, inicio };
176
+ if (!inicio && !fin) return { phase: estado === 'planned' ? PHASE.PLANNED : PHASE.UNKNOWN };
177
+ if (estado === 'planned') return { phase: PHASE.START_UNCONFIRMED, inicio };
178
+ const finEstimado = !fin && inicio && sesiones ? shiftWorkdays(inicio, sesiones - 1) : null;
179
+ const end = fin || finEstimado;
180
+ if (!end) return { phase: PHASE.UNCONFIRMED, inicio, sinceStart: daysBetween(inicio, today) };
181
+ const estimated = Boolean(finEstimado);
182
+ const graceEnd = estimated && estado !== 'completed' ? addDays(end, RT_DRAFT.STALE_DAYS) : end;
183
+ if (today <= graceEnd) return { phase: PHASE.ACTIVE, inicio, end, estimated };
184
+ const days = daysBetween(end, today);
185
+ if (estimated && estado !== 'completed') return { phase: PHASE.UNCONFIRMED, end, days };
186
+ return { phase: days > RT_DRAFT.ACUTE_DAYS ? PHASE.HISTORY : PHASE.RECENT, end, days, estimated };
187
+ }
188
+
189
+ function phaseLine(state, sesiones) {
190
+ const estimated = state.estimated ? ' estimado (±1–2 semanas)' : '';
191
+ switch (state.phase) {
192
+ case PHASE.PLANNED:
193
+ return `Fase: planeada${state.inicio ? `, inicio previsto el ${formatDmy(state.inicio)}` : ''}. Aún no hay síntomas esperables por la radioterapia.`;
194
+ case PHASE.START_UNCONFIRMED:
195
+ return `Fase: inicio por confirmar: el inicio previsto (${formatDmy(state.inicio)}) ya pasó, pero no hay registro de que haya empezado. No se sabe si recibió radioterapia.`;
196
+ case PHASE.ACTIVE: {
197
+ const total = sesiones ? Math.ceil(sesiones / WORKDAYS_PER_WEEK) : null;
198
+ const elapsed = state.inicio ? Math.max(1, Math.ceil(workdaysThrough(state.inicio, state.today) / WORKDAYS_PER_WEEK)) : null;
199
+ const week = elapsed ? `, semana ~${total ? Math.min(elapsed, total) : elapsed}${total ? ` de ~${total}` : ''}` : '';
200
+ return `Fase: en curso${week}; fin${estimated} el ${formatDmy(state.end)}. ${week ? 'La sesión exacta no se conoce, solo la semana aproximada.' : 'No se conoce la semana del curso.'}`;
201
+ }
202
+ case PHASE.RECENT:
203
+ return `Fase: terminó hace ${state.days} días (fin${estimated} el ${formatDmy(state.end)}); ventana aguda hasta el ${formatDmy(addDays(state.end, RT_DRAFT.ACUTE_DAYS))} (fin + ${RT_DRAFT.ACUTE_DAYS} días). Ya no está en tratamiento de radioterapia.`;
204
+ case PHASE.HISTORY:
205
+ return `Fase: antecedente: terminó hace ${state.days} días (más de ${RT_DRAFT.ACUTE_DAYS}). ${RT_DRAFT.SEQUELAE} Un síntoma de la zona nuevo, que regresa o que empeora ya no se explica como efecto agudo: puede ser un efecto tardío o algo nuevo que el equipo no conoce.`;
206
+ case PHASE.UNCONFIRMED:
207
+ return state.end
208
+ ? `Fase: estado por confirmar: el fin estimado (${formatDmy(state.end)}, ±1–2 semanas) pasó hace ${state.days} días sin registro de término. No se sabe si ya terminó.`
209
+ : `Fase: estado por confirmar: inició el ${formatDmy(state.inicio)}, sin fin ni número de sesiones registrados. No se sabe si sigue en curso ni cuándo terminó.`;
210
+ default:
211
+ return 'Fase: sin fechas del curso registradas.';
212
+ }
213
+ }
214
+
215
+ function inAcuteWindow(state) {
216
+ if ([PHASE.ACTIVE, PHASE.RECENT].includes(state.phase)) return true;
217
+ if (state.phase !== PHASE.UNCONFIRMED) return false;
218
+ return state.end ? state.days <= RT_DRAFT.ACUTE_DAYS : state.sinceStart <= RT_DRAFT.ACUTE_DAYS;
219
+ }
220
+
221
+ const isSrsEarly = (state) => state.phase === PHASE.ACTIVE || (state.phase === PHASE.RECENT && state.days <= RT_DRAFT.SRS_EARLY_DAYS);
222
+
223
+ function courseLine(curso) {
224
+ const parts = [curso.tecnica, curso.sesiones && `${curso.sesiones} ${curso.sesiones === 1 ? 'sesión' : 'sesiones'}`,
225
+ curso.inicio && `inicio ${formatDmy(curso.inicio)}`, curso.fin && `fin ${formatDmy(curso.fin)}`].filter(Boolean);
226
+ return parts.length ? `Curso registrado: ${parts.join(', ')}.` : null;
227
+ }
228
+
229
+ const UNKNOWN_ZONE = 'sin zona confirmada no se sabe qué síntomas explica la radioterapia.';
230
+
231
+ function zoneLine(zona, confirmada, profile) {
232
+ if (!zona) return `Zona tratada: no registrada; ${UNKNOWN_ZONE}`;
233
+ if (profile.unrecognized) return `Zona tratada: ${zona} (zona no reconocida); solo aplican los datos generales.`;
234
+ const kind = BRAIN_KIND[profile.key] || '';
235
+ return confirmada ? `Zona tratada: ${zona}${kind}.` : `Zona tratada: ${zona}${kind} (sin confirmar por el médico); ${UNKNOWN_ZONE}`;
236
+ }
237
+
238
+ function expectedFor(profile, confirmada, state) {
239
+ const zone = confirmada && profile && !profile.unrecognized ? [
240
+ ...(profile.expected || []),
241
+ ...(state.phase === PHASE.ACTIVE ? profile.activeOnly || [] : []),
242
+ ...(isSrsEarly(state) ? profile.earlyExpected || [] : []),
243
+ ] : [];
244
+ return [...RT_DRAFT.GENERAL_EXPECTED, ...zone];
245
+ }
246
+
247
+ function renderRadiotherapyBlock({ zona = null, confirmada = false, curso = null, now = Date.now() } = {}) {
248
+ const zone = typeof zona === 'string' && zona.trim() ? zona.trim() : null;
249
+ if (!zone && !curso) return '';
250
+ const today = mexicoDay(new Date(now));
251
+ const profile = zoneProfile(zone, curso);
252
+ const state = { ...phaseOf(curso || {}, today), today };
253
+ const acute = inAcuteWindow(state);
254
+ const history = state.phase === PHASE.HISTORY;
255
+ const never = [...RT_DRAFT.NEVER_EXPECTED, ...(profile?.never || []), ...(history ? profile?.late || [] : [])];
256
+ const lines = [
257
+ zoneLine(zone, confirmada, profile || {}),
258
+ curso && courseLine(curso),
259
+ phaseLine(state, curso?.sesiones),
260
+ acute && `Esperables en esta fase: ${expectedFor(profile, confirmada, state).join(', ')}.`,
261
+ acute && RT_DRAFT.SEVERITY,
262
+ history && profile?.lateEffects,
263
+ `No se explican por la radioterapia: ${never.join('; ')}.`,
264
+ profile?.pelvic && RT_DRAFT.PELVIC_BLEEDING,
265
+ RT_DRAFT.IMMUNOTHERAPY,
266
+ ].filter(Boolean);
267
+ return `${HEADER}:\n- ${lines.join('\n- ')}`;
268
+ }
269
+
270
+ module.exports = {
271
+ latestCourse, renderRadiotherapyBlock,
272
+ };
package/lib/index.d.ts CHANGED
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
468
468
  lastInboundAt?: string | null;
469
469
  lastOutboundAt?: string | null;
470
470
  lastOutreach?: string | null;
471
- checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
471
+ checkIn?: { type: string; reminderId?: string | null; planId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
473
  exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
@@ -57,6 +57,10 @@ const mexicoDay = (value) => {
57
57
  // whole days from one YYYY-MM-DD day to another
58
58
  const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
59
59
 
60
+ const addDays = (day, days) => new Date(Date.parse(`${day}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
61
+
62
+ const formatDmy = (day) => `${day.slice(8, 10)}/${day.slice(5, 7)}/${day.slice(0, 4)}`;
63
+
60
64
  const mexicoIsoWeek = (value) => {
61
65
  if (value === null || value === undefined || value === '') return null;
62
66
  const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
@@ -101,6 +105,7 @@ const addWorkingMinutes = (start, minutes, { timeZone, days, startHour, endHour
101
105
  };
102
106
 
103
107
  module.exports = {
108
+ addDays,
104
109
  addWorkingMinutes,
105
110
  getCurrentMexicoDateTime,
106
111
  getMexicoDayLabels,
@@ -110,6 +115,7 @@ module.exports = {
110
115
  ageInYears,
111
116
  isoDay,
112
117
  daysBetween,
118
+ formatDmy,
113
119
  mexicoDay,
114
120
  mexicoClock,
115
121
  mexicoIsoWeek,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.76.4",
3
+ "version": "5.76.6",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",