@peopl-health/nexus 6.5.19 → 6.5.21

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.
@@ -42,9 +42,18 @@ function gradeFor(todayGrades, catalog, term) {
42
42
  return key ? todayGrades.get(key) : null;
43
43
  }
44
44
 
45
+ const cardTerms = (element) => [...new Set([
46
+ ...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm),
47
+ ].filter(Boolean))];
48
+
49
+ function cardTodayGrade(element, { catalog, todayGrades }) {
50
+ const grades = cardTerms(element).map((term) => gradeFor(todayGrades, catalog, term)).filter((grade) => grade !== null);
51
+ return grades.length ? Math.max(...grades) : null;
52
+ }
53
+
45
54
  // Every term on the card needs today's grade and a current anchor: on a mixed card the question may be about the other term.
46
55
  function anchorsCover(element, { known, catalog, todayGrades }) {
47
- const terms = [...new Set([...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)].filter(Boolean))];
56
+ const terms = cardTerms(element);
48
57
  if (!terms.length) return false;
49
58
  return terms.every((term) => {
50
59
  const todayGrade = gradeFor(todayGrades, catalog, term);
@@ -70,4 +79,4 @@ function dropKnownFunctionalAsks(elements, { known, catalog, todayGrades } = {},
70
79
  return dropped;
71
80
  }
72
81
 
73
- module.exports = { asksFunctionalImpact, dropKnownFunctionalAsks, todayGradesByTerm };
82
+ module.exports = { asksFunctionalImpact, cardTodayGrade, dropKnownFunctionalAsks, todayGradesByTerm };
@@ -1,6 +1,7 @@
1
1
  const { recommendationId } = require('../../fhir/helpers/recommendationIds');
2
+ const { cardTodayGrade } = require('./knownCharacterizationHelper');
2
3
 
3
- function buildLegacyRecommendations({ plan, gate = null }) {
4
+ function buildLegacyRecommendations({ plan, gate = null, grades = { todayGrades: new Map() } }) {
4
5
  const ranked = [...plan.elements].sort((a, b) => a.rank - b.rank);
5
6
  return ranked.map((element) => {
6
7
  const { patient } = element.recommendation;
@@ -27,6 +28,8 @@ function buildLegacyRecommendations({ plan, gate = null }) {
27
28
  urgent_under_24h: isUrgent,
28
29
  // Gate enum only; element routes carry the palliative vocabulary.
29
30
  escalation_route: isUrgent ? (gate?.escalationRoute ?? null) : null,
31
+ // The Airtable triage directive opens on the highest-grade card.
32
+ max_reported_grade: cardTodayGrade(element, grades),
30
33
  };
31
34
  });
32
35
  }
@@ -85,7 +88,7 @@ function buildLegacyStep2(plan) {
85
88
  }
86
89
 
87
90
  // The explode trigger REGEX_EXTRACTs `recommendations` end-anchored: it must stay the last key.
88
- function buildLegacyStep3({ plan, gate = null }) {
91
+ function buildLegacyStep3({ plan, gate = null, grades }) {
89
92
  return {
90
93
  step3_careplan: {
91
94
  careplan_takeaways: {
@@ -94,7 +97,7 @@ function buildLegacyStep3({ plan, gate = null }) {
94
97
  careplan_summary_patient_facing: plan.takeaways.summaryPatientFacing,
95
98
  careplan_summary_internal: plan.takeaways.summaryInternal,
96
99
  },
97
- recommendations: buildLegacyRecommendations({ plan, gate }),
100
+ recommendations: buildLegacyRecommendations({ plan, gate, grades }),
98
101
  },
99
102
  };
100
103
  }
@@ -694,7 +694,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
694
694
  triageRecordId: payload.triageRecordId,
695
695
  step1: buildLegacyStep1(gate),
696
696
  step2: buildLegacyStep2(plan),
697
- step3: buildLegacyStep3({ plan, gate }),
697
+ step3: buildLegacyStep3({ plan, gate, grades: { catalog, todayGrades: boundary.todayGrades } }),
698
698
  };
699
699
  return finish({ status: 'success', reason: null }, mirrorPayload);
700
700
  } catch (err) {
@@ -4,7 +4,7 @@ const { 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
 
7
- const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
7
+ const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenBy, caseTakenReason } = require('./escalationReviewService');
8
8
  const { graveMissingOf, isDraftCurrent } = require('./gravePendingService');
9
9
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
10
10
  const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
@@ -14,7 +14,7 @@ const DONE_STATUSES = ['closed', 'cancelled'];
14
14
  const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
15
  const timeOf = (value) => new Date(value).getTime();
16
16
 
17
- const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, graveFlags: [], ...fields });
17
+ const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, takenBy: null, graveFlags: [], ...fields });
18
18
 
19
19
  // The stage the sweep sends on its next tick, else the next one still to come; none while untaken alerts are off.
20
20
  function nextAlertOf(review, clock, now) {
@@ -37,7 +37,13 @@ function waitingOn(review, clock, now) {
37
37
 
38
38
  async function takenOf(review, clock) {
39
39
  try {
40
- return await caseTakenReason(review, clock.since, clock.level);
40
+ const reason = await caseTakenReason(review, clock.since, clock.level);
41
+ if (!reason) return null;
42
+ const by = await caseTakenBy(review, clock.since, reason).catch((error) => {
43
+ logger.warn('[EscalationCaseState] Could not tell who took the case', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
44
+ return null;
45
+ });
46
+ return { reason, by };
41
47
  } catch (error) {
42
48
  logger.warn('[EscalationCaseState] Could not tell whether the case was taken', {
43
49
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -56,7 +62,7 @@ async function caseStateOf(review, { now = new Date(), policy } = {}) {
56
62
 
57
63
  const nextAlert = nextAlertOf(review, clock, now);
58
64
  const taken = await takenOf(review, clock);
59
- if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken });
65
+ if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken.reason, takenBy: taken.by });
60
66
  const grave = graveMissingOf(review, clock, now).map(({ flag }) => flag);
61
67
  if (grave.length) return state('grave_missing', 'Falta dato grave', { since: clock.since, nextAlert, graveFlags: grave });
62
68
  if (WITH_DOCTOR_STATUSES.includes(review.status)) return state('with_doctor', label, { since: clock.since, nextAlert });
@@ -57,7 +57,7 @@ const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService')
57
57
 
58
58
  const { getPatientInformation, logPatientChange } = require('./patientService');
59
59
  const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
60
- const { countMessages } = require('./messageService');
60
+ const { countMessages, getMessages } = require('./messageService');
61
61
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
62
62
  const { createPrescription } = require('./prescriptionService');
63
63
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
@@ -1105,29 +1105,54 @@ async function takenReason(review, since, timer, ownStart = null) {
1105
1105
  return caseTakenReason(review, from, timer.level);
1106
1106
  }
1107
1107
 
1108
+ const levelsAtOf = (review) => {
1109
+ const changes = review.urgencyReclassifications ?? [];
1110
+ return (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1111
+ };
1112
+
1113
+ // A lowering means someone looked at the case; a raise restarts the clock instead.
1114
+ const isLoweringOf = (review) => {
1115
+ const levelsAt = levelsAtOf(review);
1116
+ return (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1117
+ };
1118
+
1119
+ // Staff sign with their email; automations (the timer itself included) sign with a name and never count.
1120
+ const staffReplyFilter = (review, from) => ({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1121
+
1122
+ const atOrAfterOf = (from) => (at) => at != null && new Date(at).getTime() >= from.getTime();
1123
+
1124
+ const takingDecisionOf = (review, from) => (review.decisions ?? []).find((decision) => atOrAfterOf(from)(decision.createdAt));
1125
+ const takingLoweringOf = (review, from) => {
1126
+ const isLowering = isLoweringOf(review);
1127
+ return (review.urgencyReclassifications ?? []).find((change) => atOrAfterOf(from)(change.at) && isLowering(change));
1128
+ };
1129
+ const takingCallOf = (review, from) => (review.callLogs ?? []).find((call) => call.outcome === 'contacted' && atOrAfterOf(from)(call.calledAt));
1130
+
1108
1131
  // What says the team took the case from `from` on, for a case timed at `level`.
1109
1132
  async function caseTakenReason(review, from, level) {
1110
- const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1111
- if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1112
- const changes = review.urgencyReclassifications ?? [];
1113
- const levelsAt = (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1114
- if (level !== 'stat' && levelsAt(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1115
- // A lowering means someone looked at the case; a raise restarts the clock instead.
1116
- const lowered = (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1117
- if (changes.some((change) => atOrAfter(change.at) && lowered(change))) return 'reclassified';
1118
- if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1133
+ if (takingDecisionOf(review, from)) return 'decision';
1134
+ if (level !== 'stat' && levelsAtOf(review)(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1135
+ if (takingLoweringOf(review, from)) return 'reclassified';
1136
+ if (takingCallOf(review, from)) return 'call_contacted';
1119
1137
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1120
1138
  // anyway) skips the prompt.
1121
1139
  const thread = await getThreadInfo(review.patientCode, { rethrow: true });
1122
1140
  if (!thread) return 'thread_missing';
1123
1141
  if (thread.stopped === true) return 'thread_paused';
1124
1142
  if (thread.hospitalizedAt) return 'patient_hospitalized';
1125
- // Staff write from the platform or act through add-instruction / add-msg, always under their email;
1126
- // automations (the timer itself included) sign with a name and never count.
1127
- const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1143
+ const staffMessages = await countMessages(staffReplyFilter(review, from));
1128
1144
  return staffMessages ? 'staff_message' : null;
1129
1145
  }
1130
1146
 
1147
+ async function caseTakenBy(review, from, reason) {
1148
+ if (reason === 'decision') return takingDecisionOf(review, from)?.recordedBy ?? null;
1149
+ if (reason === 'reclassified') return takingLoweringOf(review, from)?.reclassifiedBy ?? null;
1150
+ if (reason === 'call_contacted') return takingCallOf(review, from)?.loggedBy ?? null;
1151
+ if (reason !== 'staff_message') return null;
1152
+ const [first] = await getMessages(staffReplyFilter(review, from), { select: 'triggeredBy', sort: { createdAt: 1 }, limit: 1 });
1153
+ return first?.triggeredBy ?? null;
1154
+ }
1155
+
1131
1156
  async function armPatientTimerOnJoin(review, alarm, now) {
1132
1157
  try {
1133
1158
  const level = appliedLevelOf(alarm);
@@ -2545,6 +2570,7 @@ module.exports = {
2545
2570
  _resetEscalationReviewIndexes,
2546
2571
  addCallLog,
2547
2572
  remindDoctorOfCase,
2573
+ caseTakenBy,
2548
2574
  caseTakenReason,
2549
2575
  promptedSince,
2550
2576
  currentAlarms,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.19",
3
+ "version": "6.5.21",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",