@peopl-health/nexus 6.7.0-dev.21498 → 6.7.0-dev.21499

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.
@@ -52,8 +52,18 @@ function escalationCaseFollowUpLive() {
52
52
  return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
53
53
  }
54
54
 
55
+ function escalationCaseStatusReminderLive() {
56
+ return flagOn('ESCALATION_CASE_STATUS_REMINDER_LIVE');
57
+ }
58
+
59
+ function escalationUnreviewedCaseNoticeLive() {
60
+ return flagOn('ESCALATION_UNREVIEWED_CASE_NOTICE_LIVE');
61
+ }
62
+
55
63
  module.exports = {
56
64
  escalationCaseFollowUpLive,
65
+ escalationCaseStatusReminderLive,
66
+ escalationUnreviewedCaseNoticeLive,
57
67
  escalationApproverAlertLive,
58
68
  escalationAssessmentLive,
59
69
  escalationAutoHandoffLive,
@@ -8,6 +8,7 @@ const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
9
9
  const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
10
10
  const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
11
+ const DONE_STATUSES = ['closed', 'cancelled'];
11
12
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
12
13
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
13
14
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
@@ -382,6 +383,7 @@ const escalationReviewSchema = new mongoose.Schema({
382
383
  watchNotices: { type: [watchNoticeSchema], default: [] },
383
384
  caseFollowUp: { type: caseFollowUpSchema, default: null },
384
385
  staleQueueNoticeAt: { type: Date, default: null },
386
+ caseStatusNoticeAt: { type: Date, default: null },
385
387
  blockingAsks: { type: [blockingAskSchema], default: [] },
386
388
  inTurnAsks: { type: [inTurnAskSchema], default: [] },
387
389
  feverPromptStartedAt: { type: Date, default: null },
@@ -470,6 +472,7 @@ module.exports = {
470
472
  INTERRUPTED_STATUSES,
471
473
  PLAN_DURATIONS,
472
474
  PLAN_FOLLOW_UPS,
475
+ DONE_STATUSES,
473
476
  FOLLOWUP_STATUSES,
474
477
  RETURN_REASONS,
475
478
  URGENCY_LEVELS,
@@ -1,12 +1,13 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
- const { getEscalationReview } = require('../models/escalationReviewModel');
4
- const { escalationCaseFollowUpLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
3
+ const { DONE_STATUSES, getEscalationReview, supersededCaseIds } = require('../models/escalationReviewModel');
4
+ const { escalationCaseFollowUpLive, escalationCaseStatusReminderLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
5
5
 
6
6
  const { logPatientChange } = require('./patientService');
7
7
  const { getThreadInfo } = require('./threadService');
8
- const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread } = require('./escalationReviewService');
9
- const { effectiveUrgencyOf, positiveSetting } = require('./reviewDeadlineService');
8
+ const { UNTRIAGED_CASE_STATUSES, readPatientCases } = require('./patientTaskService');
9
+ const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread, resolveSettledCases } = require('./escalationReviewService');
10
+ const { effectiveUrgencyOf, positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
10
11
  const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
11
12
 
12
13
  const OPERATOR = 'bot:caseFollowUp';
@@ -19,6 +20,8 @@ const STALE_QUEUE_STATUSES = ['indications_queued', 'needs_intervention'];
19
20
  const DEFAULT_STALE_QUEUE_HOURS = 72;
20
21
  const HOUR_MS = 60 * 60 * 1000;
21
22
  const STALE_QUEUE_LOOKBACK_MS = 7 * 24 * HOUR_MS;
23
+ const CASE_STATUS_NOTICE_MS = 24 * HOUR_MS;
24
+ const CASE_STATUS_LOOKBACK_MS = 7 * 24 * HOUR_MS;
22
25
  const STALE_QUEUE_HEADERS = {
23
26
  indications_queued: '⏳ Indicación en cola sin enviar desde hace días',
24
27
  needs_intervention: '⏳ Caso que requiere intervención sin movimiento desde hace días',
@@ -43,6 +46,7 @@ const checkAgainAt = (review, at) => getEscalationReview().updateOne(
43
46
  async function close(review, result) {
44
47
  const { review: closed } = await closeEscalationReview({ id: String(review._id), closedBy: OPERATOR, expectedAlarmCount: (review.alarms ?? []).length });
45
48
  await audit(closed, { action: 'followup_result', result });
49
+ if (result === 'answered') await resolveSettledCases(closed, OPERATOR);
46
50
  }
47
51
 
48
52
  async function keepUnanswered(review, now) {
@@ -153,4 +157,42 @@ async function sweepStaleQueues({ now = new Date() } = {}) {
153
157
  return noticed;
154
158
  }
155
159
 
156
- module.exports = { sweepCaseFollowUps, sweepStaleQueues };
160
+ // Only the team group hears of these; the doctor is never asked to close cases.
161
+ async function sweepCaseStatuses({ now = new Date() } = {}) {
162
+ if (!escalationCaseStatusReminderLive()) return 0;
163
+ const policy = responseDeadlinePolicy();
164
+ if (teamOpenAt(now, policy).getTime() !== now.getTime()) return 0;
165
+ const reviews = await getEscalationReview()
166
+ .find({
167
+ status: { $in: DONE_STATUSES },
168
+ closedAt: { $lte: new Date(now.getTime() - CASE_STATUS_NOTICE_MS), $gt: new Date(now.getTime() - CASE_STATUS_LOOKBACK_MS) },
169
+ caseStatusNoticeAt: null,
170
+ 'patientCaseRecordIds.0': { $exists: true },
171
+ })
172
+ .limit(SWEEP_LIMIT)
173
+ .lean();
174
+ let noticed = 0;
175
+ for (const review of reviews) {
176
+ try {
177
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
178
+ const covered = new Set(review.patientCaseRecordIds.filter((recordId) => !superseded.has(recordId)));
179
+ const unset = (await readPatientCases(review.patientCode))
180
+ .filter((patientCase) => covered.has(patientCase.recordId) && UNTRIAGED_CASE_STATUSES.includes(patientCase.status));
181
+ const claimed = await getEscalationReview().updateOne({ _id: review._id, caseStatusNoticeAt: null }, { $set: { caseStatusNoticeAt: now } }, BOOKKEEPING);
182
+ if (!claimed.modifiedCount || !unset.length) continue;
183
+ const numbers = unset.map((patientCase) => (patientCase.number ? `#${patientCase.number}` : patientCase.description)).filter(Boolean).join(', ');
184
+ await noticeCaseThread(review, {
185
+ header: `📋 Caso cerrado sin estado clínico: ${numbers}`,
186
+ action: 'Qué hacer: poner En tratamiento, En vigilancia o Resuelto en Pendientes',
187
+ kind: 'case_status',
188
+ });
189
+ await audit(review, { action: 'case_status_noticed', recordIds: unset.map((patientCase) => patientCase.recordId) });
190
+ noticed += 1;
191
+ } catch (error) {
192
+ logger.error('[CaseFollowUpSweep] Could not check the clinical status of a closed review\'s cases', { escalationReviewId: String(review._id), error: errorOf(error) });
193
+ }
194
+ }
195
+ return noticed;
196
+ }
197
+
198
+ module.exports = { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues };
@@ -1,6 +1,6 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
- const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
3
+ const { DONE_STATUSES, FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
4
4
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
5
  const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
6
 
@@ -10,7 +10,6 @@ const { HANDOFF_TAKES_LEVELS, pendingWaitMinutes } = require('./reviewDeadlineSe
10
10
  const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
11
11
 
12
12
  const WITH_DOCTOR_STATUSES = ['handing_off', 'awaiting_doctor'];
13
- const DONE_STATUSES = ['closed', 'cancelled'];
14
13
  const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
14
  const timeOf = (value) => new Date(value).getTime();
16
15
 
@@ -148,6 +148,7 @@ function closingCaseIdsOf(value) {
148
148
 
149
149
  // The clinical statuses a doctor closes a case with from the review; ops keep the rest in Pendientes.
150
150
  const DOCTOR_CASE_STATUSES = ['En tratamiento', 'En vigilancia', 'Resuelto'];
151
+ const RESOLVABLE_CASE_STATUSES = ['En tratamiento', 'En vigilancia'];
151
152
 
152
153
  function caseStatusMirrorsOf(value, review) {
153
154
  if (value == null) return [];
@@ -1579,6 +1580,23 @@ async function followUpCasesOf(review, sinceMs) {
1579
1580
  return { review: stored, known: new Set(known) };
1580
1581
  }
1581
1582
 
1583
+ async function resolveSettledCases(review, operator) {
1584
+ const setByDoctor = new Map((review.doctorCaseStatuses ?? []).map(({ recordId, status }) => [recordId, status]));
1585
+ if (![...setByDoctor.values()].some((status) => RESOLVABLE_CASE_STATUSES.includes(status))) return review;
1586
+ try {
1587
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
1588
+ const caseStatuses = (await readPatientCases(review.patientCode))
1589
+ .filter((patientCase) => !superseded.has(patientCase.recordId)
1590
+ && RESOLVABLE_CASE_STATUSES.includes(patientCase.status) && setByDoctor.get(patientCase.recordId) === patientCase.status)
1591
+ .map((patientCase) => ({ recordId: patientCase.recordId, status: 'Resuelto' }));
1592
+ if (!caseStatuses.length) return review;
1593
+ return (await setCaseStatuses({ id: String(review._id), caseStatuses, updatedBy: operator })).review;
1594
+ } catch (error) {
1595
+ logger.error('[EscalationReview] The settled cases were not marked resolved', { escalationReviewId: String(review._id), error: redactedError(error) });
1596
+ return review;
1597
+ }
1598
+ }
1599
+
1582
1600
  async function closeSettled(review) {
1583
1601
  try {
1584
1602
  const { review: closed } = await closeEscalationReview({
@@ -1588,7 +1606,7 @@ async function closeSettled(review) {
1588
1606
  expectedUpdatedAt: review.updatedAt,
1589
1607
  });
1590
1608
  await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
1591
- return closed;
1609
+ return resolveSettledCases(closed, AGENT_OPERATOR);
1592
1610
  } catch (error) {
1593
1611
  logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
1594
1612
  escalationReviewId: String(review._id), error: redactedError(error),
@@ -2726,6 +2744,7 @@ module.exports = {
2726
2744
  recordReviewUpdate,
2727
2745
  requestBotDraft,
2728
2746
  sendApprovedIndications,
2747
+ resolveSettledCases,
2729
2748
  setCaseStatuses,
2730
2749
  setReviewCases,
2731
2750
  suggestDraft,
@@ -162,6 +162,13 @@ async function readTasks(kind, whatsappId) {
162
162
 
163
163
  const readPatientCases = (code) => readAllTasks('cases', validWhatsappId(code));
164
164
 
165
+ async function readUnreviewedCaseCandidates(since) {
166
+ const untriaged = UNTRIAGED_CASE_STATUSES.map((status) => (status ? fieldEquals('status', status) : '{status}=BLANK()'));
167
+ const filter = `AND(${TASK_KINDS.cases.scope}, {grade}>=2, {closed_time}=BLANK(), OR(${untriaged.join(', ')}), IS_AFTER({created}, '${since.toISOString()}'))`;
168
+ const rows = await getRecordByFilter(Monitoreo_ID, TASK_KINDS.cases.table, filter, null, [...TASK_KINDS.cases.fields, 'whatsapp_id'], true);
169
+ return rows.map((row) => ({ ...toCase(row), patientCode: [row.whatsapp_id].flat()[0] ?? null }));
170
+ }
171
+
165
172
  async function openCaseIds(code) {
166
173
  const cases = await readPatientCases(code);
167
174
  return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
@@ -217,6 +224,7 @@ module.exports = {
217
224
  MAX_NOTE_LENGTH,
218
225
  UNTRIAGED_CASE_STATUSES,
219
226
  openCaseIds,
227
+ readUnreviewedCaseCandidates,
220
228
  readPatientCases,
221
229
  getPatientTasks,
222
230
  updatePatientTask,
@@ -6,7 +6,8 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
7
  const { sweepUntakenAlerts } = require('./untakenAlertService');
8
8
  const { sweepExpiredWatches } = require('./watchExpiryService');
9
- const { sweepCaseFollowUps, sweepStaleQueues } = require('./caseFollowUpSweepService');
9
+ const { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues } = require('./caseFollowUpSweepService');
10
+ const { sweepUnreviewedCases } = require('./unreviewedCaseService');
10
11
 
11
12
  const SWEEP_LIMIT = 10;
12
13
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
@@ -99,9 +100,15 @@ const watchSweeper = createIntervalSweeper({
99
100
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
100
101
  });
101
102
 
103
+ const unreviewedSweeper = createIntervalSweeper({
104
+ label: '[UnreviewedCaseSweep]',
105
+ sweep: () => sweepUnreviewedCases(),
106
+ defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
107
+ });
108
+
102
109
  const caseFollowUpSweeper = createIntervalSweeper({
103
110
  label: '[CaseFollowUpSweep]',
104
- sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
111
+ sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()) + (await sweepCaseStatuses()),
105
112
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
106
113
  });
107
114
 
@@ -110,8 +117,9 @@ const startReviewAlertSweep = (options) => {
110
117
  // A watch runs out in hours, so it keeps its own slower interval.
111
118
  watchSweeper.start();
112
119
  caseFollowUpSweeper.start();
120
+ unreviewedSweeper.start();
113
121
  return sweeper.start(options);
114
122
  };
115
- const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
123
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
116
124
 
117
125
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -2,7 +2,7 @@ const { mapConcurrent } = require('../utils/concurrencyUtils');
2
2
  const { httpError } = require('../utils/httpErrorUtils');
3
3
  const { logger } = require('../utils/logger');
4
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
- const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { DONE_STATUSES, FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
6
6
 
7
7
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
8
8
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
@@ -10,7 +10,6 @@ const { caseStateOf } = require('./escalationCaseStateService');
10
10
  const { UNTAKEN_PROJECTION } = require('./untakenAlertService');
11
11
 
12
12
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
13
- const DONE_STATUSES = ['closed', 'cancelled'];
14
13
  const BOARD_BUCKETS = ['pending', 'followup', 'done'];
15
14
  const STATE_CONCURRENCY = 10;
16
15
  const BOARD_FILTER_PREFIX = 'clinical-review-';
@@ -0,0 +1,75 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { addWorkingMinutes } = require('../utils/dateUtils');
4
+ const { getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { escalationUnreviewedCaseNoticeLive } = require('../clinical/flags/escalationFlags');
6
+ const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
7
+
8
+ const { readUnreviewedCaseCandidates } = require('./patientTaskService');
9
+ const { sendGroupNotice } = require('./teamAlertService');
10
+ const { teamAlertIdentity } = require('./escalationReviewService');
11
+ const { duration } = require('./untakenAlertService');
12
+ const { positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
+
14
+ const MINUTE_MS = 60 * 1000;
15
+ const LOOKBACK_MS = 24 * 60 * MINUTE_MS;
16
+ const DEFAULT_MINUTES = { 3: 60, 2: 120 };
17
+ const MINUTES_KEYS = { 3: 'ESCALATION_UNREVIEWED_MINUTES_G3', 2: 'ESCALATION_UNREVIEWED_MINUTES_G2' };
18
+ const noticed = new WriteClaimStore({ namespace: 'unreviewedCaseNotice', ttlMs: 14 * 24 * 60 * MINUTE_MS });
19
+
20
+ const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
21
+ const gradeOf = (patientCase) => (Number(String(patientCase.grade ?? '').match(/\d+/)?.[0]) >= 3 ? 3 : 2);
22
+ const caseLabel = (patientCase) => [patientCase.number ? `#${patientCase.number}` : null, patientCase.description].filter(Boolean).join(' · ');
23
+
24
+ function isDue(patientCase, now, policy) {
25
+ const created = new Date(patientCase.createdAt);
26
+ if (Number.isNaN(created.getTime())) return false;
27
+ const grade = gradeOf(patientCase);
28
+ return addWorkingMinutes(created, positiveSetting(MINUTES_KEYS[grade], DEFAULT_MINUTES[grade]), policy.teamHours) <= now;
29
+ }
30
+
31
+ async function reviewedCaseIds(recordIds) {
32
+ const reviews = await getEscalationReview()
33
+ .find({ closedAt: null, patientCaseRecordIds: { $in: recordIds } }, { patientCaseRecordIds: 1 })
34
+ .lean();
35
+ return new Set(reviews.flatMap((review) => review.patientCaseRecordIds ?? []));
36
+ }
37
+
38
+ async function noticePatient(patientCode, cases, now) {
39
+ const { patient, doctor, identity, link } = await teamAlertIdentity({ _id: null, patientCode });
40
+ if (identity.testPatient) return false;
41
+ const grade = Math.max(...cases.map(gradeOf));
42
+ const oldest = new Date(Math.min(...cases.map((patientCase) => new Date(patientCase.createdAt).getTime())));
43
+ const header = `📋 Caso G${grade} sin revisión clínica · creado hace ${duration(Math.max(1, Math.round((now - oldest) / MINUTE_MS)))}`;
44
+ const action = 'Qué hacer: abrir la revisión clínica o poner su estado en Pendientes';
45
+ const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...cases.map(caseLabel), action, link].join('\n'), null, [header, action].join('\n'));
46
+ if (!sent.delivered) logger.error('[UnreviewedCase] The notice did not reach the group', { error: sent.error });
47
+ return true;
48
+ }
49
+
50
+ async function sweepUnreviewedCases({ now = new Date() } = {}) {
51
+ if (!escalationUnreviewedCaseNoticeLive()) return 0;
52
+ const policy = responseDeadlinePolicy();
53
+ if (teamOpenAt(now, policy).getTime() !== now.getTime()) return 0;
54
+ const due = (await readUnreviewedCaseCandidates(new Date(now.getTime() - LOOKBACK_MS)))
55
+ .filter((patientCase) => patientCase.patientCode && isDue(patientCase, now, policy));
56
+ if (!due.length) return 0;
57
+ const reviewed = await reviewedCaseIds(due.map((patientCase) => patientCase.recordId));
58
+ const byPatient = new Map();
59
+ for (const patientCase of due) {
60
+ if (reviewed.has(patientCase.recordId)) continue;
61
+ if ((await noticed.acquire(patientCase.recordId, now.toISOString())) !== 'acquired') continue;
62
+ byPatient.set(patientCase.patientCode, [...(byPatient.get(patientCase.patientCode) ?? []), patientCase]);
63
+ }
64
+ let sent = 0;
65
+ for (const [patientCode, cases] of byPatient) {
66
+ try {
67
+ if (await noticePatient(patientCode, cases, now)) sent += 1;
68
+ } catch (error) {
69
+ logger.error('[UnreviewedCase] The notice failed', { error: errorOf(error) });
70
+ }
71
+ }
72
+ return sent;
73
+ }
74
+
75
+ module.exports = { sweepUnreviewedCases };
@@ -323,4 +323,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
323
323
  return sent;
324
324
  }
325
325
 
326
- module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
326
+ module.exports = { UNTAKEN_PROJECTION, dueStageOf, duration, sweepUntakenAlerts, untakenClockOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.0-dev.21498",
3
+ "version": "6.7.0-dev.21499",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",