@peopl-health/nexus 5.56.13 → 5.56.14
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,6 +4,14 @@ function inboundRecoveryLive() {
|
|
|
4
4
|
return String(runtimeConfig.get('INBOUND_RECOVERY_LIVE', 'true')).trim().toLowerCase() === 'true';
|
|
5
5
|
}
|
|
6
6
|
|
|
7
|
+
const COLD_MODES = ['off', 'report', 'file'];
|
|
8
|
+
|
|
9
|
+
function coldInboundMode() {
|
|
10
|
+
const raw = String(runtimeConfig.get('COLD_INBOUND_MODE', 'off')).trim().toLowerCase();
|
|
11
|
+
return COLD_MODES.includes(raw) ? raw : 'off';
|
|
12
|
+
}
|
|
13
|
+
|
|
7
14
|
module.exports = {
|
|
8
15
|
inboundRecoveryLive,
|
|
16
|
+
coldInboundMode,
|
|
9
17
|
};
|
|
@@ -103,6 +103,11 @@ messageSchema.index({ createdAt: -1 }, { name: 'global_sort_idx' });
|
|
|
103
103
|
|
|
104
104
|
messageSchema.index({ message_id: 1 }, { name: 'message_id_idx', sparse: true });
|
|
105
105
|
|
|
106
|
+
messageSchema.index(
|
|
107
|
+
{ createdAt: -1 },
|
|
108
|
+
{ name: 'failed_send_idx', partialFilterExpression: { 'statusInfo.status': 'failed' } },
|
|
109
|
+
);
|
|
110
|
+
|
|
106
111
|
messageSchema.index({ turnId: 1 }, { name: 'turn_id_idx', sparse: true });
|
|
107
112
|
|
|
108
113
|
messageSchema.index({ traceId: 1 }, { name: 'trace_id_idx', sparse: true });
|
|
@@ -5,7 +5,7 @@ const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
|
5
5
|
const { Thread } = require('../models/threadModel');
|
|
6
6
|
const { botIsPaused } = require('../helpers/pausedThreadHelper');
|
|
7
7
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
8
|
-
const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
8
|
+
const { coldInboundMode, inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
9
9
|
const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
10
10
|
const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
|
|
11
11
|
const { getMessages, countMessages, aggregateMessages } = require('./messageService');
|
|
@@ -18,6 +18,12 @@ const MAX_RECOVERIES_PER_PASS = 3;
|
|
|
18
18
|
const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
|
|
19
19
|
const REPLAY_SETTLE_MS = 5 * 60 * 1000;
|
|
20
20
|
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
21
|
+
const COLD_MIN_AGE_MS = 4 * 60 * 60 * 1000;
|
|
22
|
+
const COLD_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
23
|
+
const COLD_TICKETS_PER_PASS = 25;
|
|
24
|
+
// The cold band asks the same question of thirty days instead of one hour, so its page has
|
|
25
|
+
// to be wide enough that answered conversations at the head cannot mask the rest.
|
|
26
|
+
const COLD_SCAN_LIMIT = 1000;
|
|
21
27
|
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
|
|
22
28
|
|
|
23
29
|
const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
@@ -26,35 +32,41 @@ const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket',
|
|
|
26
32
|
const FAILED_SEND = { 'statusInfo.status': 'failed', message_id: null };
|
|
27
33
|
const UNANSWERED_QUESTION = 'El paciente escribió y no recibió respuesta.';
|
|
28
34
|
|
|
29
|
-
async function unansweredThreads(now) {
|
|
35
|
+
async function unansweredThreads(now, { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
|
|
30
36
|
return Thread.find(
|
|
31
37
|
{
|
|
32
38
|
stopped: false,
|
|
33
39
|
lastMessageFromMe: false,
|
|
34
|
-
lastMessageAt: { $gte: new Date(now.getTime() -
|
|
40
|
+
lastMessageAt: { $gte: new Date(now.getTime() - maxAgeMs), $lte: new Date(now.getTime() - minAgeMs) },
|
|
35
41
|
},
|
|
36
42
|
{ code: 1, lastMessageAt: 1 },
|
|
37
|
-
).sort({ lastMessageAt: 1 }).limit(
|
|
43
|
+
).sort({ lastMessageAt: 1 }).limit(limit).lean();
|
|
38
44
|
}
|
|
39
45
|
|
|
40
|
-
async function codesWithAFailedSend(now) {
|
|
46
|
+
async function codesWithAFailedSend(now, { maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
|
|
41
47
|
const rows = await aggregateMessages([
|
|
42
|
-
{ $match: { ...FAILED_SEND, from_me: true, createdAt: { $gte: new Date(now.getTime() -
|
|
48
|
+
{ $match: { ...FAILED_SEND, from_me: true, createdAt: { $gte: new Date(now.getTime() - maxAgeMs) } } },
|
|
43
49
|
{ $group: { _id: '$numero', firstFailedAt: { $min: '$createdAt' } } },
|
|
44
|
-
|
|
45
|
-
{ $
|
|
50
|
+
// _id breaks the tie: without it a page of shared timestamps orders differently each pass.
|
|
51
|
+
{ $sort: { firstFailedAt: 1, _id: 1 } },
|
|
52
|
+
{ $limit: limit },
|
|
46
53
|
]);
|
|
47
54
|
return rows.map((row) => row._id);
|
|
48
55
|
}
|
|
49
56
|
|
|
50
|
-
async function candidateCodes(now) {
|
|
51
|
-
const [threads, failedSends] = await Promise.all([
|
|
52
|
-
|
|
57
|
+
async function candidateCodes(now, { threadBand = null, failedMaxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
|
|
58
|
+
const [threads, failedSends] = await Promise.all([
|
|
59
|
+
unansweredThreads(now, { ...(threadBand || {}), limit }),
|
|
60
|
+
codesWithAFailedSend(now, { maxAgeMs: failedMaxAgeMs, limit }),
|
|
61
|
+
]);
|
|
62
|
+
const atCeiling = threads.length >= limit || failedSends.length >= limit;
|
|
63
|
+
const codes = [...new Set([...threads.map((thread) => thread.code), ...failedSends].filter(Boolean))];
|
|
64
|
+
return { codes, atCeiling };
|
|
53
65
|
}
|
|
54
66
|
|
|
55
67
|
const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
|
|
56
68
|
|
|
57
|
-
async function stillUnanswered(code, now = new Date()) {
|
|
69
|
+
async function stillUnanswered(code, now = new Date(), { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS } = {}) {
|
|
58
70
|
const [newest] = await getMessages(
|
|
59
71
|
{ numero: code, from_me: false, interactive_type: null },
|
|
60
72
|
{ select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
|
|
@@ -62,14 +74,19 @@ async function stillUnanswered(code, now = new Date()) {
|
|
|
62
74
|
if (!newest) return null;
|
|
63
75
|
|
|
64
76
|
const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
|
|
65
|
-
if (!Number.isFinite(ageMs) || ageMs <
|
|
77
|
+
if (!Number.isFinite(ageMs) || ageMs < minAgeMs || ageMs > maxAgeMs) return null;
|
|
66
78
|
|
|
67
79
|
const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt }, $nor: [FAILED_SEND] });
|
|
68
80
|
return replies === 0 ? newest : null;
|
|
69
81
|
}
|
|
70
82
|
|
|
71
|
-
|
|
72
|
-
const
|
|
83
|
+
function waitedFor(ageMs) {
|
|
84
|
+
const minutes = Math.max(0, Math.round(ageMs / 60000));
|
|
85
|
+
if (minutes < 120) return `lleva ${minutes} min sin respuesta`;
|
|
86
|
+
const hours = Math.round(minutes / 60);
|
|
87
|
+
if (hours < 48) return `lleva ${hours} h sin respuesta`;
|
|
88
|
+
return `lleva ${Math.round(hours / 24)} días sin respuesta`;
|
|
89
|
+
}
|
|
73
90
|
|
|
74
91
|
async function fileTicket(code, alert, ageMs) {
|
|
75
92
|
try {
|
|
@@ -97,7 +114,7 @@ async function sweepUnansweredInbound({
|
|
|
97
114
|
} = {}) {
|
|
98
115
|
let codes;
|
|
99
116
|
try {
|
|
100
|
-
codes = await candidateCodes(now);
|
|
117
|
+
({ codes } = await candidateCodes(now));
|
|
101
118
|
} catch (error) {
|
|
102
119
|
logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
|
|
103
120
|
return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
@@ -187,6 +204,66 @@ async function sweepUnansweredInbound({
|
|
|
187
204
|
return { scanned: candidates.length, recovered, alerted, skipped };
|
|
188
205
|
}
|
|
189
206
|
|
|
207
|
+
const COLD_BAND = { minAgeMs: COLD_MIN_AGE_MS, maxAgeMs: COLD_MAX_AGE_MS };
|
|
208
|
+
|
|
209
|
+
async function sweepColdUnansweredInbound({
|
|
210
|
+
now = new Date(),
|
|
211
|
+
mode = coldInboundMode(),
|
|
212
|
+
isProcessing = () => false,
|
|
213
|
+
isPaused = threadIsOwnedByAHuman,
|
|
214
|
+
ticketGate = ticketClaims,
|
|
215
|
+
alert = recordUnresolvedRequest,
|
|
216
|
+
} = {}) {
|
|
217
|
+
if (mode === 'off') return { waiting: 0, alerted: 0 };
|
|
218
|
+
|
|
219
|
+
const { codes, atCeiling } = await candidateCodes(now, {
|
|
220
|
+
threadBand: COLD_BAND, failedMaxAgeMs: COLD_MAX_AGE_MS, limit: COLD_SCAN_LIMIT,
|
|
221
|
+
});
|
|
222
|
+
// Answered conversations are filtered below, after the page is cut, so a full page is a page
|
|
223
|
+
// that may be hiding patients behind it. Say so rather than let the tail go unseen quietly.
|
|
224
|
+
if (atCeiling) {
|
|
225
|
+
logger.error('[inboundRecovery] the cold scan filled its page; patients may be waiting behind it', {
|
|
226
|
+
limit: COLD_SCAN_LIMIT, found: codes.length,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const waiting = [];
|
|
231
|
+
for (const code of codes) {
|
|
232
|
+
if (isProcessing(code)) continue;
|
|
233
|
+
try {
|
|
234
|
+
const inbound = await stillUnanswered(code, now, COLD_BAND);
|
|
235
|
+
if (inbound && !await isPaused(code)) waiting.push({ code, inbound });
|
|
236
|
+
} catch (error) {
|
|
237
|
+
logger.error('[inboundRecovery] could not read one cold conversation; leaving it for the next pass', {
|
|
238
|
+
code, error: error.message,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!waiting.length) return { waiting: 0, alerted: 0 };
|
|
244
|
+
|
|
245
|
+
waiting.sort((a, b) => new Date(a.inbound.createdAt) - new Date(b.inbound.createdAt));
|
|
246
|
+
|
|
247
|
+
if (mode === 'report') {
|
|
248
|
+
logger.error('[inboundRecovery] patients have been waiting since long before this sweep looked', {
|
|
249
|
+
waiting: waiting.length, oldest: waiting[0].inbound.createdAt, atCeiling, mode,
|
|
250
|
+
});
|
|
251
|
+
return { waiting: waiting.length, alerted: 0 };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
let alerted = 0;
|
|
255
|
+
for (const { code, inbound } of waiting) {
|
|
256
|
+
if (alerted >= COLD_TICKETS_PER_PASS) break;
|
|
257
|
+
const key = String(inbound._id);
|
|
258
|
+
if (await ticketGate.acquire(key, 'alerted') !== 'acquired') continue;
|
|
259
|
+
if (await fileTicket(code, alert, now.getTime() - new Date(inbound.createdAt).getTime())) alerted += 1;
|
|
260
|
+
else await ticketGate.release(key);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
logger.error('[inboundRecovery] filed for patients nobody had answered', { waiting: waiting.length, alerted });
|
|
264
|
+
return { waiting: waiting.length, alerted };
|
|
265
|
+
}
|
|
266
|
+
|
|
190
267
|
function sweepIntervalMs() {
|
|
191
268
|
const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
|
|
192
269
|
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
|
|
@@ -198,12 +275,18 @@ function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
|
|
|
198
275
|
if (!sweeper) {
|
|
199
276
|
sweeper = createIntervalSweeper({
|
|
200
277
|
label: '[inboundRecovery]',
|
|
201
|
-
sweep: () =>
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
278
|
+
sweep: async () => {
|
|
279
|
+
const live = await sweepUnansweredInbound({
|
|
280
|
+
recover: typeof recover === 'function'
|
|
281
|
+
? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
|
|
282
|
+
: null,
|
|
283
|
+
isProcessing,
|
|
284
|
+
});
|
|
285
|
+
await sweepColdUnansweredInbound({ isProcessing }).catch((error) => logger.error(
|
|
286
|
+
'[inboundRecovery] the cold pass failed after the live pass had already run', { error: error.message },
|
|
287
|
+
));
|
|
288
|
+
return live;
|
|
289
|
+
},
|
|
207
290
|
defaultIntervalMs: sweepIntervalMs,
|
|
208
291
|
});
|
|
209
292
|
}
|
|
@@ -221,6 +304,7 @@ module.exports = {
|
|
|
221
304
|
startInboundRecoverySweep,
|
|
222
305
|
stopInboundRecoverySweep,
|
|
223
306
|
sweepUnansweredInbound,
|
|
307
|
+
sweepColdUnansweredInbound,
|
|
224
308
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
225
309
|
stillUnanswered,
|
|
226
310
|
threadIsOwnedByAHuman,
|