@peopl-health/nexus 6.4.10 → 6.4.12
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/clinical/flags/escalationFlags.js +5 -0
- package/lib/clinical/helpers/doctorPlanHelper.js +3 -2
- package/lib/clinical/services/checkInDueService.js +2 -0
- package/lib/clinical/services/clinicalAirtableService.js +3 -2
- package/lib/clinical/services/contingencyDispatchService.js +5 -1
- package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
- package/lib/models/escalationReviewModel.js +15 -1
- package/lib/services/caseFollowUpService.js +226 -0
- package/lib/services/caseFollowUpSweepService.js +89 -0
- package/lib/services/escalationReviewService.js +22 -0
- package/lib/services/reviewAlertSweepService.js +9 -1
- package/lib/services/watchExpiryService.js +2 -1
- package/package.json +1 -1
|
@@ -40,7 +40,12 @@ function escalationWatchTeamNoticeLive() {
|
|
|
40
40
|
return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
function escalationCaseFollowUpLive() {
|
|
44
|
+
return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
|
|
45
|
+
}
|
|
46
|
+
|
|
43
47
|
module.exports = {
|
|
48
|
+
escalationCaseFollowUpLive,
|
|
44
49
|
escalationApproverAlertLive,
|
|
45
50
|
escalationAssessmentLive,
|
|
46
51
|
escalationAutoHandoffLive,
|
|
@@ -2,7 +2,7 @@ const { oneLineOf } = require('../../utils/coercionUtils');
|
|
|
2
2
|
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
3
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
4
4
|
|
|
5
|
-
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
|
|
5
|
+
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ auto: 24, check_in: 24, vigilancia: 48 });
|
|
6
6
|
|
|
7
7
|
const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
|
|
8
8
|
|
|
@@ -19,7 +19,7 @@ const PLAN_TEXTS = Object.freeze({
|
|
|
19
19
|
FOLLOW_UP_VIGILANCIA: 'Seguimiento: queda en vigilancia las próximas {horas} horas; le escribiremos para ver cómo va.',
|
|
20
20
|
});
|
|
21
21
|
|
|
22
|
-
const FOLLOW_UP_KEYS = { check_in: 'FOLLOW_UP_CHECK_IN', vigilancia: 'FOLLOW_UP_VIGILANCIA' };
|
|
22
|
+
const FOLLOW_UP_KEYS = { auto: 'FOLLOW_UP_CHECK_IN', check_in: 'FOLLOW_UP_CHECK_IN', vigilancia: 'FOLLOW_UP_VIGILANCIA' };
|
|
23
23
|
const followUpLineOf = (plan, texts = PLAN_TEXTS) => texts[FOLLOW_UP_KEYS[plan.followUp?.kind]]?.replaceAll('{horas}', plan.followUp.hours) ?? null;
|
|
24
24
|
|
|
25
25
|
function planInstructions(plan, texts = PLAN_TEXTS) {
|
|
@@ -42,6 +42,7 @@ function planSummary(plan) {
|
|
|
42
42
|
const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
|
|
43
43
|
if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
|
|
44
44
|
if (plan.note) lines.push(`Nota: ${plan.note}`);
|
|
45
|
+
if (plan.followUp?.kind === 'auto') lines.push(`Seguimiento: automático, unas ${plan.followUp.hours} h.`);
|
|
45
46
|
if (plan.followUp?.kind === 'check_in') lines.push(`Seguimiento: check-in en ${plan.followUp.hours} h.`);
|
|
46
47
|
if (plan.followUp?.kind === 'vigilancia') lines.push(`Seguimiento: vigilancia ${plan.followUp.hours} h.`);
|
|
47
48
|
return lines.join('\n');
|
|
@@ -9,6 +9,7 @@ const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUt
|
|
|
9
9
|
const { readRecommendationPlans } = require('../../fhir');
|
|
10
10
|
const { ARMED_BY } = require('../../shared/dtos/ContingencySafetyNet');
|
|
11
11
|
const { logger } = require('../../utils/logger');
|
|
12
|
+
const { isCaseFollowUpId, planCaseCheckIn } = require('../../services/caseFollowUpService');
|
|
12
13
|
const { readActiveNets, escalationUrgencyOf, CHECK_IN_WINDOW } = require('./contingencyDispatchService');
|
|
13
14
|
const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
|
|
14
15
|
|
|
@@ -181,6 +182,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
|
|
|
181
182
|
});
|
|
182
183
|
}
|
|
183
184
|
|
|
185
|
+
if (isCaseFollowUpId(reminderId)) return planCaseCheckIn({ code, reminderId, firstName, now });
|
|
184
186
|
const plan = await readPendingReminderForPatient({ code, reminderId });
|
|
185
187
|
if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
|
|
186
188
|
if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
|
|
@@ -50,6 +50,7 @@ const REMINDER_TYPE_TO_AIRTABLE = {
|
|
|
50
50
|
// of pending rows so the predicate cannot drift between them.
|
|
51
51
|
const PENDING_ROW_FILTER = 'IF({is_active}, "true", "false") = "true", IF({is_sent}, "true", "false") = "false"';
|
|
52
52
|
const ROUTINE_OUTREACH_FILTER = 'OR({type} = "seguimiento", LEFT({schedule_id}, 9) = "recovery_")';
|
|
53
|
+
const NOT_CASE_FOLLOW_UP = 'LEFT({schedule_id}, 14) != "case_followup_"';
|
|
53
54
|
const RECOVERY_FILTER = 'LEFT({schedule_id}, 9) = "recovery_"';
|
|
54
55
|
// `reminder` and `contingency` have no `source`; the lookup through the patient link carries it.
|
|
55
56
|
const ROW_PROGRAM_FIELD = 'source (from patient_id)';
|
|
@@ -525,14 +526,14 @@ async function readPendingReminderForPatient({ code, reminderId }) {
|
|
|
525
526
|
} : null;
|
|
526
527
|
}
|
|
527
528
|
|
|
528
|
-
async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false }) {
|
|
529
|
+
async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false, includeCaseFollowUp = false }) {
|
|
529
530
|
return standDownRow({
|
|
530
531
|
code,
|
|
531
532
|
trace,
|
|
532
533
|
table: 'reminder',
|
|
533
534
|
planId: null,
|
|
534
535
|
standDownReason: reason,
|
|
535
|
-
filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
|
|
536
|
+
filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${includeCaseFollowUp ? 'TRUE()' : NOT_CASE_FOLLOW_UP}, ${PENDING_ROW_FILTER})`,
|
|
536
537
|
});
|
|
537
538
|
}
|
|
538
539
|
|
|
@@ -291,6 +291,10 @@ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
|
|
|
291
291
|
patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
|
|
292
292
|
});
|
|
293
293
|
|
|
294
|
+
const retireSilenceNets = ({ patientCode, trace = null }) => retireNets({
|
|
295
|
+
patientCode, trace, isLive: null, select: (active) => active.filter((net) => net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'after the doctor decided',
|
|
296
|
+
});
|
|
297
|
+
|
|
294
298
|
function escalationUrgencyOf(net) {
|
|
295
299
|
if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
|
|
296
300
|
const silence = net?.patientReminder?.firesAfterSilenceMinutes;
|
|
@@ -493,4 +497,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
|
|
|
493
497
|
return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
|
|
494
498
|
}
|
|
495
499
|
|
|
496
|
-
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
500
|
+
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, retireSilenceNets, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
@@ -9,6 +9,7 @@ const { logger } = require('../../utils/logger');
|
|
|
9
9
|
const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
|
|
10
10
|
const { botIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
11
11
|
const { setCheckInsPausedUntil, checkInsPausedUntil } = require('../../services/threadService');
|
|
12
|
+
const { caseFollowUpMoveRefusal, isCaseFollowUpId, recordCaseFollowUpMoved } = require('../../services/caseFollowUpService');
|
|
12
13
|
|
|
13
14
|
const definition = {
|
|
14
15
|
name: 'schedulePatientReminder',
|
|
@@ -152,6 +153,10 @@ async function handler(args = {}, context = {}) {
|
|
|
152
153
|
if (actionType === 'update' && targetId && runtime.patientCode && !await isReminderPending({ code: runtime.patientCode, reminderId: targetId })) {
|
|
153
154
|
return JSON.stringify({ success: false, error: 'reminder_not_active — that reminder already went out or was stood down, so it cannot be updated. If a check is still needed, create a new one.', data: { reminder_id: targetId } });
|
|
154
155
|
}
|
|
156
|
+
if (actionType === 'update' && targetId && isCaseFollowUpId(targetId) && runtime.patientCode) {
|
|
157
|
+
const refusal = await caseFollowUpMoveRefusal({ code: runtime.patientCode, reminderId: targetId, fireAt: fireMoment.toDate() });
|
|
158
|
+
if (refusal) return JSON.stringify({ success: false, error: refusal, data: { reminder_id: targetId } });
|
|
159
|
+
}
|
|
155
160
|
if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
|
|
156
161
|
if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
|
|
157
162
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
@@ -215,6 +220,7 @@ async function handler(args = {}, context = {}) {
|
|
|
215
220
|
}
|
|
216
221
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
217
222
|
}
|
|
223
|
+
if (actionType === 'update' && isCaseFollowUpId(reminderId)) await recordCaseFollowUpMoved({ code: runtime.patientCode, reminderId, dueAt: fireMoment.toDate() });
|
|
218
224
|
}
|
|
219
225
|
|
|
220
226
|
trace.setSignals({ reminderIntents: [...existing, intent] });
|
|
@@ -258,7 +264,7 @@ async function pauseCheckIns(args, runtime) {
|
|
|
258
264
|
}
|
|
259
265
|
if (patientCode && !isShadowRun()) {
|
|
260
266
|
await setCheckInsPausedUntil(patientCode, until.toDate());
|
|
261
|
-
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused' })) {
|
|
267
|
+
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused', includeCaseFollowUp: true })) {
|
|
262
268
|
logger.warn('[schedulePatientReminder] pending seguimientos were not retired on pause', { patientCode });
|
|
263
269
|
}
|
|
264
270
|
}
|
|
@@ -274,6 +280,9 @@ async function cancelSeguimiento(args, runtime) {
|
|
|
274
280
|
}
|
|
275
281
|
const { patientCode, trace } = runtime;
|
|
276
282
|
const notPending = () => JSON.stringify({ success: false, error: 'not_pending — only a pending seguimiento listed under «Seguimientos ya programados» can be cancelled.', data: { reminder_id: reminderId } });
|
|
283
|
+
if (isCaseFollowUpId(reminderId)) {
|
|
284
|
+
return JSON.stringify({ success: false, error: 'case_follow_up — this seguimiento follows up the doctor\'s indications and ends when the case closes, not when the patient replies. If she asked to be written at another time, move it with update.', data: { reminder_id: reminderId } });
|
|
285
|
+
}
|
|
277
286
|
if (!reminderId.startsWith('followup_')) return notPending();
|
|
278
287
|
if (patientCode) {
|
|
279
288
|
const pending = await readPendingFollowUpsForPatient({ code: patientCode });
|
|
@@ -13,7 +13,7 @@ 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
15
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
16
|
-
const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
|
|
16
|
+
const PLAN_FOLLOW_UPS = ['none', 'auto', 'check_in', 'vigilancia'];
|
|
17
17
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
18
18
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
19
19
|
|
|
@@ -295,6 +295,18 @@ const identityBlockSchema = new mongoose.Schema({
|
|
|
295
295
|
blockedBy: { type: String, required: true },
|
|
296
296
|
}, { _id: false });
|
|
297
297
|
|
|
298
|
+
const caseFollowUpSchema = new mongoose.Schema({
|
|
299
|
+
decisionNumber: { type: Number, required: true },
|
|
300
|
+
kind: { type: String, enum: ['auto', 'check_in', 'vigilancia'], required: true },
|
|
301
|
+
attempt: { type: Number, required: true },
|
|
302
|
+
reminderId: { type: String, required: true },
|
|
303
|
+
dueAt: { type: Date, required: true },
|
|
304
|
+
isWritten: { type: Boolean, default: true },
|
|
305
|
+
firstDueAt: { type: Date, required: true },
|
|
306
|
+
nextCheckAt: { type: Date, default: null },
|
|
307
|
+
unansweredAt: { type: Date, default: null },
|
|
308
|
+
}, { _id: false });
|
|
309
|
+
|
|
298
310
|
const escalationReviewSchema = new mongoose.Schema({
|
|
299
311
|
patientCode: { type: String, required: true },
|
|
300
312
|
patientCaseRecordId: { type: String, default: null },
|
|
@@ -345,6 +357,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
345
357
|
quietReminders: { type: [quietReminderSchema], default: [] },
|
|
346
358
|
monitoringUntil: { type: Date, default: null },
|
|
347
359
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
360
|
+
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
348
361
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
349
362
|
feverPromptStartedAt: { type: Date, default: null },
|
|
350
363
|
approverViewedAt: { type: Date, default: null },
|
|
@@ -397,6 +410,7 @@ escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
|
397
410
|
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
398
411
|
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
399
412
|
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
413
|
+
escalationReviewSchema.index({ 'caseFollowUp.nextCheckAt': 1 }, { partialFilterExpression: { 'caseFollowUp.nextCheckAt': { $type: 'date' } } });
|
|
400
414
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
401
415
|
|
|
402
416
|
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
const moment = require('moment-timezone');
|
|
2
|
+
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
5
|
+
const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
|
|
6
|
+
const { DEFAULT_TIMEZONE, clampToHourWindow } = require('../utils/scheduleUtils');
|
|
7
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
8
|
+
const { recordReminder, cancelFollowUp } = require('../clinical/services/clinicalAirtableService');
|
|
9
|
+
const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
|
|
10
|
+
const { DEFAULT_FOLLOW_UP_HOURS, planSummary } = require('../clinical/helpers/doctorPlanHelper');
|
|
11
|
+
const { getMessages } = require('./messageService');
|
|
12
|
+
const { checkInsPausedUntil } = require('./threadService');
|
|
13
|
+
|
|
14
|
+
const PREFIX = 'case_followup_';
|
|
15
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
16
|
+
const AUTO_HOURS = 24;
|
|
17
|
+
const MOVE_WINDOW_HOURS = { earliest: 6, latest: 72 };
|
|
18
|
+
const SECOND_TRY_MS = 24 * HOUR_MS;
|
|
19
|
+
const ROW_LIFETIME_MS = 24 * HOUR_MS;
|
|
20
|
+
const SEND_WINDOW = { timeZone: DEFAULT_TIMEZONE, startHour: 11, endHour: 21 };
|
|
21
|
+
const FOLLOW_UP_STATUSES = ['indications_sent', 'monitoring'];
|
|
22
|
+
const BOOKKEEPING = { timestamps: false };
|
|
23
|
+
const PLAN_EXCERPT = 400;
|
|
24
|
+
// The follow-up template the send_reminder automation uses past the 24 h window (Airtable Monitoreo).
|
|
25
|
+
const FOLLOW_UP_TEMPLATE_SID = 'HX182fee522708bdb43db5ea614f538369';
|
|
26
|
+
// send_reminder fires up to 6 min before the row's time.
|
|
27
|
+
const SEND_LEAD_MS = 10 * 60 * 1000;
|
|
28
|
+
|
|
29
|
+
const isCaseFollowUpId = (reminderId) => typeof reminderId === 'string' && reminderId.startsWith(PREFIX);
|
|
30
|
+
const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
|
|
31
|
+
|
|
32
|
+
function followUpOf(decision) {
|
|
33
|
+
if (!decision) return null;
|
|
34
|
+
if (decision.decision === 'monitor') return { kind: 'vigilancia', hours: DEFAULT_FOLLOW_UP_HOURS.vigilancia };
|
|
35
|
+
const planned = decision.plan?.followUp;
|
|
36
|
+
if (planned?.kind === 'none') return null;
|
|
37
|
+
if (planned?.kind) return { kind: planned.kind, hours: planned.hours ?? DEFAULT_FOLLOW_UP_HOURS[planned.kind] ?? AUTO_HOURS };
|
|
38
|
+
return { kind: 'auto', hours: AUTO_HOURS };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const symptomOf = (review) => inlineOf([...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom))?.symptom) || null;
|
|
42
|
+
const dayOf = (value) => moment(value).tz(DEFAULT_TIMEZONE).format('DD/MM');
|
|
43
|
+
|
|
44
|
+
function questionFor(review, attempt) {
|
|
45
|
+
const about = symptomOf(review) ? ` con ${symptomOf(review).toLowerCase()}` : '';
|
|
46
|
+
return attempt === 1
|
|
47
|
+
? `¿Cómo has seguido${about}? Cuéntame si vas mejor, igual o peor.`
|
|
48
|
+
: `Quería saber cómo vas${about}. ¿Vas mejor, igual o peor?`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function decisionContext(decision) {
|
|
52
|
+
const what = decision.decision === 'monitor' ? 'el médico indicó vigilarlo en casa' : 'el médico le dio indicaciones';
|
|
53
|
+
const sent = decision.plan ? oneLineOf(planSummary(decision.plan)) : oneLineOf(decision.finalText);
|
|
54
|
+
const excerpt = sent && sent.length > PLAN_EXCERPT ? `${sent.slice(0, PLAN_EXCERPT)}…` : sent;
|
|
55
|
+
return `el ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function caseInstruction(review, firstName) {
|
|
59
|
+
const name = firstName || 'la paciente';
|
|
60
|
+
const symptom = symptomOf(review)?.toLowerCase() || 'lo que te contó';
|
|
61
|
+
const context = decisionContext(review.decisions.at(-1));
|
|
62
|
+
const quiet = 'No menciones alertas, revisiones, el sistema ni que este mensaje estaba programado.';
|
|
63
|
+
if (review.caseFollowUp.attempt > 1) {
|
|
64
|
+
return `Le preguntaste a ${name} cómo seguía con ${symptom} (${context}) y no ha contestado. Escríbele una vez más, con un mensaje distinto al anterior, breve y cálido, para saber si va mejor, igual o peor. No le reproches que no contestó. ${quiet}`;
|
|
65
|
+
}
|
|
66
|
+
return `Toca darle seguimiento a ${name} por ${symptom}: ${context}.
|
|
67
|
+
|
|
68
|
+
Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si dijo que va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntale una sola vez, en un mensaje breve y natural, cómo ha seguido con ${symptom}: si va mejor, igual o peor. Si contesta algo poco claro, aclara eso antes de cerrar. ${quiet}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function standDown(code, reminderId, reason) {
|
|
72
|
+
try {
|
|
73
|
+
if (!await cancelFollowUp({ code, reminderId, reason })) logger.warn('[CaseFollowUp] The follow-up row was not stood down', { reminderId, reason });
|
|
74
|
+
} catch (error) {
|
|
75
|
+
logger.warn('[CaseFollowUp] The follow-up row was not stood down', { reminderId, reason, error: errorOf(error) });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function writeRow(review, caseFollowUp) {
|
|
80
|
+
const isRecorded = await recordReminder({
|
|
81
|
+
code: review.patientCode, trace: null, actionType: 'create', reminderId: caseFollowUp.reminderId, reminderDateUtc: new Date(caseFollowUp.dueAt).toISOString(),
|
|
82
|
+
reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
|
|
83
|
+
}).catch((error) => {
|
|
84
|
+
logger.error('[CaseFollowUp] The follow-up row was not written', { escalationReviewId: String(review._id), error: errorOf(error) });
|
|
85
|
+
return false;
|
|
86
|
+
});
|
|
87
|
+
if (!isRecorded) return false;
|
|
88
|
+
const kept = await getEscalationReview().updateOne(
|
|
89
|
+
{ _id: review._id, closedAt: null, 'caseFollowUp.reminderId': caseFollowUp.reminderId },
|
|
90
|
+
{ $set: { 'caseFollowUp.isWritten': true, 'caseFollowUp.nextCheckAt': new Date(new Date(caseFollowUp.dueAt).getTime() + SECOND_TRY_MS) } },
|
|
91
|
+
BOOKKEEPING,
|
|
92
|
+
);
|
|
93
|
+
if (!kept.matchedCount) await standDown(review.patientCode, caseFollowUp.reminderId, 'case_changed');
|
|
94
|
+
return kept.matchedCount > 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function armCaseFollowUp(review, { attempt = 1, now = new Date() } = {}) {
|
|
98
|
+
if (!escalationCaseFollowUpLive()) return null;
|
|
99
|
+
const followUp = followUpOf(review.decisions?.at(-1));
|
|
100
|
+
if (!followUp) return null;
|
|
101
|
+
const decisionNumber = review.decisions.length;
|
|
102
|
+
const previous = review.caseFollowUp ?? null;
|
|
103
|
+
const code = review.patientCode;
|
|
104
|
+
const reminderId = `${PREFIX}${review._id}_${decisionNumber}_${attempt}`;
|
|
105
|
+
if (previous?.reminderId === reminderId) return null;
|
|
106
|
+
try {
|
|
107
|
+
const pausedUntil = await checkInsPausedUntil(code, now);
|
|
108
|
+
const lead = attempt === 1 ? followUp.hours * HOUR_MS : SECOND_TRY_MS;
|
|
109
|
+
const dueAt = clampToHourWindow(new Date(Math.max(now.getTime() + lead, pausedUntil ? new Date(pausedUntil).getTime() : 0)), SEND_WINDOW);
|
|
110
|
+
const caseFollowUp = {
|
|
111
|
+
decisionNumber, kind: followUp.kind, attempt, reminderId, dueAt, isWritten: false,
|
|
112
|
+
firstDueAt: attempt === 1 ? dueAt : previous.firstDueAt, nextCheckAt: new Date(now.getTime() + HOUR_MS), unansweredAt: null,
|
|
113
|
+
};
|
|
114
|
+
const stored = await getEscalationReview()
|
|
115
|
+
.findOneAndUpdate(
|
|
116
|
+
{ _id: review._id, closedAt: null, decisions: { $size: decisionNumber }, 'caseFollowUp.reminderId': previous?.reminderId ?? null },
|
|
117
|
+
{ $set: { caseFollowUp } },
|
|
118
|
+
{ new: true, ...BOOKKEEPING },
|
|
119
|
+
)
|
|
120
|
+
.lean();
|
|
121
|
+
if (!stored) return null;
|
|
122
|
+
if (previous?.reminderId && attempt === 1) await standDown(code, previous.reminderId, 'replaced');
|
|
123
|
+
if (!await writeRow(stored, caseFollowUp)) return stored;
|
|
124
|
+
return { ...stored, caseFollowUp: { ...stored.caseFollowUp, isWritten: true, nextCheckAt: new Date(dueAt.getTime() + SECOND_TRY_MS) } };
|
|
125
|
+
} catch (error) {
|
|
126
|
+
logger.error('[CaseFollowUp] The follow-up was not armed', { escalationReviewId: String(review._id), attempt, error: errorOf(error) });
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function rewriteRow(review, now = new Date()) {
|
|
132
|
+
const followUp = review.caseFollowUp;
|
|
133
|
+
const dueAt = clampToHourWindow(new Date(Math.max(new Date(followUp.dueAt).getTime(), now.getTime() + 10 * 60 * 1000)), SEND_WINDOW);
|
|
134
|
+
const moved = { dueAt, nextCheckAt: new Date(now.getTime() + HOUR_MS), ...(followUp.attempt === 1 && { firstDueAt: dueAt }) };
|
|
135
|
+
const claimed = await getEscalationReview().updateOne(
|
|
136
|
+
{ _id: review._id, closedAt: null, 'caseFollowUp.reminderId': followUp.reminderId, 'caseFollowUp.isWritten': false },
|
|
137
|
+
{ $set: Object.fromEntries(Object.entries(moved).map(([key, value]) => [`caseFollowUp.${key}`, value])) },
|
|
138
|
+
BOOKKEEPING,
|
|
139
|
+
);
|
|
140
|
+
if (!claimed.modifiedCount) return false;
|
|
141
|
+
if (await writeRow(review, { ...followUp, ...moved })) return true;
|
|
142
|
+
await getEscalationReview().updateOne({ _id: review._id, 'caseFollowUp.reminderId': followUp.reminderId }, { $set: { 'caseFollowUp.nextCheckAt': new Date(now.getTime() + HOUR_MS) } }, BOOKKEEPING);
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function cancelCaseFollowUp(review, reason) {
|
|
147
|
+
const reminderId = review?.caseFollowUp?.reminderId;
|
|
148
|
+
if (!reminderId) return;
|
|
149
|
+
await standDown(review.patientCode, reminderId, reason);
|
|
150
|
+
await getEscalationReview()
|
|
151
|
+
.updateOne({ _id: review._id, 'caseFollowUp.reminderId': reminderId }, { $set: { 'caseFollowUp.nextCheckAt': null } }, BOOKKEEPING)
|
|
152
|
+
.catch((error) => logger.warn('[CaseFollowUp] The follow-up check was not cleared', { escalationReviewId: String(review._id), error: errorOf(error) }));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function lastReplyAt(code, since, now = new Date()) {
|
|
156
|
+
const [row] = await getMessages(
|
|
157
|
+
{ numero: code, from_me: false, origin: { $ne: 'instruction' }, createdAt: { $gt: new Date(since), $lte: now } },
|
|
158
|
+
{ sort: { createdAt: -1 }, limit: 1, select: 'createdAt' },
|
|
159
|
+
) || [];
|
|
160
|
+
return row ? new Date(row.createdAt) : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function askedAt(review, now = new Date()) {
|
|
164
|
+
const since = new Date(new Date(review.caseFollowUp.firstDueAt).getTime() - SEND_LEAD_MS);
|
|
165
|
+
const [row] = await getMessages(
|
|
166
|
+
{
|
|
167
|
+
numero: review.patientCode,
|
|
168
|
+
from_me: true,
|
|
169
|
+
createdAt: { $gte: since, $lte: now },
|
|
170
|
+
$or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: FOLLOW_UP_TEMPLATE_SID }],
|
|
171
|
+
},
|
|
172
|
+
{ sort: { createdAt: 1 }, limit: 1, select: 'createdAt' },
|
|
173
|
+
) || [];
|
|
174
|
+
return row ? new Date(row.createdAt) : null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const reviewOfRow = (code, reminderId) => getEscalationReview().findOne({ patientCode: code, 'caseFollowUp.reminderId': reminderId }).lean();
|
|
178
|
+
|
|
179
|
+
async function planCaseCheckIn({ code, reminderId, firstName = null, now = new Date() }) {
|
|
180
|
+
const review = await reviewOfRow(code, reminderId);
|
|
181
|
+
if (!review || review.closedAt) return { mode: 'stale', reason: 'case_closed' };
|
|
182
|
+
if (!FOLLOW_UP_STATUSES.includes(review.status)) return { mode: 'stale', reason: 'case_reopened' };
|
|
183
|
+
if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
|
|
184
|
+
if (review.caseFollowUp.attempt > 1) {
|
|
185
|
+
const asked = await askedAt(review, now);
|
|
186
|
+
if (asked && await lastReplyAt(code, asked, now)) return { mode: 'stale', reason: 'patient_answered' };
|
|
187
|
+
}
|
|
188
|
+
return { mode: 'mandatory', planId: null, instruction: caseInstruction(review, firstName) };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function caseFollowUpMoveRefusal({ code, reminderId, fireAt }) {
|
|
192
|
+
const review = await reviewOfRow(code, reminderId);
|
|
193
|
+
if (!review || review.closedAt || !FOLLOW_UP_STATUSES.includes(review.status)) return 'reminder_not_active — that follow-up belongs to a case that is no longer open.';
|
|
194
|
+
if (review.caseFollowUp.kind !== 'auto' || review.caseFollowUp.attempt > 1) return 'case_follow_up_fixed — the doctor set when this follow-up goes out; leave it as it is.';
|
|
195
|
+
const decidedAt = new Date(review.decisions.at(-1).createdAt).getTime();
|
|
196
|
+
const earliest = decidedAt + MOVE_WINDOW_HOURS.earliest * HOUR_MS;
|
|
197
|
+
const latest = decidedAt + MOVE_WINDOW_HOURS.latest * HOUR_MS;
|
|
198
|
+
if (fireAt.getTime() < earliest || fireAt.getTime() > latest) {
|
|
199
|
+
const format = (ms) => moment(ms).tz(DEFAULT_TIMEZONE).format('YYYY-MM-DDTHH:mm');
|
|
200
|
+
return `case_follow_up_window — move it to between ${format(earliest)} and ${format(latest)}.`;
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function recordCaseFollowUpMoved({ code, reminderId, dueAt }) {
|
|
206
|
+
await getEscalationReview().updateOne(
|
|
207
|
+
{ patientCode: code, 'caseFollowUp.reminderId': reminderId, 'caseFollowUp.attempt': 1 },
|
|
208
|
+
{ $set: { 'caseFollowUp.dueAt': dueAt, 'caseFollowUp.firstDueAt': dueAt, 'caseFollowUp.nextCheckAt': new Date(dueAt.getTime() + SECOND_TRY_MS) } },
|
|
209
|
+
BOOKKEEPING,
|
|
210
|
+
).catch((error) => logger.warn('[CaseFollowUp] The moved follow-up was not recorded', { reminderId, error: errorOf(error) }));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
module.exports = {
|
|
214
|
+
FOLLOW_UP_STATUSES,
|
|
215
|
+
SECOND_TRY_MS,
|
|
216
|
+
armCaseFollowUp,
|
|
217
|
+
askedAt,
|
|
218
|
+
cancelCaseFollowUp,
|
|
219
|
+
caseFollowUpMoveRefusal,
|
|
220
|
+
caseInstruction,
|
|
221
|
+
isCaseFollowUpId,
|
|
222
|
+
lastReplyAt,
|
|
223
|
+
planCaseCheckIn,
|
|
224
|
+
recordCaseFollowUpMoved,
|
|
225
|
+
rewriteRow,
|
|
226
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
3
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
4
|
+
const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
|
|
5
|
+
|
|
6
|
+
const { logPatientChange } = require('./patientService');
|
|
7
|
+
const { getThreadInfo } = require('./threadService');
|
|
8
|
+
const { BOOKKEEPING, closeEscalationReview } = require('./escalationReviewService');
|
|
9
|
+
const { effectiveUrgencyOf } = require('./reviewDeadlineService');
|
|
10
|
+
const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
|
|
11
|
+
|
|
12
|
+
const OPERATOR = 'bot:caseFollowUp';
|
|
13
|
+
const AUDIT_SOURCE = 'escalation_review';
|
|
14
|
+
const SWEEP_LIMIT = 50;
|
|
15
|
+
const SETTLE_MS = 24 * 60 * 60 * 1000;
|
|
16
|
+
const RECHECK_MS = 60 * 60 * 1000;
|
|
17
|
+
const KEPT_OPEN_URGENCIES = ['stat', 'asap'];
|
|
18
|
+
|
|
19
|
+
const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
|
|
20
|
+
|
|
21
|
+
const audit = (review, changes) => logPatientChange({
|
|
22
|
+
code: review.patientCode,
|
|
23
|
+
updatedBy: OPERATOR,
|
|
24
|
+
source: AUDIT_SOURCE,
|
|
25
|
+
requestId: null,
|
|
26
|
+
changes: { escalationReviewId: String(review._id), ...changes },
|
|
27
|
+
}).catch((error) => logger.error('[CaseFollowUpSweep] The audit was not written', { escalationReviewId: String(review._id), error: errorOf(error) }));
|
|
28
|
+
|
|
29
|
+
const checkAgainAt = (review, at) => getEscalationReview().updateOne(
|
|
30
|
+
{ _id: review._id, 'caseFollowUp.reminderId': review.caseFollowUp.reminderId },
|
|
31
|
+
{ $set: { 'caseFollowUp.nextCheckAt': at } },
|
|
32
|
+
BOOKKEEPING,
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
async function close(review, result) {
|
|
36
|
+
const { review: closed } = await closeEscalationReview({ id: String(review._id), closedBy: OPERATOR, expectedAlarmCount: (review.alarms ?? []).length });
|
|
37
|
+
await audit(closed, { action: 'followup_result', result });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function keepUnanswered(review, now) {
|
|
41
|
+
const kept = await getEscalationReview().updateOne(
|
|
42
|
+
{ _id: review._id, 'caseFollowUp.reminderId': review.caseFollowUp.reminderId, 'caseFollowUp.unansweredAt': null },
|
|
43
|
+
{ $set: { 'caseFollowUp.unansweredAt': now, 'caseFollowUp.nextCheckAt': null, updatedSinceSeen: true } },
|
|
44
|
+
BOOKKEEPING,
|
|
45
|
+
);
|
|
46
|
+
if (kept.modifiedCount) await audit(review, { action: 'followup_result', result: 'unanswered' });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function settle(review, now) {
|
|
50
|
+
const followUp = review.caseFollowUp;
|
|
51
|
+
if ((await getThreadInfo(review.patientCode))?.stopped === true) return checkAgainAt(review, new Date(now.getTime() + RECHECK_MS));
|
|
52
|
+
if (followUp.isWritten === false) return rewriteRow(review, now);
|
|
53
|
+
const asked = await askedAt(review, now);
|
|
54
|
+
const repliedAt = asked && await lastReplyAt(review.patientCode, asked, now);
|
|
55
|
+
if (repliedAt) {
|
|
56
|
+
const settleAt = new Date(repliedAt.getTime() + SETTLE_MS);
|
|
57
|
+
return now < settleAt ? checkAgainAt(review, settleAt) : close(review, 'answered');
|
|
58
|
+
}
|
|
59
|
+
const giveUpAt = new Date(new Date(followUp.dueAt).getTime() + SECOND_TRY_MS);
|
|
60
|
+
if (now < giveUpAt) return checkAgainAt(review, giveUpAt);
|
|
61
|
+
if (followUp.attempt === 1) {
|
|
62
|
+
if (!await armCaseFollowUp(review, { attempt: 2, now })) await checkAgainAt(review, new Date(now.getTime() + RECHECK_MS));
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
if (KEPT_OPEN_URGENCIES.includes(effectiveUrgencyOf(review)?.urgency)) return keepUnanswered(review, now);
|
|
66
|
+
return close(review, 'no_answer');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function sweepCaseFollowUps({ now = new Date() } = {}) {
|
|
70
|
+
if (!escalationCaseFollowUpLive()) return 0;
|
|
71
|
+
const reviews = await getEscalationReview()
|
|
72
|
+
.find({ closedAt: null, status: { $in: FOLLOW_UP_STATUSES }, 'caseFollowUp.nextCheckAt': { $lte: now } })
|
|
73
|
+
.sort({ 'caseFollowUp.nextCheckAt': 1 })
|
|
74
|
+
.limit(SWEEP_LIMIT)
|
|
75
|
+
.lean();
|
|
76
|
+
let settled = 0;
|
|
77
|
+
for (const review of reviews) {
|
|
78
|
+
try {
|
|
79
|
+
await settle(review, now);
|
|
80
|
+
settled += 1;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
logger.error('[CaseFollowUpSweep] Could not settle a case follow-up', { escalationReviewId: String(review._id), error: errorOf(error) });
|
|
83
|
+
await checkAgainAt(review, new Date(now.getTime() + RECHECK_MS)).catch(() => {});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return settled;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = { sweepCaseFollowUps };
|
|
@@ -35,6 +35,7 @@ const { generateKeyQuestions } = require('../clinical/services/escalationQuestio
|
|
|
35
35
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
36
36
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
37
37
|
const { getPlanTexts } = require('../clinical/config/planTextsConfig');
|
|
38
|
+
const { retireSilenceNets } = require('../clinical/services/contingencyDispatchService');
|
|
38
39
|
const { DEFAULT_FOLLOW_UP_HOURS, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
|
|
39
40
|
const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
|
|
40
41
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
@@ -51,6 +52,7 @@ const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper
|
|
|
51
52
|
const { composePrompt } = require('../clinical/services/promptComposerService');
|
|
52
53
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
53
54
|
const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
|
|
55
|
+
const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService');
|
|
54
56
|
|
|
55
57
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
56
58
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
@@ -1414,6 +1416,7 @@ async function reopenFromFollowUp(review, reason) {
|
|
|
1414
1416
|
.lean();
|
|
1415
1417
|
if (!reopened) return review;
|
|
1416
1418
|
await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
|
|
1419
|
+
await cancelCaseFollowUp(reopened, 'case_reopened');
|
|
1417
1420
|
return reopened;
|
|
1418
1421
|
}
|
|
1419
1422
|
|
|
@@ -1948,6 +1951,8 @@ async function recordDoctorDecision({
|
|
|
1948
1951
|
await audit(updated, operator, requestId, {
|
|
1949
1952
|
action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
|
|
1950
1953
|
});
|
|
1954
|
+
if (decision !== 'returned' || returnReason === 'no_requiere') await retireSilenceNetsAfter(updated);
|
|
1955
|
+
if (decision === 'monitor') await armCaseFollowUp(updated);
|
|
1951
1956
|
if (returnReason === 'no_requiere') {
|
|
1952
1957
|
await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
|
|
1953
1958
|
const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
|
|
@@ -1960,6 +1965,16 @@ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
|
1960
1965
|
? { patientCaseRecordIds: review.patientCaseRecordIds }
|
|
1961
1966
|
: { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
|
|
1962
1967
|
|
|
1968
|
+
async function retireSilenceNetsAfter(review) {
|
|
1969
|
+
try {
|
|
1970
|
+
await retireSilenceNets({ patientCode: review.patientCode });
|
|
1971
|
+
} catch (error) {
|
|
1972
|
+
logger.warn('[EscalationReview] The escalation check-in was not retired after the decision or cancel', {
|
|
1973
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1963
1978
|
async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
|
|
1964
1979
|
try {
|
|
1965
1980
|
const text = String(body ?? '').trim();
|
|
@@ -2005,6 +2020,8 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
|
|
|
2005
2020
|
).lean();
|
|
2006
2021
|
if (updated) {
|
|
2007
2022
|
await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
|
|
2023
|
+
await retireSilenceNetsAfter(updated);
|
|
2024
|
+
if (!deferred) await armCaseFollowUp(updated);
|
|
2008
2025
|
const { review: synced } = await syncCase(updated, operator, null);
|
|
2009
2026
|
return synced;
|
|
2010
2027
|
}
|
|
@@ -2142,6 +2159,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2142
2159
|
}, { recommendation: finalText });
|
|
2143
2160
|
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2144
2161
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
2162
|
+
if (!deferred) await armCaseFollowUp(review);
|
|
2145
2163
|
return syncCase(review, operator, requestId);
|
|
2146
2164
|
}
|
|
2147
2165
|
|
|
@@ -2243,6 +2261,7 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2243
2261
|
action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
|
|
2244
2262
|
});
|
|
2245
2263
|
if (issues.length) await notifyPlanIssues(review, issues);
|
|
2264
|
+
if (!queued) await armCaseFollowUp(review);
|
|
2246
2265
|
// Closing waits for a sent reply that kept to the plan and the receta it promised; otherwise the team still has something to do.
|
|
2247
2266
|
if (plan.followUp.kind === 'none' && !queued && !issues.length) {
|
|
2248
2267
|
try {
|
|
@@ -2358,6 +2377,7 @@ async function closeEscalationReview({
|
|
|
2358
2377
|
escalationReviewId: String(review._id), error: redactedError(error), stack: redactedStack(error),
|
|
2359
2378
|
});
|
|
2360
2379
|
}
|
|
2380
|
+
await cancelCaseFollowUp(review, 'case_closed');
|
|
2361
2381
|
await recordEpisode(review);
|
|
2362
2382
|
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
2363
2383
|
}
|
|
@@ -2413,6 +2433,8 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingC
|
|
|
2413
2433
|
}
|
|
2414
2434
|
|
|
2415
2435
|
await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
|
|
2436
|
+
await retireSilenceNetsAfter(review);
|
|
2437
|
+
await cancelCaseFollowUp(review, 'case_cancelled');
|
|
2416
2438
|
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
2417
2439
|
}
|
|
2418
2440
|
|
|
@@ -6,6 +6,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
|
6
6
|
const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
|
|
7
7
|
const { sweepUntakenAlerts } = require('./untakenAlertService');
|
|
8
8
|
const { sweepExpiredWatches } = require('./watchExpiryService');
|
|
9
|
+
const { sweepCaseFollowUps } = require('./caseFollowUpSweepService');
|
|
9
10
|
|
|
10
11
|
const SWEEP_LIMIT = 10;
|
|
11
12
|
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
@@ -98,12 +99,19 @@ const watchSweeper = createIntervalSweeper({
|
|
|
98
99
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
99
100
|
});
|
|
100
101
|
|
|
102
|
+
const caseFollowUpSweeper = createIntervalSweeper({
|
|
103
|
+
label: '[CaseFollowUpSweep]',
|
|
104
|
+
sweep: () => sweepCaseFollowUps(),
|
|
105
|
+
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
106
|
+
});
|
|
107
|
+
|
|
101
108
|
const startReviewAlertSweep = (options) => {
|
|
102
109
|
untakenSweeper.start(options);
|
|
103
110
|
// A watch runs out in hours, so it keeps its own slower interval.
|
|
104
111
|
watchSweeper.start();
|
|
112
|
+
caseFollowUpSweeper.start();
|
|
105
113
|
return sweeper.start(options);
|
|
106
114
|
};
|
|
107
|
-
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop()]);
|
|
115
|
+
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
|
|
108
116
|
|
|
109
117
|
module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
|
|
@@ -133,7 +133,8 @@ async function noticeTeam(review, reminder, now) {
|
|
|
133
133
|
async function sweepExpiredWatches({ now = new Date() } = {}) {
|
|
134
134
|
if (!escalationWatchExpiryLive()) return 0;
|
|
135
135
|
const teamNotice = escalationWatchTeamNoticeLive();
|
|
136
|
-
|
|
136
|
+
// A watch with a case follow-up is followed up there; only the older ones are reminded here.
|
|
137
|
+
const query = { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now }, caseFollowUp: null };
|
|
137
138
|
// With no team notice a reminded watch has nothing left to send, so it must not hold a sweep slot.
|
|
138
139
|
if (!teamNotice) query.$expr = { $not: [{ $in: ['$monitoringUntil', REMINDED_UNTILS] }] };
|
|
139
140
|
const reviews = await getEscalationReview()
|