@peopl-health/nexus 5.57.0-dev.8869 → 5.57.0-dev.8873

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.
@@ -7,7 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
9
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
10
- const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned'];
10
+ const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
11
11
  const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
12
12
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
13
13
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
@@ -91,6 +91,7 @@ const escalationReviewSchema = new mongoose.Schema({
91
91
  default: 'open',
92
92
  },
93
93
  openedBy: { type: String, required: true },
94
+ assistantPausedByReview: { type: Boolean, default: false },
94
95
  callLogs: { type: [callLogSchema], default: [] },
95
96
  drafts: { type: [draftSchema], default: [] },
96
97
  doctorHandoffs: { type: [doctorHandoffSchema], default: [] },
@@ -22,6 +22,7 @@ const { generateEscalationDraft } = require('../clinical/services/escalationDraf
22
22
  const { getPatientInformation, logPatientChange } = require('./patientService');
23
23
  const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
24
24
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
25
+ const { switchThreadStoppedStatus } = require('./threadService');
25
26
 
26
27
  const AUDIT_SOURCE = 'escalation_review';
27
28
  const RECENT_REVIEW_LIMIT = 20;
@@ -30,6 +31,7 @@ const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
30
31
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
31
32
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
32
33
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
34
+ const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
33
35
  const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
34
36
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
35
37
  const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
@@ -86,6 +88,43 @@ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
86
88
  changes: { escalationReviewId: String(review._id), ...changes },
87
89
  });
88
90
 
91
+ async function pauseAssistantFor(patientCode) {
92
+ try {
93
+ const result = await switchThreadStoppedStatus(patientCode, true, { byOperator: true });
94
+ return Boolean(result?.modifiedCount);
95
+ } catch (error) {
96
+ logger.error('[EscalationReview] The assistant could not be paused for this patient', { error: error.message });
97
+ return false;
98
+ }
99
+ }
100
+
101
+ const passPauseToOpenReview = (review) => getEscalationReview().findOneAndUpdate(
102
+ { patientCode: review.patientCode, closedAt: null, _id: { $ne: review._id } },
103
+ { $set: { assistantPausedByReview: true } },
104
+ ).lean();
105
+
106
+ async function resumeAssistant(review, operator = null, requestId = null) {
107
+ if (review.assistantPausedByReview !== true) return review;
108
+ const stopClaiming = () => getEscalationReview()
109
+ .updateOne({ _id: review._id }, { $set: { assistantPausedByReview: false } });
110
+ try {
111
+ if (!await passPauseToOpenReview(review)) {
112
+ await switchThreadStoppedStatus(review.patientCode, false);
113
+ if (await passPauseToOpenReview(review)) {
114
+ await switchThreadStoppedStatus(review.patientCode, true, { byOperator: true });
115
+ }
116
+ }
117
+ await stopClaiming();
118
+ return { ...review, assistantPausedByReview: false };
119
+ } catch (error) {
120
+ logger.error('[EscalationReview] The assistant could not be resumed after this review', {
121
+ escalationReviewId: String(review._id), error: error.message,
122
+ });
123
+ await audit(review, operator ?? review.closedBy ?? 'system', requestId, { action: 'assistant_resume_failed' });
124
+ return review;
125
+ }
126
+ }
127
+
89
128
  const withCaseMirror = (review, update, changes) => {
90
129
  const recordIds = caseIdsOf(review);
91
130
  if (!recordIds.length) return update;
@@ -352,19 +391,49 @@ async function openEscalationReview({
352
391
  if (!patient) throw httpError(404, 'Patient not found');
353
392
 
354
393
  const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
355
- const fields = { patientCode, openedBy: operator, patientCaseRecordIds: recordIds };
394
+ const pausedHere = await pauseAssistantFor(patientCode);
395
+ const fields = {
396
+ patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: pausedHere,
397
+ };
356
398
 
357
399
  const EscalationReview = getEscalationReview();
358
- await ensureActiveReviewIndex(EscalationReview);
359
400
  let review;
360
401
  try {
402
+ await ensureActiveReviewIndex(EscalationReview);
361
403
  review = (await EscalationReview.create(fields)).toObject();
362
404
  } catch (error) {
363
- if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
405
+ if (error?.code !== DUPLICATE_KEY_ERROR) {
406
+ if (pausedHere) {
407
+ await switchThreadStoppedStatus(patientCode, false).catch((resumeError) => {
408
+ logger.error('[EscalationReview] A failed open left the assistant paused', {
409
+ error: resumeError.message,
410
+ });
411
+ });
412
+ }
413
+ throw error;
414
+ }
364
415
  const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
365
- if (!existing) throw httpError(409, 'This patient already has a review being opened; try again in a moment');
416
+ if (!existing) {
417
+ if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
418
+ throw httpError(409, 'This patient already has a review being opened; try again in a moment');
419
+ }
420
+ if (pausedHere && existing.assistantPausedByReview !== true) {
421
+ try {
422
+ await EscalationReview.updateOne({ _id: existing._id }, { $set: { assistantPausedByReview: true } });
423
+ existing.assistantPausedByReview = true;
424
+ } catch (error) {
425
+ logger.error('[EscalationReview] The pause was not recorded against the open review', {
426
+ escalationReviewId: String(existing._id), error: error.message,
427
+ });
428
+ }
429
+ }
366
430
  return { review: existing, created: false };
367
431
  }
432
+ const held = pausedHere || await pauseAssistantFor(patientCode);
433
+ if (held !== review.assistantPausedByReview) {
434
+ await EscalationReview.updateOne({ _id: review._id }, { $set: { assistantPausedByReview: held } });
435
+ review.assistantPausedByReview = held;
436
+ }
368
437
  await audit(review, operator, requestId, { action: 'opened', patientCaseRecordIds: recordIds });
369
438
  return { review, created: true };
370
439
  }
@@ -612,6 +681,8 @@ async function recordDoctorDecision({
612
681
  let approvedText = null;
613
682
  if (decision === 'approved') approvedText = draft.patientMessage;
614
683
  if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
684
+ // Truthiness, not != null: an empty textarea is a decline with nothing to say.
685
+ if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
615
686
 
616
687
  const updated = await updateReview(reviewId, ['awaiting_doctor'], {
617
688
  $push: {
@@ -640,16 +711,40 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
640
711
  }
641
712
 
642
713
  const claim = newOperationClaim();
643
- const claimed = await updateReview(reviewId, ['approved'], { $set: { status: 'sending', operationClaim: claim } });
714
+ const claimed = await updateReview(reviewId, SENDABLE_STATUSES, { $set: { status: 'sending', operationClaim: claim } });
644
715
  const decisionNumber = claimed.decisions.length;
645
- const { finalText } = claimed.decisions[decisionNumber - 1];
716
+ const { finalText, decision } = claimed.decisions[decisionNumber - 1];
717
+ const claimedFrom = statusAfter(decision);
718
+
719
+ if (!finalText) {
720
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
721
+ logger.error('[EscalationReview] The claim was not released after a decision with no text', {
722
+ escalationReviewId: String(claimed._id), error: releaseError.message,
723
+ });
724
+ });
725
+ throw httpError(409, 'This decision carries no approved text to send to the patient');
726
+ }
646
727
 
728
+ // Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
647
729
  let message;
648
- let result;
649
730
  try {
650
731
  message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
732
+ } catch (error) {
733
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
734
+ logger.error('[EscalationReview] The claim was not released after a send that never started', {
735
+ escalationReviewId: String(claimed._id), error: releaseError.message,
736
+ });
737
+ });
738
+ throw error;
739
+ }
740
+
741
+ let result;
742
+ try {
651
743
  result = await sendMessage(message);
652
- if (!result?.success) throw httpError(502, 'The indications could not be sent to the patient');
744
+ const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
745
+ if (!result?.success && !alreadyDelivered) {
746
+ throw httpError(502, 'The indications could not be sent to the patient');
747
+ }
653
748
  } catch (error) {
654
749
  if (!sendDidNotHappen(error)) {
655
750
  logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
@@ -658,7 +753,11 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
658
753
  });
659
754
  throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
660
755
  }
661
- await releaseReview(reviewId, 'sending', 'approved', claim);
756
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
757
+ logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
758
+ escalationReviewId: String(claimed._id), error: releaseError.message,
759
+ });
760
+ });
662
761
  throw error;
663
762
  }
664
763
 
@@ -711,7 +810,7 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
711
810
  if (interrupted) closeChanges.fromStatus = current.status;
712
811
  if (queued) closeChanges.deliveryConfirmed = true;
713
812
  await audit(review, operator, requestId, closeChanges);
714
- return syncCase(review, operator, requestId);
813
+ return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
715
814
  }
716
815
 
717
816
  async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
@@ -737,7 +836,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
737
836
  }
738
837
 
739
838
  await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
740
- return syncCase(review, operator, requestId);
839
+ return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
741
840
  }
742
841
 
743
842
  async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
@@ -35,14 +35,14 @@ const getThreadInfo = async (code) => {
35
35
  };
36
36
 
37
37
  const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } = {}) => {
38
- if (stopped && byOperator) {
39
- await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() });
40
- } else {
41
- await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
42
- }
38
+ const result = stopped && byOperator
39
+ ? await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() })
40
+ : await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
43
41
 
44
42
  updateRecordByFilter(Monitoreo_ID, 'message_monitor', `{whatsapp_id} = "${code}"`, { stopped }, code)
45
43
  .catch(err => logger.error('[switchThreadStoppedStatus] Failed to update message_monitor', { code, error: err.message }));
44
+
45
+ return result;
46
46
  };
47
47
 
48
48
  const setThreadPromptId = async (code, promptId) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0-dev.8869",
3
+ "version": "5.57.0-dev.8873",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",