@peopl-health/nexus 5.63.0-dev.11429 → 5.63.0-dev.11473

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.
@@ -12,6 +12,7 @@ const {
12
12
  listEscalationReviews,
13
13
  openEscalationReview,
14
14
  recordDoctorDecision,
15
+ requestBotDraft,
15
16
  sendApprovedIndications,
16
17
  setReviewCases,
17
18
  suggestDraft,
@@ -124,6 +125,16 @@ const suggestEscalationReviewDraftController = async (req, res) => {
124
125
  }
125
126
  };
126
127
 
128
+ const requestEscalationReviewDraftController = async (req, res) => {
129
+ try {
130
+ const { triggeredBy } = req.body || {};
131
+ const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
132
+ res.status(202).json({ success: true, review });
133
+ } catch (error) {
134
+ respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
135
+ }
136
+ };
137
+
127
138
  const suggestEscalationReviewQuestionsController = async (req, res) => {
128
139
  try {
129
140
  const { triggeredBy } = req.body || {};
@@ -249,6 +260,7 @@ module.exports = {
249
260
  closeEscalationReviewController,
250
261
  getEscalationReviewController,
251
262
  getReviewTimelineController,
263
+ requestEscalationReviewDraftController,
252
264
  handOffEscalationReviewController,
253
265
  listEscalationReviewsController,
254
266
  listReviewBoardController,
@@ -7,6 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
9
9
  const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
10
+ const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
10
11
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
11
12
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
12
13
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
@@ -224,6 +225,7 @@ module.exports = {
224
225
  DOCTOR_DECISIONS,
225
226
  HANDOFF_MODES,
226
227
  INTERRUPTED_STATUSES,
228
+ FOLLOWUP_STATUSES,
227
229
  RETURN_REASONS,
228
230
  URGENCY_RANK,
229
231
  getEscalationReview,
@@ -127,6 +127,7 @@ const escalationReviewRouteDefinitions = {
127
127
  'POST /:id/cases': 'setEscalationReviewCasesController',
128
128
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
129
129
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
130
+ 'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
130
131
  'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
131
132
  'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
132
133
  'POST /:id/drafts': 'addEscalationReviewDraftController',
@@ -299,6 +300,7 @@ const builtInControllers = {
299
300
  listReviewBoardController: escalationReviewController.listReviewBoardController,
300
301
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
301
302
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
303
+ requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
302
304
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
303
305
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
304
306
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
@@ -14,6 +14,7 @@ const {
14
14
  DOCTOR_DECISIONS,
15
15
  HANDOFF_MODES,
16
16
  INTERRUPTED_STATUSES,
17
+ FOLLOWUP_STATUSES,
17
18
  RETURN_REASONS,
18
19
  URGENCY_RANK,
19
20
  getEscalationReview,
@@ -54,7 +55,6 @@ const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
54
55
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
55
56
  const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
56
57
  const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
57
- const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
58
58
  const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
59
59
  const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
60
60
  const SETTLED_TRAJECTORIES = ['improving', 'stable'];
@@ -583,7 +583,13 @@ async function openEscalationReview({
583
583
  if (!patient) throw httpError(404, 'Patient not found');
584
584
 
585
585
  const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
586
- const fields = { patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: false };
586
+ const fields = {
587
+ patientCode,
588
+ openedBy: operator,
589
+ patientCaseRecordIds: recordIds,
590
+ assistantPausedByReview: false,
591
+ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS),
592
+ };
587
593
 
588
594
  const EscalationReview = getEscalationReview();
589
595
  let review;
@@ -619,6 +625,35 @@ async function openEscalationReview({
619
625
  return { review, created: true };
620
626
  }
621
627
 
628
+ async function requestBotDraft({ id, requestedBy, requestId = null } = {}) {
629
+ const reviewId = reviewIdOf(id);
630
+ const operator = requiredText(requestedBy, 'requestedBy');
631
+ const review = await loadReview(reviewId);
632
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
633
+ if ((review.drafts ?? []).at(-1)?.writtenBy && review.drafts.at(-1).writtenBy !== DRAFT_OPERATOR) {
634
+ throw httpError(409, 'The latest draft was written by the team; edit it instead of asking for a new one');
635
+ }
636
+ const now = new Date();
637
+ if (review.draftDueAt && new Date(review.draftDueAt) > now) return review;
638
+ const scheduled = await getEscalationReview().findOneAndUpdate(
639
+ {
640
+ _id: reviewId,
641
+ status: { $in: DOCUMENTING_STATUSES },
642
+ drafts: { $size: (review.drafts ?? []).length },
643
+ $or: [{ draftDueAt: null }, { draftDueAt: { $lte: now } }],
644
+ },
645
+ { $set: { draftDueAt: now, draftAttempts: 0 } },
646
+ { new: true },
647
+ ).lean();
648
+ if (!scheduled) {
649
+ const latest = await loadReview(reviewId);
650
+ if (latest.draftDueAt && new Date(latest.draftDueAt) > now) return latest;
651
+ throw httpError(409, STATUS_CONFLICT);
652
+ }
653
+ await audit(scheduled, operator, requestId, { action: 'draft_requested' });
654
+ return scheduled;
655
+ }
656
+
622
657
  async function isEscalationApprover(operator) {
623
658
  try {
624
659
  return Boolean(await getEscalationApprover(operator));
@@ -712,34 +747,29 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
712
747
  if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
713
748
 
714
749
  const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
750
+ const casesChanged = {
751
+ $not: [{
752
+ $setEquals: [
753
+ {
754
+ $ifNull: [
755
+ '$patientCaseRecordIds',
756
+ { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
757
+ ],
758
+ },
759
+ recordIds,
760
+ ],
761
+ }],
762
+ };
763
+ const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
715
764
 
716
765
  const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
717
766
  $set: {
718
767
  patientCaseRecordIds: recordIds,
719
- status: {
720
- $cond: [
721
- {
722
- $and: [
723
- { $eq: ['$status', 'draft_ready'] },
724
- {
725
- $not: [{
726
- $setEquals: [
727
- {
728
- $ifNull: [
729
- '$patientCaseRecordIds',
730
- { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
731
- ],
732
- },
733
- recordIds,
734
- ],
735
- }],
736
- },
737
- ],
738
- },
739
- 'documenting',
740
- '$status',
741
- ],
742
- },
768
+ status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
769
+ ...(isBotDraft && {
770
+ draftDueAt: { $cond: [casesChanged, new Date(Date.now() + DRAFT_DEBOUNCE_MS), '$draftDueAt'] },
771
+ draftAttempts: { $cond: [casesChanged, 0, '$draftAttempts'] },
772
+ }),
743
773
  pendingCaseMirrors: {
744
774
  $filter: {
745
775
  input: { $ifNull: ['$pendingCaseMirrors', []] },
@@ -980,12 +1010,12 @@ const readingOf = (impression) => (['close', 'resolve_episode'].includes(impress
980
1010
  async function followUpCasesOf(review, sinceMs) {
981
1011
  const decisionNumber = (review.decisions ?? []).length;
982
1012
  if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
983
- const known = [...new Set([
984
- ...(review.followUpCases ?? []),
985
- ...(review.updates ?? [])
986
- .filter((entry) => new Date(entry.at).getTime() <= sinceMs)
987
- .flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean)),
988
- ])];
1013
+ const caseIdsOfUpdates = (isBefore) => (review.updates ?? [])
1014
+ .filter((entry) => (new Date(entry.at).getTime() <= sinceMs) === isBefore)
1015
+ .flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean));
1016
+ let known = [...new Set([...(review.followUpCases ?? []), ...caseIdsOfUpdates(true)])];
1017
+ if (!known.length) known = [...new Set(caseIdsOfUpdates(false))];
1018
+ if (!known.length) return { review, known: new Set() };
989
1019
  const stored = await getEscalationReview()
990
1020
  .findOneAndUpdate(
991
1021
  { _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
@@ -1768,6 +1798,7 @@ module.exports = {
1768
1798
  recordDoctorDecision,
1769
1799
  sendScheduledDoctorAlert,
1770
1800
  recordReviewUpdate,
1801
+ requestBotDraft,
1771
1802
  sendApprovedIndications,
1772
1803
  setReviewCases,
1773
1804
  suggestDraft,
@@ -1,19 +1,15 @@
1
1
  const { httpError } = require('../utils/httpErrorUtils');
2
- const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
2
+ const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
3
3
 
4
4
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
5
- const RETURNED_STATUSES = ['returned'];
6
- const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
7
5
  const DONE_STATUSES = ['closed', 'cancelled'];
8
- const BOARD_BUCKETS = ['pending', 'returned', 'followup', 'done'];
6
+ const BOARD_BUCKETS = ['pending', 'followup', 'done'];
9
7
  const BOARD_FILTER_PREFIX = 'clinical-review-';
10
8
 
11
9
  const bucketQuery = (bucket, now) => {
12
10
  switch (bucket) {
13
11
  case 'pending':
14
- return { closedAt: null, status: { $nin: [...RETURNED_STATUSES, ...FOLLOWUP_STATUSES, ...DONE_STATUSES] } };
15
- case 'returned':
16
- return { closedAt: null, status: { $in: RETURNED_STATUSES } };
12
+ return { closedAt: null, status: { $nin: [...FOLLOWUP_STATUSES, ...DONE_STATUSES] } };
17
13
  case 'followup':
18
14
  return { closedAt: null, status: { $in: FOLLOWUP_STATUSES } };
19
15
  case 'done':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.63.0-dev.11429",
3
+ "version": "5.63.0-dev.11473",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",