@peopl-health/nexus 6.4.0-dev.18956 → 6.4.0-dev.18959
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.
- package/lib/adapters/TwilioProvider.js +2 -31
- package/lib/clinical/services/treatmentProposalService.js +4 -26
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/controllers/escalationReviewController.js +3 -20
- package/lib/controllers/prescriptionController.js +28 -4
- package/lib/helpers/channelRetryHelper.js +6 -1
- package/lib/helpers/messageStatusHelper.js +7 -1
- package/lib/helpers/recoveryFallbackHelper.js +146 -0
- package/lib/helpers/templateRecoveryHelper.js +33 -7
- package/lib/index.d.ts +1 -1
- package/lib/jobs/TemplateApprovalJob.js +36 -2
- package/lib/models/escalationReviewModel.js +2 -38
- package/lib/models/messageModel.js +3 -1
- package/lib/routes/index.js +0 -2
- package/lib/services/assistantMessageService.js +6 -12
- package/lib/services/contactGateService.js +2 -2
- package/lib/services/escalationReviewService.js +12 -191
- package/lib/utils/httpErrorUtils.js +1 -1
- package/lib/utils/templateTextUtils.js +64 -0
- package/package.json +1 -1
- package/lib/clinical/helpers/doctorPlanHelper.js +0 -107
- package/lib/clinical/helpers/planTextHelper.js +0 -131
- package/lib/clinical/services/doctorPlanService.js +0 -120
- package/lib/services/prescriptionService.js +0 -30
|
@@ -11,6 +11,7 @@ const { alertUndeliverable } = require('../helpers/channelRetryHelper');
|
|
|
11
11
|
|
|
12
12
|
const { contactOf } = require('../helpers/caregiverHelper');
|
|
13
13
|
const { acceptedFixedSid, claimRecoverySend, closeExpiredRecovery, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure } = require('../helpers/templateRecoveryHelper');
|
|
14
|
+
const { isFallbackEnabled, hasFallbackPlan, sendRecoveryFallback } = require('../helpers/recoveryFallbackHelper');
|
|
14
15
|
const { getMessages } = require('../services/messageService');
|
|
15
16
|
const { recordUndeliverable } = require('../services/undeliverableService');
|
|
16
17
|
|
|
@@ -25,6 +26,7 @@ const APPROVAL_CHECK_TIMEOUT_MS = 30 * 1000;
|
|
|
25
26
|
|
|
26
27
|
const WINDOW_REOPEN_SID_KEY = 'WINDOW_REOPEN_TEMPLATE_SID';
|
|
27
28
|
const WARN_AFTER_MS = 60 * 60 * 1000;
|
|
29
|
+
const FALLBACK_AFTER_MS = 20 * 60 * 1000;
|
|
28
30
|
|
|
29
31
|
const APPROVAL_POLL_DELAYS_MS = [30 * 1000, 60 * 1000, 2 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000];
|
|
30
32
|
|
|
@@ -123,6 +125,13 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
123
125
|
await closeExpiredRecovery(message);
|
|
124
126
|
return { success: false, reason: 'expired' };
|
|
125
127
|
}
|
|
128
|
+
|
|
129
|
+
const trigger = await this._fallbackTrigger(message, approvalStatus);
|
|
130
|
+
if (trigger) {
|
|
131
|
+
const fallback = await this._sendFallback(message, trigger);
|
|
132
|
+
if (fallback) return fallback;
|
|
133
|
+
}
|
|
134
|
+
|
|
126
135
|
if (checkError) {
|
|
127
136
|
logger.error('[TemplateApprovalJob] Provider error during approval check, treating as transient', {
|
|
128
137
|
templateSid, messageId, attempt, error: checkError.message
|
|
@@ -162,10 +171,35 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
162
171
|
return { success: false, reason: 'max_attempts', priorReason: reason };
|
|
163
172
|
}
|
|
164
173
|
await this._warnIfSlow(message, templateSid);
|
|
165
|
-
await this.schedule({ templateSid, messageId, originalMessageSid, attempt: nextAttempt });
|
|
174
|
+
await this.schedule({ templateSid, messageId, originalMessageSid, attempt: nextAttempt, delayMs: await this._delayBeforeFallback(message, nextAttempt) });
|
|
166
175
|
return { success: false, reason, nextAttempt };
|
|
167
176
|
}
|
|
168
177
|
|
|
178
|
+
_waitingMs(message) {
|
|
179
|
+
const startedAt = message.statusInfo?.recoveryStartedAt;
|
|
180
|
+
return startedAt ? Date.now() - new Date(startedAt).getTime() : null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async _fallbackTrigger(message, approvalStatus) {
|
|
184
|
+
if (approvalStatus === 'APPROVED' || !await isFallbackEnabled()) return null;
|
|
185
|
+
if (approvalStatus === 'REJECTED') return 'rejected';
|
|
186
|
+
const waitingMs = this._waitingMs(message);
|
|
187
|
+
return waitingMs !== null && waitingMs >= FALLBACK_AFTER_MS ? 'pending' : null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async _delayBeforeFallback(message, attempt) {
|
|
191
|
+
const waitingMs = this._waitingMs(message);
|
|
192
|
+
if (waitingMs === null || waitingMs >= FALLBACK_AFTER_MS || !await isFallbackEnabled()) return undefined;
|
|
193
|
+
return Math.min(delayForAttempt(attempt), FALLBACK_AFTER_MS - waitingMs);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async _sendFallback(message, trigger) {
|
|
197
|
+
const result = await sendRecoveryFallback(message, { trigger, send: (data) => this.sendMessage(data) });
|
|
198
|
+
if (result.sent) return { success: true, reason: 'fallback', trigger, sentParts: result.sentParts };
|
|
199
|
+
if (['already_claimed', 'outbound_blocked', 'state_unknown'].includes(result.reason)) return { success: false, reason: result.reason };
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
|
|
169
203
|
async _warnIfSlow(message, templateSid) {
|
|
170
204
|
const startedAt = message.statusInfo?.recoveryStartedAt;
|
|
171
205
|
if (!startedAt) return { warned: false, reason: 'no_start' };
|
|
@@ -249,7 +283,7 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
249
283
|
messageId: String(message._id), error: err.message
|
|
250
284
|
}));
|
|
251
285
|
|
|
252
|
-
await this._sendWindowReopenNudge(message);
|
|
286
|
+
if (!await isFallbackEnabled() || !await hasFallbackPlan(message)) await this._sendWindowReopenNudge(message);
|
|
253
287
|
}
|
|
254
288
|
|
|
255
289
|
async _sendWindowReopenNudge(message) {
|
|
@@ -12,8 +12,7 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
|
12
12
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
13
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
14
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
15
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', '
|
|
16
|
-
const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
|
|
15
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
17
16
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
18
17
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
19
18
|
|
|
@@ -194,43 +193,11 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
194
193
|
sentBy: { type: String, required: true },
|
|
195
194
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
196
195
|
|
|
197
|
-
const planItemSchema = new mongoose.Schema({
|
|
198
|
-
drug: { type: String, required: true },
|
|
199
|
-
strength: { type: String, default: null },
|
|
200
|
-
dose: { type: String, required: true },
|
|
201
|
-
frequency: { type: String, required: true },
|
|
202
|
-
days: { type: Number, required: true },
|
|
203
|
-
position: { type: String, default: null },
|
|
204
|
-
reason: { type: String, default: null },
|
|
205
|
-
formularyKey: { type: String, default: null },
|
|
206
|
-
}, { _id: false });
|
|
207
|
-
|
|
208
|
-
const planSchema = new mongoose.Schema({
|
|
209
|
-
items: { type: [planItemSchema], default: [] },
|
|
210
|
-
studies: {
|
|
211
|
-
type: [new mongoose.Schema({ name: { type: String, required: true }, instructions: { type: String, default: null } }, { _id: false })],
|
|
212
|
-
default: [],
|
|
213
|
-
},
|
|
214
|
-
homeCare: { type: [String], default: [] },
|
|
215
|
-
note: { type: String, default: null },
|
|
216
|
-
followUp: {
|
|
217
|
-
type: new mongoose.Schema({ kind: { type: String, enum: PLAN_FOLLOW_UPS, required: true }, hours: { type: Number, default: null } }, { _id: false }),
|
|
218
|
-
required: true,
|
|
219
|
-
},
|
|
220
|
-
instructions: { type: String, required: true },
|
|
221
|
-
instructionsEdited: { type: Boolean, default: false },
|
|
222
|
-
prescriber: {
|
|
223
|
-
type: new mongoose.Schema({ name: { type: String, default: null }, email: { type: String, required: true } }, { _id: false }),
|
|
224
|
-
default: null,
|
|
225
|
-
},
|
|
226
|
-
}, { _id: false });
|
|
227
|
-
|
|
228
196
|
const decisionSchema = new mongoose.Schema({
|
|
229
197
|
decision: { type: String, enum: DOCTOR_DECISIONS, required: true },
|
|
230
198
|
source: { type: String, enum: DECISION_SOURCES, required: true },
|
|
231
199
|
draftNumber: { type: Number, required: true },
|
|
232
200
|
finalText: { type: String, default: null },
|
|
233
|
-
plan: { type: planSchema, default: undefined },
|
|
234
201
|
comment: { type: String, default: null },
|
|
235
202
|
doctorReply: { type: String, default: null },
|
|
236
203
|
returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
|
|
@@ -243,9 +210,7 @@ const patientDeliverySchema = new mongoose.Schema({
|
|
|
243
210
|
decisionNumber: { type: Number, required: true },
|
|
244
211
|
messageId: { type: String, default: null },
|
|
245
212
|
status: { type: String, default: null },
|
|
246
|
-
transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'
|
|
247
|
-
prescriptionRecordId: { type: String, default: null },
|
|
248
|
-
checks: { type: [String], default: undefined },
|
|
213
|
+
transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'], required: true },
|
|
249
214
|
deferred: { type: Boolean, default: false },
|
|
250
215
|
confirmedBy: { type: String, default: null },
|
|
251
216
|
confirmedAt: { type: Date, default: null },
|
|
@@ -416,7 +381,6 @@ module.exports = {
|
|
|
416
381
|
DOCTOR_DECISIONS,
|
|
417
382
|
HANDOFF_MODES,
|
|
418
383
|
INTERRUPTED_STATUSES,
|
|
419
|
-
PLAN_FOLLOW_UPS,
|
|
420
384
|
FOLLOWUP_STATUSES,
|
|
421
385
|
RETURN_REASONS,
|
|
422
386
|
URGENCY_LEVELS,
|
|
@@ -82,7 +82,9 @@ const messageSchema = new mongoose.Schema({
|
|
|
82
82
|
recoveryCheckedAt: { type: Date, default: null },
|
|
83
83
|
recoveryAttempt: { type: Number, default: null },
|
|
84
84
|
recoveryWarnedAt: { type: Date, default: null },
|
|
85
|
-
recoveryReleasedAt: { type: Date, default: null }
|
|
85
|
+
recoveryReleasedAt: { type: Date, default: null },
|
|
86
|
+
recoveryFallbackAt: { type: Date, default: null },
|
|
87
|
+
recoveryFallbackReason: { type: String, default: null }
|
|
86
88
|
},
|
|
87
89
|
prompt: { type: Object, default: null },
|
|
88
90
|
preset: { type: Object, default: null },
|
package/lib/routes/index.js
CHANGED
|
@@ -138,7 +138,6 @@ const escalationReviewRouteDefinitions = {
|
|
|
138
138
|
'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
|
|
139
139
|
'POST /:id/drafts': 'addEscalationReviewDraftController',
|
|
140
140
|
'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
|
|
141
|
-
'POST /:id/plan-instructions': 'previewEscalationReviewPlanController',
|
|
142
141
|
'POST /:id/decisions': 'recordEscalationReviewDecisionController',
|
|
143
142
|
'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
|
|
144
143
|
'POST /:id/close': 'closeEscalationReviewController',
|
|
@@ -315,7 +314,6 @@ const builtInControllers = {
|
|
|
315
314
|
listReviewBoardController: escalationReviewController.listReviewBoardController,
|
|
316
315
|
getEscalationReviewController: escalationReviewController.getEscalationReviewController,
|
|
317
316
|
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
318
|
-
previewEscalationReviewPlanController: escalationReviewController.previewEscalationReviewPlanController,
|
|
319
317
|
requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
|
|
320
318
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
321
319
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
@@ -26,9 +26,9 @@ const ASSISTANT_MESSAGE_FAILURES = {
|
|
|
26
26
|
};
|
|
27
27
|
|
|
28
28
|
class AssistantMessageError extends Error {
|
|
29
|
-
constructor(reasonCode, acceptedCount = 0
|
|
29
|
+
constructor(reasonCode, acceptedCount = 0) {
|
|
30
30
|
const [statusCode, message] = ASSISTANT_MESSAGE_FAILURES[reasonCode];
|
|
31
|
-
super(message
|
|
31
|
+
super(message);
|
|
32
32
|
this.reasonCode = reasonCode;
|
|
33
33
|
this.statusCode = statusCode;
|
|
34
34
|
this.acceptedCount = acceptedCount;
|
|
@@ -117,10 +117,8 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
117
117
|
if (!reply) return;
|
|
118
118
|
recordPatientSend?.({ code, channel: 'assistant_instruction', sentBy: triggeredBy, text: input.messages.join('\n') });
|
|
119
119
|
|
|
120
|
-
let turn;
|
|
121
|
-
let settled = null;
|
|
122
120
|
try {
|
|
123
|
-
|
|
121
|
+
await executeWithPipeline(code, 'system', 'queue',
|
|
124
122
|
async (preProcessResult, shouldContinue, runId) => {
|
|
125
123
|
return await assistantProcessor.process({
|
|
126
124
|
code,
|
|
@@ -133,15 +131,11 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
133
131
|
signal: getAbortSignal(runId),
|
|
134
132
|
}
|
|
135
133
|
});
|
|
136
|
-
}
|
|
137
|
-
{ onSendSettled: async (outcome) => { settled = outcome; } },
|
|
134
|
+
}
|
|
138
135
|
);
|
|
139
|
-
} catch
|
|
140
|
-
|
|
141
|
-
throw new AssistantMessageError('MESSAGE_REPLY_FAILED', acceptedCount, error);
|
|
136
|
+
} catch {
|
|
137
|
+
throw new AssistantMessageError('MESSAGE_REPLY_FAILED', acceptedCount);
|
|
142
138
|
}
|
|
143
|
-
// A send that threw may still have reached the patient.
|
|
144
|
-
return { delivery: turn?.delivery ?? null, sendThrew: settled === 'threw', reply: turn?.output ?? null };
|
|
145
139
|
}
|
|
146
140
|
|
|
147
141
|
module.exports = { AssistantMessageError, injectAssistantMessages, processAssistantSystemMessage };
|
|
@@ -157,11 +157,11 @@ async function releaseSend(decisionId) {
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
// Records every send that left; a send the gate reserved only confirms its row.
|
|
160
|
+
// Records every send that left, except a later part of one message; a send the gate reserved only confirms its row.
|
|
161
161
|
async function observeSend(messageData, now = new Date()) {
|
|
162
162
|
const code = messageData?.code;
|
|
163
163
|
try {
|
|
164
|
-
if (contactGateMode() === 'off' || !code) return null;
|
|
164
|
+
if (contactGateMode() === 'off' || !code || messageData.continuesSend) return null;
|
|
165
165
|
if (messageData.contactGateDecisionId) {
|
|
166
166
|
return await ContactGateDecision.findOneAndUpdate({ _id: messageData.contactGateDecisionId }, { $set: { status: 'sent' } }, { new: true });
|
|
167
167
|
}
|
|
@@ -29,13 +29,11 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
|
29
29
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
30
30
|
const { DrainingError } = require('../core/BatchingManager');
|
|
31
31
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
32
|
-
const { conversationLink,
|
|
32
|
+
const { conversationLink, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
33
33
|
const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
34
34
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
35
35
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
36
36
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
37
|
-
const { assistantInstructionsOf, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
|
|
38
|
-
const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
|
|
39
37
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
40
38
|
const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
|
|
41
39
|
const {
|
|
@@ -55,11 +53,10 @@ const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
|
55
53
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
56
54
|
const { countMessages } = require('./messageService');
|
|
57
55
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
58
|
-
const { createPrescription } = require('./prescriptionService');
|
|
59
56
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
60
57
|
const { effectiveUrgencyOf, levelsOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
61
58
|
const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
|
|
62
|
-
const { groupConfigured,
|
|
59
|
+
const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
|
|
63
60
|
|
|
64
61
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
65
62
|
|
|
@@ -108,11 +105,7 @@ const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
|
|
|
108
105
|
const SAME_URGENCY = 'The review is already at that urgency';
|
|
109
106
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
110
107
|
const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
|
|
111
|
-
const APPROVALS = ['approved', 'edited_approved'
|
|
112
|
-
// The interface offers a resend only for SEND_NOT_SENT; SEND_UNCONFIRMED may have reached the patient.
|
|
113
|
-
const SEND_NOT_SENT = 'send_not_sent';
|
|
114
|
-
const SEND_UNCONFIRMED = 'send_unconfirmed';
|
|
115
|
-
const withSendCode = (error, errorCode) => (error instanceof Error && !Object.isFrozen(error) && !error.errorCode ? Object.assign(error, { errorCode }) : error);
|
|
108
|
+
const APPROVALS = ['approved', 'edited_approved'];
|
|
116
109
|
const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
|
|
117
110
|
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
118
111
|
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
@@ -152,7 +145,7 @@ const configured = (key) => {
|
|
|
152
145
|
return value;
|
|
153
146
|
};
|
|
154
147
|
|
|
155
|
-
const STATUS_AFTER = { edited_approved: 'approved',
|
|
148
|
+
const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
|
|
156
149
|
const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
|
|
157
150
|
|
|
158
151
|
const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
|
|
@@ -735,33 +728,6 @@ async function isEscalationApprover(operator) {
|
|
|
735
728
|
}
|
|
736
729
|
}
|
|
737
730
|
|
|
738
|
-
// Unpicked, the doctor is the one recording if they approve, or the only approver there is.
|
|
739
|
-
async function prescriberOf(email, operator) {
|
|
740
|
-
if (email != null && typeof email !== 'string') throw httpError(400, 'prescriberEmail must be text');
|
|
741
|
-
let approvers;
|
|
742
|
-
try {
|
|
743
|
-
approvers = await listEscalationApprovers();
|
|
744
|
-
} catch (error) {
|
|
745
|
-
logger.error('[EscalationReview] The approving doctors could not be listed; the plan was not recorded', { error: redactedError(error) });
|
|
746
|
-
throw httpError(503, 'The approving doctors could not be read; try again');
|
|
747
|
-
}
|
|
748
|
-
if (!approvers.length) throw httpError(409, 'No physician signs recetas: tick aprueba_vaiven on a physician');
|
|
749
|
-
const wanted = (email?.trim() || operator).trim().toLowerCase();
|
|
750
|
-
const chosen = approvers.find((approver) => approver.email === wanted) ?? (!email?.trim() && approvers.length === 1 ? approvers[0] : null);
|
|
751
|
-
if (!chosen) throw httpError(400, `prescriberEmail must be one of: ${approvers.map((approver) => approver.email).join(', ')}`);
|
|
752
|
-
return { name: chosen.name, email: chosen.email };
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
// Null when the list could not be read; the review is still returned.
|
|
756
|
-
async function prescribersForRead() {
|
|
757
|
-
try {
|
|
758
|
-
return (await listEscalationApprovers()).map(({ name, email }) => ({ name, email }));
|
|
759
|
-
} catch (error) {
|
|
760
|
-
logger.warn('[EscalationReview] The approving doctors could not be listed for the review', { error: redactedError(error) });
|
|
761
|
-
return null;
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
|
|
765
731
|
async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
766
732
|
const reviewId = reviewIdOf(id);
|
|
767
733
|
const operator = requiredText(requestedBy, 'requestedBy');
|
|
@@ -782,19 +748,7 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
|
782
748
|
.updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
|
|
783
749
|
.catch(warnUnmarked);
|
|
784
750
|
}
|
|
785
|
-
|
|
786
|
-
return {
|
|
787
|
-
review,
|
|
788
|
-
isApprover,
|
|
789
|
-
responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()),
|
|
790
|
-
proposedPlan: draft ? { draftNumber: review.drafts.length, ...proposedPlanOf(draft) } : null,
|
|
791
|
-
prescribers: draft ? await prescribersForRead() : [],
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
function previewPlanInstructions({ id, plan } = {}) {
|
|
796
|
-
reviewIdOf(id);
|
|
797
|
-
return planInstructions(planOf(plan));
|
|
751
|
+
return { review, isApprover, responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()) };
|
|
798
752
|
}
|
|
799
753
|
|
|
800
754
|
async function getReviewTimeline({ id } = {}) {
|
|
@@ -1833,9 +1787,6 @@ async function recordDoctorDecision({
|
|
|
1833
1787
|
source,
|
|
1834
1788
|
decision,
|
|
1835
1789
|
finalText = null,
|
|
1836
|
-
plan: requestedPlan = null,
|
|
1837
|
-
instructions = null,
|
|
1838
|
-
prescriberEmail = null,
|
|
1839
1790
|
comment = null,
|
|
1840
1791
|
doctorName = null,
|
|
1841
1792
|
doctorReply = null,
|
|
@@ -1864,20 +1815,6 @@ async function recordDoctorDecision({
|
|
|
1864
1815
|
if (!RETURN_REASONS.includes(reason)) throw httpError(400, `reason must be one of: ${RETURN_REASONS.join(', ')}`);
|
|
1865
1816
|
returnReason = reason;
|
|
1866
1817
|
}
|
|
1867
|
-
let plan = null;
|
|
1868
|
-
if (decision === 'plan_approved') {
|
|
1869
|
-
if (source !== 'platform') throw httpError(400, 'A plan is approved by the doctor on the platform');
|
|
1870
|
-
// The plan names the draft it started from, so a newer draft is refused instead of decided unseen.
|
|
1871
|
-
if (seenDraftNumber === null) throw httpError(400, 'draftNumber is required for a plan');
|
|
1872
|
-
plan = planOf(requestedPlan);
|
|
1873
|
-
plan = { ...plan, ...approvedInstructions(plan, instructions) };
|
|
1874
|
-
// Anyone may record a plan, often beside the doctor; one with a drug, study, note or edit names the doctor who gave it.
|
|
1875
|
-
const namesDrug = drugsNamedIn(plan.homeCare.join(' ')).length > 0;
|
|
1876
|
-
if (needsPrescriber(plan) || plan.note || plan.instructionsEdited || namesDrug) {
|
|
1877
|
-
plan = { ...plan, prescriber: await prescriberOf(prescriberEmail, operator) };
|
|
1878
|
-
decidedBy = plan.prescriber.email;
|
|
1879
|
-
}
|
|
1880
|
-
}
|
|
1881
1818
|
|
|
1882
1819
|
const review = await loadReview(reviewId);
|
|
1883
1820
|
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
@@ -1921,7 +1858,6 @@ async function recordDoctorDecision({
|
|
|
1921
1858
|
source,
|
|
1922
1859
|
draftNumber,
|
|
1923
1860
|
finalText: approvedText,
|
|
1924
|
-
...(plan && { plan }),
|
|
1925
1861
|
comment: optionalText(comment),
|
|
1926
1862
|
doctorReply: reply,
|
|
1927
1863
|
...(returnReason && { returnReason }),
|
|
@@ -2057,10 +1993,10 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2057
1993
|
const claim = newOperationClaim();
|
|
2058
1994
|
const claimed = await updateReview(reviewId, SENDABLE_STATUSES, { $set: { status: 'sending', operationClaim: claim } });
|
|
2059
1995
|
const decisionNumber = claimed.decisions.length;
|
|
2060
|
-
const { finalText, decision
|
|
1996
|
+
const { finalText, decision } = claimed.decisions[decisionNumber - 1];
|
|
2061
1997
|
const claimedFrom = statusAfter(decision);
|
|
2062
1998
|
|
|
2063
|
-
if (!finalText
|
|
1999
|
+
if (!finalText) {
|
|
2064
2000
|
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
2065
2001
|
logger.error('[EscalationReview] The claim was not released after a decision with no text', {
|
|
2066
2002
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
@@ -2078,7 +2014,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2078
2014
|
});
|
|
2079
2015
|
throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
|
|
2080
2016
|
}
|
|
2081
|
-
if (plan) return sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan, operator, requestId });
|
|
2082
2017
|
|
|
2083
2018
|
// Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
|
|
2084
2019
|
let message;
|
|
@@ -2090,7 +2025,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2090
2025
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2091
2026
|
});
|
|
2092
2027
|
});
|
|
2093
|
-
throw
|
|
2028
|
+
throw error;
|
|
2094
2029
|
}
|
|
2095
2030
|
|
|
2096
2031
|
let result;
|
|
@@ -2098,7 +2033,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2098
2033
|
result = await getMessaging().sendMessage(message);
|
|
2099
2034
|
const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
|
|
2100
2035
|
if (!result?.success && !alreadyDelivered) {
|
|
2101
|
-
throw httpError(502, 'The indications could not be sent to the patient'
|
|
2036
|
+
throw httpError(502, 'The indications could not be sent to the patient');
|
|
2102
2037
|
}
|
|
2103
2038
|
} catch (error) {
|
|
2104
2039
|
if (!sendDidNotHappen(error)) {
|
|
@@ -2106,14 +2041,14 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2106
2041
|
escalationReviewId: String(claimed._id),
|
|
2107
2042
|
error: redactedError(error),
|
|
2108
2043
|
});
|
|
2109
|
-
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again'
|
|
2044
|
+
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
|
|
2110
2045
|
}
|
|
2111
2046
|
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
2112
2047
|
logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
|
|
2113
2048
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2114
2049
|
});
|
|
2115
2050
|
});
|
|
2116
|
-
throw
|
|
2051
|
+
throw error;
|
|
2117
2052
|
}
|
|
2118
2053
|
|
|
2119
2054
|
const deferred = result.deferred === true;
|
|
@@ -2129,123 +2064,11 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2129
2064
|
const recordUpdate = withCaseMirror(claimed, {
|
|
2130
2065
|
$set: { patientDelivery: delivery },
|
|
2131
2066
|
}, { recommendation: finalText });
|
|
2132
|
-
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status)
|
|
2067
|
+
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
2133
2068
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
2134
2069
|
return syncCase(review, operator, requestId);
|
|
2135
2070
|
}
|
|
2136
2071
|
|
|
2137
|
-
// The PDF goes out from the Airtable automations; a failed receta never undoes the message already sent.
|
|
2138
|
-
async function issuePrescription(review, plan, prescriberEmail) {
|
|
2139
|
-
try {
|
|
2140
|
-
return await createPrescription({
|
|
2141
|
-
code: review.patientCode, prescription: prescriptionText(plan), authorEmail: prescriberEmail, creationSource: 'patient case',
|
|
2142
|
-
});
|
|
2143
|
-
} catch (error) {
|
|
2144
|
-
logger.error('[EscalationReview] The prescription was not created after the plan was sent', {
|
|
2145
|
-
escalationReviewId: String(review._id), error: redactedError(error),
|
|
2146
|
-
});
|
|
2147
|
-
return null;
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
|
|
2151
|
-
function replyOutcome(delivery, sendThrew) {
|
|
2152
|
-
if (sendThrew) return 'unknown';
|
|
2153
|
-
if (!delivery) return 'not_sent';
|
|
2154
|
-
if (delivery.success === true && delivery.deferred === true) return 'queued';
|
|
2155
|
-
if (delivery.success === true && typeof delivery.messageId === 'string' && delivery.messageId) return 'sent';
|
|
2156
|
-
if (delivery.success === false && delivery.deferred !== true && delivery.duplicate !== true) return 'not_sent';
|
|
2157
|
-
return 'unknown';
|
|
2158
|
-
}
|
|
2159
|
-
|
|
2160
|
-
// A notice that fails is logged and never undoes the send.
|
|
2161
|
-
async function notifyPlanIssues(review, issues) {
|
|
2162
|
-
try {
|
|
2163
|
-
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
2164
|
-
const header = '⚠️ Revisar el envío del plan';
|
|
2165
|
-
const lines = issues.map((issue) => `- ${issue}`);
|
|
2166
|
-
const action = 'Qué hacer: revisar el chat; corregir con la paciente o volver a mandar la receta si hace falta';
|
|
2167
|
-
// Every alarm, not only those since the decision: the plan is always sent after it, so the case's alarm came before.
|
|
2168
|
-
const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
|
|
2169
|
-
const quoted = await readGroupMessageId(recordId, review.patientCode);
|
|
2170
|
-
const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...lines, action, link].join('\n'), quoted, [header, ...lines, action].join('\n'));
|
|
2171
|
-
if (!sent.delivered) logger.error('[EscalationReview] The plan check notice did not reach the group', { escalationReviewId: String(review._id), error: sent.error });
|
|
2172
|
-
} catch (error) {
|
|
2173
|
-
logger.error('[EscalationReview] The plan check notice failed', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
2174
|
-
}
|
|
2175
|
-
}
|
|
2176
|
-
|
|
2177
|
-
async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan, operator, requestId }) {
|
|
2178
|
-
const reviewId = claimed._id;
|
|
2179
|
-
const release = () => releaseReview(reviewId, 'sending', 'approved', claim).catch((releaseError) => {
|
|
2180
|
-
logger.error('[EscalationReview] The claim was not released after a plan the assistant did not send', {
|
|
2181
|
-
escalationReviewId: String(reviewId), error: releaseError.message,
|
|
2182
|
-
});
|
|
2183
|
-
});
|
|
2184
|
-
|
|
2185
|
-
const prescriberEmail = needsPrescriber(plan) ? plan.prescriber?.email ?? null : null;
|
|
2186
|
-
let delivery;
|
|
2187
|
-
let sendThrew;
|
|
2188
|
-
let reply;
|
|
2189
|
-
try {
|
|
2190
|
-
if (needsPrescriber(plan) && !prescriberEmail) throw httpError(409, 'This plan names no doctor to sign the receta; record the plan again');
|
|
2191
|
-
({ delivery = null, sendThrew = false, reply = null } = await getMessaging().processSystemMessage(
|
|
2192
|
-
claimed.patientCode, [assistantInstructionsOf(plan)], 'system', { reply: true, triggeredBy: operator },
|
|
2193
|
-
) ?? {});
|
|
2194
|
-
} catch (error) {
|
|
2195
|
-
// A turn refused by a deploy's drain never ran; any other failure after the instructions were stored may have answered.
|
|
2196
|
-
if (error?.reasonCode === 'MESSAGE_REPLY_FAILED' && !(error.cause instanceof DrainingError)) {
|
|
2197
|
-
logger.error('[EscalationReview] The assistant turn failed after the instructions were stored; leaving the review in sending', {
|
|
2198
|
-
escalationReviewId: String(reviewId),
|
|
2199
|
-
});
|
|
2200
|
-
throw httpError(502, 'The assistant turn failed after the instructions were stored; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2201
|
-
}
|
|
2202
|
-
await release();
|
|
2203
|
-
if (error?.cause instanceof DrainingError) throw httpError(503, 'The server is restarting; send the plan again in a minute', SEND_NOT_SENT);
|
|
2204
|
-
throw withSendCode(error, SEND_NOT_SENT);
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
const outcome = replyOutcome(delivery, sendThrew);
|
|
2208
|
-
if (outcome === 'not_sent') {
|
|
2209
|
-
await release();
|
|
2210
|
-
throw httpError(502, 'The assistant did not send a message to the patient; check the chat and send the plan again', SEND_NOT_SENT);
|
|
2211
|
-
}
|
|
2212
|
-
if (outcome === 'unknown') {
|
|
2213
|
-
logger.error('[EscalationReview] The assistant reply could not be confirmed; leaving the review in sending', { escalationReviewId: String(reviewId) });
|
|
2214
|
-
await notifyPlanIssues(claimed, ['no se pudo confirmar que el mensaje salió; el caso sigue en «enviando»']);
|
|
2215
|
-
throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2216
|
-
}
|
|
2217
|
-
|
|
2218
|
-
// A queued reply goes out once the patient answers the recovery template; the receta, a template itself, goes now.
|
|
2219
|
-
const queued = outcome === 'queued';
|
|
2220
|
-
const prescriptionRecordId = prescriberEmail ? await issuePrescription(claimed, plan, prescriberEmail) : null;
|
|
2221
|
-
const prescriptionFailed = Boolean(prescriberEmail) && !prescriptionRecordId;
|
|
2222
|
-
const issues = [...replyIssues(plan, reply), ...(prescriptionFailed ? ['no se pudo crear la receta'] : [])];
|
|
2223
|
-
const record = {
|
|
2224
|
-
decisionNumber, messageId: delivery.messageId || null, status: delivery.status || null, transport: 'assistant', deferred: queued, sentBy: operator,
|
|
2225
|
-
...(prescriptionRecordId && { prescriptionRecordId }),
|
|
2226
|
-
...(issues.length && { checks: issues }),
|
|
2227
|
-
};
|
|
2228
|
-
const recordUpdate = withCaseMirror(claimed, { $set: { patientDelivery: record } }, { recommendation: planSummary(plan) });
|
|
2229
|
-
const status = queued ? 'indications_queued' : 'indications_sent';
|
|
2230
|
-
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2231
|
-
await audit(review, operator, requestId, {
|
|
2232
|
-
action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
|
|
2233
|
-
});
|
|
2234
|
-
if (issues.length) await notifyPlanIssues(review, issues);
|
|
2235
|
-
// Closing waits for a sent reply that kept to the plan and the receta it promised; otherwise the team still has something to do.
|
|
2236
|
-
if (plan.followUp.kind === 'none' && !queued && !issues.length) {
|
|
2237
|
-
try {
|
|
2238
|
-
return await closeEscalationReview({ id: reviewId, closedBy: operator, requestId });
|
|
2239
|
-
} catch (error) {
|
|
2240
|
-
logger.error('[EscalationReview] The review was not closed after its plan was sent', {
|
|
2241
|
-
escalationReviewId: String(reviewId), error: redactedError(error),
|
|
2242
|
-
});
|
|
2243
|
-
return syncCase(await loadReview(reviewId), operator, requestId);
|
|
2244
|
-
}
|
|
2245
|
-
}
|
|
2246
|
-
return syncCase(review, operator, requestId);
|
|
2247
|
-
}
|
|
2248
|
-
|
|
2249
2072
|
const EPISODE_TRUST = 0.7;
|
|
2250
2073
|
const EPISODE_VARIABLE = 'intercurrent_events_summary';
|
|
2251
2074
|
const EPISODE_SOURCE = 'doctor';
|
|
@@ -2253,7 +2076,6 @@ const EPISODE_SOURCE = 'doctor';
|
|
|
2253
2076
|
const DECISION_WORDS = {
|
|
2254
2077
|
approved: 'el médico aprobó las indicaciones',
|
|
2255
2078
|
edited_approved: 'el médico aprobó las indicaciones con cambios',
|
|
2256
|
-
plan_approved: 'el médico dio las indicaciones',
|
|
2257
2079
|
needs_intervention: 'el médico pidió valoración presencial',
|
|
2258
2080
|
returned: 'el médico devolvió el caso a navegación',
|
|
2259
2081
|
};
|
|
@@ -2437,7 +2259,6 @@ module.exports = {
|
|
|
2437
2259
|
generateBotDraft,
|
|
2438
2260
|
getEscalationReviewById,
|
|
2439
2261
|
getReviewTimeline,
|
|
2440
|
-
previewPlanInstructions,
|
|
2441
2262
|
handOffToDoctor,
|
|
2442
2263
|
listEscalationReviews,
|
|
2443
2264
|
openEscalationReview,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const httpError = (statusCode, message
|
|
1
|
+
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
2
2
|
|
|
3
3
|
const requiredText = (value, name) => {
|
|
4
4
|
const text = String(value ?? '').trim();
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const MAX_PARAGRAPHS = 3;
|
|
2
|
+
const MAX_PARTS = 3;
|
|
3
|
+
|
|
4
|
+
const clean = (text) => text.replace(/\s+/g, ' ').trim();
|
|
5
|
+
|
|
6
|
+
// A template variable cannot hold a line break, so a single break inside a paragraph becomes « · ».
|
|
7
|
+
function paragraphsOf(text) {
|
|
8
|
+
return String(text || '').split(/\n\s*\n/)
|
|
9
|
+
.map(paragraph => paragraph.split('\n').map(clean).filter(Boolean).join(' · '))
|
|
10
|
+
.filter(Boolean);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function splitAtWordBoundaries(text, maxLength) {
|
|
14
|
+
if (!text || text.length <= maxLength) return [text];
|
|
15
|
+
const chunks = [];
|
|
16
|
+
let remaining = text;
|
|
17
|
+
while (remaining.length > maxLength) {
|
|
18
|
+
let splitIndex = -1;
|
|
19
|
+
const searchStart = Math.max(0, maxLength - 500); // Look back up to 500 chars
|
|
20
|
+
const searchArea = remaining.substring(searchStart, maxLength + 1);
|
|
21
|
+
|
|
22
|
+
const regex = /[.!?]\s/g;
|
|
23
|
+
let match;
|
|
24
|
+
let lastMatchIndex = -1;
|
|
25
|
+
|
|
26
|
+
while ((match = regex.exec(searchArea)) !== null) {
|
|
27
|
+
const absoluteIndex = searchStart + match.index;
|
|
28
|
+
if (absoluteIndex <= maxLength) {
|
|
29
|
+
lastMatchIndex = absoluteIndex + match[0].length;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (lastMatchIndex > 0) {
|
|
34
|
+
splitIndex = lastMatchIndex;
|
|
35
|
+
} else {
|
|
36
|
+
splitIndex = remaining.lastIndexOf(' ', maxLength);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const chunk = remaining.substring(0, splitIndex === -1 ? maxLength : splitIndex).trim();
|
|
40
|
+
if (chunk) chunks.push(chunk);
|
|
41
|
+
remaining = remaining.substring(splitIndex === -1 ? maxLength : splitIndex).trim();
|
|
42
|
+
}
|
|
43
|
+
if (remaining) chunks.push(remaining);
|
|
44
|
+
return chunks;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const partLength = (part) => part.join('').length + (part.length - 1) * 2;
|
|
48
|
+
|
|
49
|
+
function shapeTemplateParts(text, budget) {
|
|
50
|
+
const parts = [];
|
|
51
|
+
for (const piece of paragraphsOf(text).flatMap(paragraph => splitAtWordBoundaries(paragraph, budget))) {
|
|
52
|
+
const part = parts[parts.length - 1];
|
|
53
|
+
if (part && part.length < MAX_PARAGRAPHS && partLength(part) + 2 + piece.length <= budget) {
|
|
54
|
+
part.push(piece);
|
|
55
|
+
} else if (part && part.length === MAX_PARAGRAPHS && partLength(part) + 1 + piece.length <= budget) {
|
|
56
|
+
part[part.length - 1] = `${part[part.length - 1]} ${piece}`;
|
|
57
|
+
} else {
|
|
58
|
+
parts.push([piece]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return parts.length && parts.length <= MAX_PARTS ? parts : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { shapeTemplateParts, splitAtWordBoundaries };
|