@peopl-health/nexus 6.5.20 → 6.5.22

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.
@@ -42,9 +42,18 @@ function gradeFor(todayGrades, catalog, term) {
42
42
  return key ? todayGrades.get(key) : null;
43
43
  }
44
44
 
45
+ const cardTerms = (element) => [...new Set([
46
+ ...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm),
47
+ ].filter(Boolean))];
48
+
49
+ function cardTodayGrade(element, { catalog, todayGrades }) {
50
+ const grades = cardTerms(element).map((term) => gradeFor(todayGrades, catalog, term)).filter((grade) => grade !== null);
51
+ return grades.length ? Math.max(...grades) : null;
52
+ }
53
+
45
54
  // Every term on the card needs today's grade and a current anchor: on a mixed card the question may be about the other term.
46
55
  function anchorsCover(element, { known, catalog, todayGrades }) {
47
- const terms = [...new Set([...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)].filter(Boolean))];
56
+ const terms = cardTerms(element);
48
57
  if (!terms.length) return false;
49
58
  return terms.every((term) => {
50
59
  const todayGrade = gradeFor(todayGrades, catalog, term);
@@ -70,4 +79,4 @@ function dropKnownFunctionalAsks(elements, { known, catalog, todayGrades } = {},
70
79
  return dropped;
71
80
  }
72
81
 
73
- module.exports = { asksFunctionalImpact, dropKnownFunctionalAsks, todayGradesByTerm };
82
+ module.exports = { asksFunctionalImpact, cardTodayGrade, dropKnownFunctionalAsks, todayGradesByTerm };
@@ -1,6 +1,7 @@
1
1
  const { recommendationId } = require('../../fhir/helpers/recommendationIds');
2
+ const { cardTodayGrade } = require('./knownCharacterizationHelper');
2
3
 
3
- function buildLegacyRecommendations({ plan, gate = null }) {
4
+ function buildLegacyRecommendations({ plan, gate = null, grades = { todayGrades: new Map() } }) {
4
5
  const ranked = [...plan.elements].sort((a, b) => a.rank - b.rank);
5
6
  return ranked.map((element) => {
6
7
  const { patient } = element.recommendation;
@@ -27,6 +28,8 @@ function buildLegacyRecommendations({ plan, gate = null }) {
27
28
  urgent_under_24h: isUrgent,
28
29
  // Gate enum only; element routes carry the palliative vocabulary.
29
30
  escalation_route: isUrgent ? (gate?.escalationRoute ?? null) : null,
31
+ // The Airtable triage directive opens on the highest-grade card.
32
+ max_reported_grade: cardTodayGrade(element, grades),
30
33
  };
31
34
  });
32
35
  }
@@ -85,7 +88,7 @@ function buildLegacyStep2(plan) {
85
88
  }
86
89
 
87
90
  // The explode trigger REGEX_EXTRACTs `recommendations` end-anchored: it must stay the last key.
88
- function buildLegacyStep3({ plan, gate = null }) {
91
+ function buildLegacyStep3({ plan, gate = null, grades }) {
89
92
  return {
90
93
  step3_careplan: {
91
94
  careplan_takeaways: {
@@ -94,7 +97,7 @@ function buildLegacyStep3({ plan, gate = null }) {
94
97
  careplan_summary_patient_facing: plan.takeaways.summaryPatientFacing,
95
98
  careplan_summary_internal: plan.takeaways.summaryInternal,
96
99
  },
97
- recommendations: buildLegacyRecommendations({ plan, gate }),
100
+ recommendations: buildLegacyRecommendations({ plan, gate, grades }),
98
101
  },
99
102
  };
100
103
  }
@@ -694,7 +694,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
694
694
  triageRecordId: payload.triageRecordId,
695
695
  step1: buildLegacyStep1(gate),
696
696
  step2: buildLegacyStep2(plan),
697
- step3: buildLegacyStep3({ plan, gate }),
697
+ step3: buildLegacyStep3({ plan, gate, grades: { catalog, todayGrades: boundary.todayGrades } }),
698
698
  };
699
699
  return finish({ status: 'success', reason: null }, mirrorPayload);
700
700
  } catch (err) {
@@ -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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.20",
3
+ "version": "6.5.22",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",