@peopl-health/nexus 5.71.22 → 5.71.24

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.
@@ -14,8 +14,13 @@ function feverPatientTimerLive() {
14
14
  return flagOn('FEVER_PATIENT_TIMER_LIVE');
15
15
  }
16
16
 
17
+ function escalationPatientTimerLive() {
18
+ return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
19
+ }
20
+
17
21
  module.exports = {
18
22
  escalationAssessmentLive,
23
+ escalationPatientTimerLive,
19
24
  escalationUpdateModeLive,
20
25
  feverPatientTimerLive,
21
26
  };
@@ -22,6 +22,7 @@ const {
22
22
  syncEscalationReviewCase,
23
23
  } = require('../services/escalationReviewService');
24
24
  const { listReviewBoard } = require('../services/reviewBoardService');
25
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
25
26
 
26
27
  const respondWithError = (res, error, action, context) => {
27
28
  logger.error(`Error ${action}:`, {
@@ -32,6 +33,8 @@ const respondWithError = (res, error, action, context) => {
32
33
  res.status(error.statusCode || 500).json({ success: false, error: error.message });
33
34
  };
34
35
 
36
+ const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
37
+
35
38
  const openEscalationReviewController = async (req, res) => {
36
39
  try {
37
40
  const { code, patientCaseRecordId = null, patientCaseRecordIds = null, triggeredBy } = req.body || {};
@@ -42,7 +45,7 @@ const openEscalationReviewController = async (req, res) => {
42
45
  openedBy: triggeredBy,
43
46
  requestId: req.requestId,
44
47
  });
45
- res.status(created ? 201 : 200).json({ success: true, review });
48
+ res.status(created ? 201 : 200).json({ success: true, review: withCaseStatus(review) });
46
49
  } catch (error) {
47
50
  respondWithError(res, error, 'opening escalation review', { code: redactDirectIdentifiers(String(req.body?.code || '')) });
48
51
  }
@@ -51,7 +54,7 @@ const openEscalationReviewController = async (req, res) => {
51
54
  const getEscalationReviewController = async (req, res) => {
52
55
  try {
53
56
  const { review, isApprover, responseDeadline } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
54
- res.status(200).json({ success: true, review, isApprover, responseDeadline });
57
+ res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline });
55
58
  } catch (error) {
56
59
  respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
57
60
  }
@@ -69,7 +72,7 @@ const getReviewTimelineController = async (req, res) => {
69
72
  const listEscalationReviewsController = async (req, res) => {
70
73
  try {
71
74
  const reviews = await listEscalationReviews({ code: req.params.code });
72
- res.status(200).json({ success: true, reviews });
75
+ res.status(200).json({ success: true, reviews: reviews.map(withCaseStatus) });
73
76
  } catch (error) {
74
77
  respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
75
78
  }
@@ -88,7 +91,7 @@ const setEscalationReviewCasesController = async (req, res) => {
88
91
  try {
89
92
  const { patientCaseRecordIds, triggeredBy } = req.body || {};
90
93
  const review = await setReviewCases({ id: req.params.id, patientCaseRecordIds, updatedBy: triggeredBy, requestId: req.requestId });
91
- res.status(200).json({ success: true, review });
94
+ res.status(200).json({ success: true, review: withCaseStatus(review) });
92
95
  } catch (error) {
93
96
  respondWithError(res, error, 'selecting escalation review cases', { reviewId: req.params?.id });
94
97
  }
@@ -98,7 +101,7 @@ const addEscalationReviewCallLogController = async (req, res) => {
98
101
  try {
99
102
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
100
103
  const review = await addCallLog({ id: req.params.id, outcome, notes, calledAt, loggedBy: triggeredBy, requestId: req.requestId });
101
- res.status(201).json({ success: true, review });
104
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
102
105
  } catch (error) {
103
106
  respondWithError(res, error, 'logging escalation review call', { reviewId: req.params?.id });
104
107
  }
@@ -110,7 +113,7 @@ const confirmEscalationReviewNoteFactsController = async (req, res) => {
110
113
  const review = await confirmNoteFacts({
111
114
  id: req.params.id, accepted, declined, confirmedBy: triggeredBy, requestId: req.requestId,
112
115
  });
113
- res.status(200).json({ success: true, review });
116
+ res.status(200).json({ success: true, review: withCaseStatus(review) });
114
117
  } catch (error) {
115
118
  respondWithError(res, error, 'confirming escalation review note facts', { reviewId: req.params?.id });
116
119
  }
@@ -130,7 +133,7 @@ const requestEscalationReviewDraftController = async (req, res) => {
130
133
  try {
131
134
  const { triggeredBy } = req.body || {};
132
135
  const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
133
- res.status(202).json({ success: true, review });
136
+ res.status(202).json({ success: true, review: withCaseStatus(review) });
134
137
  } catch (error) {
135
138
  respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
136
139
  }
@@ -150,7 +153,7 @@ const addEscalationReviewDraftController = async (req, res) => {
150
153
  try {
151
154
  const { doctorText, patientMessage, triggeredBy } = req.body || {};
152
155
  const review = await addDraft({ id: req.params.id, doctorText, patientMessage, writtenBy: triggeredBy, requestId: req.requestId });
153
- res.status(201).json({ success: true, review });
156
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
154
157
  } catch (error) {
155
158
  respondWithError(res, error, 'saving escalation review draft', { reviewId: req.params?.id });
156
159
  }
@@ -160,7 +163,7 @@ const handOffEscalationReviewController = async (req, res) => {
160
163
  try {
161
164
  const { mode, physicianEmail = null, triggeredBy } = req.body || {};
162
165
  const { review, caseMirror, caseMirrors } = await handOffToDoctor({ id: req.params.id, mode, physicianEmail, sentBy: triggeredBy, requestId: req.requestId });
163
- res.status(201).json({ success: true, review, caseMirror, caseMirrors });
166
+ res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
164
167
  } catch (error) {
165
168
  respondWithError(res, error, 'handing escalation review to doctor', { reviewId: req.params?.id });
166
169
  }
@@ -192,7 +195,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
192
195
  recordedBy: triggeredBy,
193
196
  requestId: req.requestId,
194
197
  });
195
- res.status(201).json({ success: true, review });
198
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
196
199
  } catch (error) {
197
200
  respondWithError(res, error, 'recording escalation review decision', { reviewId: req.params?.id });
198
201
  }
@@ -202,7 +205,7 @@ const sendEscalationReviewIndicationsController = async (req, res) => {
202
205
  try {
203
206
  const { outsideWindowRoute = null, triggeredBy } = req.body || {};
204
207
  const { review, caseMirror, caseMirrors } = await sendApprovedIndications({ id: req.params.id, outsideWindowRoute, sentBy: triggeredBy, requestId: req.requestId });
205
- res.status(201).json({ success: true, review, caseMirror, caseMirrors });
208
+ res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
206
209
  } catch (error) {
207
210
  respondWithError(res, error, 'sending escalation review indications', { reviewId: req.params?.id });
208
211
  }
@@ -218,7 +221,7 @@ const closeEscalationReviewController = async (req, res) => {
218
221
  interruptionNotes,
219
222
  requestId: req.requestId,
220
223
  });
221
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
224
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
222
225
  } catch (error) {
223
226
  respondWithError(res, error, 'closing escalation review', { reviewId: req.params?.id });
224
227
  }
@@ -234,7 +237,7 @@ const reclassifyEscalationReviewUrgencyController = async (req, res) => {
234
237
  reclassifiedBy: triggeredBy,
235
238
  requestId: req.requestId,
236
239
  });
237
- res.status(200).json({ success: true, review, responseDeadline });
240
+ res.status(200).json({ success: true, review: withCaseStatus(review), responseDeadline });
238
241
  } catch (error) {
239
242
  respondWithError(res, error, 'reclassifying escalation review urgency', { reviewId: req.params?.id });
240
243
  }
@@ -249,7 +252,7 @@ const cancelEscalationReviewController = async (req, res) => {
249
252
  reason,
250
253
  requestId: req.requestId,
251
254
  });
252
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
255
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
253
256
  } catch (error) {
254
257
  respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
255
258
  }
@@ -260,10 +263,10 @@ const syncEscalationReviewCaseController = async (req, res) => {
260
263
  const { triggeredBy } = req.body || {};
261
264
  const { review, caseMirror, caseMirrors } = await syncEscalationReviewCase({ id: req.params.id, syncedBy: triggeredBy, requestId: req.requestId });
262
265
  if (caseMirror === 'failed' || caseMirror === 'partial') {
263
- res.status(502).json({ success: false, error: 'The patient case could not be updated', review, caseMirror, caseMirrors });
266
+ res.status(502).json({ success: false, error: 'The patient case could not be updated', review: withCaseStatus(review), caseMirror, caseMirrors });
264
267
  return;
265
268
  }
266
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
269
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
267
270
  } catch (error) {
268
271
  respondWithError(res, error, 'syncing escalation review case', { reviewId: req.params?.id });
269
272
  }
@@ -0,0 +1,31 @@
1
+ const CASE = (status, businessStatus, label) => ({ status, businessStatus, label });
2
+
3
+ const POR_REVISAR = CASE('requested', 'por-revisar', 'Por revisar');
4
+ const EN_EVALUACION = CASE('in-progress', 'en-evaluacion', 'En evaluación');
5
+ const CON_MEDICO = CASE('in-progress', 'con-medico', 'Con el médico');
6
+ const POR_ENVIAR = CASE('in-progress', 'indicacion-por-enviar', 'Indicación por enviar');
7
+
8
+ const CASE_STATUS_BY_REVIEW_STATUS = Object.freeze({
9
+ open: POR_REVISAR,
10
+ documenting: EN_EVALUACION,
11
+ draft_ready: EN_EVALUACION,
12
+ returned: EN_EVALUACION,
13
+ handing_off: CON_MEDICO,
14
+ awaiting_doctor: CON_MEDICO,
15
+ approved: POR_ENVIAR,
16
+ sending: POR_ENVIAR,
17
+ needs_intervention: CASE('in-progress', 'requiere-valoracion', 'Requiere valoración'),
18
+ indications_queued: CASE('on-hold', 'esperando-paciente', 'Esperando paciente'),
19
+ indications_sent: CASE('in-progress', 'indicaciones-dadas', 'Indicaciones dadas'),
20
+ monitoring: CASE('in-progress', 'en-vigilancia', 'En vigilancia'),
21
+ closed: CASE('completed', 'cerrado', 'Cerrado'),
22
+ cancelled: CASE('cancelled', 'no-requiere', 'No requiere'),
23
+ });
24
+
25
+ function caseStatusOf(reviewStatus) {
26
+ const caseStatus = CASE_STATUS_BY_REVIEW_STATUS[reviewStatus];
27
+ if (!caseStatus) throw new Error(`no case status for review status ${reviewStatus}`);
28
+ return caseStatus;
29
+ }
30
+
31
+ module.exports = { CASE_STATUS_BY_REVIEW_STATUS, caseStatusOf };
@@ -4,6 +4,9 @@ const MENTION_SLUG = 'clinical-mention';
4
4
  const RESULT_SLUG = 'patient-reported-result';
5
5
  const ESCALATION_SLUG = 'dispatched-escalation';
6
6
  const ESCALATION_KIND_SLUG = 'escalation-kind';
7
+ const ESCALATION_CASE_SLUG = 'escalation-case';
8
+ const ESCALATION_CASE_STATUS_SLUG = 'escalation-case-status';
9
+ const ESCALATION_DECISION_SLUG = 'escalation-decision';
7
10
  const REMINDER_SLUG = 'reminder';
8
11
  const REMINDER_KIND_SLUG = 'reminder-kind';
9
12
  const COMMUNICATION_CHANNEL_SLUG = 'communication-channel';
@@ -36,6 +39,9 @@ module.exports = {
36
39
  RESULT_SLUG,
37
40
  ESCALATION_SLUG,
38
41
  ESCALATION_KIND_SLUG,
42
+ ESCALATION_CASE_SLUG,
43
+ ESCALATION_CASE_STATUS_SLUG,
44
+ ESCALATION_DECISION_SLUG,
39
45
  REMINDER_SLUG,
40
46
  REMINDER_KIND_SLUG,
41
47
  COMMUNICATION_CHANNEL_SLUG,
@@ -343,4 +343,5 @@ module.exports = {
343
343
  ordinalValue,
344
344
  codingsFor,
345
345
  gradeConcept,
346
+ ctcaeSlug,
346
347
  };
package/lib/fhir/index.js CHANGED
@@ -15,7 +15,7 @@ const {
15
15
  recordRecommendationReview,
16
16
  } = require('./services/recommendationService');
17
17
  const { storeContingency, readContingencies } = require('./services/contingencyService');
18
- const { readDispatchedEscalations } = require('./services/escalationService');
18
+ const { readDispatchedEscalations, storeEscalationCase } = require('./services/escalationService');
19
19
  const { storeIntervention, readInterventions } = require('./services/interventionService');
20
20
  const { storeCluster, readClusters } = require('./services/clusterService');
21
21
  const { storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
@@ -70,6 +70,7 @@ module.exports = {
70
70
  storeContingency,
71
71
  readContingencies,
72
72
  readDispatchedEscalations,
73
+ storeEscalationCase,
73
74
  storeIntervention,
74
75
  readInterventions,
75
76
  storeCluster,
@@ -1,6 +1,7 @@
1
1
  const { getDeviceId, getOrganizationId, getSystems } = require('../config/fhirConfig');
2
2
  const { stringifyValue } = require('../utils/normalizeUtils');
3
- const { fhirId } = require('../helpers/fhirHelper');
3
+ const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
4
+ const { ctcaeSlug } = require('../helpers/terminologyHelper');
4
5
  const { reference, patientReference, codeableConcept, extension, toInstant } = require('../helpers/elementHelper');
5
6
  const { baseResource, problemListCategory, observationCategory } = require('../helpers/resourceHelper');
6
7
  const { MENTION_SLUG } = require('../constants/projectionSlugs');
@@ -48,7 +49,7 @@ function primaryResource(mention) {
48
49
 
49
50
  function mentionCode(fact) {
50
51
  return fact.ctcaeTerm
51
- ? codeableConcept(fact.canonicalTerm, { code: fact.ctcaeTerm, system: getSystems().ctcae, display: fact.ctcaeTerm })
52
+ ? codeableConcept(fact.canonicalTerm, { code: ctcaeSlug(fact.ctcaeTerm), system: codeSystemUrl('ctcae-v5-term'), display: fact.ctcaeTerm })
52
53
  : codeableConcept(fact.canonicalTerm);
53
54
  }
54
55
 
@@ -10,8 +10,14 @@ const {
10
10
  const {
11
11
  ESCALATION_SLUG,
12
12
  ESCALATION_KIND_SLUG,
13
+ ESCALATION_CASE_SLUG,
14
+ ESCALATION_CASE_STATUS_SLUG,
15
+ ESCALATION_DECISION_SLUG,
13
16
  } = require('../constants/projectionSlugs');
14
17
  const { SEVERITY_TO_PRIORITY } = require('../constants/severityPriority');
18
+ const { caseStatusOf } = require('../constants/escalationCaseStatus');
19
+
20
+ const ESCALATION_CASE_CODE = 'escalation_case';
15
21
 
16
22
  const TICKET_STATUS_TO_TASK_STATUS = {
17
23
  queued: 'requested',
@@ -48,6 +54,41 @@ class Task {
48
54
  }
49
55
  return new Task(payload);
50
56
  }
57
+
58
+ // The operational case of an escalation review; its symptoms are the Conditions in `reason`.
59
+ static fromEscalationReview({ review, priority, conditionIds = [], deviceId }) {
60
+ const reviewId = String(review._id);
61
+ const { status, businessStatus, label } = caseStatusOf(review.status);
62
+ const payload = {
63
+ resourceType: 'Task',
64
+ id: fhirId(`escalation-case-${reviewId}`),
65
+ identifier: [identifier(ESCALATION_CASE_SLUG, reviewId)],
66
+ status,
67
+ businessStatus: codeableConcept(label, { code: businessStatus, system: codeSystemUrl(ESCALATION_CASE_STATUS_SLUG), display: label }),
68
+ intent: 'order',
69
+ priority: priority || 'routine',
70
+ code: codeableConcept(ESCALATION_CASE_CODE, { code: ESCALATION_CASE_CODE, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
71
+ for: patientReference(review.patientCode),
72
+ authoredOn: toIso(review.createdAt),
73
+ lastModified: toIso(review.updatedAt),
74
+ requester: reference('Device', deviceId),
75
+ executionPeriod: { start: toIso(review.createdAt), ...(review.closedAt ? { end: toIso(review.closedAt) } : {}) },
76
+ };
77
+ if (conditionIds.length) payload.reason = conditionIds.map((id) => ({ reference: reference('Condition', id) }));
78
+ // Only a code reaches FHIR: the operator's cancellation note is free text.
79
+ if (review.status === 'cancelled') {
80
+ const reasonCode = String(review.cancellationReason ?? '').startsWith('no_requiere') ? 'no_requiere' : 'cancelado_por_equipo';
81
+ payload.statusReason = { concept: codeableConcept(reasonCode) };
82
+ }
83
+ const decision = review.decisions?.at(-1)?.decision;
84
+ if (decision) {
85
+ payload.output = [{
86
+ type: codeableConcept('decision'),
87
+ valueCodeableConcept: codeableConcept(decision, { code: decision, system: codeSystemUrl(ESCALATION_DECISION_SLUG) }),
88
+ }];
89
+ }
90
+ return new Task(payload);
91
+ }
51
92
  }
52
93
 
53
94
  module.exports = { Task };
@@ -1,7 +1,10 @@
1
+ const { getDeviceId } = require('../config/fhirConfig');
1
2
  const { fhirId } = require('../helpers/fhirHelper');
2
3
  const { ESCALATION_SLUG } = require('../constants/projectionSlugs');
3
4
  const { getFhirStore } = require('../stores/fhirStore');
4
5
  const { fromFhir } = require('../projections/dispatchedEscalationProjection');
6
+ const { Task } = require('../resources/Task');
7
+ const { storeResources } = require('./fhirService');
5
8
 
6
9
  const RESOURCE_TYPES = ['Task', 'CommunicationRequest'];
7
10
 
@@ -31,6 +34,16 @@ async function readDispatchedEscalations({ patientId, since = null, limit = null
31
34
  };
32
35
  }
33
36
 
37
+ // Two syncs of the same review can finish out of order; the stored case never moves back to an older read.
38
+ const keepNewerCase = (prior, incoming) => (Date.parse(prior.lastModified) > Date.parse(incoming.lastModified) ? prior : incoming);
39
+
40
+ async function storeEscalationCase({ review, priority, conditionIds }) {
41
+ const task = Task.fromEscalationReview({ review, priority, conditionIds, deviceId: getDeviceId() });
42
+ const { stored } = await storeResources(task, { merge: keepNewerCase });
43
+ return { ids: stored };
44
+ }
45
+
34
46
  module.exports = {
35
47
  readDispatchedEscalations,
48
+ storeEscalationCase,
36
49
  };
@@ -216,14 +216,56 @@ const escalationReviewSchema = new mongoose.Schema({
216
216
  closedBy: { type: String, default: null },
217
217
  closedAt: { type: Date, default: null },
218
218
  cancellationReason: { type: String, default: null },
219
+ caseStatusMirror: { type: mongoose.Schema.Types.Mixed, default: null },
219
220
  }, { timestamps: true });
220
221
 
222
+ // The fields the FHIR case Task is built from; a write that touches one tells the listeners.
223
+ const CASE_FIELDS = ['status', 'closedAt', 'cancellationReason', 'alarms', 'urgencyReclassifications', 'decisions', 'updates', 'followUpCases'];
224
+ const caseWriteListeners = [];
225
+ const onCaseWrite = (listener) => caseWriteListeners.push(listener);
226
+ // A listener failure is logged and never fails the review write that triggered it.
227
+ const notifyCaseWrite = (id) => {
228
+ if (!id) return;
229
+ caseWriteListeners.forEach((listener) => {
230
+ try {
231
+ listener(String(id));
232
+ } catch (error) {
233
+ logger.error('[EscalationReview] A case write listener failed', { escalationReviewId: String(id), error: error.message });
234
+ }
235
+ });
236
+ };
237
+ const touchesCase = (update = {}) => Array.isArray(update) || Object.entries(update)
238
+ .flatMap(([key, value]) => (key.startsWith('$') ? Object.keys(value ?? {}) : [key]))
239
+ .some((field) => CASE_FIELDS.includes(field.split('.')[0]));
240
+
241
+ escalationReviewSchema.post('save', (doc) => notifyCaseWrite(doc._id));
242
+ escalationReviewSchema.post('findOneAndUpdate', function notifyUpdated(doc) {
243
+ if (doc && touchesCase(this.getUpdate())) notifyCaseWrite(doc._id);
244
+ });
245
+ escalationReviewSchema.post('updateOne', function notifyUpdatedOne(result) {
246
+ if (result?.modifiedCount && touchesCase(this.getUpdate())) notifyCaseWrite(this.getFilter()._id);
247
+ });
248
+
221
249
  escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
222
250
  escalationReviewSchema.index({ status: 1, closedAt: -1 });
223
251
  escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
224
252
  escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
225
253
  escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
226
254
 
255
+ const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
256
+ ? review.patientCaseRecordIds
257
+ : (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
258
+
259
+ // A closed review leaves the cases the patient's open review now holds to that review.
260
+ async function supersededCaseIds(EscalationReview, review) {
261
+ if (!review.closedAt) return new Set();
262
+ const owner = await EscalationReview
263
+ .findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
264
+ .lean();
265
+ if (!owner || String(owner._id) === String(review._id)) return new Set();
266
+ return new Set(caseIdsOf(owner));
267
+ }
268
+
227
269
  const getEscalationReview = () => {
228
270
  const dbName = getModelDatabase('EscalationReview');
229
271
  const db = dbName ? getDb(dbName) : mongoose;
@@ -245,4 +287,9 @@ module.exports = {
245
287
  URGENCY_RANK,
246
288
  getEscalationReview,
247
289
  escalationReviewSchema,
290
+ notifyCaseWrite,
291
+ onCaseWrite,
292
+ touchesCase,
293
+ caseIdsOf,
294
+ supersededCaseIds,
248
295
  };
@@ -0,0 +1,77 @@
1
+ const runtimeConfig = require('../config/runtimeConfig');
2
+ const { logger } = require('../utils/logger');
3
+ const { isShadowRun } = require('../utils/shadowScope');
4
+ const { caseIdsOf, getEscalationReview, onCaseWrite, supersededCaseIds } = require('../models/escalationReviewModel');
5
+ const { storeEscalationCase } = require('../fhir/services/escalationService');
6
+ const { caseStatusOf } = require('../fhir/constants/escalationCaseStatus');
7
+ const { effectiveUrgencyOf } = require('./reviewDeadlineService');
8
+ const { updatePatientTask } = require('./patientTaskService');
9
+
10
+ const MIRROR_OPERATOR = 'bot:escalationCase';
11
+ const MIRROR_SOURCE = 'escalation_case';
12
+
13
+ const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'false')).trim().toLowerCase() === 'true';
14
+
15
+ function conditionIdsOf(review) {
16
+ const impressed = (review.updates ?? []).flatMap((update) => (update.impressions ?? []).map((impression) => impression.caseId));
17
+ return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
18
+ }
19
+
20
+ // The linked Airtable cases show the stored Task's status in status_operaciones; only a change is written.
21
+ async function mirrorToCases(review) {
22
+ const { businessStatus, label } = caseStatusOf(review.status);
23
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
24
+ const recordIds = caseIdsOf(review).filter((recordId) => !superseded.has(recordId));
25
+ const mirrored = review.caseStatusMirror;
26
+ const pending = recordIds.filter((recordId) => mirrored?.businessStatus !== businessStatus || !mirrored.recordIds?.includes(recordId));
27
+ if (!pending.length) return;
28
+ const settled = [];
29
+ for (const recordId of pending) {
30
+ try {
31
+ await updatePatientTask({
32
+ code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
33
+ });
34
+ settled.push(recordId);
35
+ } catch (error) {
36
+ // A case of another patient or program is never written; it is settled rather than retried on every sync.
37
+ if (error?.statusCode === 404) {
38
+ logger.warn('[EscalationCaseTask] The linked case is not this patient\'s program case; it is left as is', { escalationReviewId: String(review._id), recordId });
39
+ settled.push(recordId);
40
+ } else {
41
+ logger.error('[EscalationCaseTask] The case status did not reach the Airtable case', { escalationReviewId: String(review._id), recordId, error: error.message });
42
+ }
43
+ }
44
+ }
45
+ if (!settled.length) return;
46
+ const kept = mirrored?.businessStatus === businessStatus ? mirrored.recordIds ?? [] : [];
47
+ await getEscalationReview().updateOne(
48
+ { _id: review._id },
49
+ { $set: { caseStatusMirror: { businessStatus, recordIds: [...new Set([...kept, ...settled])] } } },
50
+ { timestamps: false },
51
+ );
52
+ }
53
+
54
+ async function syncCaseTask(id) {
55
+ const review = await getEscalationReview().findById(id).lean();
56
+ if (!review) return null;
57
+ const stored = await storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
58
+ await mirrorToCases(review);
59
+ return stored;
60
+ }
61
+
62
+ // Syncs of one review run one after another, each reading the review fresh, so the last write carries the last state.
63
+ const inFlight = new Map();
64
+
65
+ function scheduleCaseSync(id) {
66
+ if (!caseTaskLive() || isShadowRun()) return null;
67
+ const next = (inFlight.get(id) ?? Promise.resolve())
68
+ .then(() => syncCaseTask(id))
69
+ .catch((error) => logger.error('[EscalationCaseTask] The FHIR case was not synced', { escalationReviewId: id, error: error.message }));
70
+ inFlight.set(id, next);
71
+ next.then(() => { if (inFlight.get(id) === next) inFlight.delete(id); }, () => {});
72
+ return next;
73
+ }
74
+
75
+ onCaseWrite(scheduleCaseSync);
76
+
77
+ module.exports = { caseTaskLive, conditionIdsOf, scheduleCaseSync, syncCaseTask };
@@ -18,7 +18,9 @@ const {
18
18
  RETURN_REASONS,
19
19
  URGENCY_LEVELS,
20
20
  URGENCY_RANK,
21
+ caseIdsOf,
21
22
  getEscalationReview,
23
+ supersededCaseIds,
22
24
  } = require('../models/escalationReviewModel');
23
25
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
24
26
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
@@ -32,7 +34,10 @@ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService'
32
34
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
33
35
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
34
36
  const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
35
- const { feverPatientTimerLive: feverTimerLive } = require('../clinical/flags/escalationFlags');
37
+ const {
38
+ feverPatientTimerLive: feverTimerLive,
39
+ escalationPatientTimerLive: escalationTimerLive,
40
+ } = require('../clinical/flags/escalationFlags');
36
41
  const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
37
42
  const { daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
38
43
  const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
@@ -45,6 +50,7 @@ const { countMessages } = require('./messageService');
45
50
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
46
51
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
47
52
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
53
+ const { caseTaskLive } = require('./escalationCaseTaskService');
48
54
 
49
55
  const getMessaging = () => require('../core/NexusMessaging');
50
56
 
@@ -77,6 +83,9 @@ const DEFAULT_FEVER_CHEMO_WINDOW_DAYS = 42;
77
83
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
78
84
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
79
85
  const FEVER_CATEGORY = 'febrile_neutropenia';
86
+ const DEFAULT_PATIENT_TIMER_MINUTES = 15;
87
+ const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
88
+ const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
80
89
  const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
81
90
  const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
82
91
  const ALERT_OPERATOR = 'bot:escalationAlert';
@@ -118,10 +127,6 @@ const configured = (key) => {
118
127
  const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
119
128
  const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
120
129
 
121
- const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
122
- ? review.patientCaseRecordIds
123
- : (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
124
-
125
130
  const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
126
131
 
127
132
  const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
@@ -216,15 +221,6 @@ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus
216
221
  throw httpError(409, STATUS_CONFLICT);
217
222
  }
218
223
 
219
- async function supersededCaseIds(EscalationReview, review) {
220
- if (!review.closedAt) return new Set();
221
- const owner = await EscalationReview
222
- .findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
223
- .lean();
224
- if (!owner || String(owner._id) === String(review._id)) return new Set();
225
- return new Set(caseIdsOf(owner));
226
- }
227
-
228
224
  const summarise = (outcomes) => {
229
225
  if (!outcomes.length) return 'skipped';
230
226
  if (outcomes.every((outcome) => outcome.status === 'superseded')) return 'superseded';
@@ -555,7 +551,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
555
551
  const joined = await join();
556
552
  if (joined) {
557
553
  await scheduleDoctorAlert(joined, entry, now);
558
- await armFeverTimerOnJoin(joined, entry, now);
554
+ await armPatientTimerOnJoin(joined, entry, now);
559
555
  if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
560
556
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
561
557
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
@@ -921,9 +917,9 @@ async function scheduleDoctorAlert(review, alarm, now) {
921
917
  }
922
918
  }
923
919
 
924
- const feverTimerMs = () => {
925
- const minutes = Number(runtimeConfig.get('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES));
926
- return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_FEVER_TIMER_MINUTES) * 60 * 1000;
920
+ const timerMs = (key, fallback) => {
921
+ const minutes = Number(runtimeConfig.get(key, fallback));
922
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
927
923
  };
928
924
 
929
925
  const feverChemoWindowDays = () => {
@@ -946,16 +942,41 @@ async function feverTimerGap(patientCode, now) {
946
942
  return days > feverChemoWindowDays() ? 'outside_chemo_window' : null;
947
943
  }
948
944
 
949
- // The timer runs from the first asap alert of this episode, so a retried alert never restarts it and a
950
- // decision taken after it (which counts as taking the case) never moves it.
951
- function feverTimerSince(review) {
952
- const asapAlerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === 'asap');
953
- if (!asapAlerts.length) return null;
954
- const lastMs = new Date(asapAlerts.at(-1).sentAt).getTime();
945
+ // The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
946
+ // and a decision taken after it (which counts as taking the case) never moves it.
947
+ function timerSince(review, level) {
948
+ const alerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === level);
949
+ if (!alerts.length) return null;
950
+ const lastMs = new Date(alerts.at(-1).sentAt).getTime();
955
951
  const decidedMs = Math.max(-Infinity, ...(review.decisions ?? [])
956
952
  .map((decision) => new Date(decision.createdAt).getTime())
957
953
  .filter((ms) => ms < lastMs));
958
- return new Date(asapAlerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
954
+ return new Date(alerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
955
+ }
956
+
957
+ // The level whose timer is running: the highest alert sent since the last decision.
958
+ function timerLevelOf(review) {
959
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
960
+ const alerted = (level) => (review.doctorAlerts ?? [])
961
+ .some((sent) => sent.kind === 'initial' && sent.urgencyLevel === level && new Date(sent.sentAt).getTime() > decidedMs);
962
+ return alerted('stat') ? 'stat' : 'asap';
963
+ }
964
+
965
+ // An asap fever on a recent cytotoxic cycle gets the fever prompt; any other stat or asap case gets its
966
+ // level's prompt while that timer is live. `gap` says why the fever prompt does not apply. Without the
967
+ // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
968
+ async function patientTimerOf(review, level, now, { firing = false } = {}) {
969
+ const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
970
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
971
+ const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
972
+ const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
973
+ if (fever && !gap) {
974
+ return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
975
+ }
976
+ if (levelTimer) {
977
+ return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: timerMs('ESCALATION_PATIENT_TIMER_MINUTES', DEFAULT_PATIENT_TIMER_MINUTES) }, gap };
978
+ }
979
+ return { timer: null, gap };
959
980
  }
960
981
 
961
982
  // One prompt per episode: a prompt delivered (or possibly delivered) since the episode began, or one whose
@@ -969,19 +990,20 @@ function promptedSince(review, since, ownStart = null) {
969
990
  return delivered || (startedMs != null && startedMs >= sinceMs && startedMs !== ownStart?.getTime());
970
991
  }
971
992
 
972
- // An approver merely opening the review does not count: only an answer, a stat escalation, a paused
973
- // thread or a staff member writing to the patient means someone took the case.
974
- async function feverTakenReason(review, since, ownStart = null) {
975
- // Staff acting before the fever reached the review (on an earlier asap of the same episode) did not
976
- // take the fever case: those signals count only from the first asap fever alarm onwards.
977
- const firstFever = feverAlarmsOf(review)[0];
978
- const from = new Date(Math.max(since.getTime(), firstFever ? new Date(firstFever.raisedAt).getTime() : -Infinity));
993
+ // An approver merely opening the review does not count: only an answer, a stat escalation of an asap
994
+ // case, a paused thread or a staff member writing to the patient means someone took the case.
995
+ async function takenReason(review, since, timer, ownStart = null) {
996
+ // Staff acting before the case reached its timed level (on an earlier alarm of the same episode) did
997
+ // not take it: those signals count only from the first alarm the timer is for.
998
+ const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
999
+ const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
1000
+ const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
979
1001
  const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
980
1002
  if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
981
1003
  if (promptedSince(review, since, ownStart)) return 'already_prompted';
982
1004
  if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
983
1005
  const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
984
- if (currentAlarms(review).some(stat)) return 'stat_alarm';
1006
+ if (timer.level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
985
1007
  if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
986
1008
  if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
987
1009
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
@@ -995,26 +1017,27 @@ async function feverTakenReason(review, since, ownStart = null) {
995
1017
  return staffMessages ? 'staff_message' : null;
996
1018
  }
997
1019
 
998
- async function armFeverTimerOnJoin(review, alarm, now) {
1020
+ async function armPatientTimerOnJoin(review, alarm, now) {
999
1021
  try {
1000
- if (!feverTimerLive() || appliedLevelOf(alarm) !== 'asap' || alarm.category !== FEVER_CATEGORY) return;
1001
- if (alertedRankOf(review) !== URGENCY_RANK.asap) return;
1002
- const since = feverTimerSince(review);
1022
+ const level = appliedLevelOf(alarm);
1023
+ if (!escalationTimerLive() && !(feverTimerLive() && level === 'asap' && alarm.category === FEVER_CATEGORY)) return;
1024
+ if (!ALERTED_URGENCIES.includes(level) || alertedRankOf(review) !== URGENCY_RANK[level]) return;
1025
+ const since = timerSince(review, level);
1003
1026
  if (!since || promptedSince(review, since)) return;
1004
1027
  if (review.doctorAlertDueAt) return;
1005
- const gap = await feverTimerGap(review.patientCode, now);
1006
- if (gap) {
1007
- await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1028
+ const { timer, gap } = await patientTimerOf(review, level, now);
1029
+ if (!timer) {
1030
+ if (gap) await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1008
1031
  return;
1009
1032
  }
1010
1033
  // The patient gets the full timer from when the case became eligible, not from the earlier alert.
1011
1034
  await getEscalationReview().updateOne(
1012
1035
  { _id: review._id, doctorAlertDueAt: null },
1013
- { $set: { doctorAlertDueAt: new Date(now.getTime() + feverTimerMs()), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1036
+ { $set: { doctorAlertDueAt: new Date(now.getTime() + timer.ms), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1014
1037
  BOOKKEEPING,
1015
1038
  );
1016
1039
  } catch (error) {
1017
- logger.error('[EscalationReview] The fever patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1040
+ logger.error('[EscalationReview] The patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1018
1041
  }
1019
1042
  }
1020
1043
 
@@ -1056,33 +1079,36 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1056
1079
  await audit(current, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason });
1057
1080
  return null;
1058
1081
  };
1059
- if (!feverTimerLive()) return skip(review, 'flag_off');
1060
- const since = feverTimerSince(review);
1061
- if (!since) return skip(review, 'no_asap_alert');
1062
- const taken = await feverTakenReason(review, since);
1082
+ if (!feverTimerLive() && !escalationTimerLive()) return skip(review, 'flag_off');
1083
+ const level = timerLevelOf(review);
1084
+ const since = timerSince(review, level);
1085
+ if (!since) return skip(review, `no_${level}_alert`);
1086
+ const { timer, gap } = await patientTimerOf(review, level, now, { firing: true });
1087
+ if (!timer) return skip(review, gap ?? 'flag_off');
1088
+ const taken = await takenReason(review, since, timer);
1063
1089
  if (taken) return skip(review, taken);
1064
1090
 
1065
1091
  let directive;
1066
1092
  try {
1067
- directive = String((await composePrompt({ promptId: FEVER_TIMER_PROMPT_ID }))?.resolvedPrompt ?? '').trim();
1093
+ directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
1068
1094
  } catch (composeError) {
1069
1095
  // A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
1070
1096
  // drops it (with a ledger entry) if Airtable stays unreachable.
1071
- logger.error('[EscalationReview] The fever patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1097
+ logger.error('[EscalationReview] The patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1072
1098
  await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt' });
1073
1099
  return null;
1074
1100
  }
1075
- let error = directive ? null : `the ${FEVER_TIMER_PROMPT_ID} prompt is empty or missing`;
1101
+ let error = directive ? null : `the ${timer.promptId} prompt is empty or missing`;
1076
1102
  let outcome = null;
1077
1103
  let startedAt = null;
1078
1104
  const settle = () => getEscalationReview()
1079
1105
  .updateOne({ _id: review._id, feverPromptStartedAt: startedAt }, { $set: { feverPromptStartedAt: null } }, BOOKKEEPING);
1080
1106
  if (error) {
1081
- logger.error('[EscalationReview] The fever patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1107
+ logger.error('[EscalationReview] The patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1082
1108
  await release();
1083
1109
  } else {
1084
1110
  const fresh = await loadReview(review._id);
1085
- const takenNow = await feverTakenReason(fresh, since);
1111
+ const takenNow = await takenReason(fresh, since, timer);
1086
1112
  if (takenNow) return skip(fresh, takenNow);
1087
1113
  // The instruction runs a whole agent turn, which can outlast the sweep's lease; letting go of the
1088
1114
  // slot first keeps a second sweep from prompting the patient twice.
@@ -1098,7 +1124,7 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1098
1124
  // No turn ran: the same prompt comes back shortly, under the sweep's attempt cap. A draining
1099
1125
  // instance refused it before doing anything, so that refusal does not use up an attempt.
1100
1126
  const rearm = async (why) => {
1101
- logger.warn('[EscalationReview] The fever patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1127
+ logger.warn('[EscalationReview] The patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1102
1128
  const attempts = review.doctorAlertAttempts ?? 0;
1103
1129
  await settle();
1104
1130
  await getEscalationReview().updateOne(
@@ -1110,9 +1136,9 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1110
1136
  };
1111
1137
  // The gate runs again under the chat lock, right before the turn: a patient turn queued ahead of
1112
1138
  // this one can raise the case to stat, pause the bot or bring staff in while the prompt waits.
1113
- const beforeRun = async () => feverTakenReason(await loadReview(review._id), since, startedAt);
1139
+ const beforeRun = async () => takenReason(await loadReview(review._id), since, timer, startedAt);
1114
1140
  try {
1115
- const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: FEVER_TIMER_OPERATOR, beforeRun });
1141
+ const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: timer.operator, beforeRun });
1116
1142
  outcome = result?.outcome ?? null;
1117
1143
  if (outcome === 'gated') {
1118
1144
  await settle();
@@ -1129,10 +1155,10 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1129
1155
  // send happened: the same prompt comes back under the sweep's attempt cap.
1130
1156
  return rearm(sendError instanceof DrainingError ? 'draining' : redactedError(sendError));
1131
1157
  }
1132
- if (error) logger.error('[EscalationReview] The fever patient prompt was not sent', { escalationReviewId: String(review._id), error });
1158
+ if (error) logger.error('[EscalationReview] The patient prompt was not sent', { escalationReviewId: String(review._id), error });
1133
1159
  }
1134
1160
 
1135
- const sent = { kind: 'patient_prompt', urgencyLevel: 'asap', error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1161
+ const sent = { kind: 'patient_prompt', urgencyLevel: level, error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1136
1162
  const updated = await getEscalationReview()
1137
1163
  .findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1138
1164
  if (startedAt) await settle();
@@ -1184,14 +1210,12 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1184
1210
 
1185
1211
  const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1186
1212
  const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1187
- // A fever asap case gets the patient timer even when the doctor alert failed: the doctor is retried
1188
- // while there is time before the prompt and attempts left, then the patient prompt is the safety net.
1189
- // Stat already sends the patient to the ED.
1213
+ // A timed case gets the patient timer even when the doctor alert failed: the doctor is retried while
1214
+ // there is time before the prompt and attempts left, then the patient prompt is the safety net.
1190
1215
  const latestReview = updated ?? review;
1191
- const since = feverTimerSince(latestReview) ?? now;
1192
- const feverCase = urgencyLevel === 'asap' && feverTimerLive() && feverAlarmsOf(latestReview).length > 0 && !promptedSince(latestReview, since);
1193
- const feverGap = feverCase ? await feverTimerGap(review.patientCode, now) : null;
1194
- const promptAt = feverCase && !feverGap ? since.getTime() + feverTimerMs() : null;
1216
+ const since = timerSince(latestReview, urgencyLevel) ?? now;
1217
+ const { timer, gap } = promptedSince(latestReview, since) ? {} : await patientTimerOf(latestReview, urgencyLevel, now);
1218
+ const promptAt = timer ? since.getTime() + timer.ms : null;
1195
1219
  const retriesDoctor = sent.error
1196
1220
  && (promptAt == null || (now.getTime() + ALERT_RETRY_DELAY_MS < promptAt && (review.doctorAlertAttempts ?? 0) < MAX_ALERT_ATTEMPTS));
1197
1221
  if (promptAt != null && !retriesDoctor) {
@@ -1218,7 +1242,7 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1218
1242
  await audit(updated ?? review, ALERT_OPERATOR, null, {
1219
1243
  action: 'doctor_alerted', urgencyLevel, delivered: !sent.error,
1220
1244
  });
1221
- if (feverGap) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: feverGap });
1245
+ if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1222
1246
  return updated;
1223
1247
  }
1224
1248
 
@@ -1599,7 +1623,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1599
1623
  $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
1600
1624
  $unset: { identityBlock: '' },
1601
1625
  };
1602
- const recordUpdate = withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
1626
+ // With the case Task live, the case's operations status comes from the Task; the clinical status stays clinical.
1627
+ const recordUpdate = caseTaskLive() ? handoff : withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
1603
1628
  updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
1604
1629
  } catch (error) {
1605
1630
  await releaseReview(reviewId, 'handing_off', review.status, claim);
@@ -18,6 +18,7 @@ const {
18
18
  const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
19
19
  const { logPatientChange } = require('../services/patientService');
20
20
  const { clearOpenTaskSummary } = require('../services/patientTaskSummaryService');
21
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
21
22
 
22
23
  const MAX_ROWS = 50;
23
24
  const MAX_NOTE_LENGTH = 5000;
@@ -58,15 +59,8 @@ const CASE_STATUSES = [
58
59
  'radioterapia_revisión',
59
60
  'internado',
60
61
  ];
61
- const OPERATIONS_STATUSES = [
62
- 'cerrado',
63
- 'coordinación médica',
64
- 'síntoma marcado',
65
- 'pendiente',
66
- 'notificado ops',
67
- 'notificado medical',
68
- 'sin caracterizar',
69
- ];
62
+ // The operations status of a case is its FHIR case Task status, the same vocabulary nexus mirrors.
63
+ const OPERATIONS_STATUSES = [...new Set(Object.values(CASE_STATUS_BY_REVIEW_STATUS).map(({ label }) => label))];
70
64
 
71
65
  const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
72
66
 
@@ -1,6 +1,7 @@
1
1
  const { httpError } = require('../utils/httpErrorUtils');
2
2
  const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
3
3
 
4
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
4
5
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
5
6
 
6
7
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
@@ -31,6 +32,7 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
31
32
  patientCode: review.patientCode,
32
33
  bucket,
33
34
  status: review.status,
35
+ caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null,
34
36
  urgency: lead?.urgency || null,
35
37
  symptom: lead?.symptom || null,
36
38
  alarmCount: alarms.length,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.22",
3
+ "version": "5.71.24",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",