@peopl-health/nexus 5.72.7 → 5.72.9

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.
@@ -186,9 +186,11 @@ async function generateEscalationDraft({
186
186
  logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
187
187
  return { completed: false, attempted: true, rejected: true, reason: 'the model returned no usable text' };
188
188
  }
189
- if (TECHNICAL_TOKEN.test(`${composeDoctorBody({ ...draft, alarm: null })}\n${patientMessage}`)) {
190
- logger.warn('[escalationDraft] generation leaked a technical token into the text', { reviewId });
191
- return { completed: false, attempted: true, rejected: true, reason: 'the model wrote a field name or technical token into the doctor or patient text' };
189
+ // The token goes into the reason because the audit log keeps the reason: it says which prompt rule leaked.
190
+ const leaked = TECHNICAL_TOKEN.exec(`${composeDoctorBody({ ...draft, alarm: null })}\n${patientMessage}`)?.[0].slice(0, 40);
191
+ if (leaked) {
192
+ logger.warn('[escalationDraft] generation leaked a technical token into the text', { reviewId, token: leaked });
193
+ return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
192
194
  }
193
195
 
194
196
  return {
@@ -16,7 +16,6 @@ const {
16
16
  requestBotDraft,
17
17
  sendApprovedIndications,
18
18
  setReviewCases,
19
- listReviewCaseCandidates,
20
19
  suggestDraft,
21
20
  suggestKeyQuestions,
22
21
  confirmNoteFacts,
@@ -98,15 +97,6 @@ const setEscalationReviewCasesController = async (req, res) => {
98
97
  }
99
98
  };
100
99
 
101
- const listEscalationReviewCaseCandidatesController = async (req, res) => {
102
- try {
103
- const candidates = await listReviewCaseCandidates({ id: req.params.id });
104
- res.status(200).json({ success: true, candidates });
105
- } catch (error) {
106
- respondWithError(res, error, 'listing escalation review case candidates', { reviewId: req.params?.id });
107
- }
108
- };
109
-
110
100
  const addEscalationReviewCallLogController = async (req, res) => {
111
101
  try {
112
102
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
@@ -190,6 +180,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
190
180
  doctorReply = null,
191
181
  reason = null,
192
182
  draftNumber = null,
183
+ closingCaseIds = null,
193
184
  triggeredBy,
194
185
  } = req.body || {};
195
186
  const review = await recordDoctorDecision({
@@ -202,6 +193,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
202
193
  doctorReply,
203
194
  reason,
204
195
  draftNumber,
196
+ closingCaseIds,
205
197
  recordedBy: triggeredBy,
206
198
  requestId: req.requestId,
207
199
  });
@@ -223,12 +215,13 @@ const sendEscalationReviewIndicationsController = async (req, res) => {
223
215
 
224
216
  const closeEscalationReviewController = async (req, res) => {
225
217
  try {
226
- const { triggeredBy, deliveryConfirmed = false, interruptionNotes = null } = req.body || {};
218
+ const { triggeredBy, deliveryConfirmed = false, interruptionNotes = null, closingCaseIds = null } = req.body || {};
227
219
  const { review, caseMirror, caseMirrors } = await closeEscalationReview({
228
220
  id: req.params.id,
229
221
  closedBy: triggeredBy,
230
222
  deliveryConfirmed,
231
223
  interruptionNotes,
224
+ closingCaseIds,
232
225
  requestId: req.requestId,
233
226
  });
234
227
  res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
@@ -255,11 +248,12 @@ const reclassifyEscalationReviewUrgencyController = async (req, res) => {
255
248
 
256
249
  const cancelEscalationReviewController = async (req, res) => {
257
250
  try {
258
- const { triggeredBy, reason = null } = req.body || {};
251
+ const { triggeredBy, reason = null, closingCaseIds = null } = req.body || {};
259
252
  const { review, caseMirror, caseMirrors } = await cancelEscalationReview({
260
253
  id: req.params.id,
261
254
  cancelledBy: triggeredBy,
262
255
  reason,
256
+ closingCaseIds,
263
257
  requestId: req.requestId,
264
258
  });
265
259
  res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
@@ -299,7 +293,6 @@ module.exports = {
299
293
  recordEscalationReviewDecisionController,
300
294
  sendEscalationReviewIndicationsController,
301
295
  setEscalationReviewCasesController,
302
- listEscalationReviewCaseCandidatesController,
303
296
  suggestEscalationReviewDraftController,
304
297
  suggestEscalationReviewQuestionsController,
305
298
  syncEscalationReviewCaseController,
@@ -217,6 +217,7 @@ const escalationReviewSchema = new mongoose.Schema({
217
217
  closedAt: { type: Date, default: null },
218
218
  cancellationReason: { type: String, default: null },
219
219
  caseStatusMirror: { type: mongoose.Schema.Types.Mixed, default: null },
220
+ closingCaseIds: { type: [String], default: undefined },
220
221
  }, { timestamps: true });
221
222
 
222
223
  // The fields the FHIR case Task is built from; a write that touches one tells the listeners.
@@ -128,7 +128,6 @@ const escalationReviewRouteDefinitions = {
128
128
  'GET /by-patient/:code': 'listEscalationReviewsController',
129
129
  'GET /:id': 'getEscalationReviewController',
130
130
  'GET /:id/timeline': 'getReviewTimelineController',
131
- 'GET /:id/case-candidates': 'listEscalationReviewCaseCandidatesController',
132
131
  'POST /:id/cases': 'setEscalationReviewCasesController',
133
132
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
134
133
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
@@ -312,7 +311,6 @@ const builtInControllers = {
312
311
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
313
312
  requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
314
313
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
315
- listEscalationReviewCaseCandidatesController: escalationReviewController.listEscalationReviewCaseCandidatesController,
316
314
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
317
315
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
318
316
  suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
@@ -5,7 +5,7 @@ const { caseIdsOf, getEscalationReview, onCaseWrite, supersededCaseIds } = requi
5
5
  const { storeEscalationCase } = require('../fhir/services/escalationService');
6
6
  const { caseStatusOf } = require('../fhir/constants/escalationCaseStatus');
7
7
  const { effectiveUrgencyOf } = require('./reviewDeadlineService');
8
- const { updatePatientTask } = require('./patientTaskService');
8
+ const { readPatientCases, updatePatientTask } = require('./patientTaskService');
9
9
 
10
10
  const MIRROR_OPERATOR = 'bot:escalationCase';
11
11
  const MIRROR_SOURCE = 'escalation_case';
@@ -17,36 +17,87 @@ function conditionIdsOf(review) {
17
17
  return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
18
18
  }
19
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);
20
+ // The labels that close a case in Airtable, including the legacy lowercase one.
21
+ const CLOSING_LABELS = new Set(['Cerrado', 'No requiere', 'cerrado']);
22
+ const CLOSING_TASK_STATUSES = new Set(['completed', 'cancelled']);
23
+ const TO_REVIEW = caseStatusOf('open');
24
+
25
+ // A closed case, by ops by hand or by a review, is left as it was closed.
26
+ const isClosed = (patientCase) => CLOSING_LABELS.has(patientCase?.operationsStatus);
27
+
28
+ // A review is of the whole patient: it covers every case the patient raised before it closed that is still open.
29
+ // A closed review takes none once the patient has a newer review, which covers them instead.
30
+ async function withOpenCases(review, cases) {
31
+ try {
32
+ if (review.closedAt && await getEscalationReview().findOne({ patientCode: review.patientCode, createdAt: { $gt: review.createdAt } }, { _id: 1 }).lean()) return review;
33
+ const until = review.closedAt ? new Date(review.closedAt).getTime() : Infinity;
34
+ const covered = caseIdsOf(review);
35
+ const adopted = cases
36
+ .filter((patientCase) => patientCase.isOpen && !isClosed(patientCase))
37
+ .filter((patientCase) => !covered.includes(patientCase.recordId) && Date.parse(patientCase.createdAt) <= until)
38
+ .map((patientCase) => patientCase.recordId);
39
+ if (!adopted.length) return review;
40
+ const recordIds = [...covered, ...adopted];
41
+ // A review that closed while its cases were read keeps none of them; the sync of its close takes them.
42
+ const covering = await getEscalationReview().updateOne({ _id: review._id, closedAt: review.closedAt ?? null }, { $addToSet: { patientCaseRecordIds: { $each: recordIds } } }, { timestamps: false });
43
+ if (!covering?.modifiedCount) return review;
44
+ return { ...review, patientCaseRecordIds: recordIds };
45
+ } catch (error) {
46
+ logger.error('[EscalationCaseTask] The patient\'s open cases were not added to the review; it keeps the ones it covers', { escalationReviewId: String(review._id), error: error.message });
47
+ return review;
48
+ }
49
+ }
50
+
51
+ // Nobody closes a case they did not see: a review closes the cases its panel showed at the close or, closed without
52
+ // that list (by the follow-up, or an older client), the ones raised before the team's last decision.
53
+ function closingIdsOf(review, cases) {
54
+ if (Array.isArray(review.closingCaseIds)) return new Set(review.closingCaseIds);
55
+ const decidedAt = Date.parse((review.decisions ?? []).at(-1)?.createdAt ?? '');
56
+ if (!Number.isFinite(decidedAt)) return new Set();
57
+ return new Set(cases.filter((patientCase) => Date.parse(patientCase.createdAt) <= decidedAt).map((patientCase) => patientCase.recordId));
58
+ }
59
+
60
+ // The previous shape, one status for a list of cases, reads as each of those cases showing it.
61
+ const mirroredByCase = (mirror) => mirror?.byCase
62
+ ?? Object.fromEntries((mirror?.recordIds ?? []).map((recordId) => [recordId, mirror.businessStatus]));
63
+
64
+ // The covered Airtable cases show the stored Task's status in status_operaciones, except the cases a closing review
65
+ // does not close, which go back to "Por revisar"; only a change is written.
66
+ async function mirrorToCases(review, cases) {
67
+ const reviewStatus = caseStatusOf(review.status);
68
+ const closing = CLOSING_TASK_STATUSES.has(reviewStatus.status) ? closingIdsOf(review, cases) : null;
23
69
  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));
70
+ const byId = new Map(cases.map((patientCase) => [patientCase.recordId, patientCase]));
71
+ const mirrored = mirroredByCase(review.caseStatusMirror);
72
+ const pending = caseIdsOf(review)
73
+ .filter((recordId) => !superseded.has(recordId))
74
+ .map((recordId) => ({ recordId, caseStatus: !closing || closing.has(recordId) ? reviewStatus : TO_REVIEW }))
75
+ .filter(({ recordId, caseStatus }) => mirrored[recordId] !== caseStatus.businessStatus)
76
+ .filter(({ recordId }) => !isClosed(byId.get(recordId)))
77
+ // A case resolved meanwhile that the review does not close is left resolved, not sent back to be reviewed.
78
+ .filter(({ recordId }) => !closing || closing.has(recordId) || byId.get(recordId)?.isOpen !== false);
27
79
  if (!pending.length) return;
28
- const settled = [];
29
- for (const recordId of pending) {
80
+ const settled = {};
81
+ for (const { recordId, caseStatus } of pending) {
30
82
  try {
31
83
  await updatePatientTask({
32
- code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
84
+ code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: caseStatus.label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
33
85
  });
34
- settled.push(recordId);
86
+ settled[recordId] = caseStatus.businessStatus;
35
87
  } catch (error) {
36
88
  // A case of another patient or program is never written; it is settled rather than retried on every sync.
37
89
  if (error?.statusCode === 404) {
38
90
  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);
91
+ settled[recordId] = caseStatus.businessStatus;
40
92
  } else {
41
93
  logger.error('[EscalationCaseTask] The case status did not reach the Airtable case', { escalationReviewId: String(review._id), recordId, error: error.message });
42
94
  }
43
95
  }
44
96
  }
45
- if (!settled.length) return;
46
- const kept = mirrored?.businessStatus === businessStatus ? mirrored.recordIds ?? [] : [];
97
+ if (!Object.keys(settled).length) return;
47
98
  await getEscalationReview().updateOne(
48
99
  { _id: review._id },
49
- { $set: { caseStatusMirror: { businessStatus, recordIds: [...new Set([...kept, ...settled])] } } },
100
+ { $set: { caseStatusMirror: { byCase: { ...mirrored, ...settled } } } },
50
101
  { timestamps: false },
51
102
  );
52
103
  }
@@ -55,7 +106,14 @@ async function syncCaseTask(id) {
55
106
  const review = await getEscalationReview().findById(id).lean();
56
107
  if (!review) return null;
57
108
  const stored = await storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
58
- await mirrorToCases(review);
109
+ let cases;
110
+ try {
111
+ cases = await readPatientCases(review.patientCode);
112
+ } catch (error) {
113
+ logger.error('[EscalationCaseTask] The patient\'s cases could not be read; their status waits for the next sync', { escalationReviewId: String(review._id), error: error.message });
114
+ return stored;
115
+ }
116
+ await mirrorToCases(await withOpenCases(review, cases), cases);
59
117
  return stored;
60
118
  }
61
119
 
@@ -24,7 +24,6 @@ const {
24
24
  } = require('../models/escalationReviewModel');
25
25
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
26
26
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
27
- const { caseCandidates } = require('../helpers/reviewCaseCandidateHelper');
28
27
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
29
28
  const { DrainingError } = require('../core/BatchingManager');
30
29
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
@@ -51,7 +50,7 @@ const { countMessages } = require('./messageService');
51
50
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
52
51
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
53
52
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
54
- const { caseTaskLive } = require('./escalationCaseTaskService');
53
+ const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
55
54
 
56
55
  const getMessaging = () => require('../core/NexusMessaging');
57
56
 
@@ -69,8 +68,6 @@ const BOOKKEEPING = { timestamps: false };
69
68
  const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
70
69
  const DUPLICATE_KEY_ERROR = 11000;
71
70
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
72
- // The cases a review covers can change while it is open and no operation is in flight.
73
- const CASE_SELECTABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor', 'approved', 'needs_intervention', ...FOLLOWUP_STATUSES];
74
71
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
75
72
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
76
73
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
@@ -116,6 +113,13 @@ const patientCodeOf = (code) => {
116
113
 
117
114
  const optionalText = (value) => (value == null ? null : String(value));
118
115
 
116
+ // The open triage cases the team saw when closing the review; null when the caller did not say.
117
+ function closingCaseIdsOf(value) {
118
+ if (value == null) return null;
119
+ if (!Array.isArray(value) || value.some((recordId) => typeof recordId !== 'string')) throw httpError(400, 'closingCaseIds must be a list of case ids');
120
+ return [...new Set(value.map((recordId) => recordId.trim()).filter(Boolean))];
121
+ }
122
+
119
123
  const reviewIdOf = (id) => {
120
124
  if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
121
125
  return id;
@@ -799,7 +803,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
799
803
  const operator = requiredText(updatedBy, 'updatedBy');
800
804
  if (!Array.isArray(patientCaseRecordIds)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
801
805
  const current = await loadReview(reviewId);
802
- if (!CASE_SELECTABLE_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
806
+ if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
803
807
 
804
808
  const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
805
809
  const casesChanged = {
@@ -817,7 +821,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
817
821
  };
818
822
  const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
819
823
 
820
- const review = await updateReview(reviewId, CASE_SELECTABLE_STATUSES, [{
824
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
821
825
  $set: {
822
826
  patientCaseRecordIds: recordIds,
823
827
  status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
@@ -838,12 +842,6 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
838
842
  return review;
839
843
  }
840
844
 
841
- async function listReviewCaseCandidates({ id } = {}) {
842
- const review = await loadReview(reviewIdOf(id));
843
- const cases = await readPatientCases(review.patientCode);
844
- return caseCandidates({ review, cases, linkedIds: caseIdsOf(review) });
845
- }
846
-
847
845
  async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
848
846
  const reviewId = reviewIdOf(id);
849
847
  const operator = requiredText(loggedBy, 'loggedBy');
@@ -1657,11 +1655,13 @@ async function recordDoctorDecision({
1657
1655
  doctorReply = null,
1658
1656
  reason = null,
1659
1657
  draftNumber: seenDraftNumber = null,
1658
+ closingCaseIds = null,
1660
1659
  recordedBy,
1661
1660
  requestId = null,
1662
1661
  } = {}) {
1663
1662
  const reviewId = reviewIdOf(id);
1664
1663
  const operator = requiredText(recordedBy, 'recordedBy');
1664
+ const closingIds = closingCaseIdsOf(closingCaseIds);
1665
1665
  const sources = DECISION_SOURCES.filter((entry) => entry !== 'chat');
1666
1666
  const decisions = DOCTOR_DECISIONS.filter((entry) => entry !== 'direct_chat');
1667
1667
  if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
@@ -1727,7 +1727,7 @@ async function recordDoctorDecision({
1727
1727
  },
1728
1728
  },
1729
1729
  $set: returnReason === 'no_requiere'
1730
- ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}` }
1730
+ ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
1731
1731
  : { status: statusAfter(decision) },
1732
1732
  }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1733
1733
  await audit(updated, operator, requestId, {
@@ -1965,10 +1965,11 @@ async function recordEpisode(review, now = new Date()) {
1965
1965
  }
1966
1966
 
1967
1967
  async function closeEscalationReview({
1968
- id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
1968
+ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, closingCaseIds = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
1969
1969
  } = {}) {
1970
1970
  const reviewId = reviewIdOf(id);
1971
1971
  const operator = requiredText(closedBy, 'closedBy');
1972
+ const closingIds = closingCaseIdsOf(closingCaseIds);
1972
1973
 
1973
1974
  const current = await loadReview(reviewId);
1974
1975
  const queued = current.status === 'indications_queued';
@@ -1983,7 +1984,7 @@ async function closeEscalationReview({
1983
1984
  if (sinceStatusChanged < INTERRUPTION_GRACE_MS) throw httpError(409, INTERRUPTION_TOO_SOON);
1984
1985
  }
1985
1986
 
1986
- const closure = { status: 'closed', closedBy: operator, closedAt: new Date() };
1987
+ const closure = { status: 'closed', closedBy: operator, closedAt: new Date(), ...(closingIds && { closingCaseIds: closingIds }) };
1987
1988
  if (queued) Object.assign(closure, { 'patientDelivery.confirmedBy': operator, 'patientDelivery.confirmedAt': new Date() });
1988
1989
  if (interrupted) closure.interruptionResolution = { fromStatus: current.status, notes };
1989
1990
 
@@ -2037,9 +2038,10 @@ async function reclassifyUrgency({ id, urgencyLevel, reason, reclassifiedBy, req
2037
2038
  return { review, responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()) };
2038
2039
  }
2039
2040
 
2040
- async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
2041
+ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingCaseIds = null, requestId = null } = {}) {
2041
2042
  const reviewId = reviewIdOf(id);
2042
2043
  const operator = requiredText(cancelledBy, 'cancelledBy');
2044
+ const closingIds = closingCaseIdsOf(closingCaseIds);
2043
2045
  if (reason != null && typeof reason !== 'string') throw httpError(400, 'reason must be text');
2044
2046
  const notes = String(reason ?? '').trim() || null;
2045
2047
 
@@ -2050,7 +2052,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
2050
2052
  let review;
2051
2053
  try {
2052
2054
  review = await updateReview(reviewId, allowed, {
2053
- $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
2055
+ $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes, ...(closingIds && { closingCaseIds: closingIds }) },
2054
2056
  }, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
2055
2057
  } catch (error) {
2056
2058
  if (error?.statusCode !== 409 || notes) throw error;
@@ -2067,6 +2069,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
2067
2069
  async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
2068
2070
  const reviewId = reviewIdOf(id);
2069
2071
  const operator = requiredText(syncedBy, 'syncedBy');
2072
+ if (caseTaskLive()) await scheduleCaseSync(reviewId);
2070
2073
  return syncCase(await loadReview(reviewId), operator, requestId);
2071
2074
  }
2072
2075
 
@@ -2098,7 +2101,6 @@ module.exports = {
2098
2101
  sendApprovedIndications,
2099
2102
  setAlarmAppliedLevel,
2100
2103
  setReviewCases,
2101
- listReviewCaseCandidates,
2102
2104
  suggestDraft,
2103
2105
  suggestKeyQuestions,
2104
2106
  confirmNoteFacts,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.7",
3
+ "version": "5.72.9",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,51 +0,0 @@
1
- // Triage cases a review can cover: the patient's cases raised from a day before the review opened, plus
2
- // the ones it already covers. A case is only suggested; the team decides which ones the review covers.
3
- const LOOKBACK_MS = 24 * 60 * 60 * 1000;
4
- const NEAR_ALARM_MS = 2 * 60 * 60 * 1000;
5
- const STEM_LENGTH = 5;
6
- // Stems too common in symptom names and alarm text to tell two symptoms apart.
7
- const GENERIC_STEMS = new Set(['dolor', 'grado', 'sinto', 'para', 'del', 'con', 'las', 'los', 'una', 'que', 'por', 'sin', 'dific', 'frecu']);
8
-
9
- const words = (text) => String(text ?? '')
10
- .toLowerCase()
11
- .normalize('NFD')
12
- .replace(/[̀-ͯ]/g, '')
13
- .split(/[^a-z]+/)
14
- .filter((word) => word.length >= 3)
15
- .map((word) => word.slice(0, STEM_LENGTH))
16
- .filter((stem) => !GENERIC_STEMS.has(stem));
17
-
18
- const symptomOf = (description) => String(description ?? '').replace(/\s*Grado\s*-\s*\d+\s*$/i, '');
19
-
20
- // Suggested when an alarm of the review came within two hours of the case and names the same symptom.
21
- function isSuggested(patientCase, alarms) {
22
- const caseWords = words(symptomOf(patientCase.description));
23
- const createdAt = Date.parse(patientCase.createdAt);
24
- if (!caseWords.length || !Number.isFinite(createdAt)) return false;
25
- return alarms.some((alarm) => {
26
- if (!(Math.abs(new Date(alarm.raisedAt).getTime() - createdAt) <= NEAR_ALARM_MS)) return false;
27
- const alarmWords = new Set(words(`${alarm.symptom ?? ''} ${alarm.suspectedCondition ?? ''}`));
28
- return caseWords.some((word) => alarmWords.has(word));
29
- });
30
- }
31
-
32
- function caseCandidates({ review, cases, linkedIds }) {
33
- const since = new Date(review.createdAt).getTime() - LOOKBACK_MS;
34
- const linked = new Set(linkedIds);
35
- return cases
36
- .filter((patientCase) => linked.has(patientCase.recordId) || Date.parse(patientCase.createdAt) >= since)
37
- .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
38
- .map((patientCase) => ({
39
- recordId: patientCase.recordId,
40
- number: patientCase.number,
41
- createdAt: patientCase.createdAt,
42
- description: patientCase.description,
43
- grade: patientCase.grade,
44
- status: patientCase.status,
45
- operationsStatus: patientCase.operationsStatus,
46
- isLinked: linked.has(patientCase.recordId),
47
- isSuggested: !linked.has(patientCase.recordId) && isSuggested(patientCase, review.alarms ?? []),
48
- }));
49
- }
50
-
51
- module.exports = { caseCandidates };