@peopl-health/nexus 5.54.0-dev.7969 → 5.54.0-dev.7971
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -4,7 +4,7 @@ const DEFAULT_OFFER_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
|
4
4
|
const DEFAULT_HUMAN_QUIET_MS = 24 * 60 * 60 * 1000;
|
|
5
5
|
const DEFAULT_ACTIVITY_QUIET_MS = 2 * 60 * 60 * 1000;
|
|
6
6
|
const DEFAULT_TAP_WINDOW_MS = 30 * 60 * 1000;
|
|
7
|
-
const DEFAULT_PLEDGE_MS =
|
|
7
|
+
const DEFAULT_PLEDGE_MS = 8 * 60 * 60 * 1000;
|
|
8
8
|
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
9
9
|
|
|
10
10
|
const CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
|
|
@@ -14,6 +14,7 @@ const SAFETY_NET_SOURCE = 'paused_safety_net';
|
|
|
14
14
|
const PATIENT_FACING_ORIGINS = ['whatsapp_platform', 'assistant'];
|
|
15
15
|
const HUMAN_ORIGINS = ['whatsapp_platform'];
|
|
16
16
|
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|
|
17
|
+
const RECEIVED_STATUSES = ['delivered', 'read'];
|
|
17
18
|
|
|
18
19
|
const anyReplyFilter = (code, since) => ({
|
|
19
20
|
numero: code,
|
|
@@ -30,6 +31,14 @@ const humanReplyFilter = (code, since) => ({
|
|
|
30
31
|
origin: { $in: HUMAN_ORIGINS }
|
|
31
32
|
});
|
|
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
|
+
|
|
33
42
|
const CHOICE_LABEL_KEYS = {
|
|
34
43
|
callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL'
|
|
35
44
|
};
|
|
@@ -58,8 +67,10 @@ const duration = (key, envKey, fallback) => {
|
|
|
58
67
|
module.exports = {
|
|
59
68
|
CONTACT_WINDOW,
|
|
60
69
|
SAFETY_NET_SOURCE,
|
|
70
|
+
DEFAULT_PLEDGE_MS,
|
|
61
71
|
anyReplyFilter,
|
|
62
72
|
humanReplyFilter,
|
|
73
|
+
settledHumanReplyFilter,
|
|
63
74
|
CHOICE_LABEL_KEYS,
|
|
64
75
|
configureSafetyNet,
|
|
65
76
|
_resetSafetyNetConfig,
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
const {
|
|
2
|
-
CONTACT_WINDOW,
|
|
3
2
|
SAFETY_NET_SOURCE,
|
|
4
3
|
getActivityQuietMs,
|
|
5
4
|
getHumanQuietMs,
|
|
6
5
|
getOfferWindowMs,
|
|
7
|
-
getPledgeMs,
|
|
8
6
|
getSafetyNetContentSid,
|
|
9
7
|
getSafetyNetLabel,
|
|
10
8
|
getSafetyNetPhone,
|
|
@@ -200,17 +198,6 @@ const withPhone = (text, closing) => {
|
|
|
200
198
|
return phone ? `${text} ${closing.replace('{phone}', phone)}` : text;
|
|
201
199
|
};
|
|
202
200
|
|
|
203
|
-
function pledgeWindowText() {
|
|
204
|
-
const minutes = Math.ceil(getPledgeMs() / 60000);
|
|
205
|
-
if (minutes < 120) return `en los próximos ${minutes} minutos`;
|
|
206
|
-
|
|
207
|
-
const hours = Math.ceil(minutes / 60);
|
|
208
|
-
if (hours < 24) return `en las próximas ${hours} horas`;
|
|
209
|
-
|
|
210
|
-
const days = Math.ceil(hours / 24);
|
|
211
|
-
return days <= 1 ? 'en menos de 24 horas' : `en menos de ${days} días`;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
201
|
function ackFor(choice, outcome) {
|
|
215
202
|
if (outcome.stale) {
|
|
216
203
|
return withPhone('Recibimos tu respuesta y el equipo va a revisar tu conversación.', 'Si necesitas ayuda ahora, llámanos al {phone}.');
|
|
@@ -224,15 +211,8 @@ function ackFor(choice, outcome) {
|
|
|
224
211
|
return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
|
|
225
212
|
}
|
|
226
213
|
|
|
227
|
-
if (outcome.pledge.deferredToWindow) {
|
|
228
|
-
return withPhone(
|
|
229
|
-
`Listo, ya avisamos al equipo. Te van a contactar en cuanto abran, a partir de las ${CONTACT_WINDOW.startHour}:00.`,
|
|
230
|
-
'Si es una urgencia médica, llámanos ahora al {phone}.'
|
|
231
|
-
);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
214
|
return withPhone(
|
|
235
|
-
|
|
215
|
+
'Listo. Un miembro del equipo te va a contactar a la brevedad.',
|
|
236
216
|
'Si te sientes peor antes, llámanos al {phone}.'
|
|
237
217
|
);
|
|
238
218
|
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
const {
|
|
1
|
+
const {
|
|
2
|
+
CONTACT_WINDOW, DEFAULT_PLEDGE_MS, anyReplyFilter, getPledgeMs, getSweepIntervalMs, humanReplyFilter,
|
|
3
|
+
settledHumanReplyFilter
|
|
4
|
+
} = require('../config/safetyNetConfig');
|
|
2
5
|
const { createIntervalSweeper } = require('../../utils/intervalSweeper');
|
|
3
6
|
const { logger } = require('../../utils/logger');
|
|
4
|
-
const {
|
|
7
|
+
const { addContactHours } = require('../../utils/scheduleUtils');
|
|
5
8
|
|
|
6
9
|
const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
|
|
7
10
|
|
|
@@ -13,33 +16,36 @@ const SWEEP_LIMIT = 200;
|
|
|
13
16
|
const BREACH_CATEGORY = 'contact_team_member';
|
|
14
17
|
const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
|
|
15
18
|
|
|
19
|
+
const DELIVERY_GRACE_MS = 10 * 60 * 1000;
|
|
20
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
21
|
+
|
|
16
22
|
async function repliedSince(filter) {
|
|
17
23
|
const [reply] = await getMessages(filter, { sort: { createdAt: -1 }, limit: 1 });
|
|
18
24
|
return Boolean(reply);
|
|
19
25
|
}
|
|
20
26
|
|
|
21
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
|
+
);
|
|
22
31
|
const anyoneRepliedSince = (code, since) => repliedSince(anyReplyFilter(code, since));
|
|
23
32
|
|
|
24
33
|
function pledgeDueAt(pledgedAt) {
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
const pulled = clampBackToHourWindow(target, CONTACT_WINDOW);
|
|
28
|
-
if (pulled && pulled.getTime() > pledgedAt.getTime()) {
|
|
29
|
-
return { dueAt: pulled, deferredToWindow: false };
|
|
30
|
-
}
|
|
34
|
+
const configured = addContactHours(pledgedAt, getPledgeMs() / HOUR_MS, CONTACT_WINDOW);
|
|
35
|
+
if (configured) return { dueAt: configured };
|
|
31
36
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
37
|
+
logger.error('[SafetyNetPledge] The configured pledge does not fit in working hours; using the default', {
|
|
38
|
+
pledgeMs: getPledgeMs()
|
|
39
|
+
});
|
|
40
|
+
return { dueAt: addContactHours(pledgedAt, DEFAULT_PLEDGE_MS / HOUR_MS, CONTACT_WINDOW) };
|
|
35
41
|
}
|
|
36
42
|
|
|
37
43
|
async function openPledge({ code }) {
|
|
38
44
|
const pledgedAt = new Date();
|
|
39
|
-
const { dueAt
|
|
40
|
-
const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt
|
|
41
|
-
logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt
|
|
42
|
-
return { pledgeId: pledge._id, dueAt
|
|
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 };
|
|
43
49
|
}
|
|
44
50
|
|
|
45
51
|
async function reportBreach(pledge) {
|
|
@@ -60,6 +66,11 @@ const settle = async (id, from, state) => Boolean(
|
|
|
60
66
|
await SafetyNetPledge.findOneAndUpdate({ _id: id, state: from }, { $set: { state, resolvedAt: new Date() } }).lean()
|
|
61
67
|
);
|
|
62
68
|
|
|
69
|
+
const returnToPending = (id) => SafetyNetPledge.updateOne(
|
|
70
|
+
{ _id: id, state: 'reporting' },
|
|
71
|
+
{ $set: { state: 'pending', reportingSince: null } }
|
|
72
|
+
);
|
|
73
|
+
|
|
63
74
|
const takeReportingLease = async (id) => Boolean(
|
|
64
75
|
await SafetyNetPledge.findOneAndUpdate(
|
|
65
76
|
{ _id: id, $or: [{ state: 'pending' }, { state: 'reporting', reportingSince: { $lt: new Date(Date.now() - REPORT_LEASE_MS) } }] },
|
|
@@ -82,13 +93,18 @@ async function sweepSafetyNetPledges() {
|
|
|
82
93
|
try {
|
|
83
94
|
if (!await takeReportingLease(pledge._id)) continue;
|
|
84
95
|
|
|
85
|
-
if (await
|
|
96
|
+
if (await humanReplySettledSince(pledge.code, pledge.pledgedAt)) {
|
|
86
97
|
await settle(pledge._id, 'reporting', 'met');
|
|
87
98
|
continue;
|
|
88
99
|
}
|
|
89
100
|
|
|
101
|
+
if (await humanRepliedSince(pledge.code, pledge.pledgedAt)) {
|
|
102
|
+
await returnToPending(pledge._id);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
|
|
90
106
|
if (!await reportBreach(pledge)) {
|
|
91
|
-
await
|
|
107
|
+
await returnToPending(pledge._id);
|
|
92
108
|
logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
|
|
93
109
|
continue;
|
|
94
110
|
}
|
|
@@ -115,6 +131,7 @@ module.exports = {
|
|
|
115
131
|
stopSafetyNetSweep,
|
|
116
132
|
anyoneRepliedSince,
|
|
117
133
|
humanRepliedSince,
|
|
134
|
+
humanReplySettledSince,
|
|
118
135
|
openPledge,
|
|
119
136
|
pledgeDueAt,
|
|
120
137
|
sweepSafetyNetPledges,
|
|
@@ -6,7 +6,6 @@ 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 },
|
|
10
9
|
state: { type: String, enum: PLEDGE_STATES, default: 'pending' },
|
|
11
10
|
reportingSince: { type: Date, default: null },
|
|
12
11
|
resolvedAt: { type: Date, default: null },
|
|
@@ -18,18 +18,6 @@ function clampToHourWindow(when, { timeZone, startHour, endHour }) {
|
|
|
18
18
|
return local.startOf('day').hour(startHour).toDate();
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
function clampBackToHourWindow(when, { timeZone, startHour, endHour }) {
|
|
22
|
-
const local = moment.tz(when, timeZone);
|
|
23
|
-
if (!local.isValid()) {
|
|
24
|
-
logger.warn('[clampBackToHourWindow] Invalid date', { when, timeZone });
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
const hour = local.hour();
|
|
28
|
-
if (hour >= startHour && hour < endHour) return local.toDate();
|
|
29
|
-
if (hour < startHour) local.subtract(1, 'day');
|
|
30
|
-
return local.startOf('day').hour(endHour).subtract(1, 'minute').toDate();
|
|
31
|
-
}
|
|
32
|
-
|
|
33
21
|
function isWithinHourWindow(when, { timeZone, startHour, endHour }) {
|
|
34
22
|
const local = moment.tz(when, timeZone);
|
|
35
23
|
if (!local.isValid()) {
|
|
@@ -62,6 +50,29 @@ function contactHoursBetween(from, to, { timeZone, startHour, endHour }) {
|
|
|
62
50
|
return cursor.isBefore(end) ? Infinity : total;
|
|
63
51
|
}
|
|
64
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
|
+
|
|
65
76
|
function calculateDelay(sendTime, timeZone) {
|
|
66
77
|
if (!sendTime) return DEFAULT_DELAY;
|
|
67
78
|
|
|
@@ -100,4 +111,4 @@ function calculateDelay(sendTime, timeZone) {
|
|
|
100
111
|
}
|
|
101
112
|
}
|
|
102
113
|
|
|
103
|
-
module.exports = {
|
|
114
|
+
module.exports = { addContactHours, calculateDelay, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
|