@peopl-health/nexus 6.0.6 → 6.0.8

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.
@@ -37,8 +37,13 @@ const COURTESY_ONLY = 'courtesy_only';
37
37
  const UNANSWERED_LOOKBACK = 20;
38
38
  const COURTESY_ANCHORS = new Set(['hola', 'gracias', 'agradezco', 'agradecida', 'agradecido', 'saludos', 'buen', 'buenas', 'buenos', 'bendiciones']);
39
39
  const COURTESY_MODIFIERS = new Set(['muchas', 'mil', 'tardes', 'dias', 'días', 'noches', 'su', 'tu', 'la', 'informacion', 'información', 'igualmente']);
40
+ const COURTESY = { anchors: COURTESY_ANCHORS, modifiers: COURTESY_MODIFIERS, characters: /^[\p{L}\s.,!¡]*$/u };
41
+ const CONFIRMATION = {
42
+ anchors: new Set([...COURTESY_ANCHORS, 'confirmo', 'confirmado', 'confirmada', 'perfecto', 'acuerdo', 'enterado', 'enterada', 'estaré', 'estare', 'asistiré', 'asistire']),
43
+ modifiers: new Set([...COURTESY_MODIFIERS, 'cita', 'de', 'ahí', 'ahi', 'allí', 'alli', 'doctor', 'doctora', 'dr', 'dra']),
44
+ characters: /^[\p{L}\s.,!¡?¿]*$/u
45
+ };
40
46
  const COURTESY_EMOJI = /(?:😊|🙂|🙏|❤|👍)\uFE0F?[\u{1F3FB}-\u{1F3FF}]?/gu;
41
- const COURTESY_CHARACTERS = /^[\p{L}\s.,!¡]*$/u;
42
47
 
43
48
  const REQUEST_COPY = {
44
49
  callback: {
@@ -119,24 +124,30 @@ function templateFor(reason) {
119
124
 
120
125
  const writtenText = (message) => String(message?.plainBody || message?.body || '').trim();
121
126
 
122
- function isCourtesyText(text) {
127
+ function isCourtesyText(text, { anchors, modifiers, characters }) {
123
128
  const plain = text.normalize('NFC').replace(COURTESY_EMOJI, ' ');
124
- if (!COURTESY_CHARACTERS.test(plain)) return false;
129
+ if (!characters.test(plain)) return false;
125
130
  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));
131
+ return words.some((word) => anchors.has(word))
132
+ && words.every((word) => anchors.has(word) || modifiers.has(word));
128
133
  }
129
134
 
130
- const isCourtesy = (message) => !message.media?.mediaType && !message.media?.key && !message.interactive_type
131
- && isCourtesyText(writtenText(message));
135
+ const isCourtesy = (message, vocabulary) => !message.media?.mediaType && !message.media?.key && !message.interactive_type
136
+ && isCourtesyText(writtenText(message), vocabulary);
137
+
138
+ const vocabularyFor = (message, staffSend) => (staffSend && message.createdAt > staffSend.createdAt ? CONFIRMATION : COURTESY);
132
139
 
133
140
  async function hasOnlyCourtesyUnanswered(code) {
134
141
  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);
142
+ const [unanswered, staffSend] = await Promise.all([
143
+ getMessages(
144
+ { numero: code, from_me: false, createdAt: { $gt: new Date(Date.now() - getOfferWindowMs()) } },
145
+ { sort: { createdAt: -1 }, limit: UNANSWERED_LOOKBACK, select: { body: 1, plainBody: 1, media: 1, interactive_type: 1, createdAt: 1 } }
146
+ ),
147
+ lastStaffSendSince(code, new Date(Date.now() - getHumanQuietMs()))
148
+ ]);
149
+ return unanswered.length > 0 && unanswered.length < UNANSWERED_LOOKBACK
150
+ && unanswered.every((message) => isCourtesy(message, vocabularyFor(message, staffSend)));
140
151
  } catch (error) {
141
152
  logger.warn('[PausedSafetyNet] Could not read the unanswered messages; offering the net', { code, error: error.message });
142
153
  return false;
@@ -192,10 +203,10 @@ async function unansweredText(code) {
192
203
  return written ? writtenText(written) : null;
193
204
  }
194
205
 
195
- async function staffSenderSince(code, since) {
206
+ async function lastStaffSendSince(code, since) {
196
207
  try {
197
208
  const [sent] = await getMessages(staffSendFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
198
- return isStaffSend(sent?.triggeredBy) ? sent.triggeredBy : null;
209
+ return isStaffSend(sent?.triggeredBy) ? sent : null;
199
210
  } catch (error) {
200
211
  logger.warn('[PausedSafetyNet] Could not read who last wrote to the patient', { code, error: error.message });
201
212
  return null;
@@ -204,8 +215,8 @@ async function staffSenderSince(code, since) {
204
215
 
205
216
  async function opsAlertFor(code, reason) {
206
217
  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;
218
+ const staffSend = await lastStaffSendSince(code, new Date(Date.now() - getHumanQuietMs()));
219
+ return staffSend ? { ...alert, summary: `escribió después de un mensaje de ${staffSend.triggeredBy}` } : alert;
209
220
  }
210
221
 
211
222
  const assistantNamedOn = (thread) => Boolean(thread?.getAssistantId?.() || thread?.assistant_id);
@@ -5,7 +5,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
6
6
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
7
7
 
8
- const { countMessages } = require('./messageService');
8
+ const { countMessages, getMessages } = require('./messageService');
9
9
  const { logPatientChange } = require('./patientService');
10
10
  const { getThreadInfo } = require('./threadService');
11
11
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
@@ -26,6 +26,7 @@ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contest
26
26
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
27
27
  // A reminder this late (an outage, a deploy) is not sent.
28
28
  const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
29
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
29
30
  const getMessaging = () => require('../core/NexusMessaging');
30
31
 
31
32
  const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
@@ -247,8 +248,14 @@ async function remindQuietPatient(review, clock, now) {
247
248
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
248
249
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
249
250
 
251
+ // The draft's missing datum never reaches the bot, so the reminder needs a question of the bot's own still open in the chat.
252
+ // The reminder itself and a send that never arrived are no question of the bot's.
253
+ const [last] = await getMessages({
254
+ numero: review.patientCode, origin: { $nin: ['system', 'instruction'] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
255
+ }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
250
256
  let skippedReason = null;
251
257
  if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
258
+ else if (!last?.from_me || !String(last.body ?? '').includes('?')) skippedReason = 'no_open_question';
252
259
  else skippedReason = await takenOf(review, clock);
253
260
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
254
261
  const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.6",
3
+ "version": "6.0.8",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",