@peopl-health/nexus 6.5.17 → 6.5.19

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.
@@ -104,10 +104,10 @@ function regimenText(context) {
104
104
 
105
105
  function statusLine(last, active, days) {
106
106
  const cycle = [last.ciclo ? `ciclo ${last.ciclo}` : '', last.sesion ? `sesión ${last.sesion}${last.total ? `/${last.total}` : ''}` : ''].filter(Boolean).join(', ');
107
- const when = days === null ? `última aplicación registrada ${dmy(last.fecha)}` : `última aplicación ${dmy(last.fecha)} (hace ${days} días)`;
107
+ const when = days === null ? `última aplicación registrada ${weekdayDmy(last.fecha)}` : `última aplicación ${weekdayDmy(last.fecha)} (hace ${days} días)`;
108
108
  return active
109
109
  ? `Estado: en quimioterapia activa; ${when}${cycle ? `, ${cycle}` : ''}`
110
- : `Estado: sin aplicaciones registradas en la unidad desde ${dmy(last.fecha)} (hace ${days} días); confirma con el paciente si sigue en tratamiento`;
110
+ : `Estado: sin aplicaciones registradas en la unidad desde ${weekdayDmy(last.fecha)} (hace ${days} días); confirma con el paciente si sigue en tratamiento`;
111
111
  }
112
112
 
113
113
  function chemoLines(context, today) {
@@ -121,7 +121,7 @@ function chemoLines(context, today) {
121
121
  if (context.vigilancia.length) lines.push(`Vigilar por sus fármacos: ${context.vigilancia.join('; ')}`);
122
122
  if (active && days !== null && context.nadirDias && days <= context.nadirDias[1]) {
123
123
  const [from, to] = context.nadirDias;
124
- lines.push(`Mayor riesgo de defensas bajas: días ${from} a ${to} después de la aplicación (${dmy(addDays(last.fecha, from))} al ${dmy(addDays(last.fecha, to))}); hoy es el día ${days}. Fiebre de 38 °C o más es urgente cualquier día`);
124
+ lines.push(`Mayor riesgo de defensas bajas: días ${from} a ${to} después de la aplicación (${weekdayDmy(addDays(last.fecha, from))} al ${weekdayDmy(addDays(last.fecha, to))}); hoy es el día ${days}. Fiebre de 38 °C o más es urgente cualquier día`);
125
125
  }
126
126
  }
127
127
  if (context.enCasa.length) {
@@ -143,7 +143,7 @@ function chemoLines(context, today) {
143
143
  const care = texts(support.detalle);
144
144
  lines.push(`Próxima visita a la unidad sin quimioterapia: ${weekdayDmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
145
145
  }
146
- if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
146
+ if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(weekdayDmy).join(', ')}`);
147
147
  if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
148
148
  if (context.acceso) lines.push(`Acceso venoso: ${context.acceso}`);
149
149
  if (Number.isFinite(context.peso?.kg)) {
@@ -3,8 +3,7 @@ const { getCurrentMexicoDateTime, getMexicoDayLabels, getMexicoUpcomingDayLabels
3
3
  const ANCHOR_SPAN_DAYS = 7;
4
4
  const UPCOMING_SPAN_DAYS = 14;
5
5
 
6
- function buildDateAnchor() {
7
- const at = Date.now();
6
+ function buildDateAnchor(at = Date.now()) {
8
7
  const labels = getMexicoDayLabels({ days: ANCHOR_SPAN_DAYS, at });
9
8
  const week = labels.map((label, i) => (i === labels.length - 1 ? `${label} (hoy)` : label));
10
9
  const upcoming = getMexicoUpcomingDayLabels({ days: UPCOMING_SPAN_DAYS, at });
@@ -364,7 +364,7 @@ async function recordClinicalIntake({ code, trace, messageRaw, source = 'self',
364
364
  return written;
365
365
  }
366
366
 
367
- async function recordReminder({ code, trace, actionType, reminderId, reminderDateUtc, reminderType, description: rawDescription, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern = null, windowReasoning = null, isLive = null }) {
367
+ async function recordReminder({ code, trace, actionType, reminderId, reminderDateUtc, reminderType, description: rawDescription, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern = null, windowReasoning = null, templateSid = null, templateVariables = null, isLive = null }) {
368
368
  const description = decodeUnicodeEscapes(rawDescription);
369
369
  const type = REMINDER_TYPE_TO_AIRTABLE[reminderType] || reminderType;
370
370
  if (actionType === 'update') {
@@ -416,6 +416,7 @@ async function recordReminder({ code, trace, actionType, reminderId, reminderDat
416
416
  // written once at arm time and never read back into the system, so it cannot feed drift.
417
417
  ...(concern ? { concern } : {}),
418
418
  ...(windowReasoning ? { window_reasoning: windowReasoning } : {}),
419
+ ...(templateSid && templateVariables ? { template_sid: templateSid, template_variables: JSON.stringify(templateVariables) } : {}),
419
420
  },
420
421
  {
421
422
  referenceTable: 'estado_general',
@@ -1,6 +1,7 @@
1
1
  const { getEscalationDraft } = require('../config/subAgentsConfig');
2
2
 
3
3
  const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
4
+ const { buildDateAnchor } = require('../helpers/dateAnchorHelper');
4
5
  const { readStructuredText } = require('../helpers/structuredTextHelper');
5
6
  const { createLLMProvider } = require('../providers/createLLMProvider');
6
7
  const { FORMULARY_VERSION, TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
@@ -9,6 +10,7 @@ const { getEscalationContext } = require('../../services/escalationContextServic
9
10
 
10
11
  const { inlineOf, normalizedKeyOf } = require('../../utils/coercionUtils');
11
12
  const { logger } = require('../../utils/logger');
13
+ const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
12
14
  const { arrayArg, safeParse } = require('../../utils/jsonUtils');
13
15
  const { withTiming } = require('../../utils/tracingDecorator');
14
16
 
@@ -84,7 +86,9 @@ function suggestCallOf(value) {
84
86
  return { value: value.value, reason: trimmed(value.reason) || null };
85
87
  }
86
88
 
87
- function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
89
+ const localStampOf = (at) => (at ? getCurrentMexicoDateTime(at) : null);
90
+
91
+ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null, now = Date.now() }) {
88
92
  const conversation = Array.isArray(context?.conversation)
89
93
  ? context.conversation.slice(-CONVERSATION_TURNS)
90
94
  : context?.conversation ?? null;
@@ -95,8 +99,9 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
95
99
 
96
100
  return {
97
101
  protocolVersion: FORMULARY_VERSION,
102
+ currentDate: buildDateAnchor(now),
98
103
  protocol,
99
- alarms,
104
+ alarms: alarms.map((alarm) => ({ ...alarm, raisedAtLocal: localStampOf(alarm.raisedAt) })),
100
105
  agentCharacterization,
101
106
  patient: {
102
107
  clinicalContext: context?.agentContext ?? null,
@@ -109,6 +114,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
109
114
  outcome: log?.outcome ?? null,
110
115
  notes: trimmed(log?.notes) || null,
111
116
  calledAt: log?.calledAt ?? null,
117
+ calledAtLocal: localStampOf(log?.calledAt),
112
118
  })),
113
119
  sectionsUnavailable: context?.degradedSections ?? [],
114
120
  };
@@ -157,7 +163,7 @@ async function generateEscalationDraft({
157
163
  }
158
164
 
159
165
  const context = await getEscalationContext({ code, now });
160
- const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization });
166
+ const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization, now });
161
167
 
162
168
  // Past this point a generation run was issued. Whether the request actually left the process is
163
169
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -4,6 +4,7 @@ const { logger } = require('../utils/logger');
4
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
6
  const { DEFAULT_TIMEZONE, clampToHourWindow } = require('../utils/scheduleUtils');
7
+ const { getMexicoDayLabel } = require('../utils/dateUtils');
7
8
  const { getEscalationReview } = require('../models/escalationReviewModel');
8
9
  const { recordReminder, cancelFollowUp } = require('../clinical/services/clinicalAirtableService');
9
10
  const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
@@ -24,6 +25,12 @@ const PLAN_EXCERPT = 400;
24
25
  const PATIENT_LABEL_MAX = 40;
25
26
  // The follow-up template the send_reminder automation uses past the 24 h window (Airtable Monitoreo).
26
27
  const FOLLOW_UP_TEMPLATE_SID = 'HX182fee522708bdb43db5ea614f538369';
28
+ // Meta-approved UTILITY templates, by try and by whether she has a label: {{1}} name, {{2}} day she told us, {{3}} label.
29
+ const CASE_TEMPLATES = {
30
+ first: { label: 'HXe9ee7b7cdb018ca78970cd919342de4e', plain: 'HXb079b8c9892d963d1851addcce8b3c6e' },
31
+ retry: { label: 'HXb92572f8516f448c95257b933b123ab0', plain: 'HX6f19d545f6298f97c9d578a62ee2520c' },
32
+ };
33
+ const SENT_TEMPLATE_SIDS = [FOLLOW_UP_TEMPLATE_SID, ...Object.values(CASE_TEMPLATES).flatMap(Object.values)];
27
34
  // send_reminder fires up to 6 min before the row's time.
28
35
  const SEND_LEAD_MS = 10 * 60 * 1000;
29
36
 
@@ -60,6 +67,15 @@ function questionFor(review, attempt) {
60
67
  : 'seguimos pendientes de ti. ¿Cómo sigues?';
61
68
  }
62
69
 
70
+ function templateFor(review, attempt, sendAt) {
71
+ const label = patientLabelOf(review);
72
+ const templates = attempt === 1 ? CASE_TEMPLATES.first : CASE_TEMPLATES.retry;
73
+ return {
74
+ templateSid: label ? templates.label : templates.plain,
75
+ templateVariables: { 2: getMexicoDayLabel(caseAlarmOf(review)?.raisedAt ?? review.createdAt, sendAt), ...(label && { 3: label }) },
76
+ };
77
+ }
78
+
63
79
  function decisionContext(decision) {
64
80
  const what = decision.decision === 'monitor' ? 'el médico indicó vigilarlo en casa' : 'el médico le dio indicaciones';
65
81
  const sent = decision.plan ? oneLineOf(planSummary(decision.plan)) : oneLineOf(decision.finalText);
@@ -95,9 +111,10 @@ async function standDown(code, reminderId, reason) {
95
111
  }
96
112
 
97
113
  async function writeRow(review, caseFollowUp) {
114
+ const template = templateFor(review, caseFollowUp.attempt, caseFollowUp.dueAt);
98
115
  const isRecorded = await recordReminder({
99
116
  code: review.patientCode, trace: null, actionType: 'create', reminderId: caseFollowUp.reminderId, reminderDateUtc: new Date(caseFollowUp.dueAt).toISOString(),
100
- reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
117
+ reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), ...template, expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
101
118
  }).catch((error) => {
102
119
  logger.error('[CaseFollowUp] The follow-up row was not written', { escalationReviewId: String(review._id), error: errorOf(error) });
103
120
  return false;
@@ -185,7 +202,7 @@ async function askedAt(review, now = new Date()) {
185
202
  numero: review.patientCode,
186
203
  from_me: true,
187
204
  createdAt: { $gte: since, $lte: now },
188
- $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: FOLLOW_UP_TEMPLATE_SID }],
205
+ $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: { $in: SENT_TEMPLATE_SIDS } }],
189
206
  },
190
207
  { sort: { createdAt: 1 }, limit: 1, select: 'createdAt' },
191
208
  ) || [];
@@ -8,6 +8,8 @@ const getCurrentMexicoDateTime = (at) => nowInMexico(at).format(MEXICO_STAMP);
8
8
 
9
9
  const dayLabel = (day, now) => (day.year() === now.year() ? day.format('dddd D [de] MMMM') : day.format('dddd D [de] MMMM [de] YYYY'));
10
10
 
11
+ const getMexicoDayLabel = (day, at) => dayLabel(nowInMexico(day), nowInMexico(at));
12
+
11
13
  const getMexicoDayLabels = ({ days, at }) => {
12
14
  const now = nowInMexico(at);
13
15
  const labels = [];
@@ -113,6 +115,7 @@ module.exports = {
113
115
  addDays,
114
116
  addWorkingMinutes,
115
117
  getCurrentMexicoDateTime,
118
+ getMexicoDayLabel,
116
119
  getMexicoDayLabels,
117
120
  getMexicoUpcomingDayLabels,
118
121
  parseDate,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.17",
3
+ "version": "6.5.19",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",