@peopl-health/nexus 6.4.4 → 6.4.6

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.
@@ -18,9 +18,9 @@ const MS_PER_HOUR = 60 * MS_PER_MINUTE;
18
18
  const EXPIRY_WINDOW_MULTIPLIER = 6;
19
19
  const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
20
20
  const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
21
- const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
22
- // Nets armed before the change keep their level until they expire (stat 120, asap 180).
23
- const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
21
+ const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 120 };
22
+ // Urgent nets armed with the old 4 h window keep their level until they expire (48 h).
23
+ const LEGACY_ESCALATION_SILENCE_MINUTES = { urgent: 240 };
24
24
  const OPEN_CEILING_SILENCE_MINUTES = 720;
25
25
  const OPEN_CEILING_ORIGIN = 'open_ceiling';
26
26
  const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
@@ -23,6 +23,8 @@ const {
23
23
  syncEscalationReviewCase,
24
24
  } = require('../services/escalationReviewService');
25
25
  const { listReviewBoard } = require('../services/reviewBoardService');
26
+ const { caseStateOf } = require('../services/escalationCaseStateService');
27
+ const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
26
28
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
27
29
 
28
30
  const respondWithError = (res, error, action, context) => {
@@ -34,6 +36,12 @@ const respondWithError = (res, error, action, context) => {
34
36
  res.status(error.statusCode || 500).json({ success: false, error: error.message, ...(error.errorCode && { errorCode: error.errorCode }) });
35
37
  };
36
38
 
39
+ // The review still reads when its case state cannot be worked out.
40
+ const safeCaseStateOf = (review) => caseStateOf(review, { policy: responseDeadlinePolicy() }).catch((error) => {
41
+ logger.warn('[EscalationReview] Could not read the case state', { escalationReviewId: String(review?._id), error: redactDirectIdentifiers(String(error?.message || error)) });
42
+ return null;
43
+ });
44
+
37
45
  const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
38
46
 
39
47
  const openEscalationReviewController = async (req, res) => {
@@ -55,7 +63,8 @@ const openEscalationReviewController = async (req, res) => {
55
63
  const getEscalationReviewController = async (req, res) => {
56
64
  try {
57
65
  const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
58
- res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, proposedPlan, prescribers });
66
+ const caseState = await safeCaseStateOf(review);
67
+ res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers });
59
68
  } catch (error) {
60
69
  respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
61
70
  }
@@ -82,7 +91,11 @@ const getReviewTimelineController = async (req, res) => {
82
91
  const listEscalationReviewsController = async (req, res) => {
83
92
  try {
84
93
  const reviews = await listEscalationReviews({ code: req.params.code });
85
- res.status(200).json({ success: true, reviews: reviews.map(withCaseStatus) });
94
+ // Only the open review gets its state, so the panel's poll stays fresh without reading the review as seen.
95
+ const listed = await Promise.all(reviews.map(async (review) => (review.closedAt
96
+ ? withCaseStatus(review)
97
+ : { ...withCaseStatus(review), caseState: await safeCaseStateOf(review) })));
98
+ res.status(200).json({ success: true, reviews: listed });
86
99
  } catch (error) {
87
100
  respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
88
101
  }
@@ -0,0 +1,68 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
4
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
+ const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
+
7
+ const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
8
+ const { graveMissingOf, isDraftCurrent } = require('./gravePendingService');
9
+ const { pendingWaitMinutes } = require('./reviewDeadlineService');
10
+ const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
11
+
12
+ const WITH_DOCTOR_STATUSES = ['handing_off', 'awaiting_doctor'];
13
+ const DONE_STATUSES = ['closed', 'cancelled'];
14
+ const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
+ const timeOf = (value) => new Date(value).getTime();
16
+
17
+ const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, graveFlags: [], ...fields });
18
+
19
+ // The stage the sweep sends on its next tick, else the next one still to come; none while untaken alerts are off.
20
+ function nextAlertOf(review, clock, now) {
21
+ if (!escalationUntakenAlertsLive()) return null;
22
+ const next = dueStageOf(review, clock, now) ?? clock.stages.find((stage) => stage.dueAt && stage.dueAt > now);
23
+ return next ? { stage: next.stage, dueAt: next.dueAt } : null;
24
+ }
25
+
26
+ // The bot's question for its current draft, while the patient still has the level's wait to answer it.
27
+ function waitingOn(review, clock, now) {
28
+ const latest = (review.drafts ?? []).at(-1);
29
+ const wait = pendingWaitMinutes(clock.level);
30
+ if (review.status !== 'draft_ready' || !wait || latest?.writtenBy !== DRAFT_OPERATOR) return null;
31
+ if (timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return null;
32
+ const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
33
+ if (!ask || ask.skippedReason || (ask.outcome != null && !ANSWERABLE_OUTCOMES.includes(ask.outcome))) return null;
34
+ const dueAt = new Date(timeOf(ask.sentAt) + wait * 60000);
35
+ return dueAt > now ? { since: new Date(ask.sentAt), dueAt, question: ask.question ?? null } : null;
36
+ }
37
+
38
+ async function takenOf(review, clock) {
39
+ try {
40
+ return await caseTakenReason(review, clock.since, clock.level);
41
+ } catch (error) {
42
+ logger.warn('[EscalationCaseState] Could not tell whether the case was taken', {
43
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
44
+ });
45
+ return null;
46
+ }
47
+ }
48
+
49
+ // One state per case for the team: where it is, who has it and what comes next.
50
+ async function caseStateOf(review, { now = new Date(), policy } = {}) {
51
+ const label = CASE_STATUS_BY_REVIEW_STATUS[review.status]?.label ?? null;
52
+ if (review.closedAt || DONE_STATUSES.includes(review.status)) return state('closed', label);
53
+ if (FOLLOWUP_STATUSES.includes(review.status)) return state('followup', label);
54
+ const clock = PRE_DECISION_STATUSES.includes(review.status) ? untakenClockOf(review, policy) : null;
55
+ if (!clock) return state('in_progress', label);
56
+
57
+ const nextAlert = nextAlertOf(review, clock, now);
58
+ const taken = await takenOf(review, clock);
59
+ if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken });
60
+ const grave = graveMissingOf(review, clock, now).map(({ flag }) => flag);
61
+ if (grave.length) return state('grave_missing', 'Falta dato grave', { since: clock.since, nextAlert, graveFlags: grave });
62
+ if (WITH_DOCTOR_STATUSES.includes(review.status)) return state('with_doctor', label, { since: clock.since, nextAlert });
63
+ const waiting = waitingOn(review, clock, now);
64
+ if (waiting) return state('waiting_patient', 'Esperando paciente', { since: waiting.since, dueAt: waiting.dueAt, nextAlert });
65
+ return state('untaken', 'Sin tomar', { since: clock.since, dueAt: nextAlert?.dueAt ?? null, nextAlert });
66
+ }
67
+
68
+ module.exports = { caseStateOf };
@@ -1,12 +1,18 @@
1
+ const { mapConcurrent } = require('../utils/concurrencyUtils');
1
2
  const { httpError } = require('../utils/httpErrorUtils');
3
+ const { logger } = require('../utils/logger');
4
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
2
5
  const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
3
6
 
4
7
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
8
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
9
+ const { caseStateOf } = require('./escalationCaseStateService');
10
+ const { UNTAKEN_PROJECTION } = require('./untakenAlertService');
6
11
 
7
12
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
8
13
  const DONE_STATUSES = ['closed', 'cancelled'];
9
14
  const BOARD_BUCKETS = ['pending', 'followup', 'done'];
15
+ const STATE_CONCURRENCY = 10;
10
16
  const BOARD_FILTER_PREFIX = 'clinical-review-';
11
17
 
12
18
  const bucketQuery = (bucket, now) => {
@@ -22,7 +28,7 @@ const bucketQuery = (bucket, now) => {
22
28
  }
23
29
  };
24
30
 
25
- const boardRowOf = (review, bucket, deadlinePolicy) => {
31
+ const boardRowOf = (review, bucket, deadlinePolicy, state) => {
26
32
  const alarms = review.alarms || [];
27
33
  const lead = effectiveUrgencyOf(review);
28
34
  const raised = alarms.map((alarm) => alarm.raisedAt).filter(Boolean);
@@ -40,9 +46,21 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
40
46
  closedAt: review.closedAt || null,
41
47
  updatedSinceSeen: review.updatedSinceSeen === true,
42
48
  responseDeadline: responseDeadlineOf(review, deadlinePolicy),
49
+ caseState: state,
43
50
  };
44
51
  };
45
52
 
53
+ const ROW_PROJECTION = {
54
+ patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
55
+ 'decisions.createdAt': 1, urgencyReclassifications: 1,
56
+ };
57
+
58
+ // A row whose state cannot be read still shows, with its case status.
59
+ const stateOf = (review, now, policy) => caseStateOf(review, { now, policy }).catch((error) => {
60
+ logger.warn('[ReviewBoard] Could not read the case state of a row', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
61
+ return null;
62
+ });
63
+
46
64
  const byUrgencyThenAge = (a, b) => (URGENCY_RANK[b.urgency] || 0) - (URGENCY_RANK[a.urgency] || 0)
47
65
  || new Date(a.since) - new Date(b.since);
48
66
 
@@ -50,13 +68,13 @@ const byMostRecentlyClosed = (a, b) => new Date(b.closedAt) - new Date(a.closedA
50
68
 
51
69
  async function listReviewBoard({ bucket, now = new Date() } = {}) {
52
70
  const reviews = await getEscalationReview()
53
- .find(bucketQuery(bucket, now), {
54
- patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
55
- 'decisions.createdAt': 1, urgencyReclassifications: 1,
56
- })
71
+ .find(bucketQuery(bucket, now), bucket === 'pending' ? { ...UNTAKEN_PROJECTION, createdAt: 1, updatedSinceSeen: 1 } : ROW_PROJECTION)
57
72
  .lean();
58
73
  const deadlinePolicy = responseDeadlinePolicy();
59
- const rows = reviews.map((review) => boardRowOf(review, bucket, deadlinePolicy))
74
+ // Each open case reads its thread and messages, so a long board must not open hundreds of queries at once.
75
+ const states = [];
76
+ await mapConcurrent(reviews, STATE_CONCURRENCY, async (review, index) => { states[index] = await stateOf(review, now, deadlinePolicy); });
77
+ const rows = reviews.map((review, index) => boardRowOf(review, bucket, deadlinePolicy, states[index]))
60
78
  .sort(bucket === 'done' ? byMostRecentlyClosed : byUrgencyThenAge);
61
79
  const seen = new Set();
62
80
  return rows.filter((row) => !seen.has(row.patientCode) && seen.add(row.patientCode));
@@ -26,6 +26,11 @@ const ACTIONS = {
26
26
  urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
27
27
  };
28
28
  const MAX_QUESTION_LENGTH = 200;
29
+ // Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
30
+ const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
31
+ 'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
32
+ 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
33
+ };
29
34
 
30
35
  const duration = (minutes) => {
31
36
  const hours = Math.floor(minutes / 60);
@@ -177,10 +182,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
177
182
  closedAt: null,
178
183
  status: { $in: PRE_DECISION_STATUSES },
179
184
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
180
- }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
181
- 'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
182
- 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
183
- })
185
+ }, UNTAKEN_PROJECTION)
184
186
  .sort({ _id: -1 })
185
187
  .limit(SWEEP_LIMIT)
186
188
  .lean();
@@ -217,4 +219,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
217
219
  return sent;
218
220
  }
219
221
 
220
- module.exports = { sweepUntakenAlerts };
222
+ module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.4",
3
+ "version": "6.4.6",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",