@peopl-health/nexus 5.75.3 → 5.75.5
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.
|
@@ -41,6 +41,15 @@ const anyReplyFilter = (code, since) => ({
|
|
|
41
41
|
]
|
|
42
42
|
});
|
|
43
43
|
|
|
44
|
+
const staffSendFilter = (code, since) => ({
|
|
45
|
+
numero: code,
|
|
46
|
+
from_me: true,
|
|
47
|
+
origin: { $in: HUMAN_ORIGINS },
|
|
48
|
+
triggeredBy: { $regex: '@' },
|
|
49
|
+
'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
|
|
50
|
+
createdAt: { $gt: since }
|
|
51
|
+
});
|
|
52
|
+
|
|
44
53
|
const settledHumanReplyFilter = (code, since, unconfirmedBefore) => ({
|
|
45
54
|
...humanReplyFilter(code, since),
|
|
46
55
|
$or: [
|
|
@@ -81,6 +90,7 @@ module.exports = {
|
|
|
81
90
|
anyReplyFilter,
|
|
82
91
|
humanReplyFilter,
|
|
83
92
|
settledHumanReplyFilter,
|
|
93
|
+
staffSendFilter,
|
|
84
94
|
CHOICE_LABEL_KEYS,
|
|
85
95
|
configureSafetyNet,
|
|
86
96
|
_resetSafetyNetConfig,
|
|
@@ -401,7 +401,9 @@ class BaseLLMProvider {
|
|
|
401
401
|
};
|
|
402
402
|
const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
|
|
403
403
|
const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
|
|
404
|
+
const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
|
|
404
405
|
const pending = lines([
|
|
406
|
+
['este check-in', self],
|
|
405
407
|
['lo que querías preguntarle', checkIn.question],
|
|
406
408
|
['por qué quedó abierto', checkIn.concern],
|
|
407
409
|
['qué dato esperabas', checkIn.awaiting],
|
|
@@ -424,6 +426,7 @@ class BaseLLMProvider {
|
|
|
424
426
|
'', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
|
|
425
427
|
'',
|
|
426
428
|
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
|
|
429
|
+
'- Este check-in es el seguimiento que está venciendo ahora, aunque lo veas programado unos minutos más tarde: ya no está pendiente y no se puede actualizar. Si decides esperar, programa uno nuevo.',
|
|
427
430
|
'- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
|
|
428
431
|
'- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
|
|
429
432
|
'- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
|
|
@@ -96,6 +96,8 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
96
96
|
if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused', planId };
|
|
97
97
|
checkIn = {
|
|
98
98
|
type,
|
|
99
|
+
reminderId,
|
|
100
|
+
dueAt: null,
|
|
99
101
|
question: netQuestion,
|
|
100
102
|
concern: net.carePlan.concern,
|
|
101
103
|
awaiting: net.carePlan.awaitingCharacterization,
|
|
@@ -111,6 +113,8 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
111
113
|
if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
|
|
112
114
|
checkIn = {
|
|
113
115
|
type,
|
|
116
|
+
reminderId,
|
|
117
|
+
dueAt: plan.fireAt || null,
|
|
114
118
|
question: plan.message || question,
|
|
115
119
|
concern: plan.windowReasoning,
|
|
116
120
|
awaiting: null,
|
|
@@ -8,10 +8,12 @@ const {
|
|
|
8
8
|
getSafetyNetLabel,
|
|
9
9
|
getSafetyNetPhone,
|
|
10
10
|
getSafetyNetUnassignedContentSid,
|
|
11
|
-
getTapWindowMs
|
|
11
|
+
getTapWindowMs,
|
|
12
|
+
staffSendFilter
|
|
12
13
|
} = require('../config/safetyNetConfig');
|
|
13
14
|
const { logger } = require('../../utils/logger');
|
|
14
15
|
const { phoneDigits } = require('../../helpers/whatsappHelper');
|
|
16
|
+
const { isStaffSend } = require('../../helpers/staffSendHelper');
|
|
15
17
|
|
|
16
18
|
const { patientIsDeceased, pausedSince } = require('../../helpers/pausedThreadHelper');
|
|
17
19
|
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../../helpers/sendClaimHelper');
|
|
@@ -31,6 +33,12 @@ const CHOICES = ['callback'];
|
|
|
31
33
|
const PAUSED = 'paused';
|
|
32
34
|
const UNASSIGNED = 'unassigned';
|
|
33
35
|
const REQUEST_CATEGORY = 'contact_team_member';
|
|
36
|
+
const COURTESY_ONLY = 'courtesy_only';
|
|
37
|
+
const UNANSWERED_LOOKBACK = 20;
|
|
38
|
+
const COURTESY_ANCHORS = new Set(['hola', 'gracias', 'agradezco', 'agradecida', 'agradecido', 'saludos', 'buen', 'buenas', 'buenos', 'bendiciones']);
|
|
39
|
+
const COURTESY_MODIFIERS = new Set(['muchas', 'mil', 'tardes', 'dias', 'días', 'noches', 'su', 'tu', 'la', 'informacion', 'información', 'igualmente']);
|
|
40
|
+
const COURTESY_EMOJI = /(?:😊|🙂|🙏|❤|👍)\uFE0F?[\u{1F3FB}-\u{1F3FF}]?/gu;
|
|
41
|
+
const COURTESY_CHARACTERS = /^[\p{L}\s.,!¡]*$/u;
|
|
34
42
|
|
|
35
43
|
const REQUEST_COPY = {
|
|
36
44
|
callback: {
|
|
@@ -109,6 +117,32 @@ function templateFor(reason) {
|
|
|
109
117
|
return getSafetyNetUnassignedContentSid() || getSafetyNetContentSid();
|
|
110
118
|
}
|
|
111
119
|
|
|
120
|
+
const writtenText = (message) => String(message?.plainBody || message?.body || '').trim();
|
|
121
|
+
|
|
122
|
+
function isCourtesyText(text) {
|
|
123
|
+
const plain = text.normalize('NFC').replace(COURTESY_EMOJI, ' ');
|
|
124
|
+
if (!COURTESY_CHARACTERS.test(plain)) return false;
|
|
125
|
+
const words = plain.toLowerCase().split(/[^\p{L}]+/u).filter(Boolean);
|
|
126
|
+
return words.some((word) => COURTESY_ANCHORS.has(word))
|
|
127
|
+
&& words.every((word) => COURTESY_ANCHORS.has(word) || COURTESY_MODIFIERS.has(word));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const isCourtesy = (message) => !message.media?.mediaType && !message.media?.key && !message.interactive_type
|
|
131
|
+
&& isCourtesyText(writtenText(message));
|
|
132
|
+
|
|
133
|
+
async function hasOnlyCourtesyUnanswered(code) {
|
|
134
|
+
try {
|
|
135
|
+
const unanswered = await getMessages(
|
|
136
|
+
{ numero: code, from_me: false, createdAt: { $gt: new Date(Date.now() - getOfferWindowMs()) } },
|
|
137
|
+
{ sort: { createdAt: -1 }, limit: UNANSWERED_LOOKBACK, select: { body: 1, plainBody: 1, media: 1, interactive_type: 1 } }
|
|
138
|
+
);
|
|
139
|
+
return unanswered.length > 0 && unanswered.length < UNANSWERED_LOOKBACK && unanswered.every(isCourtesy);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
logger.warn('[PausedSafetyNet] Could not read the unanswered messages; offering the net', { code, error: error.message });
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
112
146
|
async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
113
147
|
try {
|
|
114
148
|
if (!code || !getSafetyNetContentSid() || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
|
|
@@ -117,6 +151,7 @@ async function offerSafetyNet({ code, reason = PAUSED }) {
|
|
|
117
151
|
if (await pausedSince(code, new Date(Date.now() - getPauseQuietMs()))) return { sent: false, reason: 'just_paused' };
|
|
118
152
|
if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
|
|
119
153
|
if (await anyoneRepliedSince(code, new Date(Date.now() - getActivityQuietMs()))) return { sent: false, reason: 'conversation_active' };
|
|
154
|
+
if (await hasOnlyCourtesyUnanswered(code)) return { sent: false, reason: COURTESY_ONLY };
|
|
120
155
|
|
|
121
156
|
const contentSid = templateFor(reason);
|
|
122
157
|
await warnIfPhoneDiffersFromTemplate(contentSid);
|
|
@@ -154,7 +189,23 @@ async function unansweredText(code) {
|
|
|
154
189
|
{ numero: code, from_me: false, interactive_type: null },
|
|
155
190
|
{ sort: { createdAt: -1 }, limit: 1 }
|
|
156
191
|
);
|
|
157
|
-
return written ? written
|
|
192
|
+
return written ? writtenText(written) : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function staffSenderSince(code, since) {
|
|
196
|
+
try {
|
|
197
|
+
const [sent] = await getMessages(staffSendFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
|
|
198
|
+
return isStaffSend(sent?.triggeredBy) ? sent.triggeredBy : null;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
logger.warn('[PausedSafetyNet] Could not read who last wrote to the patient', { code, error: error.message });
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function opsAlertFor(code, reason) {
|
|
206
|
+
const alert = OPS_ALERTS[reason] || OPS_ALERTS.paused;
|
|
207
|
+
const staff = await staffSenderSince(code, new Date(Date.now() - getHumanQuietMs()));
|
|
208
|
+
return staff ? { ...alert, summary: `escribió después de un mensaje de ${staff}` } : alert;
|
|
158
209
|
}
|
|
159
210
|
|
|
160
211
|
const assistantNamedOn = (thread) => Boolean(thread?.getAssistantId?.() || thread?.assistant_id);
|
|
@@ -175,11 +226,12 @@ async function coverUnansweredPatient({ code, reason = PAUSED }) {
|
|
|
175
226
|
if (!claim.acquired) return;
|
|
176
227
|
|
|
177
228
|
const results = await Promise.allSettled([
|
|
178
|
-
unansweredText(code)
|
|
229
|
+
Promise.all([unansweredText(code), opsAlertFor(code, reason)])
|
|
230
|
+
.then(([text, alert]) => recordPausedThreadMessage({ code, text, alert })),
|
|
179
231
|
offerSafetyNet({ code, reason }),
|
|
180
232
|
]);
|
|
181
233
|
|
|
182
|
-
const covered = results.every((r) => r.status === 'fulfilled');
|
|
234
|
+
const covered = results.every((r) => r.status === 'fulfilled') && results[1].value?.reason !== COURTESY_ONLY;
|
|
183
235
|
if (covered) await completeSendClaim(claim.claimId);
|
|
184
236
|
else await releaseSendClaim(claim.claimId);
|
|
185
237
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
|
|
|
468
468
|
lastInboundAt?: string | null;
|
|
469
469
|
lastOutboundAt?: string | null;
|
|
470
470
|
lastOutreach?: string | null;
|
|
471
|
-
checkIn?: { type: string; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
|
|
471
|
+
checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
|
|
472
472
|
recentCheckIns?: string[];
|
|
473
473
|
exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number } | null;
|
|
474
474
|
asOf?: string | null;
|