@peopl-health/nexus 5.56.37 → 5.56.38
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.
|
@@ -4,7 +4,7 @@ const mongoose = require('mongoose');
|
|
|
4
4
|
const { logger } = require('../utils/logger');
|
|
5
5
|
|
|
6
6
|
const { ScheduledMessage } = require('../models/agendaMessageModel.js');
|
|
7
|
-
const { DeliveryAttempt } = require('../models/deliveryAttemptModel.js');
|
|
7
|
+
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
|
|
8
8
|
const { FlowRouting } = require('../models/flowRoutingModel.js');
|
|
9
9
|
|
|
10
10
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
@@ -275,7 +275,7 @@ const checkMessageStatusController = async (req, res) => {
|
|
|
275
275
|
}
|
|
276
276
|
const status = msg.statusInfo?.status;
|
|
277
277
|
const errorCode = msg.statusInfo?.errorCode || null;
|
|
278
|
-
const isSent =
|
|
278
|
+
const isSent = DELIVERY_ATTEMPT_LANDED_STATUSES.includes(status);
|
|
279
279
|
return res.status(200).json({ success: true, sent: isSent, status: status || null, errorCode });
|
|
280
280
|
} catch (error) {
|
|
281
281
|
logger.error('Error checking message status:', { error: error.message });
|
|
@@ -5,13 +5,12 @@ const { createEvent, safeEmit } = require('../utils/eventUtils');
|
|
|
5
5
|
|
|
6
6
|
const { Message } = require('../models/messageModel');
|
|
7
7
|
const { ScheduledMessage } = require('../models/agendaMessageModel');
|
|
8
|
-
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
8
|
+
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
|
|
9
9
|
|
|
10
10
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
11
11
|
|
|
12
12
|
const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
|
|
13
13
|
const SIGNED_MEDIA_PATH = /^\d+\/\d+\/(\d{13})\//;
|
|
14
|
-
const LANDED_STATUSES = ['sent', 'delivered', 'read'];
|
|
15
14
|
|
|
16
15
|
function retryDelays() {
|
|
17
16
|
const override = runtimeConfig.get('CHANNEL_RETRY_DELAYS_MS');
|
|
@@ -3,6 +3,7 @@ const mongoose = require('mongoose');
|
|
|
3
3
|
const KIND_VALUES = ['freeform', 'template', 'recovery_template', 'recovery_template_setup', 'window_reopen_nudge'];
|
|
4
4
|
const STATUS_VALUES = [null, 'queued', 'sending', 'sent', 'delivered', 'undelivered', 'failed', 'read'];
|
|
5
5
|
const TERMINAL_STATUS_VALUES = ['read', 'failed', 'undelivered'];
|
|
6
|
+
const LANDED_STATUS_VALUES = ['sent', 'delivered', 'read'];
|
|
6
7
|
const ERROR_SOURCE_VALUES = [null, 'twilio_sync', 'twilio_async', 'server'];
|
|
7
8
|
|
|
8
9
|
const deliveryAttemptSchema = new mongoose.Schema({
|
|
@@ -40,6 +41,7 @@ const deliveryAttemptSchema = new mongoose.Schema({
|
|
|
40
41
|
deliveryAttemptSchema.index({ messageId: 1, attemptedAt: 1 }, { name: 'message_attempt_history_idx' });
|
|
41
42
|
deliveryAttemptSchema.index({ kind: 1, status: 1, attemptedAt: -1 }, { name: 'analytics_idx' });
|
|
42
43
|
deliveryAttemptSchema.index({ twilioSid: 1 }, { name: 'twilio_sid_idx', sparse: true });
|
|
44
|
+
deliveryAttemptSchema.index({ 'variables.2': 1 }, { name: 'second_variable_idx', sparse: true });
|
|
43
45
|
|
|
44
46
|
const DeliveryAttempt = mongoose.model('DeliveryAttempt', deliveryAttemptSchema);
|
|
45
47
|
|
|
@@ -48,5 +50,6 @@ module.exports = {
|
|
|
48
50
|
DELIVERY_ATTEMPT_KINDS: KIND_VALUES,
|
|
49
51
|
DELIVERY_ATTEMPT_STATUSES: STATUS_VALUES,
|
|
50
52
|
DELIVERY_ATTEMPT_TERMINAL_STATUSES: TERMINAL_STATUS_VALUES,
|
|
53
|
+
DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUS_VALUES,
|
|
51
54
|
DELIVERY_ATTEMPT_ERROR_SOURCES: ERROR_SOURCE_VALUES
|
|
52
55
|
};
|
|
@@ -2,8 +2,11 @@ const { Symptoms_ID: symptomsId } = require('../config/airtableConfig');
|
|
|
2
2
|
const { firstOf } = require('../utils/coercionUtils');
|
|
3
3
|
const { paginate } = require('../utils/paginationUtils');
|
|
4
4
|
const { MapCache } = require('../utils/MapCache');
|
|
5
|
+
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel');
|
|
6
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
5
7
|
const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
6
8
|
const { getRecordByFilter } = require('./airtableService');
|
|
9
|
+
const { getMessages } = require('./messageService');
|
|
7
10
|
|
|
8
11
|
const DEFAULT_LIMIT = 50;
|
|
9
12
|
const CACHE_TTL_MS = 60 * 1000;
|
|
@@ -27,10 +30,13 @@ const CAROUSEL_INDEX_FIELDS = ['recordID', 'Created'];
|
|
|
27
30
|
const CAROUSEL_STATUS_FIELDS = [
|
|
28
31
|
'recordID',
|
|
29
32
|
'Created',
|
|
33
|
+
'cluster_resolutions',
|
|
30
34
|
...CAROUSEL_DELIVERY_FIELDS,
|
|
31
35
|
];
|
|
32
36
|
|
|
33
37
|
const RESOLUTION_FIELDS = ['rank', 'element_name_short'];
|
|
38
|
+
const FIRST_RESOLUTION_VARIABLE = '2';
|
|
39
|
+
const UNSUCCESSFUL_SEND_STATUSES = ['failed', 'undelivered'];
|
|
34
40
|
const carouselCache = new MapCache({ maxSize: 30, ttl: CACHE_TTL_MS });
|
|
35
41
|
const carouselRowCache = new MapCache({ maxSize: 500, ttl: CACHE_TTL_MS });
|
|
36
42
|
const inFlight = new Map();
|
|
@@ -66,6 +72,65 @@ const deliveryOf = (row) => ({
|
|
|
66
72
|
error: row.twilio_error || null,
|
|
67
73
|
});
|
|
68
74
|
|
|
75
|
+
function sentDeliveryStatus(status) {
|
|
76
|
+
if (UNSUCCESSFUL_SEND_STATUSES.includes(status)) return 'failed';
|
|
77
|
+
return DELIVERY_ATTEMPT_LANDED_STATUSES.includes(status) ? status : 'queued';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function sentDeliveryOf(message) {
|
|
81
|
+
const statusInfo = message.statusInfo || {};
|
|
82
|
+
const status = sentDeliveryStatus(statusInfo.status);
|
|
83
|
+
return {
|
|
84
|
+
status,
|
|
85
|
+
statusUpdatedAt: statusInfo.updatedAt || null,
|
|
86
|
+
error: status === 'failed' ? statusInfo.errorMessage || null : null,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const reachedPatient = (message) => DELIVERY_ATTEMPT_LANDED_STATUSES.includes(message.statusInfo?.status);
|
|
91
|
+
|
|
92
|
+
const firstResolutionOf = (row) => (
|
|
93
|
+
Array.isArray(row.cluster_resolutions) ? row.cluster_resolutions[0] || null : null
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
async function sendsByFirstResolution(code, rows) {
|
|
97
|
+
const resolutionIds = [...new Set(rows.map(firstResolutionOf).filter(Boolean))];
|
|
98
|
+
if (!resolutionIds.length) return new Map();
|
|
99
|
+
|
|
100
|
+
const attempts = await DeliveryAttempt.find({
|
|
101
|
+
[`variables.${FIRST_RESOLUTION_VARIABLE}`]: { $in: resolutionIds },
|
|
102
|
+
}).select('messageId variables').sort({ attemptedAt: 1 }).lean();
|
|
103
|
+
if (!attempts.length) return new Map();
|
|
104
|
+
|
|
105
|
+
const messages = await getMessages({
|
|
106
|
+
_id: { $in: attempts.map((attempt) => attempt.messageId) },
|
|
107
|
+
numero: ensureWhatsAppFormat(code),
|
|
108
|
+
}, { select: '_id createdAt statusInfo' });
|
|
109
|
+
const messageById = new Map(messages.map((message) => [String(message._id), message]));
|
|
110
|
+
|
|
111
|
+
const sends = new Map();
|
|
112
|
+
attempts.forEach((attempt) => {
|
|
113
|
+
const message = messageById.get(String(attempt.messageId));
|
|
114
|
+
if (!message) return;
|
|
115
|
+
const resolutionId = attempt.variables[FIRST_RESOLUTION_VARIABLE];
|
|
116
|
+
const current = sends.get(resolutionId);
|
|
117
|
+
if (!current || (!reachedPatient(current) && reachedPatient(message))) {
|
|
118
|
+
sends.set(resolutionId, message);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
return sends;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function sendFieldsOf(row, sends) {
|
|
125
|
+
const message = sends.get(firstResolutionOf(row));
|
|
126
|
+
if (!message) return { sentAt: null, messageId: null, delivery: deliveryOf(row) };
|
|
127
|
+
return {
|
|
128
|
+
sentAt: message.createdAt || null,
|
|
129
|
+
messageId: String(message._id),
|
|
130
|
+
delivery: sentDeliveryOf(message),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
69
134
|
function recommendationIdOf(recommendation) {
|
|
70
135
|
return recommendation?.recommendation_id || recommendation?.recommendationId || null;
|
|
71
136
|
}
|
|
@@ -149,7 +214,7 @@ async function resolutionMapFor(rows) {
|
|
|
149
214
|
return new Map(resolutionRows.map((row) => [row._recordId, row]));
|
|
150
215
|
}
|
|
151
216
|
|
|
152
|
-
function projectCarousel(row, resolutionById) {
|
|
217
|
+
function projectCarousel(row, resolutionById, sends) {
|
|
153
218
|
const recommendations = parseRecommendations(row.recommendations);
|
|
154
219
|
const images = Array.isArray(row.images) ? row.images : [];
|
|
155
220
|
const resolutionsByRank = new Map(
|
|
@@ -179,13 +244,13 @@ function projectCarousel(row, resolutionById) {
|
|
|
179
244
|
triageRecordId: Array.isArray(row.triaje_symptoms) ? row.triaje_symptoms[0] || null : null,
|
|
180
245
|
createdAt: row.Created || row._createdTime || null,
|
|
181
246
|
cards,
|
|
182
|
-
|
|
247
|
+
...sendFieldsOf(row, sends),
|
|
183
248
|
};
|
|
184
249
|
}
|
|
185
250
|
|
|
186
|
-
const projectCarouselStatus = (row) => ({
|
|
251
|
+
const projectCarouselStatus = (row, sends) => ({
|
|
187
252
|
id: row._recordId || row.recordID,
|
|
188
|
-
|
|
253
|
+
...sendFieldsOf(row, sends),
|
|
189
254
|
});
|
|
190
255
|
|
|
191
256
|
async function readPatientCarouselStatuses(code) {
|
|
@@ -197,8 +262,9 @@ async function readPatientCarouselStatuses(code) {
|
|
|
197
262
|
CAROUSEL_STATUS_FIELDS,
|
|
198
263
|
true,
|
|
199
264
|
) || [];
|
|
265
|
+
const sends = await sendsByFirstResolution(code, rows);
|
|
200
266
|
return rows
|
|
201
|
-
.map(projectCarouselStatus)
|
|
267
|
+
.map((row) => projectCarouselStatus(row, sends))
|
|
202
268
|
.filter((record) => record.id);
|
|
203
269
|
}
|
|
204
270
|
|
|
@@ -259,12 +325,15 @@ async function getRecommendationCarousels({ code, limit, page, baseUrl = '/api/p
|
|
|
259
325
|
});
|
|
260
326
|
const ids = result.records.map((row) => row._recordId || row.recordID).filter(Boolean);
|
|
261
327
|
const rows = await readPatientCarouselRows(code, ids);
|
|
262
|
-
const resolutionById = await
|
|
328
|
+
const [resolutionById, sends] = await Promise.all([
|
|
329
|
+
resolutionMapFor(rows),
|
|
330
|
+
sendsByFirstResolution(code, rows),
|
|
331
|
+
]);
|
|
263
332
|
return {
|
|
264
333
|
...result,
|
|
265
334
|
records: rows.map((row) => publicCarousel(
|
|
266
335
|
code,
|
|
267
|
-
projectCarousel(row, resolutionById),
|
|
336
|
+
projectCarousel(row, resolutionById, sends),
|
|
268
337
|
baseUrl,
|
|
269
338
|
)),
|
|
270
339
|
};
|