@peopl-health/nexus 6.3.6 → 6.3.7

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,11 +1,15 @@
1
1
  const { logger } = require('../utils/logger');
2
2
 
3
3
  const { handle24HourWindowError } = require('./templateRecoveryHelper');
4
- const { handleRetryableChannelError } = require('./channelRetryHelper');
4
+ const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
5
+
6
+ const BLOCKED_DELIVERY = { name: 'blocked_delivery', handle: handleBlockedDelivery };
5
7
 
6
8
  const CHANNEL_ERROR_STRATEGIES = {
7
9
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
8
- 63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) }
10
+ 63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) },
11
+ 63032: BLOCKED_DELIVERY,
12
+ 63049: BLOCKED_DELIVERY
9
13
  };
10
14
 
11
15
  function resolveChannelErrorStrategy(errorCode) {
@@ -7,10 +7,16 @@ 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 { closeExpiredRecovery } = require('./templateRecoveryHelper');
10
+ const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
11
+ const { closeExpiredRecovery, fixedTemplateFor, recoverySendData } = require('./templateRecoveryHelper');
12
+ const { patientIsDeceased } = require('./pausedThreadHelper');
13
+ const { isStaffSend } = require('./staffSendHelper');
14
+ const { phoneDigits } = require('./whatsappHelper');
11
15
 
12
16
  const getMessaging = () => require('../core/NexusMessaging');
13
17
 
18
+ const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
19
+
14
20
  const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
15
21
  const SIGNED_MEDIA_PATH = /^\d+\/\d+\/(\d{13})\//;
16
22
 
@@ -162,4 +168,60 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
162
168
  return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
163
169
  }
164
170
 
165
- module.exports = { handleRetryableChannelError, alertUndeliverable };
171
+ async function reportBlockedDelivery(messageDoc, logCtx) {
172
+ alertUndeliverable({ ...logCtx, reason: 'blocked_by_meta' });
173
+ const sender = isStaffSend(messageDoc.triggeredBy) ? `de ${messageDoc.triggeredBy}` : 'del asistente';
174
+ const recipient = messageDoc.contact_code ? ` a su cuidador (+${phoneDigits(messageDoc.contact_code)})` : '';
175
+ const written = await recordUnresolvedRequest({
176
+ code: messageDoc.numero,
177
+ trace: null,
178
+ category: 'contact_team_member',
179
+ question: 'Mensaje de WhatsApp no entregado',
180
+ details: formatOpsAlert(messageDoc.numero, {
181
+ label: 'Mensaje no entregado',
182
+ summary: `WhatsApp bloqueó (${logCtx.errorCode}) un mensaje ${sender}${recipient}; hay que llamarle`
183
+ })
184
+ });
185
+ if (written) return { retried: false, reason: 'reported' };
186
+ logger.error('[ChannelRetry] No new ops alert: the write failed or a recent one is still open', logCtx);
187
+ return { retried: false, reason: 'alert_not_written' };
188
+ }
189
+
190
+ async function resendOnFixedTemplate(messageDoc, attempt, logCtx) {
191
+ try {
192
+ const template = await fixedTemplateFor(messageDoc);
193
+ if (!template || template.contentSid === attempt.contentSid) return 'failed';
194
+ const result = await getMessaging().sendMessage({
195
+ ...recoverySendData(messageDoc, template),
196
+ idempotencyKey: `blocked-retry:${messageDoc._id}`
197
+ });
198
+ if (result?.messageId && result.status !== 'failed') return 'sent';
199
+ return REFUSED_ON_PURPOSE.has(result?.status) ? 'refused' : 'failed';
200
+ } catch (err) {
201
+ logger.error('[ChannelRetry] Could not resend the blocked message', { ...logCtx, error: err.message });
202
+ return 'failed';
203
+ }
204
+ }
205
+
206
+ async function handleBlockedDelivery(messageDoc, twilioSid, errorCode) {
207
+ if (messageDoc.origin !== 'assistant' && !isStaffSend(messageDoc.triggeredBy)) return { retried: false, reason: 'not_a_personal_send' };
208
+ if (isAtOrBefore(messageDoc.expiresAt, Date.now())) return { retried: false, reason: 'expired' };
209
+
210
+ const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'kind contentSid').lean();
211
+ if (attempt && attempt.kind !== 'recovery_template') return { retried: false, reason: 'not_a_personal_send' };
212
+
213
+ if (await patientIsDeceased(messageDoc.numero)) return { retried: false, reason: 'patient_deceased' };
214
+
215
+ const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
216
+ const claimed = attempt && (await Message.updateOne(
217
+ { _id: messageDoc._id, 'statusInfo.blockedRetryAt': null },
218
+ { $set: { 'statusInfo.blockedRetryAt': new Date() } }
219
+ )).modifiedCount;
220
+ const outcome = claimed ? await resendOnFixedTemplate(messageDoc, attempt, logCtx) : 'failed';
221
+ if (outcome === 'refused') return { retried: false, reason: 'refused' };
222
+ if (outcome === 'failed') return reportBlockedDelivery(messageDoc, logCtx);
223
+ logger.warn('[ChannelRetry] Blocked by Meta, resent on the fixed template', logCtx);
224
+ return { retried: true, reason: 'fixed_template' };
225
+ }
226
+
227
+ module.exports = { handleBlockedDelivery, handleRetryableChannelError, alertUndeliverable };
@@ -23,6 +23,12 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
23
23
  ...(errorMessage && { 'statusInfo.errorMessage': errorMessage })
24
24
  };
25
25
 
26
+ const attempt = await DeliveryAttempt.findOne({ twilioSid: messageSid }, '_id messageId status').lean();
27
+ if (DELIVERY_ATTEMPT_TERMINAL_STATUSES.includes(attempt?.status)) {
28
+ logger.info('[MessageStatus] Ignoring a callback for a settled attempt', { messageSid, status });
29
+ return null;
30
+ }
31
+
26
32
  const notTerminal = { 'statusInfo.status': { $nin: DELIVERY_ATTEMPT_TERMINAL_STATUSES } };
27
33
 
28
34
  let updated = await Message.findOneAndUpdate(
@@ -32,7 +38,6 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
32
38
  );
33
39
 
34
40
  if (!updated) {
35
- const attempt = await DeliveryAttempt.findOne({ twilioSid: messageSid }, '_id messageId').lean();
36
41
  if (attempt?.messageId) {
37
42
  updated = await Message.findOneAndUpdate(
38
43
  { _id: attempt.messageId, ...notTerminal },
@@ -76,6 +76,7 @@ const messageSchema = new mongoose.Schema({
76
76
  recoveryTemplateSid: { type: String, default: null },
77
77
  recoveryStartedAt: { type: Date, default: null },
78
78
  recoverySentAt: { type: Date, default: null },
79
+ blockedRetryAt: { type: Date, default: null },
79
80
  recoveryRejectedAt: { type: Date, default: null },
80
81
  recoveryFailedAt: { type: Date, default: null },
81
82
  recoveryCheckedAt: { type: Date, default: null },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.3.6",
3
+ "version": "6.3.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",