@peopl-health/nexus 6.9.0-dev.21862 → 6.9.0-dev.22012

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.
@@ -68,6 +68,10 @@ function escalationUnreviewedCaseNoticeLive() {
68
68
  return flagOn('ESCALATION_UNREVIEWED_CASE_NOTICE_LIVE');
69
69
  }
70
70
 
71
+ function escalationManualHandoffLive() {
72
+ return flagOn('ESCALATION_MANUAL_HANDOFF_LIVE');
73
+ }
74
+
71
75
  module.exports = {
72
76
  escalationCaseFollowUpLive,
73
77
  escalationCaseStatusReminderLive,
@@ -85,4 +89,5 @@ module.exports = {
85
89
  escalationStaleQueueNoticeLive,
86
90
  escalationWatchTeamNoticeLive,
87
91
  feverPatientTimerLive,
92
+ escalationManualHandoffLive,
88
93
  };
@@ -174,7 +174,7 @@ const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'p
174
174
  const HOLDABLE_CHANGES = [ANSWER_ONLY, IMPROVING];
175
175
 
176
176
  const WHAT_CHANGED_PROPERTY = nullableEnum(WHAT_CHANGED);
177
- WHAT_CHANGED_PROPERTY.description = 'Solo en `update`: qué trae de nuevo. `answer_only` cuando el paciente solo respondió lo que se le preguntó y su respuesta no agrega síntoma, grado, bandera roja ni empeoramiento (por ejemplo «no tengo fiebre, puedo tragar»). Si el equipo ya decidió el caso, un `answer_only` sin subir el nivel queda anotado en el caso sin volver a avisar al equipo. `improving` cuando el paciente cuenta que el síntoma ya escalado mejoró, se resolvió o sigue igual de estable, sin síntoma nuevo, sin bandera roja y sin nada que empeore (por ejemplo «ya no me duele la garganta, solo quedó la ronquera»): queda anotado en el caso, abierto o cerrado en los últimos 7 días, sin volver a avisar al equipo; no aplica a la fiebre. Ante cualquier duda usa el valor que corresponda o `null`: nunca `answer_only` ni `improving` si algo empeoró, apareció algo nuevo o la mejoría es solo parcial con un dato que preocupa.';
177
+ WHAT_CHANGED_PROPERTY.description = 'Solo en `update`: qué trae de nuevo. `answer_only` cuando el paciente solo respondió lo que se le preguntó y su respuesta no agrega síntoma, grado, bandera roja ni empeoramiento (por ejemplo «no tengo fiebre, puedo tragar»). Si el equipo ya decidió el caso, un `answer_only` sin subir el nivel queda anotado en el caso sin volver a avisar al equipo. `improving` cuando el síntoma ya escalado se resolvió o bajó de grado, o ya no tiene lo que motivó el nivel, sin síntoma nuevo, sin bandera roja y sin nada que empeore (por ejemplo «ya estoy bien», «ya no me duele la garganta, solo quedó la ronquera»); si sigue igual, no es `improving`. Un `improving` con `urgent` queda anotado en el caso, abierto o cerrado en los últimos 7 días, sin volver a avisar al equipo; si el síntoma sigue presente y todavía necesita al equipo en asap o stat, deja ese nivel y el equipo recibe el aviso. En un update nunca uses `routine`: abre una solicitud aparte y la mejoría no queda en el caso. No aplica a la fiebre. Ante cualquier duda usa el valor que corresponda o `null`: nunca `answer_only` ni `improving` si algo empeoró, apareció algo nuevo o la mejoría es solo parcial con un dato que preocupa.';
178
178
 
179
179
  const FEVER_RULED_OUT_PROPERTY = nullable({
180
180
  'type': 'boolean',
@@ -24,6 +24,7 @@ const {
24
24
  syncEscalationReviewCase,
25
25
  } = require('../services/escalationReviewService');
26
26
  const { listReviewBoard } = require('../services/reviewBoardService');
27
+ const { manualHandoffStateOf, requestManualHandoff } = require('../services/manualHandoffService');
27
28
  const { caseStateOf } = require('../services/escalationCaseStateService');
28
29
  const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
29
30
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
@@ -66,7 +67,7 @@ const getEscalationReviewController = async (req, res) => {
66
67
  try {
67
68
  const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
68
69
  const caseState = await safeCaseStateOf(review);
69
- res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers, doctorCaseStatusLive: escalationDoctorCaseStatusLive() });
70
+ res.status(200).json({ success: true, review: { ...withCaseStatus(review), manualHandoff: manualHandoffStateOf(review) }, isApprover, responseDeadline, caseState, proposedPlan, prescribers, doctorCaseStatusLive: escalationDoctorCaseStatusLive() });
70
71
  } catch (error) {
71
72
  respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
72
73
  }
@@ -96,7 +97,7 @@ const listEscalationReviewsController = async (req, res) => {
96
97
  // Only the open review gets its state, so the panel's poll stays fresh without reading the review as seen.
97
98
  const listed = await Promise.all(reviews.map(async (review) => (review.closedAt
98
99
  ? withCaseStatus(review)
99
- : { ...withCaseStatus(review), caseState: await safeCaseStateOf(review) })));
100
+ : { ...withCaseStatus(review), caseState: await safeCaseStateOf(review), manualHandoff: manualHandoffStateOf(review) })));
100
101
  res.status(200).json({ success: true, reviews: listed });
101
102
  } catch (error) {
102
103
  respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
@@ -212,6 +213,16 @@ const handOffEscalationReviewController = async (req, res) => {
212
213
  }
213
214
  };
214
215
 
216
+ const requestManualHandoffController = async (req, res) => {
217
+ try {
218
+ const { reason, seenHandoffs = null, triggeredBy } = req.body || {};
219
+ const { review, caseMirror, caseMirrors, handedOff: isHandedOff } = await requestManualHandoff({ id: req.params.id, reason, requestedBy: triggeredBy, seenHandoffs, requestId: req.requestId });
220
+ res.status(isHandedOff ? 201 : 202).json({ success: true, handedOff: isHandedOff, review: { ...withCaseStatus(review), manualHandoff: manualHandoffStateOf(review) }, caseMirror, caseMirrors });
221
+ } catch (error) {
222
+ respondWithError(res, error, 'handing escalation review to doctor by hand', { reviewId: req.params?.id });
223
+ }
224
+ };
225
+
215
226
  const recordEscalationReviewDecisionController = async (req, res) => {
216
227
  try {
217
228
  const {
@@ -338,6 +349,7 @@ module.exports = {
338
349
  previewEscalationReviewPlanController,
339
350
  requestEscalationReviewDraftController,
340
351
  handOffEscalationReviewController,
352
+ requestManualHandoffController,
341
353
  listEscalationReviewsController,
342
354
  listReviewBoardController,
343
355
  openEscalationReviewController,
@@ -28,6 +28,7 @@ const { isOutboundAllowed } = require('../helpers/outboundAllowlistHelper');
28
28
 
29
29
  const { createMessagingProvider } = require('../adapters/registry');
30
30
  const { ensureThreadExists, resolveThreadCode } = require('../services/threadService');
31
+ const { numberUnreachable } = require('../services/unreachableNumberService');
31
32
  const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
32
33
 
33
34
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
@@ -116,6 +117,7 @@ function createDefaultLlmMonitor(options, loader = loadDefaultLlmMonitor) {
116
117
  * Core messaging orchestrator for providers, storage, and assistant processing.
117
118
  */
118
119
  const NOT_SENT_DECEASED = { success: false, messageId: null, status: 'patient_deceased', delivered: false, deferred: false };
120
+ const NOT_SENT_UNREACHABLE = { success: false, messageId: null, status: 'number_unreachable', delivered: false, deferred: false };
119
121
  const NOT_SENT_EXPIRED = { success: false, messageId: null, status: 'expired', delivered: false, deferred: false };
120
122
 
121
123
  class NexusMessaging {
@@ -397,6 +399,7 @@ class NexusMessaging {
397
399
  // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
398
400
  const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
399
401
  if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
402
+ if (!operatorNow && !messageData.contactCode && await numberUnreachable(messageData.code, { canRetest: Boolean(messageData.contentSid) })) return NOT_SENT_UNREACHABLE;
400
403
  const claim = await acquireSendClaim(messageData);
401
404
  if (!claim.acquired) {
402
405
  return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
@@ -519,6 +522,7 @@ class NexusMessaging {
519
522
 
520
523
  async sendAssistantReply(messageData) {
521
524
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
525
+ if (!messageData.contactCode && await numberUnreachable(messageData.code)) return NOT_SENT_UNREACHABLE;
522
526
  if (messageData.outreachStartedAt) {
523
527
  const patientActivity = await getMessages({
524
528
  numero: messageData.code,
@@ -1,5 +1,6 @@
1
1
  const { logger } = require('../utils/logger');
2
2
 
3
+ const { handleUnreachableNumber } = require('../services/unreachableNumberService');
3
4
  const { handle24HourWindowError } = require('./templateRecoveryHelper');
4
5
  const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
5
6
 
@@ -10,6 +11,7 @@ const CHANNEL_ERROR_STRATEGIES = {
10
11
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
11
12
  63007: CONTENT_RETRY,
12
13
  63021: CONTENT_RETRY,
14
+ 63024: { name: 'unreachable_number', handle: handleUnreachableNumber },
13
15
  63032: BLOCKED_DELIVERY,
14
16
  63049: BLOCKED_DELIVERY
15
17
  };
@@ -16,7 +16,7 @@ const { phoneDigits } = require('./whatsappHelper');
16
16
 
17
17
  const getMessaging = () => require('../core/NexusMessaging');
18
18
 
19
- const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
19
+ const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked', 'number_unreachable']);
20
20
 
21
21
  const FREEFORM_RETRYABLE_CODES = new Set(['63007']);
22
22
  const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
@@ -9,11 +9,14 @@ const { DeliveryAttempt, DELIVERY_ATTEMPT_TERMINAL_STATUSES } = require('../mode
9
9
  const { cleanupRecoveryTemplate } = require('../helpers/templateRecoveryHelper');
10
10
  const { updateDeliveryAttemptByTwilioSid } = require('../helpers/deliveryAttemptHelper');
11
11
  const { handleChannelError } = require('../helpers/channelErrorHelper');
12
+ const { clearNumberUnreachable } = require('../services/unreachableNumberService');
12
13
 
13
14
  const { updateRecordByFilter } = require('../services/airtableService');
14
15
  const { recordUndeliverable } = require('../services/undeliverableService');
15
16
  const { getMessages } = require('../services/messageService');
16
17
 
18
+ const LANDED = new Set(['delivered', 'read']);
19
+
17
20
  async function updateMessageStatus(messageSid, status, errorCode = null, errorMessage = null) {
18
21
  try {
19
22
  const updateData = {
@@ -63,6 +66,9 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
63
66
  if (status === 'failed' || status === 'undelivered') {
64
67
  recordUndeliverable(updated, { status, errorCode });
65
68
  } else {
69
+ if (LANDED.has(status) && !updated.contact_code) {
70
+ clearNumberUnreachable(updated.numero).catch(err => logger.warn('[MessageStatus] Could not clear the unreachable mark', { messageSid, error: err.message }));
71
+ }
66
72
  updateRecordByFilter(
67
73
  Monitoreo_ID,
68
74
  'undelivered_messages',
@@ -19,6 +19,7 @@ const STALE_SENDING_MS = 5 * 60 * 1000;
19
19
 
20
20
  const CANCELLED_SEND_MESSAGES = {
21
21
  patient_deceased: 'The patient is deceased',
22
+ number_unreachable: 'The number is not on WhatsApp',
22
23
  expired: 'Expired before it could be sent',
23
24
  outbound_blocked: 'The outbound allowlist refused the number',
24
25
  contact_capped: 'Contact limit reached'
@@ -232,8 +232,19 @@ const doctorHandoffSchema = new mongoose.Schema({
232
232
  alarmCount: { type: Number, default: null },
233
233
  promptAt: { type: Date, default: null },
234
234
  sentBy: { type: String, required: true },
235
+ manual: { type: Boolean, default: undefined },
236
+ reason: { type: String, default: undefined },
235
237
  }, { timestamps: { createdAt: true, updatedAt: false } });
236
238
 
239
+ const manualHandoffRequestSchema = new mongoose.Schema({
240
+ requestedBy: { type: String, required: true },
241
+ reason: { type: String, required: true },
242
+ requestedAt: { type: Date, required: true },
243
+ claimedAt: { type: Date, default: null },
244
+ failedAt: { type: Date, default: null },
245
+ failure: { type: String, default: null },
246
+ }, { _id: false });
247
+
237
248
  const planItemSchema = new mongoose.Schema({
238
249
  drug: { type: String, required: true },
239
250
  strength: { type: String, default: null },
@@ -394,6 +405,7 @@ const escalationReviewSchema = new mongoose.Schema({
394
405
  digestQueuedAt: { type: Date, default: null },
395
406
  digestClaimedAt: { type: Date, default: null },
396
407
  digestSentAt: { type: Date, default: null },
408
+ manualHandoffRequest: { type: manualHandoffRequestSchema, default: null },
397
409
  quietReminders: { type: [quietReminderSchema], default: [] },
398
410
  monitoringUntil: { type: Date, default: null },
399
411
  watchNotices: { type: [watchNoticeSchema], default: [] },
@@ -455,6 +467,7 @@ escalationReviewSchema.index({ status: 1, closedAt: -1 });
455
467
  escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
456
468
  escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
457
469
  escalationReviewSchema.index({ 'caseFollowUp.nextCheckAt': 1 }, { partialFilterExpression: { 'caseFollowUp.nextCheckAt': { $type: 'date' } } });
470
+ escalationReviewSchema.index({ 'manualHandoffRequest.requestedAt': 1 }, { partialFilterExpression: { 'manualHandoffRequest.requestedAt': { $type: 'date' } } });
458
471
  escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
459
472
 
460
473
  const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
@@ -16,6 +16,9 @@ const threadSchema = new mongoose.Schema({
16
16
  deceasedAt: { type: Date, default: null },
17
17
  programStatusBeforeDeath: { type: String, default: null },
18
18
  hospitalizedAt: { type: Date, default: null },
19
+ whatsappUnreachableAt: { type: Date, default: null },
20
+ whatsappRetryAt: { type: Date, default: null },
21
+ whatsappRetries: { type: Number },
19
22
  doNotAlertThrough: { type: Date, default: null },
20
23
  review: { type: Boolean, default: false },
21
24
  version: { type: Number, default: null },
@@ -139,6 +139,7 @@ const escalationReviewRouteDefinitions = {
139
139
  'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
140
140
  'POST /:id/drafts': 'addEscalationReviewDraftController',
141
141
  'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
142
+ 'POST /:id/manual-handoffs': 'requestManualHandoffController',
142
143
  'POST /:id/plan-instructions': 'previewEscalationReviewPlanController',
143
144
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
144
145
  'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
@@ -326,6 +327,7 @@ const builtInControllers = {
326
327
  confirmEscalationReviewNoteFactsController: escalationReviewController.confirmEscalationReviewNoteFactsController,
327
328
  addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
328
329
  handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
330
+ requestManualHandoffController: escalationReviewController.requestManualHandoffController,
329
331
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
330
332
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
331
333
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
@@ -9,11 +9,12 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
9
9
  const { countMessages, getMessages } = require('./messageService');
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { getThreadInfo } = require('./threadService');
12
- const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
12
+ const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, carriesUpdates, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
14
14
  const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
15
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
16
  const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
17
+ const { isManualHandoffWaiting } = require('./manualHandoffService');
17
18
 
18
19
  const OPERATOR = AUTO_HANDOFF_OPERATOR;
19
20
  const AUDIT_SOURCE = 'escalation_review';
@@ -85,12 +86,13 @@ function outcomeOf(review, clock, now) {
85
86
  const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => timeOf(decision.createdAt)));
86
87
  const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) > decidedAt);
87
88
  const last = handoffs.at(-1);
88
- // After the bot's own handoff, a newer draft goes as an update, unless a person handed it over, the doctor already answered or the phone rang too often.
89
- if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.filter((handoff) => handoff.transport).length > MAX_DOCTOR_UPDATES) return null;
89
+ // After the bot's handoff or a manual one, a newer draft goes as an update, unless a person sent it otherwise, the doctor already answered or the phone rang too often.
90
+ if (handoffs.some((handoff) => !carriesUpdates(handoff)) || handoffs.filter((handoff) => handoff.transport).length > MAX_DOCTOR_UPDATES) return null;
90
91
  const latest = (review.drafts ?? []).at(-1);
91
92
  const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
92
93
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < after || !isDraftCurrent(review, latest)) return null;
93
94
  const update = Boolean(last);
95
+ if (!update && isManualHandoffWaiting(review, now)) return null;
94
96
  if (review.status === 'awaiting_doctor' && !update) return null;
95
97
  const withUpdate = (note) => (update ? noteOf([UPDATE_NOTE, note].filter(Boolean).join(' · ')) : note);
96
98
 
@@ -205,7 +205,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
205
205
  for (const chunk of perCase ? entries.map((entry) => [entry]) : chunksOf(entries)) {
206
206
  const claimed = [];
207
207
  for (const entry of chunk) {
208
- const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
208
+ const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestQueuedAt: entry.review.digestQueuedAt, digestSentAt: null, ...unclaimed };
209
209
  if ((await getEscalationReview().updateOne(filter, { $set: { digestClaimedAt: now } }, BOOKKEEPING)).modifiedCount) claimed.push(entry);
210
210
  }
211
211
  if (!claimed.length) continue;
@@ -78,6 +78,8 @@ const INBOUND_DRAFT_DELAY_MS = 90 * 1000;
78
78
  const DRAFT_OPERATOR = 'bot:escalationDraft';
79
79
  const AUTO_HANDOFF_OPERATOR = 'bot:characterizationOutcome';
80
80
  const MAX_DOCTOR_UPDATES = 3;
81
+ const DOCTOR_PHONE_UNUSABLE = 'doctor_phone_unusable';
82
+ const carriesUpdates = (handoff) => handoff?.sentBy === AUTO_HANDOFF_OPERATOR || handoff?.manual === true;
81
83
  const DIRECT_CHAT_ATTEMPTS = 3;
82
84
  const RECHECK_DELAY_MS = 60 * 1000;
83
85
  const ALERT_RETRY_DELAY_MS = 2 * 60 * 1000;
@@ -116,6 +118,7 @@ const ALERT_OPERATOR = 'bot:escalationAlert';
116
118
  const AIRTABLE_TRANSPORT = 'airtable';
117
119
  const NOT_RECORDED = 'no se registró en Airtable';
118
120
  const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
121
+ const FOLLOWUP_CALL_STATUSES = [...FOLLOWUP_STATUSES, 'approved', 'needs_intervention'];
119
122
  const SAME_URGENCY = 'The review is already at that urgency';
120
123
  const STAT_WATCH = 'A stat case is not watched at home; lower its urgency with a reason first';
121
124
  const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
@@ -466,7 +469,7 @@ async function blockForMissingIdentity({ review, missing, operator }) {
466
469
 
467
470
  async function sendDoctorAlert({ message, approver, operator }) {
468
471
  const doctorCode = whatsAppCodeFromPhone(approver.phone);
469
- if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
472
+ if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record', DOCTOR_PHONE_UNUSABLE);
470
473
  const inWindow = await isWithin24HourWindow(doctorCode);
471
474
  const outgoing = inWindow
472
475
  ? { code: doctorCode, body: message.body, triggeredBy: operator }
@@ -635,7 +638,7 @@ const notAboveCase = (review, alarm, alarmsOf = (of) => of.alarms ?? []) => {
635
638
  return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
636
639
  };
637
640
  const isImprovingUpdate = (alarm, mode) => mode === 'update' && alarm.whatChanged === IMPROVING;
638
- const isQuietImprovement = (review, alarm) => alarm.category !== FEVER_CATEGORY
641
+ const isQuietImprovement = (review, alarm) => alarm.category !== FEVER_CATEGORY && !ALERTED_URGENCIES.includes(alarm.urgencyLevel)
639
642
  && !(review.alarms ?? []).some(isLiveFeverOf(review))
640
643
  && !((review.drafts ?? []).at(-1)?.urgentPresentRedFlags?.length);
641
644
  const decidedEpisodeOf = (review) => {
@@ -988,6 +991,9 @@ async function appendWithDoctor(id, entry) {
988
991
  throw httpError(409, STATUS_CONFLICT);
989
992
  }
990
993
 
994
+ // After the decision the call keeps the status; it flags the case and refreshes the follow-up summary, which is where the team reads it.
995
+ const appendInFollowUp = (id, entry) => updateReview(id, FOLLOWUP_CALL_STATUSES, { $push: { callLogs: entry }, $set: { updatedSinceSeen: true, ...redraftAfterCall() } });
996
+
991
997
  async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
992
998
  const reviewId = reviewIdOf(id);
993
999
  const operator = requiredText(updatedBy, 'updatedBy');
@@ -1058,10 +1064,11 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
1058
1064
  const review = await (outcome === 'contacted'
1059
1065
  ? updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
1060
1066
  : appendKeepingDraft(reviewId, entry))
1061
- .catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)));
1067
+ .catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)))
1068
+ .catch((error) => (error.statusCode === 409 ? appendInFollowUp(reviewId, entry) : Promise.reject(error)));
1062
1069
  await audit(review, operator, requestId, { action: 'call_logged', outcome });
1063
- // Note facts are confirmed only while the case is documented, so none are proposed while it is with the doctor.
1064
- if (outcome !== 'contacted' || review.status === 'awaiting_doctor') return review;
1070
+ // Note facts are confirmed only while the case is documented, so none are proposed once it reached the doctor.
1071
+ if (outcome !== 'contacted' || !DOCUMENTING_STATUSES.includes(review.status)) return review;
1065
1072
  return proposeNoteFacts(review, operator, requestId);
1066
1073
  }
1067
1074
 
@@ -1734,12 +1741,12 @@ async function settleFollowUp(snapshot, { background = true, canClose = true } =
1734
1741
  return review;
1735
1742
  }
1736
1743
 
1737
- // A case the bot handed over by itself is redrafted where it stands, so the doctor can get what the patient said next.
1744
+ // A case the bot or a person's manual handoff passed is redrafted where it stands, so the doctor can get what the patient said next.
1738
1745
  function updatesDoctor(review) {
1739
- if (!escalationAutoHandoffLive() || review.status !== 'awaiting_doctor' || review.doctorHandoffs?.at(-1)?.sentBy !== AUTO_HANDOFF_OPERATOR) return false;
1746
+ if (!escalationAutoHandoffLive() || review.status !== 'awaiting_doctor' || !carriesUpdates(review.doctorHandoffs?.at(-1))) return false;
1740
1747
  const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
1741
1748
  // Only handoffs that reached the doctor's phone count; one recorded silently costs the doctor nothing.
1742
- const botHandoffs = review.doctorHandoffs.filter((handoff) => handoff.sentBy === AUTO_HANDOFF_OPERATOR && handoff.transport && new Date(handoff.createdAt).getTime() > decidedAt);
1749
+ const botHandoffs = review.doctorHandoffs.filter((handoff) => carriesUpdates(handoff) && handoff.transport && new Date(handoff.createdAt).getTime() > decidedAt);
1743
1750
  return botHandoffs.length <= MAX_DOCTOR_UPDATES;
1744
1751
  }
1745
1752
 
@@ -2055,13 +2062,14 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
2055
2062
  return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
2056
2063
  }
2057
2064
  const opener = [reminder, note, timer].filter(Boolean).join(' · ') || null;
2058
- const headline = kind && doctorAlertHeadline({ review, kind, note: opener, level, symptom });
2065
+ const headline = kind && doctorAlertHeadline({ review, kind, note: [note, timer].filter(Boolean).join(' · ') || null, level, symptom });
2059
2066
  const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
2067
+ const summary = kind ? [reminder, templateSummary(review, { level, symptom }), note, timer] : [templateSummary(review, { level, symptom }), opener];
2060
2068
  return {
2061
- body: [headline ? doctorAlertOpener(kind, headline) : opener, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
2069
+ body: [headline ? [reminder, doctorAlertOpener(kind, headline)].filter(Boolean).join('\n') : opener, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
2062
2070
  template: kindSid
2063
- ? { 1: headline, 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
2064
- : { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), opener].filter(Boolean).join(' · ')), 4: link },
2071
+ ? { 1: oneLineOf([reminder, headline].filter(Boolean).join(' · ')), 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
2072
+ : { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf(summary.filter(Boolean).join(' · ')), 4: link },
2065
2073
  ...(kindSid && { contentSid: kindSid }),
2066
2074
  };
2067
2075
  }
@@ -2079,7 +2087,7 @@ async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), opera
2079
2087
  }
2080
2088
 
2081
2089
  // With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
2082
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, change = null, level = null, symptom = null, requestId = null } = {}) {
2090
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, change = null, level = null, symptom = null, manual = false, reason = null, requestId = null } = {}) {
2083
2091
  const reviewId = reviewIdOf(id);
2084
2092
  const operator = requiredText(sentBy, 'sentBy');
2085
2093
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -2108,7 +2116,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
2108
2116
  const armedAt = mode === 'sent_whatsapp' ? patientPromptAt(review) : null;
2109
2117
  const promptAt = armedAt && new Date(armedAt) > new Date() ? new Date(armedAt) : null;
2110
2118
  const timer = promptAt && patientPromptNotice(promptAt, responseDeadlinePolicy().teamHours.timeZone);
2111
- const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, timer });
2119
+ const lead = manual ? `Pasado a mano: ${oneLineOf(reason)}` : null;
2120
+ const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, timer, reminder: lead });
2112
2121
 
2113
2122
  const patientCaseRecordIds = await reviewCaseIds(review);
2114
2123
 
@@ -2127,8 +2136,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
2127
2136
  if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
2128
2137
  const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
2129
2138
  const handoff = {
2130
- $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, ...(sent && promptAt && { promptAt }), sentBy: operator } },
2139
+ $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, ...(sent && promptAt && { promptAt }), sentBy: operator, ...(manual && { manual: true, reason }) } },
2131
2140
  $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
2141
+ ...(manual && { $set: { digestQueuedAt: null, manualHandoffRequest: null } }),
2132
2142
  $unset: { identityBlock: '' },
2133
2143
  };
2134
2144
  // With the case Task live, the case's operations status comes from the Task; the clinical status stays clinical.
@@ -2139,9 +2149,10 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
2139
2149
  throw error;
2140
2150
  }
2141
2151
  await audit(updated, operator, requestId, {
2142
- action: mode === 'copied' ? 'copied_for_doctor' : 'sent_to_doctor',
2152
+ action: (mode === 'copied' && 'copied_for_doctor') || (manual ? 'sent_to_doctor_manually' : 'sent_to_doctor'),
2143
2153
  draftNumber,
2144
2154
  transport: delivery.transport ?? null,
2155
+ ...(manual && { reason }),
2145
2156
  });
2146
2157
  return syncCase(updated, operator, requestId);
2147
2158
  }
@@ -2214,7 +2225,7 @@ async function recordDoctorDecision({
2214
2225
  }
2215
2226
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
2216
2227
  // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
2217
- const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
2228
+ const onUnsentUpdate = carriesUpdates(handoff) && Number(seenDraftNumber) === review.drafts.length
2218
2229
  && review.drafts.at(-1)?.writtenBy === DRAFT_OPERATOR;
2219
2230
  const draftNumber = onUnsentUpdate ? review.drafts.length : handoff?.draftNumber ?? review.drafts.length;
2220
2231
  const draft = review.drafts[draftNumber - 1];
@@ -2790,6 +2801,15 @@ module.exports = {
2790
2801
  BOOKKEEPING,
2791
2802
  notifiedApprover,
2792
2803
  AUTO_HANDOFF_OPERATOR,
2804
+ DOCTOR_PHONE_UNUSABLE,
2805
+ HANDOFF_STATUSES,
2806
+ audit,
2807
+ STATUS_CONFLICT,
2808
+ carriesUpdates,
2809
+ draftTimeOf,
2810
+ arrivedAfter,
2811
+ loadReview,
2812
+ reviewIdOf,
2793
2813
  DOCUMENTING_STATUSES,
2794
2814
  DRAFT_OPERATOR,
2795
2815
  MAX_DOCTOR_UPDATES,
@@ -0,0 +1,264 @@
1
+ const { httpError, requiredText } = require('../utils/httpErrorUtils');
2
+ const { oneLineOf } = require('../utils/coercionUtils');
3
+ const { logger } = require('../utils/logger');
4
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
+ const { getEscalationReview } = require('../models/escalationReviewModel');
6
+ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
7
+ const { escalationManualHandoffLive } = require('../clinical/flags/escalationFlags');
8
+
9
+ const { isDraftCurrent } = require('./gravePendingService');
10
+ const { effectiveUrgencyOf } = require('./reviewDeadlineService');
11
+ const { sendGroupNotice } = require('./teamAlertService');
12
+ const {
13
+ BOOKKEEPING, DOCTOR_PHONE_UNUSABLE, DRAFT_OPERATOR, HANDOFF_STATUSES, STATUS_CONFLICT, audit, arrivedAfter, draftTimeOf, handOffToDoctor, loadReview, reviewIdOf, teamAlertIdentity, updatesDoctor,
14
+ } = require('./escalationReviewService');
15
+
16
+ const OPERATOR = 'bot:manualHandoff';
17
+ const MANUAL_HANDOFF_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor'];
18
+ const MAX_REASON_LENGTH = 100;
19
+ const SUMMARY_WAIT_MS = 10 * 60 * 1000;
20
+ const CLAIM_LEASE_MS = 5 * 60 * 1000;
21
+ const SWEEP_LIMIT = 10;
22
+ const LEVEL_LABELS = { stat: 'STAT', asap: 'ASAP', urgent: 'URGENT', routine: 'RUTINA' };
23
+
24
+ const MANUAL_HANDOFF_OFF = 'manual_handoff_off';
25
+ const REASON_REQUIRED = 'reason_required';
26
+ const ALREADY_WITH_DOCTOR = 'already_with_doctor';
27
+ const HANDOFF_CHANGED = 'handoff_changed';
28
+ const TEAM_DRAFT_STALE = 'team_draft_stale';
29
+ const IDENTITY_MISSING = 'identity_missing';
30
+ const ALREADY_REQUESTED = 'already_requested';
31
+ const FAILURES = {
32
+ no_summary: 'no se pudo generar el resumen',
33
+ identity_missing: 'faltan datos de la paciente (nombre o médico tratante)',
34
+ send_failed: 'no se pudo enviar el mensaje al médico',
35
+ doctor_phone: 'el médico aprobador no tiene un WhatsApp válido',
36
+ handoff_blocked: 'el caso no se pudo pasar (revisa que haya un médico aprobador principal)',
37
+ };
38
+
39
+ const timeOf = (value) => (value ? new Date(value).getTime() : 0);
40
+ const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
41
+
42
+ const decidedAtOf = (review) => Math.max(0, ...(review.decisions ?? []).map((decision) => timeOf(decision.createdAt)));
43
+
44
+ function alreadyWithDoctor(review) {
45
+ if (review.status !== 'awaiting_doctor') return false;
46
+ const last = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) > decidedAtOf(review)).at(-1);
47
+ return Boolean(last?.transport) && last.draftNumber === (review.drafts ?? []).length;
48
+ }
49
+
50
+ function readyDraftOf(review) {
51
+ const latest = (review.drafts ?? []).at(-1);
52
+ if (!latest || !HANDOFF_STATUSES.includes(review.status) || arrivedAfter(review, draftTimeOf(latest))) return null;
53
+ if (latest.writtenBy === DRAFT_OPERATOR && !isDraftCurrent(review, latest)) return null;
54
+ return latest;
55
+ }
56
+
57
+ const pendingOf = (review) => review.manualHandoffRequest ?? null;
58
+
59
+ const isExpired = (request, now) => now.getTime() - timeOf(request.requestedAt) >= SUMMARY_WAIT_MS;
60
+
61
+ const isManualHandoffWaiting = (review, now = new Date()) => {
62
+ const request = pendingOf(review);
63
+ return Boolean(request?.requestedAt) && !request.failedAt && !isExpired(request, now) && escalationManualHandoffLive();
64
+ };
65
+
66
+ const isSettled = (review, request) => Boolean(review.closedAt) || decidedAtOf(review) > timeOf(request.requestedAt)
67
+ || (alreadyWithDoctor(review) && (review.doctorHandoffs ?? []).some((handoff) => handoff.transport && timeOf(handoff.createdAt) > timeOf(request.requestedAt)));
68
+
69
+ // What the panel needs to offer the button; the rules live here so the interface does not repeat them.
70
+ function manualHandoffStateOf(review) {
71
+ const isLive = escalationManualHandoffLive();
72
+ const stored = review ? pendingOf(review) : null;
73
+ const pending = stored && !isSettled(review, stored) ? stored : null;
74
+ const isOpen = Boolean(review) && !review.closedAt && MANUAL_HANDOFF_STATUSES.includes(review.status);
75
+ return {
76
+ live: isLive,
77
+ maxReasonLength: MAX_REASON_LENGTH,
78
+ canHandOff: isLive && isOpen && !alreadyWithDoctor(review) && (!pending || Boolean(pending.failedAt)),
79
+ pending: pending && {
80
+ requestedBy: pending.requestedBy,
81
+ reason: pending.reason,
82
+ requestedAt: pending.requestedAt,
83
+ failedAt: pending.failedAt ?? null,
84
+ failure: pending.failure ? FAILURES[pending.failure] ?? pending.failure : null,
85
+ },
86
+ };
87
+ }
88
+
89
+ const operatorName = (operator) => String(operator).split('@')[0];
90
+
91
+ async function postGroupNotice(review, header, lines) {
92
+ try {
93
+ const { patient, doctor, link } = await teamAlertIdentity(review);
94
+ const lead = effectiveUrgencyOf(review);
95
+ const alarm = (review.alarms ?? []).find((entry) => entry.emergencyRecordId);
96
+ const body = [
97
+ [header, LEVEL_LABELS[lead?.urgency]].filter(Boolean).join(' · '),
98
+ [`${patient} (${doctor})`, oneLineOf(lead?.symptom)].filter(Boolean).join(' · '),
99
+ ...lines,
100
+ link,
101
+ ].filter(Boolean).join('\n');
102
+ const quoted = await readGroupMessageId(alarm?.emergencyRecordId, review.patientCode);
103
+ return await sendGroupNotice(body, quoted, [header, ...lines].filter(Boolean).join('\n'));
104
+ } catch (error) {
105
+ logger.error('[ManualHandoff] The group notice was not sent', { escalationReviewId: String(review._id), error: errorOf(error) });
106
+ return { delivered: false };
107
+ }
108
+ }
109
+
110
+ async function handOver(review, { requestedBy, reason, seenHandoffs, requestId }) {
111
+ const latest = review.drafts.at(-1);
112
+ const lead = effectiveUrgencyOf(review);
113
+ const result = await handOffToDoctor({
114
+ id: String(review._id),
115
+ mode: 'sent_whatsapp',
116
+ sentBy: requestedBy,
117
+ handoffs: seenHandoffs ?? (review.doctorHandoffs ?? []).length,
118
+ kind: latest.urgentPresentRedFlags?.length ? 'act_now' : 'ready',
119
+ level: lead?.urgency ?? null,
120
+ symptom: lead?.symptom ?? null,
121
+ manual: true,
122
+ reason,
123
+ requestId,
124
+ });
125
+ await postGroupNotice(result.review, `📋 Pasó al médico a mano (${operatorName(requestedBy)})`, [`Motivo: ${reason}`]);
126
+ return result;
127
+ }
128
+
129
+ const reasonOf = (value) => {
130
+ const reason = oneLineOf(String(value ?? '')).trim();
131
+ if (!reason) throw httpError(400, 'A reason is required to hand the case to the doctor', REASON_REQUIRED);
132
+ if (reason.length > MAX_REASON_LENGTH) throw httpError(400, `The reason must be at most ${MAX_REASON_LENGTH} characters`, REASON_REQUIRED);
133
+ return reason;
134
+ };
135
+
136
+ async function requestManualHandoff({ id, reason: rawReason, requestedBy, seenHandoffs = null, requestId = null, now = new Date() } = {}) {
137
+ const reviewId = reviewIdOf(id);
138
+ if (!escalationManualHandoffLive()) throw httpError(409, 'Handing a case to the doctor by hand is not enabled', MANUAL_HANDOFF_OFF);
139
+ const operator = requiredText(requestedBy, 'requestedBy');
140
+ const reason = reasonOf(rawReason);
141
+ const review = await loadReview(reviewId);
142
+ if (review.closedAt || !MANUAL_HANDOFF_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
143
+ if (alreadyWithDoctor(review)) throw httpError(409, 'The doctor already has the latest summary of this case', ALREADY_WITH_DOCTOR);
144
+ const handoffs = (review.doctorHandoffs ?? []).length;
145
+ const seen = seenHandoffs == null || seenHandoffs === '' ? null : Number(seenHandoffs);
146
+ if (seen !== null && seen !== handoffs) throw httpError(409, 'The case was handed to the doctor while you were reading it', HANDOFF_CHANGED);
147
+ const waiting = pendingOf(review);
148
+ if (waiting && !waiting.failedAt && !isSettled(review, waiting)) throw httpError(409, 'Someone already asked to hand this case to the doctor', ALREADY_REQUESTED);
149
+
150
+ if (readyDraftOf(review)) {
151
+ const result = await handOver(review, { requestedBy: operator, reason, seenHandoffs: handoffs, requestId });
152
+ return { ...result, handedOff: true };
153
+ }
154
+
155
+ const latest = (review.drafts ?? []).at(-1);
156
+ if (latest && latest.writtenBy !== DRAFT_OPERATOR) {
157
+ throw httpError(409, 'New information arrived after the team summary; update it before handing the case to the doctor', TEAM_DRAFT_STALE);
158
+ }
159
+ if (review.identityBlock) throw httpError(422, 'The patient record lacks the name or treating doctor the doctor needs', IDENTITY_MISSING);
160
+ if (review.status === 'awaiting_doctor' && !updatesDoctor(review)) throw httpError(409, STATUS_CONFLICT);
161
+
162
+ const isRedraftDue = review.draftDueAt && timeOf(review.draftDueAt) > now.getTime();
163
+ const request = { requestedBy: operator, reason, requestedAt: now, claimedAt: null, failedAt: null, failure: null };
164
+ const updated = await getEscalationReview().findOneAndUpdate(
165
+ {
166
+ _id: reviewId, closedAt: null, status: review.status, doctorHandoffs: { $size: handoffs }, drafts: { $size: (review.drafts ?? []).length },
167
+ $or: [{ manualHandoffRequest: null }, { 'manualHandoffRequest.failedAt': { $ne: null } }, { 'manualHandoffRequest.requestedAt': waiting?.requestedAt ?? null }],
168
+ },
169
+ { $set: { manualHandoffRequest: request, ...(!isRedraftDue && { draftDueAt: now, draftAttempts: 0, draftFailedAt: null }) } },
170
+ { new: true },
171
+ ).lean();
172
+ if (!updated) throw httpError(409, STATUS_CONFLICT);
173
+ await audit(updated, operator, requestId, { action: 'manual_handoff_requested', reason });
174
+ return { review: updated, caseMirror: 'skipped', caseMirrors: [], handedOff: false };
175
+ }
176
+
177
+ async function markFailed(review, request, failure, now) {
178
+ const marked = await getEscalationReview().updateOne(
179
+ { _id: review._id, 'manualHandoffRequest.requestedAt': request.requestedAt },
180
+ { $set: { 'manualHandoffRequest.failedAt': now, 'manualHandoffRequest.failure': failure, 'manualHandoffRequest.claimedAt': null } },
181
+ BOOKKEEPING,
182
+ );
183
+ if (!marked.modifiedCount) return;
184
+ await audit(review, OPERATOR, null, { action: 'manual_handoff_failed', failure });
185
+ await postGroupNotice(review, '⚠️ No se pudo pasar al médico a mano', [`Motivo del pase: ${request.reason}`, `Qué pasó: ${FAILURES[failure]}`, 'Qué hacer: revisar el caso y volver a intentarlo']);
186
+ }
187
+
188
+ async function dropRequest(review, request, why) {
189
+ const dropped = await getEscalationReview().updateOne(
190
+ { _id: review._id, 'manualHandoffRequest.requestedAt': request.requestedAt },
191
+ { $set: { manualHandoffRequest: null } },
192
+ BOOKKEEPING,
193
+ );
194
+ if (dropped.modifiedCount) await audit(review, OPERATOR, null, { action: 'manual_handoff_dropped', why });
195
+ }
196
+
197
+ const failureOf = (error) => {
198
+ if (error?.errorCode === DOCTOR_PHONE_UNUSABLE) return 'doctor_phone';
199
+ return error?.statusCode === 422 ? 'identity_missing' : 'send_failed';
200
+ };
201
+
202
+ async function settleRequest(review, now) {
203
+ const request = pendingOf(review);
204
+ const requestedAt = timeOf(request.requestedAt);
205
+ if (review.closedAt || decidedAtOf(review) > requestedAt) return dropRequest(review, request, 'decided_or_closed');
206
+ if ((review.doctorHandoffs ?? []).some((handoff) => handoff.transport && timeOf(handoff.createdAt) > requestedAt) && alreadyWithDoctor(review)) {
207
+ return dropRequest(review, request, 'already_with_doctor');
208
+ }
209
+ if (!MANUAL_HANDOFF_STATUSES.includes(review.status)) {
210
+ if (isExpired(request, now)) await markFailed(review, request, 'handoff_blocked', now);
211
+ return null;
212
+ }
213
+
214
+ if (readyDraftOf(review)) {
215
+ const claim = await getEscalationReview().findOneAndUpdate(
216
+ { _id: review._id, 'manualHandoffRequest.requestedAt': request.requestedAt, 'manualHandoffRequest.failedAt': null, $or: [{ 'manualHandoffRequest.claimedAt': null }, { 'manualHandoffRequest.claimedAt': { $lte: new Date(now.getTime() - CLAIM_LEASE_MS) } }] },
217
+ { $set: { 'manualHandoffRequest.claimedAt': now } },
218
+ { ...BOOKKEEPING, new: true },
219
+ ).lean();
220
+ if (!claim) return null;
221
+ try {
222
+ await handOver(claim, { requestedBy: request.requestedBy, reason: request.reason, requestId: null });
223
+ return true;
224
+ } catch (error) {
225
+ logger.error('[ManualHandoff] The requested handoff did not reach the doctor', { escalationReviewId: String(review._id), statusCode: error?.statusCode ?? null, error: errorOf(error) });
226
+ if (error?.statusCode === 409 && !isExpired(request, now)) {
227
+ await getEscalationReview().updateOne({ _id: review._id, 'manualHandoffRequest.claimedAt': now }, { $set: { 'manualHandoffRequest.claimedAt': null } }, BOOKKEEPING);
228
+ return null;
229
+ }
230
+ await markFailed(review, request, error?.statusCode === 409 ? 'handoff_blocked' : failureOf(error), now);
231
+ return false;
232
+ }
233
+ }
234
+
235
+ const hasDraftFailed = timeOf(review.draftFailedAt) >= requestedAt;
236
+ if (review.identityBlock) await markFailed(review, request, 'identity_missing', now);
237
+ else if (hasDraftFailed || isExpired(request, now)) await markFailed(review, request, 'no_summary', now);
238
+ return null;
239
+ }
240
+
241
+ async function sweepManualHandoffs({ now = new Date() } = {}) {
242
+ if (!escalationManualHandoffLive()) return 0;
243
+ const due = await getEscalationReview()
244
+ .find({ 'manualHandoffRequest.requestedAt': { $type: 'date' }, 'manualHandoffRequest.failedAt': null })
245
+ .sort({ 'manualHandoffRequest.requestedAt': 1 })
246
+ .limit(SWEEP_LIMIT)
247
+ .lean();
248
+ let handed = 0;
249
+ for (const review of due) {
250
+ try {
251
+ if (await settleRequest(review, now) === true) handed += 1;
252
+ } catch (error) {
253
+ logger.error('[ManualHandoff] Could not settle a requested handoff', { escalationReviewId: String(review._id), error: errorOf(error) });
254
+ }
255
+ }
256
+ return handed;
257
+ }
258
+
259
+ module.exports = {
260
+ isManualHandoffWaiting,
261
+ manualHandoffStateOf,
262
+ requestManualHandoff,
263
+ sweepManualHandoffs,
264
+ };
@@ -59,7 +59,7 @@ async function insertMessage(values) {
59
59
  Thread.findOneAndUpdate(
60
60
  { code: values.numero },
61
61
  {
62
- $set: threadPreview(values, new Date()),
62
+ $set: { ...threadPreview(values, new Date()), ...(!values.from_me && !values.contact_code ? { whatsappUnreachableAt: null } : {}) },
63
63
  $inc: {
64
64
  messageCount: 1,
65
65
  ...(!values.from_me ? { unreadCount: 1 } : {})
@@ -174,7 +174,7 @@ const rewriteOps = (docs, setFor) => docs.map((doc) => ({
174
174
  }));
175
175
 
176
176
  // The new number may write mid-migration and get its own thread; the source thread is then archived like a merge.
177
- const renameThread = (thread, target) => Thread.updateOne({ _id: thread._id }, { $set: { code: target } }).then(() => true, (error) => {
177
+ const renameThread = (thread, target) => Thread.updateOne({ _id: thread._id }, { $set: { code: target, whatsappUnreachableAt: null } }).then(() => true, (error) => {
178
178
  if (error.code !== 11000) throw error;
179
179
  return false;
180
180
  });
@@ -9,9 +9,11 @@ const { sweepUnopenedCases } = require('./unopenedCaseService');
9
9
  const { sweepExpiredWatches } = require('./watchExpiryService');
10
10
  const { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues } = require('./caseFollowUpSweepService');
11
11
  const { sweepUnreviewedCases } = require('./unreviewedCaseService');
12
+ const { sweepManualHandoffs } = require('./manualHandoffService');
12
13
 
13
14
  const SWEEP_LIMIT = 10;
14
15
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
16
+ const MANUAL_HANDOFF_INTERVAL_MS = 15 * 1000;
15
17
  const WATCH_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
16
18
  const LEASE_MS = 5 * 60 * 1000;
17
19
  const SEND_TIMEOUT_MS = 2 * 60 * 1000;
@@ -113,6 +115,13 @@ const unreviewedSweeper = createIntervalSweeper({
113
115
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
114
116
  });
115
117
 
118
+ // A person waits on the panel for this one, so it runs more often than the alerts.
119
+ const manualHandoffSweeper = createIntervalSweeper({
120
+ label: '[ManualHandoffSweep]',
121
+ sweep: () => sweepManualHandoffs(),
122
+ defaultIntervalMs: () => MANUAL_HANDOFF_INTERVAL_MS,
123
+ });
124
+
116
125
  const caseFollowUpSweeper = createIntervalSweeper({
117
126
  label: '[CaseFollowUpSweep]',
118
127
  sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()) + (await sweepCaseStatuses()),
@@ -126,8 +135,9 @@ const startReviewAlertSweep = (options) => {
126
135
  watchSweeper.start();
127
136
  caseFollowUpSweeper.start();
128
137
  unreviewedSweeper.start();
138
+ manualHandoffSweeper.start();
129
139
  return sweeper.start(options);
130
140
  };
131
- const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), unopenedSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
141
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), unopenedSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop(), manualHandoffSweeper.stop()]);
132
142
 
133
143
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -0,0 +1,69 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { Thread } = require('../models/threadModel');
3
+ const { phoneDigits } = require('../helpers/whatsappHelper');
4
+ const { formatOpsAlert, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
5
+
6
+ const RETRY_DAYS = [1, 3, 7, 14, 30];
7
+ const DAY_MS = 24 * 60 * 60 * 1000;
8
+ const retryAfter = (retries) => new Date(Date.now() + RETRY_DAYS[Math.min(retries, RETRY_DAYS.length - 1)] * DAY_MS);
9
+
10
+ // The conditional update lets only one of several concurrent sends through.
11
+ async function claimRetest(thread) {
12
+ const retries = thread.whatsappRetries + 1;
13
+ const { modifiedCount } = await Thread.updateOne(
14
+ { _id: thread._id, whatsappRetryAt: thread.whatsappRetryAt },
15
+ { $set: { whatsappRetryAt: retryAfter(retries), whatsappRetries: retries } }
16
+ );
17
+ if (modifiedCount > 0) logger.info('[UnreachableNumber] Retesting a number without WhatsApp', { threadId: String(thread._id), retries });
18
+ return modifiedCount > 0;
19
+ }
20
+
21
+ // Only a template can retest: free text never reaches a number that has not written in the last 24h.
22
+ async function numberUnreachable(code, { canRetest = false } = {}) {
23
+ // Without a database connection the mark cannot be read; the query would only wait for one.
24
+ if (Thread.db?.readyState !== 1) return false;
25
+ try {
26
+ const thread = await Thread.findOne({ code, whatsappUnreachableAt: { $ne: null } }, { whatsappRetryAt: 1, whatsappRetries: 1 }).lean();
27
+ if (!thread) return false;
28
+ if (!canRetest || thread.whatsappRetryAt > new Date()) return true;
29
+ return !(await claimRetest(thread));
30
+ } catch (error) {
31
+ logger.warn('[UnreachableNumber] Thread state unreadable; sending anyway', { code, error: error.message });
32
+ return false;
33
+ }
34
+ }
35
+
36
+ async function clearNumberUnreachable(code) {
37
+ await Thread.updateOne({ code, whatsappUnreachableAt: { $ne: null } }, { $set: { whatsappUnreachableAt: null } });
38
+ }
39
+
40
+ async function markNumberUnreachable(code) {
41
+ const { modifiedCount } = await Thread.updateOne({ code, whatsappUnreachableAt: null }, { $set: { whatsappUnreachableAt: new Date(), whatsappRetryAt: retryAfter(0), whatsappRetries: 0 } });
42
+ return modifiedCount > 0;
43
+ }
44
+
45
+ const alertOps = (messageDoc, label, summary) => writeUnresolvedRequest({
46
+ code: messageDoc.numero,
47
+ trace: null,
48
+ category: 'contact_team_member',
49
+ question: label,
50
+ details: formatOpsAlert(messageDoc.numero, { label, summary })
51
+ });
52
+
53
+ // Twilio 63024: the recipient is not a WhatsApp user.
54
+ async function handleUnreachableNumber(messageDoc, twilioSid, errorCode) {
55
+ const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
56
+ if (messageDoc.contact_code) {
57
+ logger.warn('[UnreachableNumber] Caregiver number is not on WhatsApp', logCtx);
58
+ await alertOps(messageDoc, 'Cuidador sin WhatsApp', `WhatsApp no reconoce el número del cuidador (+${phoneDigits(messageDoc.contact_code)}); hay que conseguir otro contacto`);
59
+ return { marked: false, reason: 'caregiver_recipient' };
60
+ }
61
+ if (!(await markNumberUnreachable(messageDoc.numero))) return { marked: false, reason: 'already_marked' };
62
+ const { written, duplicate } = await alertOps(messageDoc, 'Número sin WhatsApp', 'WhatsApp no reconoce este número. Pausamos los mensajes automáticos y lo volvemos a probar solos a 1, 3, 7 y 14 días, y luego cada 30; se reanudan en cuanto un mensaje le llegue o el paciente escriba');
63
+ if (written || duplicate) return { marked: true, reason: 'not_on_whatsapp' };
64
+ logger.error('[UnreachableNumber] Ops alert not written; leaving the number unmarked', logCtx);
65
+ await clearNumberUnreachable(messageDoc.numero);
66
+ return { marked: false, reason: 'alert_not_written' };
67
+ }
68
+
69
+ module.exports = { clearNumberUnreachable, handleUnreachableNumber, numberUnreachable };
@@ -37,7 +37,7 @@ const REMINDER_RETRY_MS = 3 * 60 * 1000;
37
37
  const REMINDER_SEND_TIMEOUT_MS = 60 * 1000;
38
38
  const MAX_REMINDER_ATTEMPTS = 3;
39
39
  // Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
40
- const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, 'doctorHandoffs.promptAt': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
40
+ const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, 'doctorHandoffs.promptAt': 1, 'doctorHandoffs.manual': 1, 'manualHandoffRequest.requestedAt': 1, 'manualHandoffRequest.failedAt': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
41
41
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
42
42
  'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
43
43
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.9.0-dev.21862",
3
+ "version": "6.9.0-dev.22012",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",