@peopl-health/nexus 5.56.12 → 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,8 +5,8 @@ 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');
|
|
9
|
-
const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
8
|
+
const { coldInboundMode, inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
9
|
+
const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
10
10
|
const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
|
|
11
11
|
const { getMessages, countMessages, aggregateMessages } = require('./messageService');
|
|
12
12
|
|
|
@@ -18,42 +18,55 @@ 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 });
|
|
24
30
|
const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
25
31
|
|
|
26
32
|
const FAILED_SEND = { 'statusInfo.status': 'failed', message_id: null };
|
|
33
|
+
const UNANSWERED_QUESTION = 'El paciente escribió y no recibió respuesta.';
|
|
27
34
|
|
|
28
|
-
async function unansweredThreads(now) {
|
|
35
|
+
async function unansweredThreads(now, { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
|
|
29
36
|
return Thread.find(
|
|
30
37
|
{
|
|
31
38
|
stopped: false,
|
|
32
39
|
lastMessageFromMe: false,
|
|
33
|
-
lastMessageAt: { $gte: new Date(now.getTime() -
|
|
40
|
+
lastMessageAt: { $gte: new Date(now.getTime() - maxAgeMs), $lte: new Date(now.getTime() - minAgeMs) },
|
|
34
41
|
},
|
|
35
42
|
{ code: 1, lastMessageAt: 1 },
|
|
36
|
-
).sort({ lastMessageAt: 1 }).limit(
|
|
43
|
+
).sort({ lastMessageAt: 1 }).limit(limit).lean();
|
|
37
44
|
}
|
|
38
45
|
|
|
39
|
-
async function codesWithAFailedSend(now) {
|
|
46
|
+
async function codesWithAFailedSend(now, { maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
|
|
40
47
|
const rows = await aggregateMessages([
|
|
41
|
-
{ $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) } } },
|
|
42
49
|
{ $group: { _id: '$numero', firstFailedAt: { $min: '$createdAt' } } },
|
|
43
|
-
|
|
44
|
-
{ $
|
|
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 },
|
|
45
53
|
]);
|
|
46
54
|
return rows.map((row) => row._id);
|
|
47
55
|
}
|
|
48
56
|
|
|
49
|
-
async function candidateCodes(now) {
|
|
50
|
-
const [threads, failedSends] = await Promise.all([
|
|
51
|
-
|
|
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 };
|
|
52
65
|
}
|
|
53
66
|
|
|
54
67
|
const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
|
|
55
68
|
|
|
56
|
-
async function stillUnanswered(code, now = new Date()) {
|
|
69
|
+
async function stillUnanswered(code, now = new Date(), { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS } = {}) {
|
|
57
70
|
const [newest] = await getMessages(
|
|
58
71
|
{ numero: code, from_me: false, interactive_type: null },
|
|
59
72
|
{ select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
|
|
@@ -61,15 +74,28 @@ async function stillUnanswered(code, now = new Date()) {
|
|
|
61
74
|
if (!newest) return null;
|
|
62
75
|
|
|
63
76
|
const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
|
|
64
|
-
if (!Number.isFinite(ageMs) || ageMs <
|
|
77
|
+
if (!Number.isFinite(ageMs) || ageMs < minAgeMs || ageMs > maxAgeMs) return null;
|
|
65
78
|
|
|
66
79
|
const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt }, $nor: [FAILED_SEND] });
|
|
67
80
|
return replies === 0 ? newest : null;
|
|
68
81
|
}
|
|
69
82
|
|
|
70
|
-
|
|
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
|
+
}
|
|
90
|
+
|
|
91
|
+
async function fileTicket(code, alert, ageMs) {
|
|
71
92
|
try {
|
|
72
|
-
return Boolean(await alert({
|
|
93
|
+
return Boolean(await alert({
|
|
94
|
+
code,
|
|
95
|
+
category: 'contact_team_member',
|
|
96
|
+
question: UNANSWERED_QUESTION,
|
|
97
|
+
details: formatOpsAlert(code, { label: 'Paciente sin respuesta', summary: waitedFor(ageMs) }),
|
|
98
|
+
}));
|
|
73
99
|
} catch (error) {
|
|
74
100
|
logger.error('[inboundRecovery] could not file the ops ticket', { code, error: error.message });
|
|
75
101
|
return false;
|
|
@@ -88,7 +114,7 @@ async function sweepUnansweredInbound({
|
|
|
88
114
|
} = {}) {
|
|
89
115
|
let codes;
|
|
90
116
|
try {
|
|
91
|
-
codes = await candidateCodes(now);
|
|
117
|
+
({ codes } = await candidateCodes(now));
|
|
92
118
|
} catch (error) {
|
|
93
119
|
logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
|
|
94
120
|
return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
@@ -142,7 +168,7 @@ async function sweepUnansweredInbound({
|
|
|
142
168
|
if (ticket !== 'acquired') { skipped += 1; continue; }
|
|
143
169
|
|
|
144
170
|
logger.error('[inboundRecovery] a replay already ran and the patient is still unanswered', { code, ageMs });
|
|
145
|
-
if (await fileTicket(code, alert)) {
|
|
171
|
+
if (await fileTicket(code, alert, ageMs)) {
|
|
146
172
|
alerted += 1;
|
|
147
173
|
} else {
|
|
148
174
|
await ticketGate.release(key);
|
|
@@ -168,7 +194,7 @@ async function sweepUnansweredInbound({
|
|
|
168
194
|
logger.error('[inboundRecovery] patient was left unanswered', {
|
|
169
195
|
code, ageMs, recoveryLive: canRecover, reachable,
|
|
170
196
|
});
|
|
171
|
-
if (await fileTicket(code, alert)) {
|
|
197
|
+
if (await fileTicket(code, alert, ageMs)) {
|
|
172
198
|
alerted += 1;
|
|
173
199
|
} else {
|
|
174
200
|
await claims.release(key);
|
|
@@ -178,6 +204,66 @@ async function sweepUnansweredInbound({
|
|
|
178
204
|
return { scanned: candidates.length, recovered, alerted, skipped };
|
|
179
205
|
}
|
|
180
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
|
+
|
|
181
267
|
function sweepIntervalMs() {
|
|
182
268
|
const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
|
|
183
269
|
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
|
|
@@ -189,12 +275,18 @@ function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
|
|
|
189
275
|
if (!sweeper) {
|
|
190
276
|
sweeper = createIntervalSweeper({
|
|
191
277
|
label: '[inboundRecovery]',
|
|
192
|
-
sweep: () =>
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
+
},
|
|
198
290
|
defaultIntervalMs: sweepIntervalMs,
|
|
199
291
|
});
|
|
200
292
|
}
|
|
@@ -212,6 +304,7 @@ module.exports = {
|
|
|
212
304
|
startInboundRecoverySweep,
|
|
213
305
|
stopInboundRecoverySweep,
|
|
214
306
|
sweepUnansweredInbound,
|
|
307
|
+
sweepColdUnansweredInbound,
|
|
215
308
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
216
309
|
stillUnanswered,
|
|
217
310
|
threadIsOwnedByAHuman,
|