@peopl-health/nexus 5.54.0-dev.7971 → 5.54.0-dev.7974
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/clinical/config/safetyNetConfig.js +8 -31
- package/lib/clinical/flags/inboundRecoveryFlags.js +9 -0
- package/lib/clinical/services/assistantService.js +2 -2
- package/lib/clinical/services/pausedSafetyNetService.js +65 -38
- package/lib/clinical/services/recommendationRecoveryService.js +3 -12
- package/lib/clinical/services/safetyNetPledgeService.js +14 -41
- package/lib/config/lifecycle.js +2 -1
- package/lib/core/NexusMessaging.js +67 -46
- package/lib/helpers/pausedThreadHelper.js +15 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +14 -0
- package/lib/models/safetyNetPledgeModel.js +1 -0
- package/lib/services/inboundRecoveryService.js +209 -0
- package/lib/utils/scheduleUtils.js +1 -24
- package/package.json +1 -1
|
@@ -1,46 +1,28 @@
|
|
|
1
1
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
2
2
|
|
|
3
|
-
const DEFAULT_OFFER_WINDOW_MS =
|
|
4
|
-
const DEFAULT_HUMAN_QUIET_MS =
|
|
5
|
-
const DEFAULT_ACTIVITY_QUIET_MS = 2 * 60 * 60 * 1000;
|
|
3
|
+
const DEFAULT_OFFER_WINDOW_MS = 4 * 60 * 60 * 1000;
|
|
4
|
+
const DEFAULT_HUMAN_QUIET_MS = 60 * 60 * 1000;
|
|
6
5
|
const DEFAULT_TAP_WINDOW_MS = 30 * 60 * 1000;
|
|
7
|
-
const DEFAULT_PLEDGE_MS =
|
|
6
|
+
const DEFAULT_PLEDGE_MS = 30 * 60 * 1000;
|
|
8
7
|
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
9
8
|
|
|
10
9
|
const CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
|
|
11
10
|
|
|
12
11
|
const SAFETY_NET_SOURCE = 'paused_safety_net';
|
|
13
12
|
|
|
14
|
-
const
|
|
15
|
-
const HUMAN_ORIGINS = ['whatsapp_platform'];
|
|
16
|
-
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|
|
17
|
-
const RECEIVED_STATUSES = ['delivered', 'read'];
|
|
18
|
-
|
|
19
|
-
const anyReplyFilter = (code, since) => ({
|
|
13
|
+
const humanReplyFilter = (code, since) => ({
|
|
20
14
|
numero: code,
|
|
21
15
|
from_me: true,
|
|
22
16
|
content_sid: null,
|
|
23
|
-
origin: { $
|
|
24
|
-
'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
|
|
17
|
+
origin: { $ne: 'assistant' },
|
|
25
18
|
triggeredBy: { $ne: SAFETY_NET_SOURCE },
|
|
26
19
|
createdAt: { $gt: since }
|
|
27
20
|
});
|
|
28
21
|
|
|
29
|
-
const humanReplyFilter = (code, since) => ({
|
|
30
|
-
...anyReplyFilter(code, since),
|
|
31
|
-
origin: { $in: HUMAN_ORIGINS }
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const settledHumanReplyFilter = (code, since, unconfirmedBefore) => ({
|
|
35
|
-
...humanReplyFilter(code, since),
|
|
36
|
-
$or: [
|
|
37
|
-
{ 'statusInfo.status': { $in: RECEIVED_STATUSES } },
|
|
38
|
-
{ createdAt: { $lte: unconfirmedBefore } }
|
|
39
|
-
]
|
|
40
|
-
});
|
|
41
|
-
|
|
42
22
|
const CHOICE_LABEL_KEYS = {
|
|
43
|
-
|
|
23
|
+
urgent: 'PAUSED_SAFETY_NET_URGENT_LABEL',
|
|
24
|
+
callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL',
|
|
25
|
+
later: 'PAUSED_SAFETY_NET_LATER_LABEL'
|
|
44
26
|
};
|
|
45
27
|
|
|
46
28
|
let injected = {};
|
|
@@ -67,20 +49,15 @@ const duration = (key, envKey, fallback) => {
|
|
|
67
49
|
module.exports = {
|
|
68
50
|
CONTACT_WINDOW,
|
|
69
51
|
SAFETY_NET_SOURCE,
|
|
70
|
-
DEFAULT_PLEDGE_MS,
|
|
71
|
-
anyReplyFilter,
|
|
72
52
|
humanReplyFilter,
|
|
73
|
-
settledHumanReplyFilter,
|
|
74
53
|
CHOICE_LABEL_KEYS,
|
|
75
54
|
configureSafetyNet,
|
|
76
55
|
_resetSafetyNetConfig,
|
|
77
56
|
getSafetyNetContentSid: () => text('contentSid', 'PAUSED_SAFETY_NET_CONTENT_SID'),
|
|
78
|
-
getSafetyNetUnassignedContentSid: () => text('unassignedContentSid', 'PAUSED_SAFETY_NET_UNASSIGNED_CONTENT_SID'),
|
|
79
57
|
getSafetyNetPhone: () => text('phone', 'PAUSED_SAFETY_NET_PHONE'),
|
|
80
58
|
getSafetyNetLabel: (choice) => text(`${choice}Label`, CHOICE_LABEL_KEYS[choice]),
|
|
81
59
|
getOfferWindowMs: () => duration('offerWindowMs', 'PAUSED_SAFETY_NET_WINDOW_MS', DEFAULT_OFFER_WINDOW_MS),
|
|
82
60
|
getHumanQuietMs: () => duration('humanQuietMs', 'SAFETY_NET_HUMAN_QUIET_MS', DEFAULT_HUMAN_QUIET_MS),
|
|
83
|
-
getActivityQuietMs: () => duration('activityQuietMs', 'SAFETY_NET_ACTIVITY_QUIET_MS', DEFAULT_ACTIVITY_QUIET_MS),
|
|
84
61
|
getTapWindowMs: () => duration('tapWindowMs', 'SAFETY_NET_TAP_WINDOW_MS', DEFAULT_TAP_WINDOW_MS),
|
|
85
62
|
getPledgeMs: () => duration('pledgeMs', 'SAFETY_NET_PLEDGE_MS', DEFAULT_PLEDGE_MS),
|
|
86
63
|
getSweepIntervalMs: () => duration('sweepIntervalMs', 'SAFETY_NET_SWEEP_INTERVAL_MS', DEFAULT_SWEEP_INTERVAL_MS)
|
|
@@ -15,7 +15,7 @@ const { cleanupFiles } = require('../../helpers/filesHelper.js');
|
|
|
15
15
|
const { getMessages, countMessages } = require('../../services/messageService');
|
|
16
16
|
|
|
17
17
|
const { getAssistantById } = require('./assistantResolver');
|
|
18
|
-
const {
|
|
18
|
+
const { coverUnansweredPatient } = require('./pausedSafetyNetService');
|
|
19
19
|
|
|
20
20
|
const MEDIA_BACKLOG_LIMIT = 10;
|
|
21
21
|
|
|
@@ -112,7 +112,7 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
|
|
|
112
112
|
return { shouldProcess: false, messages: null, timings, pendingMediaUpdates: [] };
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
if (thread.stopped) await coverUnansweredPatient({ code
|
|
115
|
+
if (thread.stopped) await coverUnansweredPatient({ code });
|
|
116
116
|
|
|
117
117
|
const backlog = await fetchMediaBacklog(code, lastMessage[0]);
|
|
118
118
|
const replies = [...backlog, ...lastMessage];
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
const {
|
|
2
|
+
CONTACT_WINDOW,
|
|
2
3
|
SAFETY_NET_SOURCE,
|
|
3
|
-
getActivityQuietMs,
|
|
4
4
|
getHumanQuietMs,
|
|
5
5
|
getOfferWindowMs,
|
|
6
|
+
getPledgeMs,
|
|
6
7
|
getSafetyNetContentSid,
|
|
7
8
|
getSafetyNetLabel,
|
|
8
9
|
getSafetyNetPhone,
|
|
9
|
-
getSafetyNetUnassignedContentSid,
|
|
10
10
|
getTapWindowMs
|
|
11
11
|
} = require('../config/safetyNetConfig');
|
|
12
12
|
const { logger } = require('../../utils/logger');
|
|
@@ -15,23 +15,28 @@ const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../..
|
|
|
15
15
|
|
|
16
16
|
const { normalizePayload: normalize, registerInteractiveRoute, unregisterInteractiveRoute } = require('../../core/interactiveRouteService');
|
|
17
17
|
const { getMessages } = require('../../services/messageService');
|
|
18
|
+
const { getPatientTasks, updatePatientTask } = require('../../services/patientTaskService');
|
|
18
19
|
|
|
19
20
|
const { WriteClaimStore } = require('./writeClaimStore');
|
|
20
|
-
const { recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
21
|
-
const {
|
|
21
|
+
const { PAUSED_THREAD_DETAILS_PREFIX, recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
22
|
+
const { humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
|
|
22
23
|
|
|
23
24
|
const getMessaging = () => require('../../core/NexusMessaging');
|
|
24
25
|
|
|
25
26
|
const SOURCE = SAFETY_NET_SOURCE;
|
|
26
27
|
const PAYLOAD_PREFIX = 'peopl_safetynet_';
|
|
27
|
-
const CHOICES = ['callback'];
|
|
28
|
-
const PAUSED = 'paused';
|
|
29
|
-
const UNASSIGNED = 'unassigned';
|
|
28
|
+
const CHOICES = ['urgent', 'callback', 'later'];
|
|
30
29
|
const REQUEST_CATEGORY = 'contact_team_member';
|
|
30
|
+
const CAN_WAIT_NOTE = 'El paciente indicó que su solicitud puede esperar.';
|
|
31
|
+
const ATTENDED_STATUS = 'sin atender';
|
|
31
32
|
|
|
32
33
|
const REQUEST_COPY = {
|
|
34
|
+
urgent: {
|
|
35
|
+
question: 'El paciente indicó que su situación es urgente',
|
|
36
|
+
details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y eligió "urgencia". Se le dio el número para llamar. Revisar la conversación ahora.`
|
|
37
|
+
},
|
|
33
38
|
callback: {
|
|
34
|
-
question: 'El paciente pidió que el equipo lo contacte',
|
|
39
|
+
question: 'El paciente pidió que el equipo lo contacte hoy',
|
|
35
40
|
details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y pidió que lo contacten. Se le prometió contacto; revisar la conversación.`
|
|
36
41
|
}
|
|
37
42
|
};
|
|
@@ -76,25 +81,15 @@ function matchSafetyNetChoice(payload, title) {
|
|
|
76
81
|
}) || null;
|
|
77
82
|
}
|
|
78
83
|
|
|
79
|
-
const dialledNumbers = (template) => Object.values(template?.types ?? {})
|
|
80
|
-
.flatMap((type) => type?.actions ?? [])
|
|
81
|
-
.filter((action) => action?.type === 'PHONE_NUMBER')
|
|
82
|
-
.map((action) => action?.phone);
|
|
83
|
-
|
|
84
84
|
async function warnIfPhoneDiffersFromTemplate(contentSid) {
|
|
85
85
|
const phone = getSafetyNetPhone();
|
|
86
86
|
if (!phone || phoneCheckedFor === contentSid) return;
|
|
87
87
|
phoneCheckedFor = contentSid;
|
|
88
88
|
try {
|
|
89
|
-
const
|
|
89
|
+
const body = await getMessaging().requireProvider().renderTemplate(contentSid);
|
|
90
90
|
const digits = (value) => String(value ?? '').replace(/\D/g, '');
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (dialledNumbers(await provider.getTemplate(contentSid)).map(digits).includes(wanted)) return;
|
|
94
|
-
|
|
95
|
-
const body = await provider.renderTemplate(contentSid);
|
|
96
|
-
if (body && !digits(body).includes(wanted)) {
|
|
97
|
-
logger.error('[PausedSafetyNet] The configured phone number is absent from the template', { contentSid });
|
|
91
|
+
if (body && !digits(body).includes(digits(phone))) {
|
|
92
|
+
logger.error('[PausedSafetyNet] The configured phone number is absent from the template body', { contentSid });
|
|
98
93
|
}
|
|
99
94
|
} catch (error) {
|
|
100
95
|
phoneCheckedFor = null;
|
|
@@ -102,19 +97,13 @@ async function warnIfPhoneDiffersFromTemplate(contentSid) {
|
|
|
102
97
|
}
|
|
103
98
|
}
|
|
104
99
|
|
|
105
|
-
function
|
|
106
|
-
if (reason !== UNASSIGNED) return getSafetyNetContentSid();
|
|
107
|
-
return getSafetyNetUnassignedContentSid() || getSafetyNetContentSid();
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
100
|
+
async function offerSafetyNet({ code }) {
|
|
111
101
|
try {
|
|
112
|
-
|
|
102
|
+
const contentSid = getSafetyNetContentSid();
|
|
103
|
+
if (!code || !contentSid || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
|
|
113
104
|
if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
|
|
114
105
|
if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
|
|
115
|
-
if (await anyoneRepliedSince(code, new Date(Date.now() - getActivityQuietMs()))) return { sent: false, reason: 'conversation_active' };
|
|
116
106
|
|
|
117
|
-
const contentSid = templateFor(reason);
|
|
118
107
|
await warnIfPhoneDiffersFromTemplate(contentSid);
|
|
119
108
|
|
|
120
109
|
const result = await getMessaging().sendMessage({ code, contentSid, triggeredBy: SOURCE });
|
|
@@ -129,13 +118,11 @@ async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
|
129
118
|
}
|
|
130
119
|
}
|
|
131
120
|
|
|
132
|
-
const offerContentSids = () => [getSafetyNetContentSid(), getSafetyNetUnassignedContentSid()].filter(Boolean);
|
|
133
|
-
|
|
134
121
|
async function offerIsLive(code) {
|
|
135
122
|
try {
|
|
136
123
|
const since = new Date(Date.now() - getOfferWindowMs());
|
|
137
124
|
const [sent] = await getMessages(
|
|
138
|
-
{ numero: code, from_me: true, content_sid:
|
|
125
|
+
{ numero: code, from_me: true, content_sid: getSafetyNetContentSid(), createdAt: { $gt: since } },
|
|
139
126
|
{ sort: { createdAt: -1 }, limit: 1 }
|
|
140
127
|
);
|
|
141
128
|
return Boolean(sent);
|
|
@@ -153,7 +140,7 @@ async function unansweredText(code) {
|
|
|
153
140
|
return written ? written.plainBody || written.body : null;
|
|
154
141
|
}
|
|
155
142
|
|
|
156
|
-
async function coverUnansweredPatient({ code
|
|
143
|
+
async function coverUnansweredPatient({ code }) {
|
|
157
144
|
if (!code) return;
|
|
158
145
|
|
|
159
146
|
const claim = await acquireSendClaim({ idempotencyKey: `safetynet-cover:${code}` });
|
|
@@ -161,7 +148,7 @@ async function coverUnansweredPatient({ code, reason = PAUSED }) {
|
|
|
161
148
|
|
|
162
149
|
const results = await Promise.allSettled([
|
|
163
150
|
unansweredText(code).then((text) => recordPausedThreadMessage({ code, text })),
|
|
164
|
-
offerSafetyNet({ code
|
|
151
|
+
offerSafetyNet({ code }),
|
|
165
152
|
]);
|
|
166
153
|
|
|
167
154
|
const covered = results.every((r) => r.status === 'fulfilled');
|
|
@@ -181,8 +168,32 @@ async function fileUrgentRequest(code, choice) {
|
|
|
181
168
|
});
|
|
182
169
|
}
|
|
183
170
|
|
|
171
|
+
async function markCanWait(code) {
|
|
172
|
+
const { requests = [] } = await getPatientTasks(code);
|
|
173
|
+
const target = requests.find((request) => request.status === ATTENDED_STATUS
|
|
174
|
+
&& request.category === REQUEST_CATEGORY
|
|
175
|
+
&& String(request.details || '').startsWith(PAUSED_THREAD_DETAILS_PREFIX));
|
|
176
|
+
if (!target) return false;
|
|
177
|
+
|
|
178
|
+
await updatePatientTask({
|
|
179
|
+
code,
|
|
180
|
+
kind: 'requests',
|
|
181
|
+
recordId: target.recordId,
|
|
182
|
+
changes: {
|
|
183
|
+
urgency: 'routine',
|
|
184
|
+
note: [target.note, CAN_WAIT_NOTE].filter(Boolean).join('\n')
|
|
185
|
+
},
|
|
186
|
+
updatedBy: SOURCE,
|
|
187
|
+
source: SOURCE
|
|
188
|
+
});
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
184
192
|
async function applyChoice(code, choice) {
|
|
193
|
+
if (choice === 'later') return { queued: true, downgraded: await markCanWait(code), pledge: null };
|
|
194
|
+
|
|
185
195
|
const queued = await fileUrgentRequest(code, choice);
|
|
196
|
+
if (choice !== 'callback') return { queued, pledge: null };
|
|
186
197
|
if (!queued) return { queued, pledge: null };
|
|
187
198
|
|
|
188
199
|
try {
|
|
@@ -207,12 +218,30 @@ function ackFor(choice, outcome) {
|
|
|
207
218
|
return withPhone('No pudimos registrar tu solicitud.', 'Por favor llámanos al {phone} para que te atendamos.');
|
|
208
219
|
}
|
|
209
220
|
|
|
221
|
+
if (choice === 'urgent') {
|
|
222
|
+
return withPhone('Entendido, ya avisamos al equipo.', 'Si es una urgencia médica, llámanos ahora al {phone}.');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (choice === 'later') {
|
|
226
|
+
return outcome.downgraded
|
|
227
|
+
? withPhone('Gracias, lo anotamos. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.')
|
|
228
|
+
: withPhone('Gracias. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.');
|
|
229
|
+
}
|
|
230
|
+
|
|
210
231
|
if (!outcome.pledge) {
|
|
211
232
|
return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
|
|
212
233
|
}
|
|
213
234
|
|
|
235
|
+
if (outcome.pledge.deferredToWindow) {
|
|
236
|
+
return withPhone(
|
|
237
|
+
`Listo, ya avisamos al equipo. Te van a contactar en cuanto abran, a partir de las ${CONTACT_WINDOW.startHour}:00.`,
|
|
238
|
+
'Si es una urgencia médica, llámanos ahora al {phone}.'
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const minutes = Math.round(getPledgeMs() / 60000);
|
|
214
243
|
return withPhone(
|
|
215
|
-
|
|
244
|
+
`Listo. Un miembro del equipo te va a contactar en los próximos ${minutes} minutos.`,
|
|
216
245
|
'Si te sientes peor antes, llámanos al {phone}.'
|
|
217
246
|
);
|
|
218
247
|
}
|
|
@@ -281,8 +310,6 @@ module.exports = {
|
|
|
281
310
|
coverUnansweredPatient,
|
|
282
311
|
disarmSafetyNet,
|
|
283
312
|
offerSafetyNet,
|
|
284
|
-
PAUSED,
|
|
285
|
-
UNASSIGNED,
|
|
286
313
|
handleSafetyNetTap,
|
|
287
314
|
matchSafetyNetChoice,
|
|
288
315
|
registerSafetyNetRoutes,
|
|
@@ -3,9 +3,9 @@ const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
|
3
3
|
const { logger } = require('../../utils/logger');
|
|
4
4
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
5
|
const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
|
|
6
|
-
const { Thread } = require('../../models/threadModel');
|
|
7
6
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
8
7
|
const { createIntervalSweeper } = require('../../utils/intervalSweeper');
|
|
8
|
+
const { botIsPaused: threadIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
9
9
|
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
10
10
|
const { handleTriageCompleted } = require('./triageRecommendationService');
|
|
11
11
|
const { WriteClaimStore } = require('./writeClaimStore');
|
|
@@ -25,6 +25,8 @@ const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttl
|
|
|
25
25
|
|
|
26
26
|
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
27
27
|
|
|
28
|
+
const botIsPaused = (code) => threadIsPaused(code, { label: '[recommendationRecovery]' });
|
|
29
|
+
|
|
28
30
|
function orphanFormula(now) {
|
|
29
31
|
const newest = new Date(now.getTime() - MIN_AGE_MS).toISOString();
|
|
30
32
|
const oldest = new Date(now.getTime() - SCAN_WINDOW_MS).toISOString();
|
|
@@ -53,17 +55,6 @@ function describe(row) {
|
|
|
53
55
|
};
|
|
54
56
|
}
|
|
55
57
|
|
|
56
|
-
async function botIsPaused(code) {
|
|
57
|
-
if (!code) return false;
|
|
58
|
-
try {
|
|
59
|
-
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
60
|
-
return Boolean(paused);
|
|
61
|
-
} catch (error) {
|
|
62
|
-
logger.warn('[recommendationRecovery] thread state unreadable; treating the bot as paused', { code, error: error.message });
|
|
63
|
-
return true;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
58
|
async function fileOpsTicket(orphan) {
|
|
68
59
|
if (!orphan.code) return false;
|
|
69
60
|
return recordUnresolvedRequest({
|
|
@@ -1,10 +1,7 @@
|
|
|
1
|
-
const {
|
|
2
|
-
CONTACT_WINDOW, DEFAULT_PLEDGE_MS, anyReplyFilter, getPledgeMs, getSweepIntervalMs, humanReplyFilter,
|
|
3
|
-
settledHumanReplyFilter
|
|
4
|
-
} = require('../config/safetyNetConfig');
|
|
1
|
+
const { CONTACT_WINDOW, getPledgeMs, getSweepIntervalMs, humanReplyFilter } = require('../config/safetyNetConfig');
|
|
5
2
|
const { createIntervalSweeper } = require('../../utils/intervalSweeper');
|
|
6
3
|
const { logger } = require('../../utils/logger');
|
|
7
|
-
const {
|
|
4
|
+
const { clampToHourWindow } = require('../../utils/scheduleUtils');
|
|
8
5
|
|
|
9
6
|
const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
|
|
10
7
|
|
|
@@ -16,36 +13,24 @@ const SWEEP_LIMIT = 200;
|
|
|
16
13
|
const BREACH_CATEGORY = 'contact_team_member';
|
|
17
14
|
const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
|
|
18
15
|
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
async function repliedSince(filter) {
|
|
23
|
-
const [reply] = await getMessages(filter, { sort: { createdAt: -1 }, limit: 1 });
|
|
16
|
+
async function humanRepliedSince(code, since) {
|
|
17
|
+
const [reply] = await getMessages(humanReplyFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
|
|
24
18
|
return Boolean(reply);
|
|
25
19
|
}
|
|
26
20
|
|
|
27
|
-
const humanRepliedSince = (code, since) => repliedSince(humanReplyFilter(code, since));
|
|
28
|
-
const humanReplySettledSince = (code, since) => repliedSince(
|
|
29
|
-
settledHumanReplyFilter(code, since, new Date(Date.now() - DELIVERY_GRACE_MS))
|
|
30
|
-
);
|
|
31
|
-
const anyoneRepliedSince = (code, since) => repliedSince(anyReplyFilter(code, since));
|
|
32
|
-
|
|
33
21
|
function pledgeDueAt(pledgedAt) {
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
pledgeMs: getPledgeMs()
|
|
39
|
-
});
|
|
40
|
-
return { dueAt: addContactHours(pledgedAt, DEFAULT_PLEDGE_MS / HOUR_MS, CONTACT_WINDOW) };
|
|
22
|
+
const target = new Date(pledgedAt.getTime() + getPledgeMs());
|
|
23
|
+
const opened = clampToHourWindow(target, CONTACT_WINDOW);
|
|
24
|
+
if (!opened) return { dueAt: target, deferredToWindow: false };
|
|
25
|
+
return { dueAt: opened, deferredToWindow: opened.getTime() > target.getTime() };
|
|
41
26
|
}
|
|
42
27
|
|
|
43
28
|
async function openPledge({ code }) {
|
|
44
29
|
const pledgedAt = new Date();
|
|
45
|
-
const { dueAt } = pledgeDueAt(pledgedAt);
|
|
46
|
-
const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt });
|
|
47
|
-
logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt });
|
|
48
|
-
return { pledgeId: pledge._id, dueAt };
|
|
30
|
+
const { dueAt, deferredToWindow } = pledgeDueAt(pledgedAt);
|
|
31
|
+
const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt, deferredToWindow });
|
|
32
|
+
logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt, deferredToWindow });
|
|
33
|
+
return { pledgeId: pledge._id, dueAt, deferredToWindow };
|
|
49
34
|
}
|
|
50
35
|
|
|
51
36
|
async function reportBreach(pledge) {
|
|
@@ -66,11 +51,6 @@ const settle = async (id, from, state) => Boolean(
|
|
|
66
51
|
await SafetyNetPledge.findOneAndUpdate({ _id: id, state: from }, { $set: { state, resolvedAt: new Date() } }).lean()
|
|
67
52
|
);
|
|
68
53
|
|
|
69
|
-
const returnToPending = (id) => SafetyNetPledge.updateOne(
|
|
70
|
-
{ _id: id, state: 'reporting' },
|
|
71
|
-
{ $set: { state: 'pending', reportingSince: null } }
|
|
72
|
-
);
|
|
73
|
-
|
|
74
54
|
const takeReportingLease = async (id) => Boolean(
|
|
75
55
|
await SafetyNetPledge.findOneAndUpdate(
|
|
76
56
|
{ _id: id, $or: [{ state: 'pending' }, { state: 'reporting', reportingSince: { $lt: new Date(Date.now() - REPORT_LEASE_MS) } }] },
|
|
@@ -93,18 +73,13 @@ async function sweepSafetyNetPledges() {
|
|
|
93
73
|
try {
|
|
94
74
|
if (!await takeReportingLease(pledge._id)) continue;
|
|
95
75
|
|
|
96
|
-
if (await humanReplySettledSince(pledge.code, pledge.pledgedAt)) {
|
|
97
|
-
await settle(pledge._id, 'reporting', 'met');
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
76
|
if (await humanRepliedSince(pledge.code, pledge.pledgedAt)) {
|
|
102
|
-
await
|
|
77
|
+
await settle(pledge._id, 'reporting', 'met');
|
|
103
78
|
continue;
|
|
104
79
|
}
|
|
105
80
|
|
|
106
81
|
if (!await reportBreach(pledge)) {
|
|
107
|
-
await
|
|
82
|
+
await SafetyNetPledge.updateOne({ _id: pledge._id, state: 'reporting' }, { $set: { state: 'pending', reportingSince: null } });
|
|
108
83
|
logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
|
|
109
84
|
continue;
|
|
110
85
|
}
|
|
@@ -129,9 +104,7 @@ const stopSafetyNetSweep = () => sweeper.stop();
|
|
|
129
104
|
module.exports = {
|
|
130
105
|
startSafetyNetSweep,
|
|
131
106
|
stopSafetyNetSweep,
|
|
132
|
-
anyoneRepliedSince,
|
|
133
107
|
humanRepliedSince,
|
|
134
|
-
humanReplySettledSince,
|
|
135
108
|
openPledge,
|
|
136
109
|
pledgeDueAt,
|
|
137
110
|
sweepSafetyNetPledges,
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -5,6 +5,7 @@ const { logger } = require('../utils/logger');
|
|
|
5
5
|
const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
|
|
6
6
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
7
7
|
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
8
|
+
const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
|
|
8
9
|
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
9
10
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
10
11
|
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
@@ -19,7 +20,7 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
|
19
20
|
const SWEEP_STOP_MS = 2000;
|
|
20
21
|
|
|
21
22
|
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
22
|
-
const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep()]);
|
|
23
|
+
const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep()]);
|
|
23
24
|
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
24
25
|
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
25
26
|
}
|
|
@@ -31,7 +31,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
|
|
|
31
31
|
const { BatchingManager } = require('../core/BatchingManager');
|
|
32
32
|
const { ProcessingPipeline } = require('../core/ProcessingPipeline');
|
|
33
33
|
const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
|
|
34
|
-
const {
|
|
34
|
+
const { coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
|
|
35
35
|
const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
|
|
36
36
|
const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
|
|
37
37
|
const {
|
|
@@ -674,54 +674,75 @@ class NexusMessaging {
|
|
|
674
674
|
|
|
675
675
|
async _handleWithCheckAfter(chatId) {
|
|
676
676
|
return await this._executeWithPipeline(chatId, 'message', 'preempt',
|
|
677
|
-
async (preProcessResult, shouldContinue, runId) =>
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
return null;
|
|
682
|
-
});
|
|
683
|
-
if (!resolved) {
|
|
684
|
-
await coverUnansweredPatient({ code: chatId, reason: UNASSIGNED });
|
|
685
|
-
return null;
|
|
686
|
-
}
|
|
677
|
+
async (preProcessResult, shouldContinue, runId) =>
|
|
678
|
+
this._runPatientTurn(chatId, preProcessResult, shouldContinue, runId)
|
|
679
|
+
);
|
|
680
|
+
}
|
|
687
681
|
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
{ message_id: u.message_id },
|
|
695
|
-
{ $set: {
|
|
696
|
-
assistant_id: u.assistantId,
|
|
697
|
-
thread_id: u.threadId,
|
|
698
|
-
'media.metadata.processedContent': encoded,
|
|
699
|
-
}}
|
|
700
|
-
),
|
|
701
|
-
() => null,
|
|
702
|
-
)
|
|
703
|
-
));
|
|
704
|
-
|
|
705
|
-
if (!preProcessed.shouldProcess) return null;
|
|
706
|
-
|
|
707
|
-
const result = await this.assistantProcessor.executeLLM(
|
|
708
|
-
resolved.thread, resolved.assistant,
|
|
709
|
-
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
710
|
-
preProcessed.messages[0]
|
|
711
|
-
);
|
|
682
|
+
async recoverInboundTurn(code, { confirmStillUnanswered = null } = {}) {
|
|
683
|
+
return await this._executeWithPipeline(code, 'message', 'queue',
|
|
684
|
+
async (preProcessResult, shouldContinue, runId) =>
|
|
685
|
+
this._runPatientTurn(code, preProcessResult, shouldContinue, runId, { confirmStillUnanswered })
|
|
686
|
+
);
|
|
687
|
+
}
|
|
712
688
|
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
}, shouldContinue, runId);
|
|
689
|
+
async _runPatientTurn(chatId, preProcessResult, shouldContinue, runId, { confirmStillUnanswered = null } = {}) {
|
|
690
|
+
return await this._processMessages(chatId, async () => {
|
|
691
|
+
const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
|
|
692
|
+
logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
|
|
693
|
+
return null;
|
|
694
|
+
});
|
|
695
|
+
if (!resolved) {
|
|
696
|
+
await coverUnansweredPatient({ code: chatId });
|
|
697
|
+
return null;
|
|
723
698
|
}
|
|
724
|
-
|
|
699
|
+
|
|
700
|
+
const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
|
|
701
|
+
|
|
702
|
+
await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
|
|
703
|
+
this.phiProcessor.inData(
|
|
704
|
+
{ body: u.processedContent, code: chatId },
|
|
705
|
+
({ body: encoded }) => updateMessage(
|
|
706
|
+
{ message_id: u.message_id },
|
|
707
|
+
{ $set: {
|
|
708
|
+
assistant_id: u.assistantId,
|
|
709
|
+
thread_id: u.threadId,
|
|
710
|
+
'media.metadata.processedContent': encoded,
|
|
711
|
+
}}
|
|
712
|
+
),
|
|
713
|
+
() => null,
|
|
714
|
+
)
|
|
715
|
+
));
|
|
716
|
+
|
|
717
|
+
if (!preProcessed.shouldProcess) return null;
|
|
718
|
+
|
|
719
|
+
if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
|
|
720
|
+
logger.info('[inboundRecovery] a reply landed while the replay was queued; standing down', { code: chatId });
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const result = await this.assistantProcessor.executeLLM(
|
|
725
|
+
resolved.thread, resolved.assistant,
|
|
726
|
+
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
727
|
+
preProcessed.messages[0]
|
|
728
|
+
);
|
|
729
|
+
|
|
730
|
+
if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
|
|
731
|
+
logger.info('[inboundRecovery] a reply landed while the replay was generating; discarding it', { code: chatId });
|
|
732
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
733
|
+
return null;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
try {
|
|
737
|
+
if (storeRunMetrics) {
|
|
738
|
+
await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
|
|
739
|
+
}
|
|
740
|
+
} catch (error) {
|
|
741
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
742
|
+
throw error;
|
|
743
|
+
}
|
|
744
|
+
return { ...result, timings: preProcessed.timings };
|
|
745
|
+
}, shouldContinue, runId);
|
|
725
746
|
}
|
|
726
747
|
|
|
727
748
|
async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { Thread } = require('../models/threadModel');
|
|
3
|
+
|
|
4
|
+
async function botIsPaused(code, { label = '[pausedThread]' } = {}) {
|
|
5
|
+
if (!code) return false;
|
|
6
|
+
try {
|
|
7
|
+
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
8
|
+
return Boolean(paused);
|
|
9
|
+
} catch (error) {
|
|
10
|
+
logger.warn(`${label} thread state unreadable; treating the bot as paused`, { code, error: error.message });
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { botIsPaused };
|
package/lib/index.d.ts
CHANGED
|
@@ -331,6 +331,7 @@ declare module '@peopl-health/nexus' {
|
|
|
331
331
|
parserConfig?: ParserConfig;
|
|
332
332
|
ner?: NerOptions;
|
|
333
333
|
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
334
|
+
inboundRecovery?: InboundRecoveryOptions;
|
|
334
335
|
}
|
|
335
336
|
|
|
336
337
|
export interface RecommendationRecoveryOptions {
|
|
@@ -338,6 +339,11 @@ declare module '@peopl-health/nexus' {
|
|
|
338
339
|
intervalMs?: number;
|
|
339
340
|
}
|
|
340
341
|
|
|
342
|
+
export interface InboundRecoveryOptions {
|
|
343
|
+
enabled: boolean;
|
|
344
|
+
intervalMs?: number;
|
|
345
|
+
}
|
|
346
|
+
|
|
341
347
|
export interface NerEntity {
|
|
342
348
|
start: number;
|
|
343
349
|
end: number;
|
package/lib/index.js
CHANGED
|
@@ -31,6 +31,7 @@ const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
|
|
|
31
31
|
const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
|
|
32
32
|
const { startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
33
|
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
|
+
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
34
35
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
35
36
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
36
37
|
const { createWorkflowRunner } = require('./core/workflowRunner');
|
|
@@ -199,6 +200,19 @@ class Nexus {
|
|
|
199
200
|
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
200
201
|
}
|
|
201
202
|
|
|
203
|
+
try {
|
|
204
|
+
if (options.inboundRecovery?.enabled === true) {
|
|
205
|
+
startInboundRecoverySweep({
|
|
206
|
+
recover: (code, opts) => this.messaging.recoverInboundTurn(code, opts),
|
|
207
|
+
isProcessing: (code) => this.messaging.isProcessing(code),
|
|
208
|
+
intervalMs: options.inboundRecovery.intervalMs,
|
|
209
|
+
});
|
|
210
|
+
logger.info('[Nexus] inbound recovery sweep armed');
|
|
211
|
+
}
|
|
212
|
+
} catch (e) {
|
|
213
|
+
logger.warn('Warning: failed to arm the inbound recovery sweep:', e?.message || e);
|
|
214
|
+
}
|
|
215
|
+
|
|
202
216
|
try {
|
|
203
217
|
if (options.recommendationRecovery?.enabled === true) {
|
|
204
218
|
startRecommendationRecoverySweep({ intervalMs: options.recommendationRecovery.intervalMs });
|
|
@@ -6,6 +6,7 @@ const safetyNetPledgeSchema = new mongoose.Schema({
|
|
|
6
6
|
code: { type: String, required: true },
|
|
7
7
|
pledgedAt: { type: Date, required: true },
|
|
8
8
|
dueAt: { type: Date, required: true },
|
|
9
|
+
deferredToWindow: { type: Boolean, default: false },
|
|
9
10
|
state: { type: String, enum: PLEDGE_STATES, default: 'pending' },
|
|
10
11
|
reportingSince: { type: Date, default: null },
|
|
11
12
|
resolvedAt: { type: Date, default: null },
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { isWithinHourWindow } = require('../utils/scheduleUtils');
|
|
4
|
+
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
5
|
+
const { Thread } = require('../models/threadModel');
|
|
6
|
+
const { botIsPaused } = require('../helpers/pausedThreadHelper');
|
|
7
|
+
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
8
|
+
const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
9
|
+
const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
10
|
+
const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
|
|
11
|
+
const { getMessages, countMessages } = require('./messageService');
|
|
12
|
+
|
|
13
|
+
const MIN_AGE_MS = 5 * 60 * 1000;
|
|
14
|
+
const MAX_AGE_MS = 60 * 60 * 1000;
|
|
15
|
+
const SCAN_LIMIT = 200;
|
|
16
|
+
const MAX_CANDIDATES = 20;
|
|
17
|
+
const MAX_RECOVERIES_PER_PASS = 3;
|
|
18
|
+
const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
|
|
19
|
+
const REPLAY_SETTLE_MS = 5 * 60 * 1000;
|
|
20
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
21
|
+
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
|
|
22
|
+
|
|
23
|
+
const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
24
|
+
const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
25
|
+
|
|
26
|
+
async function unansweredThreads(now) {
|
|
27
|
+
return Thread.find(
|
|
28
|
+
{
|
|
29
|
+
stopped: false,
|
|
30
|
+
lastMessageFromMe: false,
|
|
31
|
+
lastMessageAt: { $gte: new Date(now.getTime() - MAX_AGE_MS), $lte: new Date(now.getTime() - MIN_AGE_MS) },
|
|
32
|
+
},
|
|
33
|
+
{ code: 1, lastMessageAt: 1 },
|
|
34
|
+
).sort({ lastMessageAt: 1 }).limit(SCAN_LIMIT).lean();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
|
|
38
|
+
|
|
39
|
+
async function stillUnanswered(code, now = new Date()) {
|
|
40
|
+
const [newest] = await getMessages(
|
|
41
|
+
{ numero: code, from_me: false, interactive_type: null },
|
|
42
|
+
{ select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
|
|
43
|
+
);
|
|
44
|
+
if (!newest) return null;
|
|
45
|
+
|
|
46
|
+
const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
|
|
47
|
+
if (!Number.isFinite(ageMs) || ageMs < MIN_AGE_MS || ageMs > MAX_AGE_MS) return null;
|
|
48
|
+
|
|
49
|
+
const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt } });
|
|
50
|
+
return replies === 0 ? newest : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function fileTicket(code, alert) {
|
|
54
|
+
try {
|
|
55
|
+
return Boolean(await alert({ code, category: 'contact_team_member', question: 'El paciente escribió y no recibió respuesta.' }));
|
|
56
|
+
} catch (error) {
|
|
57
|
+
logger.error('[inboundRecovery] could not file the ops ticket', { code, error: error.message });
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function sweepUnansweredInbound({
|
|
63
|
+
now = new Date(),
|
|
64
|
+
recover = null,
|
|
65
|
+
isProcessing = () => false,
|
|
66
|
+
live = inboundRecoveryLive,
|
|
67
|
+
claims = recoveryClaims,
|
|
68
|
+
ticketGate = ticketClaims,
|
|
69
|
+
isPaused = threadIsOwnedByAHuman,
|
|
70
|
+
alert = recordUnresolvedRequest,
|
|
71
|
+
} = {}) {
|
|
72
|
+
let threads;
|
|
73
|
+
try {
|
|
74
|
+
threads = await unansweredThreads(now);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
|
|
77
|
+
return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const candidates = [];
|
|
81
|
+
for (const thread of threads) {
|
|
82
|
+
if (!thread.code) continue;
|
|
83
|
+
if (isProcessing(thread.code)) continue;
|
|
84
|
+
try {
|
|
85
|
+
const inbound = await stillUnanswered(thread.code, now);
|
|
86
|
+
if (inbound) candidates.push({ code: thread.code, inbound });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
|
|
89
|
+
code: thread.code, error: error.message,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!candidates.length) return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
95
|
+
|
|
96
|
+
if (candidates.length > MAX_CANDIDATES) {
|
|
97
|
+
logger.error('[inboundRecovery] too many patients look unanswered; acting on none', {
|
|
98
|
+
found: candidates.length, ceiling: MAX_CANDIDATES,
|
|
99
|
+
});
|
|
100
|
+
return { scanned: candidates.length, recovered: 0, alerted: 0, skipped: candidates.length };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const canRecover = live() && typeof recover === 'function';
|
|
104
|
+
let recovered = 0;
|
|
105
|
+
let alerted = 0;
|
|
106
|
+
let skipped = 0;
|
|
107
|
+
|
|
108
|
+
for (const { code, inbound } of candidates) {
|
|
109
|
+
const key = String(inbound._id);
|
|
110
|
+
const ageMs = now.getTime() - new Date(inbound.createdAt).getTime();
|
|
111
|
+
|
|
112
|
+
if (await isPaused(code)) { skipped += 1; continue; }
|
|
113
|
+
|
|
114
|
+
const claim = await claims.acquire(key, 'handled');
|
|
115
|
+
if (claim === 'unavailable') {
|
|
116
|
+
skipped += 1;
|
|
117
|
+
logger.error('[inboundRecovery] patient looks unanswered and could not be claimed', { code, ageMs });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (claim === 'taken') {
|
|
122
|
+
const claimedAt = typeof claims.claimedAtMs === 'function' ? await claims.claimedAtMs(key) : null;
|
|
123
|
+
if (claimedAt === null || (now.getTime() - claimedAt) < REPLAY_SETTLE_MS) { skipped += 1; continue; }
|
|
124
|
+
|
|
125
|
+
const ticket = await ticketGate.acquire(key, 'alerted');
|
|
126
|
+
if (ticket !== 'acquired') { skipped += 1; continue; }
|
|
127
|
+
|
|
128
|
+
logger.error('[inboundRecovery] a replay already ran and the patient is still unanswered', { code, ageMs });
|
|
129
|
+
if (await fileTicket(code, alert)) {
|
|
130
|
+
alerted += 1;
|
|
131
|
+
} else {
|
|
132
|
+
await ticketGate.release(key);
|
|
133
|
+
}
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const reachable = isWithinHourWindow(now, PATIENT_CONTACT_WINDOW) && await isWithin24HourWindow(code);
|
|
138
|
+
|
|
139
|
+
if (canRecover && reachable && recovered < MAX_RECOVERIES_PER_PASS) {
|
|
140
|
+
logger.error('[inboundRecovery] patient was left unanswered, replaying the turn', { code, ageMs });
|
|
141
|
+
try {
|
|
142
|
+
await recover(code);
|
|
143
|
+
recovered += 1;
|
|
144
|
+
continue;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
await claims.release(key);
|
|
147
|
+
logger.error('[inboundRecovery] replay could not be dispatched', { code, ageMs, error: error.message });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
logger.error('[inboundRecovery] patient was left unanswered', {
|
|
153
|
+
code, ageMs, recoveryLive: canRecover, reachable,
|
|
154
|
+
});
|
|
155
|
+
if (await fileTicket(code, alert)) {
|
|
156
|
+
alerted += 1;
|
|
157
|
+
} else {
|
|
158
|
+
await claims.release(key);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { scanned: candidates.length, recovered, alerted, skipped };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function sweepIntervalMs() {
|
|
166
|
+
const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
|
|
167
|
+
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
let sweeper = null;
|
|
171
|
+
|
|
172
|
+
function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
|
|
173
|
+
if (!sweeper) {
|
|
174
|
+
sweeper = createIntervalSweeper({
|
|
175
|
+
label: '[inboundRecovery]',
|
|
176
|
+
sweep: () => sweepUnansweredInbound({
|
|
177
|
+
recover: typeof recover === 'function'
|
|
178
|
+
? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
|
|
179
|
+
: null,
|
|
180
|
+
isProcessing,
|
|
181
|
+
}),
|
|
182
|
+
defaultIntervalMs: sweepIntervalMs,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return sweeper.start({ intervalMs });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function stopInboundRecoverySweep() {
|
|
189
|
+
if (!sweeper) return Promise.resolve();
|
|
190
|
+
const stopping = sweeper.stop();
|
|
191
|
+
sweeper = null;
|
|
192
|
+
return stopping;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = {
|
|
196
|
+
startInboundRecoverySweep,
|
|
197
|
+
stopInboundRecoverySweep,
|
|
198
|
+
sweepUnansweredInbound,
|
|
199
|
+
DEFAULT_SWEEP_INTERVAL_MS,
|
|
200
|
+
stillUnanswered,
|
|
201
|
+
threadIsOwnedByAHuman,
|
|
202
|
+
_claims: recoveryClaims,
|
|
203
|
+
_ticketClaims: ticketClaims,
|
|
204
|
+
MIN_AGE_MS,
|
|
205
|
+
MAX_AGE_MS,
|
|
206
|
+
MAX_CANDIDATES,
|
|
207
|
+
MAX_RECOVERIES_PER_PASS,
|
|
208
|
+
SCAN_LIMIT,
|
|
209
|
+
};
|
|
@@ -50,29 +50,6 @@ function contactHoursBetween(from, to, { timeZone, startHour, endHour }) {
|
|
|
50
50
|
return cursor.isBefore(end) ? Infinity : total;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
function addContactHours(from, hours, { timeZone, startHour, endHour }) {
|
|
54
|
-
const start = moment.tz(from, timeZone);
|
|
55
|
-
if (!start.isValid() || !(hours >= 0)) {
|
|
56
|
-
logger.warn('[addContactHours] Invalid input', { from, hours, timeZone });
|
|
57
|
-
return null;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
let remaining = hours * 60 * 60 * 1000;
|
|
61
|
-
let cursor = start.clone();
|
|
62
|
-
for (let day = 0; day < MAX_CONTACT_SPAN_DAYS; day += 1) {
|
|
63
|
-
const opens = cursor.clone().startOf('day').hour(startHour);
|
|
64
|
-
const closes = cursor.clone().startOf('day').hour(endHour);
|
|
65
|
-
if (cursor.isBefore(opens)) cursor = opens;
|
|
66
|
-
if (cursor.isBefore(closes)) {
|
|
67
|
-
const available = closes.diff(cursor);
|
|
68
|
-
if (remaining < available) return cursor.clone().add(remaining, 'ms').toDate();
|
|
69
|
-
remaining -= available;
|
|
70
|
-
}
|
|
71
|
-
cursor = opens.clone().add(1, 'day');
|
|
72
|
-
}
|
|
73
|
-
return null;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
53
|
function calculateDelay(sendTime, timeZone) {
|
|
77
54
|
if (!sendTime) return DEFAULT_DELAY;
|
|
78
55
|
|
|
@@ -111,4 +88,4 @@ function calculateDelay(sendTime, timeZone) {
|
|
|
111
88
|
}
|
|
112
89
|
}
|
|
113
90
|
|
|
114
|
-
module.exports = {
|
|
91
|
+
module.exports = { calculateDelay, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
|