@peopl-health/nexus 5.56.36 → 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.
- package/lib/controllers/assistantController.js +31 -2
- package/lib/controllers/messageController.js +2 -2
- package/lib/helpers/channelRetryHelper.js +1 -2
- package/lib/helpers/pausedThreadHelper.js +13 -1
- package/lib/models/deliveryAttemptModel.js +3 -0
- package/lib/models/threadModel.js +1 -0
- package/lib/routes/index.js +4 -1
- package/lib/services/inboundRecoveryService.js +10 -4
- package/lib/services/recommendationCarouselService.js +76 -7
- package/lib/services/threadService.js +3 -0
- package/package.json +1 -1
|
@@ -3,17 +3,19 @@ const runtimeConfig = require('../config/runtimeConfig');
|
|
|
3
3
|
|
|
4
4
|
const { logger } = require('../utils/logger');
|
|
5
5
|
|
|
6
|
-
const { getThreadInfo, switchThreadStoppedStatus } = require('../services/threadService');
|
|
6
|
+
const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
|
|
7
7
|
|
|
8
8
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
9
9
|
const { sendMessage, processInstruction, processSystemMessage } = require('../core/NexusMessaging');
|
|
10
10
|
const { createAssistant, switchAssistant } = require('../clinical');
|
|
11
11
|
|
|
12
|
+
const asBoolean = (value) => (typeof value === 'string' ? value === 'true' : !!value);
|
|
13
|
+
|
|
12
14
|
const stopAssistantController = async (req, res) => {
|
|
13
15
|
const { code, stop } = req.body;
|
|
14
16
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
15
17
|
|
|
16
|
-
const stopped =
|
|
18
|
+
const stopped = asBoolean(stop);
|
|
17
19
|
try {
|
|
18
20
|
await switchThreadStoppedStatus(code, stopped, { byOperator: true });
|
|
19
21
|
return res.status(200).json({ success: true, message: stopped ? 'Assistant stopped' : 'Assistant resumed' });
|
|
@@ -23,6 +25,32 @@ const stopAssistantController = async (req, res) => {
|
|
|
23
25
|
}
|
|
24
26
|
};
|
|
25
27
|
|
|
28
|
+
const observedSilence = (through) => {
|
|
29
|
+
if (through === undefined || through === null || through === '') return null;
|
|
30
|
+
const at = new Date(through);
|
|
31
|
+
if (Number.isNaN(at.getTime()) || at.getTime() > Date.now()) return undefined;
|
|
32
|
+
return at;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const doNotAlertController = async (req, res) => {
|
|
36
|
+
const { code, doNotAlert, through } = req.body;
|
|
37
|
+
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
38
|
+
|
|
39
|
+
const observed = observedSilence(through);
|
|
40
|
+
if (observed === undefined) return res.status(400).json({ success: false, error: 'through must be a past timestamp' });
|
|
41
|
+
|
|
42
|
+
const muted = asBoolean(doNotAlert);
|
|
43
|
+
try {
|
|
44
|
+
const result = await setThreadDoNotAlert(code, muted, observed);
|
|
45
|
+
if (!result.matchedCount) return res.status(404).json({ success: false, error: 'No conversation with that code' });
|
|
46
|
+
logger.info('[AssistantController] Alerts for a contact were switched', { code, doNotAlert: muted, through: observed });
|
|
47
|
+
return res.status(200).json({ success: true, message: muted ? 'Alerts muted for this contact' : 'Alerts restored for this contact' });
|
|
48
|
+
} catch (error) {
|
|
49
|
+
logger.error('[AssistantController] Failed to switch alerts for a contact', { error: error.message, code });
|
|
50
|
+
return res.status(500).json({ success: false, error: 'Failed to switch alerts for this contact' });
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
26
54
|
const addInsAssistantController = async (req, res) => {
|
|
27
55
|
const { code, instruction, triggeredBy } = req.body;
|
|
28
56
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
@@ -113,6 +141,7 @@ module.exports = {
|
|
|
113
141
|
addInsAssistantController,
|
|
114
142
|
addMsgAssistantController,
|
|
115
143
|
createAssistantController,
|
|
144
|
+
doNotAlertController,
|
|
116
145
|
getInfoAssistantController,
|
|
117
146
|
listAssistantController,
|
|
118
147
|
switchAssistantController,
|
|
@@ -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');
|
|
@@ -12,9 +12,21 @@ async function botIsPaused(code, { label = '[pausedThread]' } = {}) {
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
async function alertsMutedFor(code, inboundAt, { label = '[pausedThread]' } = {}) {
|
|
16
|
+
if (!code || !inboundAt) return false;
|
|
17
|
+
try {
|
|
18
|
+
const thread = await Thread.findOne({ code }, { doNotAlertThrough: 1 }).lean();
|
|
19
|
+
if (!thread?.doNotAlertThrough) return false;
|
|
20
|
+
return new Date(inboundAt).getTime() <= new Date(thread.doNotAlertThrough).getTime();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
logger.warn(`${label} could not read whether this silence was waved off; alerting anyway`, { code, error: error.message });
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
15
27
|
async function pausedSince(code, since) {
|
|
16
28
|
const paused = await Thread.findOne({ code, stopped: true, pausedAt: { $gt: since } }, { _id: 1 }).lean();
|
|
17
29
|
return Boolean(paused);
|
|
18
30
|
}
|
|
19
31
|
|
|
20
|
-
module.exports = { botIsPaused, pausedSince };
|
|
32
|
+
module.exports = { alertsMutedFor, botIsPaused, pausedSince };
|
|
@@ -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
|
};
|
|
@@ -11,6 +11,7 @@ const threadSchema = new mongoose.Schema({
|
|
|
11
11
|
nombre: { type: String, default: null },
|
|
12
12
|
stopped: { type: Boolean, default: false },
|
|
13
13
|
pausedAt: { type: Date, default: null },
|
|
14
|
+
doNotAlertThrough: { type: Date, default: null },
|
|
14
15
|
review: { type: Boolean, default: false },
|
|
15
16
|
version: { type: Number, default: null },
|
|
16
17
|
preset_id: { type: String, default: null },
|
package/lib/routes/index.js
CHANGED
|
@@ -7,7 +7,8 @@ const assistantRouteDefinitions = {
|
|
|
7
7
|
'POST /info': 'getInfoAssistantController',
|
|
8
8
|
'GET /list': 'listAssistantController',
|
|
9
9
|
'POST /switch': 'switchAssistantController',
|
|
10
|
-
'POST /stop': 'stopAssistantController'
|
|
10
|
+
'POST /stop': 'stopAssistantController',
|
|
11
|
+
'POST /do-not-alert': 'doNotAlertController'
|
|
11
12
|
};
|
|
12
13
|
|
|
13
14
|
const contingencyRouteDefinitions = {
|
|
@@ -183,6 +184,7 @@ const builtInControllers = {
|
|
|
183
184
|
listAssistantController: assistantController.listAssistantController,
|
|
184
185
|
switchAssistantController: assistantController.switchAssistantController,
|
|
185
186
|
stopAssistantController: assistantController.stopAssistantController,
|
|
187
|
+
doNotAlertController: assistantController.doNotAlertController,
|
|
186
188
|
|
|
187
189
|
// Contingency controllers
|
|
188
190
|
contingencyEventController: contingencyController.contingencyEventController,
|
|
@@ -340,6 +342,7 @@ module.exports = {
|
|
|
340
342
|
traceRoutes: traceRouteDefinitions,
|
|
341
343
|
escalationReviewRoutes: escalationReviewRouteDefinitions,
|
|
342
344
|
|
|
345
|
+
builtInControllers,
|
|
343
346
|
createRouter,
|
|
344
347
|
setupDefaultRoutes
|
|
345
348
|
};
|
|
@@ -3,7 +3,7 @@ const { logger } = require('../utils/logger');
|
|
|
3
3
|
const { isWithinHourWindow } = require('../utils/scheduleUtils');
|
|
4
4
|
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
5
5
|
const { Thread } = require('../models/threadModel');
|
|
6
|
-
const { botIsPaused } = require('../helpers/pausedThreadHelper');
|
|
6
|
+
const { alertsMutedFor, botIsPaused } = require('../helpers/pausedThreadHelper');
|
|
7
7
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
8
8
|
const { coldInboundMode, inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
9
9
|
const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
@@ -41,6 +41,7 @@ async function unansweredThreads(now, { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AG
|
|
|
41
41
|
stopped: false,
|
|
42
42
|
lastMessageFromMe: false,
|
|
43
43
|
lastMessageAt: { $gte: new Date(now.getTime() - maxAgeMs), $lte: new Date(now.getTime() - minAgeMs) },
|
|
44
|
+
$or: [{ doNotAlertThrough: null }, { $expr: { $lt: ['$doNotAlertThrough', '$lastMessageAt'] } }],
|
|
44
45
|
},
|
|
45
46
|
{ code: 1, lastMessageAt: 1 },
|
|
46
47
|
).sort({ lastMessageAt: 1 }).limit(limit).lean();
|
|
@@ -68,6 +69,7 @@ async function candidateCodes(now, { threadBand = null, failedMaxAgeMs = MAX_AGE
|
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
|
|
72
|
+
const silenceWasWavedOff = (code, inboundAt) => alertsMutedFor(code, inboundAt, { label: '[inboundRecovery]' });
|
|
71
73
|
|
|
72
74
|
async function stillUnanswered(code, now = new Date(), { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS } = {}) {
|
|
73
75
|
const [newest] = await getMessages(
|
|
@@ -113,6 +115,7 @@ async function sweepUnansweredInbound({
|
|
|
113
115
|
claims = recoveryClaims,
|
|
114
116
|
ticketGate = ticketClaims,
|
|
115
117
|
isPaused = threadIsOwnedByAHuman,
|
|
118
|
+
isMuted = silenceWasWavedOff,
|
|
116
119
|
alert = recordUnresolvedRequest,
|
|
117
120
|
} = {}) {
|
|
118
121
|
let codes;
|
|
@@ -128,7 +131,7 @@ async function sweepUnansweredInbound({
|
|
|
128
131
|
if (isProcessing(code)) continue;
|
|
129
132
|
try {
|
|
130
133
|
const inbound = await stillUnanswered(code, now);
|
|
131
|
-
if (inbound) candidates.push({ code, inbound });
|
|
134
|
+
if (inbound && !await isMuted(code, inbound.createdAt)) candidates.push({ code, inbound });
|
|
132
135
|
} catch (error) {
|
|
133
136
|
logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
|
|
134
137
|
code, error: error.message,
|
|
@@ -154,7 +157,7 @@ async function sweepUnansweredInbound({
|
|
|
154
157
|
const key = String(inbound._id);
|
|
155
158
|
const ageMs = now.getTime() - new Date(inbound.createdAt).getTime();
|
|
156
159
|
|
|
157
|
-
if (await isPaused(code)) { skipped += 1; continue; }
|
|
160
|
+
if (await isPaused(code) || await isMuted(code, inbound.createdAt)) { skipped += 1; continue; }
|
|
158
161
|
|
|
159
162
|
const claim = await claims.acquire(key, 'handled');
|
|
160
163
|
if (claim === 'unavailable') {
|
|
@@ -224,6 +227,7 @@ async function sweepColdUnansweredInbound({
|
|
|
224
227
|
mode = coldInboundMode(),
|
|
225
228
|
isProcessing = () => false,
|
|
226
229
|
isPaused = threadIsOwnedByAHuman,
|
|
230
|
+
isMuted = silenceWasWavedOff,
|
|
227
231
|
ticketGate = ticketClaims,
|
|
228
232
|
coldGate = coldTicketClaims,
|
|
229
233
|
alert = recordUnresolvedRequest,
|
|
@@ -246,7 +250,7 @@ async function sweepColdUnansweredInbound({
|
|
|
246
250
|
if (isProcessing(code)) continue;
|
|
247
251
|
try {
|
|
248
252
|
const inbound = await stillUnanswered(code, now, COLD_BAND);
|
|
249
|
-
if (inbound && !await isPaused(code)) waiting.push({ code, inbound });
|
|
253
|
+
if (inbound && !await isPaused(code) && !await isMuted(code, inbound.createdAt)) waiting.push({ code, inbound });
|
|
250
254
|
} catch (error) {
|
|
251
255
|
logger.error('[inboundRecovery] could not read one cold conversation; leaving it for the next pass', {
|
|
252
256
|
code, error: error.message,
|
|
@@ -277,6 +281,7 @@ async function sweepColdUnansweredInbound({
|
|
|
277
281
|
for (const { code, inbound } of waiting) {
|
|
278
282
|
if ((await spent() ?? COLD_TICKETS_PER_DAY) >= COLD_TICKETS_PER_DAY) break;
|
|
279
283
|
const key = String(inbound._id);
|
|
284
|
+
if (await isMuted(code, inbound.createdAt)) continue;
|
|
280
285
|
if (await ticketGate.has(key) !== false) continue;
|
|
281
286
|
if (await coldGate.acquire(key, 'cold') !== 'acquired') continue;
|
|
282
287
|
if (await fileTicket(code, alert, now.getTime() - new Date(inbound.createdAt).getTime())) alerted += 1;
|
|
@@ -331,6 +336,7 @@ module.exports = {
|
|
|
331
336
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
332
337
|
stillUnanswered,
|
|
333
338
|
threadIsOwnedByAHuman,
|
|
339
|
+
silenceWasWavedOff,
|
|
334
340
|
_claims: recoveryClaims,
|
|
335
341
|
_ticketClaims: ticketClaims,
|
|
336
342
|
_coldTicketClaims: coldTicketClaims,
|
|
@@ -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
|
};
|
|
@@ -45,6 +45,8 @@ const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } =
|
|
|
45
45
|
return result;
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
+
const setThreadDoNotAlert = async (code, doNotAlert, through = null) => Thread.updateMany({ code }, { $set: { doNotAlertThrough: doNotAlert ? (through || new Date()) : null } });
|
|
49
|
+
|
|
48
50
|
const setThreadPromptId = async (code, promptId) => {
|
|
49
51
|
const updateFields = {};
|
|
50
52
|
Thread.setAssistantId(updateFields, promptId);
|
|
@@ -103,5 +105,6 @@ module.exports = {
|
|
|
103
105
|
createPlaceholderThread,
|
|
104
106
|
ensureThreadExists,
|
|
105
107
|
switchThreadStoppedStatus,
|
|
108
|
+
setThreadDoNotAlert,
|
|
106
109
|
setThreadPromptId
|
|
107
110
|
};
|