@peopl-health/nexus 6.4.6 → 6.4.7

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.
@@ -32,6 +32,10 @@ function escalationUntakenAlertsLive() {
32
32
  return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
33
33
  }
34
34
 
35
+ function escalationWatchExpiryLive() {
36
+ return flagNotOff('ESCALATION_WATCH_EXPIRY_LIVE');
37
+ }
38
+
35
39
  module.exports = {
36
40
  escalationApproverAlertLive,
37
41
  escalationAssessmentLive,
@@ -39,5 +43,6 @@ module.exports = {
39
43
  escalationPatientTimerLive,
40
44
  escalationUntakenAlertsLive,
41
45
  escalationUpdateModeLive,
46
+ escalationWatchExpiryLive,
42
47
  feverPatientTimerLive,
43
48
  };
@@ -91,6 +91,16 @@ const quietReminderSchema = new mongoose.Schema({
91
91
  delivered: { type: Boolean, default: null },
92
92
  }, { _id: false });
93
93
 
94
+ const watchNoticeSchema = new mongoose.Schema({
95
+ until: { type: Date, required: true },
96
+ kind: { type: String, enum: ['reminder', 'team'], required: true },
97
+ sentAt: { type: Date, required: true },
98
+ skippedReason: { type: String, default: null },
99
+ // sent | queued (recovery template) | not_sent | skipped | failed (team, tried again); null while in flight.
100
+ outcome: { type: String, default: null },
101
+ status: { type: String, default: null },
102
+ }, { _id: false });
103
+
94
104
  const blockingAskSchema = new mongoose.Schema({
95
105
  draftAt: { type: Date, required: true },
96
106
  question: { type: String, default: null },
@@ -333,6 +343,8 @@ const escalationReviewSchema = new mongoose.Schema({
333
343
  digestClaimedAt: { type: Date, default: null },
334
344
  digestSentAt: { type: Date, default: null },
335
345
  quietReminders: { type: [quietReminderSchema], default: [] },
346
+ monitoringUntil: { type: Date, default: null },
347
+ watchNotices: { type: [watchNoticeSchema], default: [] },
336
348
  blockingAsks: { type: [blockingAskSchema], default: [] },
337
349
  feverPromptStartedAt: { type: Date, default: null },
338
350
  approverViewedAt: { type: Date, default: null },
@@ -34,7 +34,7 @@ const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSum
34
34
  const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
35
35
  const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
36
36
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
37
- const { assistantInstructionsOf, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
37
+ const { DEFAULT_FOLLOW_UP_HOURS, assistantInstructionsOf, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
38
38
  const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
39
39
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
40
40
  const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
@@ -106,6 +106,7 @@ const AIRTABLE_TRANSPORT = 'airtable';
106
106
  const NOT_RECORDED = 'no se registró en Airtable';
107
107
  const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
108
108
  const SAME_URGENCY = 'The review is already at that urgency';
109
+ const STAT_WATCH = 'A stat case is not watched at home; lower its urgency with a reason first';
109
110
  const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
110
111
  const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
111
112
  const APPROVALS = ['approved', 'edited_approved', 'plan_approved'];
@@ -1883,6 +1884,15 @@ async function recordDoctorDecision({
1883
1884
  const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
1884
1885
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
1885
1886
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1887
+ let monitoringUntil = null;
1888
+ if (decision === 'monitor') {
1889
+ // Team rule (2026-10-31): stat goes to the ER; watching one at home first takes a lowering with its reason.
1890
+ const open = currentAlarms(review);
1891
+ if (effectiveUrgencyOf({ ...review, alarms: open.length ? open : review.alarms })?.urgency === 'stat') throw httpError(409, STAT_WATCH);
1892
+ // A watch recorded by someone who is not an approver names the doctor who ordered it.
1893
+ if (source === 'platform' && !await isEscalationApprover(operator)) decidedBy = requiredText(doctorName, 'doctorName');
1894
+ monitoringUntil = new Date(Date.now() + DEFAULT_FOLLOW_UP_HOURS.vigilancia * 60 * 60 * 1000);
1895
+ }
1886
1896
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1887
1897
  // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
1888
1898
  const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
@@ -1932,7 +1942,7 @@ async function recordDoctorDecision({
1932
1942
  },
1933
1943
  $set: returnReason === 'no_requiere'
1934
1944
  ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
1935
- : { status: statusAfter(decision) },
1945
+ : { status: statusAfter(decision), ...(monitoringUntil && { monitoringUntil }) },
1936
1946
  }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1937
1947
  await audit(updated, operator, requestId, {
1938
1948
  action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
@@ -5,9 +5,11 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
6
  const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
7
  const { sweepUntakenAlerts } = require('./untakenAlertService');
8
+ const { sweepExpiredWatches } = require('./watchExpiryService');
8
9
 
9
10
  const SWEEP_LIMIT = 10;
10
11
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
12
+ const WATCH_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
11
13
  const LEASE_MS = 5 * 60 * 1000;
12
14
  const SEND_TIMEOUT_MS = 2 * 60 * 1000;
13
15
  const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
@@ -90,10 +92,18 @@ const untakenSweeper = createIntervalSweeper({
90
92
  defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
91
93
  });
92
94
 
95
+ const watchSweeper = createIntervalSweeper({
96
+ label: '[WatchExpirySweep]',
97
+ sweep: () => sweepExpiredWatches(),
98
+ defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
99
+ });
100
+
93
101
  const startReviewAlertSweep = (options) => {
94
102
  untakenSweeper.start(options);
103
+ // A watch runs out in hours, so it keeps its own slower interval.
104
+ watchSweeper.start();
95
105
  return sweeper.start(options);
96
106
  };
97
- const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop()]);
107
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop()]);
98
108
 
99
109
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -0,0 +1,155 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { getEscalationReview } = require('../models/escalationReviewModel');
4
+ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
5
+ const { escalationWatchExpiryLive } = require('../clinical/flags/escalationFlags');
6
+
7
+ const { countMessages } = require('./messageService');
8
+ const { logPatientChange } = require('./patientService');
9
+ const { getThreadInfo } = require('./threadService');
10
+ const { BOOKKEEPING, teamAlertIdentity } = require('./escalationReviewService');
11
+ const { responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
+ const { sendGroupNotice } = require('./teamAlertService');
13
+
14
+ const OPERATOR = 'bot:watchExpiry';
15
+ const AUDIT_SOURCE = 'escalation_review';
16
+ const SWEEP_LIMIT = 50;
17
+ const REMINDER_TEXT = 'Hola, ¿cómo sigues? Cuéntame por aquí cómo te has sentido.';
18
+ const TEAM_HEADER = '⏰ Vigilancia vencida, sigue abierta';
19
+ const TEAM_ACTION = 'Qué hacer: ver cómo sigue y cerrar el caso o pedir indicaciones al médico';
20
+ const ANSWERED_NOTE = 'Respondió al recordatorio, pero no quedó claro que siga igual o mejor';
21
+ const MAX_TEAM_ATTEMPTS = 3;
22
+ // After the reminder the patient gets this long to answer before the team is told.
23
+ const TEAM_WAIT_MS = 2 * 60 * 60 * 1000;
24
+ // A reminder this late (an outage, a deploy) is not sent; the team notice still goes.
25
+ const STALE_MS = 30 * 60 * 1000;
26
+ const getMessaging = () => require('../core/NexusMessaging');
27
+
28
+ const timeOf = (value) => new Date(value).getTime();
29
+
30
+ const audit = (review, changes) => logPatientChange({
31
+ code: review.patientCode,
32
+ updatedBy: OPERATOR,
33
+ source: AUDIT_SOURCE,
34
+ requestId: null,
35
+ changes: { escalationReviewId: String(review._id), ...changes },
36
+ }).catch((error) => logger.error('[WatchExpiry] The audit was not written', {
37
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
38
+ }));
39
+
40
+ const noticesOf = (review, kind) => (review.watchNotices ?? []).filter((entry) => entry.kind === kind && timeOf(entry.until) === timeOf(review.monitoringUntil));
41
+ const failed = (entry) => entry.outcome === 'failed';
42
+
43
+ // A notice is claimed before it is sent, so two sweeps never send it twice; only a failed one is tried again.
44
+ async function claim(review, entry) {
45
+ const claimed = await getEscalationReview().updateOne(
46
+ {
47
+ _id: review._id, closedAt: null, status: 'monitoring', monitoringUntil: review.monitoringUntil,
48
+ watchNotices: { $not: { $elemMatch: { kind: entry.kind, until: review.monitoringUntil, outcome: { $ne: 'failed' } } } },
49
+ },
50
+ { $push: { watchNotices: entry } },
51
+ BOOKKEEPING,
52
+ );
53
+ return claimed.modifiedCount > 0;
54
+ }
55
+
56
+ // A crash between the claim and this leaves the outcome null, and the notice is not sent again.
57
+ const settle = (review, kind, fields) => getEscalationReview().updateOne(
58
+ { _id: review._id, watchNotices: { $elemMatch: { kind, until: review.monitoringUntil, outcome: null } } },
59
+ { $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`watchNotices.$.${key}`, value])) },
60
+ BOOKKEEPING,
61
+ );
62
+
63
+ async function skipReasonOf(review, due, now) {
64
+ if (now.getTime() - due.getTime() > STALE_MS) return 'stale';
65
+ const thread = await getThreadInfo(review.patientCode);
66
+ if (thread?.stopped === true) return 'thread_paused';
67
+ return null;
68
+ }
69
+
70
+ // Outside the 24 h window sendMessage queues the recovery template, and the reminder goes once the patient answers it.
71
+ async function remindPatient(review, now) {
72
+ const due = teamOpenAt(new Date(review.monitoringUntil), responseDeadlinePolicy());
73
+ if (now < due) return false;
74
+ const skippedReason = await skipReasonOf(review, due, now);
75
+ if (!await claim(review, { until: review.monitoringUntil, kind: 'reminder', sentAt: now, skippedReason, outcome: skippedReason ? 'skipped' : null })) return false;
76
+ if (skippedReason) {
77
+ await audit(review, { action: 'watch_reminder_skipped', reason: skippedReason });
78
+ return true;
79
+ }
80
+ let outcome = 'failed';
81
+ let status = null;
82
+ try {
83
+ const result = await getMessaging().sendMessage({
84
+ code: review.patientCode, body: REMINDER_TEXT, triggeredBy: OPERATOR, idempotencyKey: `watch-reminder:${review._id}:${timeOf(review.monitoringUntil)}`,
85
+ });
86
+ if (result?.success) outcome = result.deferred ? 'queued' : 'sent';
87
+ status = result?.status ?? null;
88
+ } catch (error) {
89
+ status = 'threw';
90
+ logger.error('[WatchExpiry] The watch reminder was not sent', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
91
+ }
92
+ // A reminder that failed is not tried again: the team notice still follows it.
93
+ const stored = outcome === 'failed' ? 'not_sent' : outcome;
94
+ await settle(review, 'reminder', { outcome: stored, status });
95
+ await audit(review, { action: `watch_reminder_${stored}`, status });
96
+ return true;
97
+ }
98
+
99
+ async function teamNoticeOf(review, reminder) {
100
+ const { patient, doctor, link } = await teamAlertIdentity(review);
101
+ const reminded = ['sent', 'queued'].includes(reminder.outcome);
102
+ const answered = reminded && await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: reminder.sentAt } });
103
+ const note = answered ? ANSWERED_NOTE : null;
104
+ return {
105
+ body: [TEAM_HEADER, `${patient} (${doctor})`, note, TEAM_ACTION, link].filter(Boolean).join('\n'),
106
+ threadBody: [TEAM_HEADER, note, TEAM_ACTION].filter(Boolean).join('\n'),
107
+ };
108
+ }
109
+
110
+ async function noticeTeam(review, reminder, now) {
111
+ const due = teamOpenAt(new Date(timeOf(reminder.sentAt) + TEAM_WAIT_MS), responseDeadlinePolicy());
112
+ if (now < due) return false;
113
+ const attempts = noticesOf(review, 'team').filter(failed).length;
114
+ if (attempts >= MAX_TEAM_ATTEMPTS) return false;
115
+ if (!await claim(review, { until: review.monitoringUntil, kind: 'team', sentAt: now, skippedReason: null, outcome: null })) return false;
116
+ let delivered = false;
117
+ try {
118
+ const { body, threadBody } = await teamNoticeOf(review, reminder);
119
+ const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
120
+ const quoted = await readGroupMessageId(recordId, review.patientCode);
121
+ delivered = (await sendGroupNotice(body, quoted, threadBody)).delivered === true;
122
+ } catch (error) {
123
+ logger.error('[WatchExpiry] The watch team notice failed', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
124
+ }
125
+ await settle(review, 'team', { outcome: delivered ? 'sent' : 'failed' });
126
+ if (!delivered && attempts + 1 >= MAX_TEAM_ATTEMPTS) logger.error('[WatchExpiry] The watch team notice failed on every attempt', { escalationReviewId: String(review._id) });
127
+ await audit(review, { action: 'watch_team_notified', delivered, attempt: attempts + 1 });
128
+ return true;
129
+ }
130
+
131
+ // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told.
132
+ async function sweepExpiredWatches({ now = new Date() } = {}) {
133
+ if (!escalationWatchExpiryLive()) return 0;
134
+ const reviews = await getEscalationReview()
135
+ .find(
136
+ { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now } },
137
+ { patientCode: 1, status: 1, monitoringUntil: 1, watchNotices: 1, 'alarms.emergencyRecordId': 1 },
138
+ )
139
+ .sort({ monitoringUntil: 1 })
140
+ .limit(SWEEP_LIMIT)
141
+ .lean();
142
+ let sent = 0;
143
+ for (const review of reviews) {
144
+ try {
145
+ if (noticesOf(review, 'team').some((entry) => !failed(entry))) continue;
146
+ const [reminder] = noticesOf(review, 'reminder');
147
+ if (await (reminder ? noticeTeam(review, reminder, now) : remindPatient(review, now))) sent += 1;
148
+ } catch (error) {
149
+ logger.error('[WatchExpiry] Could not check an expired watch', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
150
+ }
151
+ }
152
+ return sent;
153
+ }
154
+
155
+ module.exports = { REMINDER_TEXT, sweepExpiredWatches };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.6",
3
+ "version": "6.4.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",