@peopl-health/nexus 5.54.0-dev.7970 → 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 = 24 * 60 * 60 * 1000;
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 };
@@ -67,6 +67,7 @@ const duration = (key, envKey, fallback) => {
67
67
  module.exports = {
68
68
  CONTACT_WINDOW,
69
69
  SAFETY_NET_SOURCE,
70
+ DEFAULT_PLEDGE_MS,
70
71
  anyReplyFilter,
71
72
  humanReplyFilter,
72
73
  settledHumanReplyFilter,
@@ -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 las próximas 24 horas' : `en los próximos ${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
- `Listo. Un miembro del equipo te va a contactar ${pledgeWindowText()}.`,
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,9 +1,10 @@
1
1
  const {
2
- CONTACT_WINDOW, anyReplyFilter, getPledgeMs, getSweepIntervalMs, humanReplyFilter, settledHumanReplyFilter
2
+ CONTACT_WINDOW, DEFAULT_PLEDGE_MS, anyReplyFilter, getPledgeMs, getSweepIntervalMs, humanReplyFilter,
3
+ settledHumanReplyFilter
3
4
  } = require('../config/safetyNetConfig');
4
5
  const { createIntervalSweeper } = require('../../utils/intervalSweeper');
5
6
  const { logger } = require('../../utils/logger');
6
- const { clampBackToHourWindow, clampToHourWindow } = require('../../utils/scheduleUtils');
7
+ const { addContactHours } = require('../../utils/scheduleUtils');
7
8
 
8
9
  const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
9
10
 
@@ -16,6 +17,7 @@ const BREACH_CATEGORY = 'contact_team_member';
16
17
  const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
17
18
 
18
19
  const DELIVERY_GRACE_MS = 10 * 60 * 1000;
20
+ const HOUR_MS = 60 * 60 * 1000;
19
21
 
20
22
  async function repliedSince(filter) {
21
23
  const [reply] = await getMessages(filter, { sort: { createdAt: -1 }, limit: 1 });
@@ -29,24 +31,21 @@ const humanReplySettledSince = (code, since) => repliedSince(
29
31
  const anyoneRepliedSince = (code, since) => repliedSince(anyReplyFilter(code, since));
30
32
 
31
33
  function pledgeDueAt(pledgedAt) {
32
- const target = new Date(pledgedAt.getTime() + getPledgeMs());
34
+ const configured = addContactHours(pledgedAt, getPledgeMs() / HOUR_MS, CONTACT_WINDOW);
35
+ if (configured) return { dueAt: configured };
33
36
 
34
- const pulled = clampBackToHourWindow(target, CONTACT_WINDOW);
35
- if (pulled && pulled.getTime() > pledgedAt.getTime()) {
36
- return { dueAt: pulled, deferredToWindow: false };
37
- }
38
-
39
- const pushed = clampToHourWindow(target, CONTACT_WINDOW);
40
- if (!pushed) return { dueAt: target, deferredToWindow: false };
41
- return { dueAt: pushed, deferredToWindow: pushed.getTime() > target.getTime() };
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) };
42
41
  }
43
42
 
44
43
  async function openPledge({ code }) {
45
44
  const pledgedAt = new Date();
46
- const { dueAt, deferredToWindow } = pledgeDueAt(pledgedAt);
47
- const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt, deferredToWindow });
48
- logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt, deferredToWindow });
49
- return { pledgeId: pledge._id, dueAt, deferredToWindow };
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 };
50
49
  }
51
50
 
52
51
  async function reportBreach(pledge) {
@@ -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 = { calculateDelay, clampBackToHourWindow, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
114
+ module.exports = { addContactHours, calculateDelay, clampToHourWindow, isWithinHourWindow, contactHoursBetween, DEFAULT_TIMEZONE };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.54.0-dev.7970",
3
+ "version": "5.54.0-dev.7971",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",