@peopl-health/nexus 6.5.21 → 6.5.23

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.
@@ -13,6 +13,8 @@ const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
14
14
  const { logger } = require('../../utils/logger');
15
15
 
16
+ const ABSENT_ONLY_IF_DENIED = 'Escribe como ausente solo lo que el paciente negó cuando se le preguntó por eso en este episodio; lo que nadie preguntó va como «no preguntado» ("debilidad en piernas: no preguntado"), nunca como «sin debilidad» ni «descartado». Los equipos y los borradores leen tu texto como dato del paciente. ';
17
+
16
18
  const FEVER_RUBRIC_STAT = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
17
19
 
18
20
  const FEVER_RUBRIC_ASAP = 'fiebre ≥38.0 °C, o temperatura baja (menos de 36.0 °C) confirmada al volver a medir con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
@@ -64,7 +66,7 @@ const definition = {
64
66
  'urgency_justification': {
65
67
  'type': 'string',
66
68
  'description': 'Por qué ESTE nivel — y explícitamente por qué no el inmediato superior ni el inferior (qué dato objetivo define el tier). Es el registro auditable de la decisión. Una o dos frases. INTERNO; el paciente nunca lo ve. '
67
- + MEDICATION_NAMING_RULE
69
+ + ABSENT_ONLY_IF_DENIED + MEDICATION_NAMING_RULE
68
70
  },
69
71
  'details': {
70
72
  'type': 'object',
@@ -116,7 +118,7 @@ const definition = {
116
118
  'anyOf': [
117
119
  {
118
120
  'type': 'string',
119
- 'description': 'Sospecha operativa interna para triage. NUNCA se menciona al paciente.'
121
+ 'description': 'Sospecha operativa interna para triage. NUNCA se menciona al paciente. ' + ABSENT_ONLY_IF_DENIED
120
122
  },
121
123
  {
122
124
  'type': 'null'
@@ -4,10 +4,12 @@ const { handle24HourWindowError } = require('./templateRecoveryHelper');
4
4
  const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
5
5
 
6
6
  const BLOCKED_DELIVERY = { name: 'blocked_delivery', handle: handleBlockedDelivery };
7
+ const CONTENT_RETRY = { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) };
7
8
 
8
9
  const CHANNEL_ERROR_STRATEGIES = {
9
10
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
10
- 63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) },
11
+ 63007: CONTENT_RETRY,
12
+ 63021: CONTENT_RETRY,
11
13
  63032: BLOCKED_DELIVERY,
12
14
  63049: BLOCKED_DELIVERY
13
15
  };
@@ -7,6 +7,7 @@ const { isAtOrBefore } = require('../utils/dateUtils');
7
7
  const { Message } = require('../models/messageModel');
8
8
  const { ScheduledMessage } = require('../models/agendaMessageModel');
9
9
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
10
+ const { freeformRetryBlockedReason } = require('../services/channelRetryService');
10
11
  const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
11
12
  const { closeExpiredRecovery, fixedTemplateFor, recoverySendData } = require('./templateRecoveryHelper');
12
13
  const { patientIsDeceased } = require('./pausedThreadHelper');
@@ -17,6 +18,7 @@ const getMessaging = () => require('../core/NexusMessaging');
17
18
 
18
19
  const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
19
20
 
21
+ const FREEFORM_RETRYABLE_CODES = new Set(['63007']);
20
22
  const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
21
23
  const SIGNED_MEDIA_PATH = /^\d+\/\d+\/(\d{13})\//;
22
24
 
@@ -79,7 +81,7 @@ function earliestMediaExpiry(variables) {
79
81
  }
80
82
 
81
83
  function alertUndeliverable(payload) {
82
- logger.error('[ChannelRetry] Message undeliverable, no retries left', payload);
84
+ logger.error('[ChannelRetry] Message undeliverable, not retrying', payload);
83
85
  try {
84
86
  const eventBus = getMessaging().getEventBus();
85
87
  safeEmit(eventBus, 'message:undeliverable', createEvent('message:undeliverable', payload));
@@ -88,24 +90,44 @@ function alertUndeliverable(payload) {
88
90
  }
89
91
  }
90
92
 
91
- async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
92
- const messageId = messageDoc?._id;
93
- const code = messageDoc?.numero;
94
- if (!messageId || !code) return { retried: false, reason: 'incomplete_message' };
93
+ async function scheduleRetry(messageDoc, retry, logCtx) {
94
+ const scheduled = await ScheduledMessage.create({
95
+ code: messageDoc.numero,
96
+ ...retry,
97
+ parentMessageId: messageDoc._id,
98
+ triggeredBy: 'channel_retry',
99
+ expiresAt: messageDoc.expiresAt
100
+ });
95
101
 
96
- const logCtx = { twilioSid, errorCode, messageId: String(messageId) };
102
+ try {
103
+ await getMessaging().sendScheduledMessage(scheduled);
104
+ } catch (err) {
105
+ await ScheduledMessage.deleteOne({ _id: scheduled._id }).catch(cleanupErr =>
106
+ logger.error('[ChannelRetry] Could not remove the unqueued retry', {
107
+ ...logCtx, scheduledMessageId: String(scheduled._id), error: cleanupErr.message
108
+ })
109
+ );
110
+ alertUndeliverable({ ...logCtx, reason: 'enqueue_failed', error: err.message });
111
+ return null;
112
+ }
113
+ return scheduled;
114
+ }
97
115
 
98
- const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'contentSid variables').lean();
116
+ async function expiresBeforeRetry(messageDoc, delay, logCtx) {
117
+ if (!isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) return false;
118
+ logger.info('[ChannelRetry] Message expires before the retry, skipping', { ...logCtx, expiresAt: messageDoc.expiresAt });
119
+ await closeExpiredRecovery(messageDoc);
120
+ return true;
121
+ }
99
122
 
100
- if (!attempt?.contentSid) {
101
- logger.info('[ChannelRetry] Not a template send, skipping retry', logCtx);
102
- return { retried: false, reason: 'not_a_template' };
103
- }
123
+ async function retryTemplate(messageDoc, attempt, logCtx) {
124
+ const messageId = messageDoc._id;
125
+ logCtx = { ...logCtx, contentSid: attempt.contentSid };
104
126
 
105
127
  // An attempt written before the variables field existed omits the key entirely, and there the
106
128
  // payload is genuinely unknown. A recorded null means the send carried no contentVariables.
107
129
  if (!Object.prototype.hasOwnProperty.call(attempt, 'variables')) {
108
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, reason: 'variables_not_recorded' });
130
+ alertUndeliverable({ ...logCtx, reason: 'variables_not_recorded' });
109
131
  return { retried: false, reason: 'variables_not_recorded' };
110
132
  }
111
133
 
@@ -122,14 +144,10 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
122
144
  : await DeliveryAttempt.countDocuments({ messageId, kind: 'template' });
123
145
  const delay = retryDelays()[priorAttempts - 1];
124
146
 
125
- if (isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) {
126
- logger.info('[ChannelRetry] Message expires before the retry, skipping', { ...logCtx, expiresAt: messageDoc.expiresAt });
127
- await closeExpiredRecovery(messageDoc);
128
- return { retried: false, reason: 'expires_before_retry' };
129
- }
147
+ if (await expiresBeforeRetry(messageDoc, delay, logCtx)) return { retried: false, reason: 'expires_before_retry' };
130
148
 
131
149
  if (delay === undefined) {
132
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, attempts: priorAttempts, reason: 'max_attempts' });
150
+ alertUndeliverable({ ...logCtx, attempts: priorAttempts, reason: 'max_attempts' });
133
151
  return { retried: false, reason: 'max_attempts' };
134
152
  }
135
153
 
@@ -138,39 +156,86 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
138
156
 
139
157
  if (mediaExpiry !== null && mediaExpiry <= sendTime.getTime()) {
140
158
  alertUndeliverable({
141
- ...logCtx, contentSid: attempt.contentSid, reason: 'media_expires_before_retry',
159
+ ...logCtx, reason: 'media_expires_before_retry',
142
160
  mediaExpiry: new Date(mediaExpiry).toISOString(), sendTime: sendTime.toISOString()
143
161
  });
144
162
  return { retried: false, reason: 'media_expires_before_retry' };
145
163
  }
146
164
 
147
- const scheduled = await ScheduledMessage.create({
148
- code,
149
- contentSid: attempt.contentSid,
150
- variables,
151
- sendTime,
152
- parentMessageId: messageId,
153
- triggeredBy: 'channel_retry',
154
- expiresAt: messageDoc.expiresAt
155
- });
165
+ const scheduled = await scheduleRetry(messageDoc, { contentSid: attempt.contentSid, variables, sendTime }, logCtx);
166
+ if (!scheduled) return { retried: false, reason: 'enqueue_failed' };
156
167
 
157
- try {
158
- await getMessaging().sendScheduledMessage(scheduled);
159
- } catch (err) {
160
- await ScheduledMessage.deleteOne({ _id: scheduled._id }).catch(cleanupErr =>
161
- logger.error('[ChannelRetry] Could not remove the unqueued retry', {
162
- ...logCtx, scheduledMessageId: String(scheduled._id), error: cleanupErr.message
163
- })
164
- );
165
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, reason: 'enqueue_failed', error: err.message });
166
- return { retried: false, reason: 'enqueue_failed' };
168
+ logger.warn('[ChannelRetry] Retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
169
+ return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
170
+ }
171
+
172
+ const hasMedia = media => Boolean(media && Object.values(media).some(value => value != null));
173
+
174
+ async function retryFreeform(messageDoc, attempt, logCtx) {
175
+ if (hasMedia(messageDoc.media)) {
176
+ alertUndeliverable({ ...logCtx, reason: 'media_not_recorded' });
177
+ return { retried: false, reason: 'media_not_recorded' };
167
178
  }
168
179
 
169
- logger.warn('[ChannelRetry] Retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
180
+ if (!attempt.body) {
181
+ alertUndeliverable({ ...logCtx, reason: 'body_not_recorded' });
182
+ return { retried: false, reason: 'body_not_recorded' };
183
+ }
184
+
185
+ if (!messageDoc.createdAt) return { retried: false, reason: 'incomplete_message' };
186
+
187
+ if (await DeliveryAttempt.exists({ messageId: messageDoc._id, kind: 'freeform', body: { $ne: attempt.body } })) {
188
+ alertUndeliverable({ ...logCtx, reason: 'chunked_message' });
189
+ return { retried: false, reason: 'chunked_message' };
190
+ }
191
+
192
+ const blocked = await freeformRetryBlockedReason(messageDoc, attempt.body);
193
+ if (blocked === 'already_sent') {
194
+ logger.info('[ChannelRetry] Same text already landed for this number, skipping retry', logCtx);
195
+ return { retried: false, reason: blocked };
196
+ }
197
+ if (blocked) {
198
+ alertUndeliverable({ ...logCtx, reason: blocked });
199
+ return { retried: false, reason: blocked };
200
+ }
201
+
202
+ const priorAttempts = await DeliveryAttempt.countDocuments({ messageId: messageDoc._id, kind: 'freeform', body: attempt.body });
203
+ const delay = retryDelays()[priorAttempts - 1];
204
+
205
+ if (await expiresBeforeRetry(messageDoc, delay, logCtx)) return { retried: false, reason: 'expires_before_retry' };
170
206
 
207
+ if (delay === undefined) {
208
+ alertUndeliverable({ ...logCtx, attempts: priorAttempts, reason: 'max_attempts' });
209
+ return { retried: false, reason: 'max_attempts' };
210
+ }
211
+
212
+ const scheduled = await scheduleRetry(messageDoc, { message: attempt.body, sendTime: new Date(Date.now() + delay) }, logCtx);
213
+ if (!scheduled) return { retried: false, reason: 'enqueue_failed' };
214
+
215
+ logger.warn('[ChannelRetry] Freeform retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
171
216
  return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
172
217
  }
173
218
 
219
+ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
220
+ const messageId = messageDoc?._id;
221
+ if (!messageId || !messageDoc?.numero) return { retried: false, reason: 'incomplete_message' };
222
+
223
+ const logCtx = { twilioSid, errorCode, messageId: String(messageId) };
224
+
225
+ if (messageDoc.contact_code) {
226
+ alertUndeliverable({ ...logCtx, reason: 'caregiver_recipient' });
227
+ return { retried: false, reason: 'caregiver_recipient' };
228
+ }
229
+
230
+ const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'kind contentSid variables body').lean();
231
+
232
+ if (attempt?.contentSid) return retryTemplate(messageDoc, attempt, logCtx);
233
+ if (attempt?.kind === 'freeform' && FREEFORM_RETRYABLE_CODES.has(String(errorCode))) return retryFreeform(messageDoc, attempt, logCtx);
234
+
235
+ logger.info('[ChannelRetry] No retryable attempt recorded, skipping retry', logCtx);
236
+ return { retried: false, reason: 'not_retryable' };
237
+ }
238
+
174
239
  async function reportBlockedDelivery(messageDoc, logCtx) {
175
240
  alertUndeliverable({ ...logCtx, reason: 'blocked_by_meta' });
176
241
  const sender = isStaffSend(messageDoc.triggeredBy) ? `de ${messageDoc.triggeredBy}` : 'del asistente';
@@ -1,6 +1,8 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { isRetryableError } = require('../utils/retryUtils');
3
3
  const { ScheduledMessage } = require('../models/agendaMessageModel');
4
+ const { alertUndeliverable } = require('../helpers/channelRetryHelper');
5
+ const { scheduledRetryBlockedReason } = require('../services/channelRetryService');
4
6
  const { BaseJob } = require('./BaseJob');
5
7
 
6
8
  const QUEUE_NAME = 'scheduled-messages';
@@ -63,6 +65,20 @@ class ScheduledMessageJob extends BaseJob {
63
65
  return `scheduled-msg-${scheduledMessageId}`;
64
66
  }
65
67
 
68
+ async _cancelUnwantedRetry(msg) {
69
+ const reason = await scheduledRetryBlockedReason(msg);
70
+ if (!reason) return null;
71
+ await ScheduledMessage.updateOne(
72
+ { _id: msg._id },
73
+ { $set: { status: 'cancelled', errorCode: reason, errorMessage: 'Channel retry no longer wanted' } }
74
+ );
75
+ logger.info('[ScheduledMessageJob] Channel retry cancelled', { scheduledMessageId: String(msg._id), reason });
76
+ if (reason !== 'already_sent') {
77
+ alertUndeliverable({ scheduledMessageId: String(msg._id), messageId: String(msg.parentMessageId), code: msg.code, reason });
78
+ }
79
+ return { success: false, reason };
80
+ }
81
+
66
82
  async _process({ scheduledMessageId }) {
67
83
  const msg = await ScheduledMessage.findById(scheduledMessageId);
68
84
 
@@ -99,6 +115,11 @@ class ScheduledMessageJob extends BaseJob {
99
115
  }
100
116
 
101
117
  try {
118
+ if (msg.triggeredBy === 'channel_retry' && msg.message && !msg.contentSid) {
119
+ const cancelled = await this._cancelUnwantedRetry(msg);
120
+ if (cancelled) return cancelled;
121
+ }
122
+
102
123
  const parentMessageId = msg.parentMessageId || null;
103
124
 
104
125
  const result = await this.sendMessage({
@@ -0,0 +1,45 @@
1
+ const { Message } = require('../models/messageModel');
2
+ const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
3
+ const { botIsPaused } = require('../helpers/pausedThreadHelper');
4
+
5
+ async function freeformLandedElsewhere(messageDoc, body) {
6
+ const siblingMessages = await Message.find({
7
+ numero: messageDoc.numero,
8
+ _id: { $ne: messageDoc._id },
9
+ createdAt: { $gte: messageDoc.createdAt },
10
+ 'statusInfo.status': { $in: LANDED_STATUSES }
11
+ }, '_id').lean();
12
+
13
+ const landed = await DeliveryAttempt.findOne({
14
+ kind: 'freeform',
15
+ status: { $in: LANDED_STATUSES },
16
+ body,
17
+ messageId: { $in: [messageDoc._id, ...siblingMessages.map(m => m._id)] }
18
+ }, '_id').lean();
19
+
20
+ return Boolean(landed);
21
+ }
22
+
23
+ async function patientWroteSince(messageDoc) {
24
+ const inbound = await Message.findOne({
25
+ numero: messageDoc.numero,
26
+ from_me: false,
27
+ createdAt: { $gt: messageDoc.createdAt }
28
+ }, '_id').lean();
29
+ return Boolean(inbound);
30
+ }
31
+
32
+ async function freeformRetryBlockedReason(messageDoc, body) {
33
+ if (await freeformLandedElsewhere(messageDoc, body)) return 'already_sent';
34
+ if (await patientWroteSince(messageDoc)) return 'superseded_by_patient';
35
+ if (messageDoc.origin === 'assistant' && await botIsPaused(messageDoc.numero, { label: '[ChannelRetry]' })) return 'bot_paused';
36
+ return null;
37
+ }
38
+
39
+ async function scheduledRetryBlockedReason(scheduled) {
40
+ const parent = await Message.findById(scheduled.parentMessageId).lean();
41
+ if (!parent?.createdAt) return 'parent_missing';
42
+ return freeformRetryBlockedReason(parent, scheduled.message);
43
+ }
44
+
45
+ module.exports = { freeformRetryBlockedReason, scheduledRetryBlockedReason };
@@ -22,7 +22,8 @@ const LEVEL_LABELS = { asap: 'ASAP', urgent: 'URGENT' };
22
22
  const HANDOFF_RETRY_MS = 10 * 60 * 1000;
23
23
  const MAX_HANDOFF_ATTEMPTS = 4;
24
24
  const MAX_NOTE_LENGTH = 200;
25
- const UPDATE_NOTE = 'Actualización: la paciente contestó';
25
+ // A redraft also follows a call note or the agent's own update, so the note does not say the patient answered.
26
+ const UPDATE_NOTE = 'Actualización del caso';
26
27
  const GRAVE_RETRY_MS = 5 * 60 * 1000;
27
28
  const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó', not_said: 'no lo ha dicho' };
28
29
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
@@ -63,8 +64,8 @@ function teamGraveOf(review, clock, grave, now) {
63
64
  .filter((ask) => timeOf(ask.draftAt) >= timeOf(firstSeenAt) && (ask.flags ?? []).map(normalizedKeyOf).includes(flag))
64
65
  .map((ask) => timeOf(ask.sentAt)),
65
66
  );
66
- const dueAt = (entry) => (entry.reason === 'unobtainable' ? -Infinity : askedAt(entry) + waitMs);
67
- // A datum the bot never asked about calls no one: it reaches the doctor in the note.
67
+ const dueAt = (entry) => (entry.reason === 'unobtainable' ? Infinity : askedAt(entry) + waitMs);
68
+ // A datum the bot never asked about, or one the patient cannot give, calls no one: it reaches the doctor in the note.
68
69
  const asked = grave.filter((entry) => dueAt(entry) < Infinity);
69
70
  if (asked.some((entry) => dueAt(entry) <= now.getTime())) return { due: asked, waiting: [] };
70
71
  return { due: [], waiting: asked };
@@ -112,7 +113,7 @@ function outcomeOf(review, clock, now) {
112
113
  const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
113
114
  const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
114
115
  if (graveFlags.length || present.length) {
115
- const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
+ const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag, reason }) => (reason === 'unobtainable' ? `${flag} (${GRAVE_REASONS.unobtainable})` : flag)).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
117
  // A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
117
118
  const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !graveFlags.some((entry) => entry.flag === flag));
118
119
  const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, lacking, pending.length && `Pendiente: ${pending.join(', ')}`];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.21",
3
+ "version": "6.5.23",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",