@peopl-health/nexus 5.63.0-dev.11427 → 5.63.0-dev.11473
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clinical/models/supportLightModel.js +0 -3
- package/lib/clinical/services/supportLightService.js +8 -87
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +1 -8
- package/lib/controllers/escalationReviewController.js +12 -0
- package/lib/index.d.ts +0 -12
- package/lib/models/escalationReviewModel.js +4 -1
- package/lib/routes/index.js +2 -0
- package/lib/services/escalationReviewService.js +74 -38
- package/lib/services/reviewBoardService.js +3 -7
- package/package.json +1 -1
- package/lib/clinical/flags/supportLightFlags.js +0 -7
|
@@ -46,7 +46,6 @@ const supportLightSchema = new mongoose.Schema({
|
|
|
46
46
|
supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
|
|
47
47
|
supportLightSchema.index({ service: 1, color: 1 });
|
|
48
48
|
supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
|
|
49
|
-
supportLightSchema.index({ 'outbox.at': 1 }, { sparse: true });
|
|
50
49
|
|
|
51
50
|
const supportLightEventSchema = new mongoose.Schema({
|
|
52
51
|
patientId: { type: String, required: true },
|
|
@@ -56,8 +55,6 @@ const supportLightEventSchema = new mongoose.Schema({
|
|
|
56
55
|
|
|
57
56
|
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
58
57
|
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
59
|
-
supportLightEventSchema.index({ service: 1, to: 1, at: 1 });
|
|
60
|
-
supportLightEventSchema.index({ at: 1 });
|
|
61
58
|
|
|
62
59
|
const supportLightSweepSchema = new mongoose.Schema({
|
|
63
60
|
patientId: { type: String, required: true, unique: true },
|
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
|
|
2
2
|
const { logger } = require('../../utils/logger');
|
|
3
|
-
const { supportLightFromChatLive } = require('../flags/supportLightFlags');
|
|
4
3
|
const { nextLight } = require('./supportInvitability');
|
|
5
4
|
|
|
6
5
|
const AI_ACTOR = 'ai';
|
|
7
6
|
const BOARD_LIMIT = 2000;
|
|
8
7
|
const HISTORY_READ_LIMIT = 200;
|
|
9
|
-
const EVENT_READ_LIMIT = 500;
|
|
10
|
-
const MAX_CHAT_REASON_CHARS = 1000;
|
|
11
|
-
const RISK_FIELD = { nutrition: 'nutritionRisk', psychology: 'psychologyRisk' };
|
|
12
8
|
|
|
13
9
|
function requireText(value, name) {
|
|
14
10
|
if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
|
|
@@ -140,26 +136,6 @@ async function readSupportLights(patientId, { Model = getSupportLightModel() } =
|
|
|
140
136
|
return Model.find({ patientId }).select('-outbox').lean();
|
|
141
137
|
}
|
|
142
138
|
|
|
143
|
-
function eventKey(event) {
|
|
144
|
-
return `${event.patientId}:${event.service}:${event.revision}`;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function withOutboxEvents(stored, lights) {
|
|
148
|
-
const byKey = new Map(stored.map((event) => [eventKey(event), event]));
|
|
149
|
-
for (const light of lights) {
|
|
150
|
-
for (const outboxEvent of light.outbox || []) {
|
|
151
|
-
const event = { ...outboxEvent, patientId: light.patientId, service: light.service };
|
|
152
|
-
if (!byKey.has(eventKey(event))) byKey.set(eventKey(event), event);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return [...byKey.values()];
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
function byTimeThenIdentity(left, right) {
|
|
159
|
-
return new Date(left.at) - new Date(right.at) || left.patientId.localeCompare(right.patientId)
|
|
160
|
-
|| left.service.localeCompare(right.service) || left.revision - right.revision;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
139
|
async function readSupportLightHistory(patientId, {
|
|
164
140
|
service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
|
|
165
141
|
} = {}) {
|
|
@@ -170,7 +146,14 @@ async function readSupportLightHistory(patientId, {
|
|
|
170
146
|
EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
|
|
171
147
|
Model.find(scope).select('patientId service outbox').lean(),
|
|
172
148
|
]);
|
|
173
|
-
|
|
149
|
+
const byKey = new Map(stored.map((event) => [`${event.service}:${event.revision}`, event]));
|
|
150
|
+
for (const light of lights) {
|
|
151
|
+
for (const event of light.outbox || []) {
|
|
152
|
+
const key = `${light.service}:${event.revision}`;
|
|
153
|
+
if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return [...byKey.values()]
|
|
174
157
|
.sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
|
|
175
158
|
|| left.service.localeCompare(right.service))
|
|
176
159
|
.slice(0, bounded);
|
|
@@ -207,70 +190,8 @@ async function readSupportLightBoard({ service = null, color = null, isPendingOn
|
|
|
207
190
|
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
208
191
|
}
|
|
209
192
|
|
|
210
|
-
async function readSupportLightEvents({
|
|
211
|
-
since, service = null, outcome = null, to = null,
|
|
212
|
-
} = {}, { limit = EVENT_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
|
|
213
|
-
const from = since == null ? null : new Date(since);
|
|
214
|
-
if (!from || Number.isNaN(from.getTime())) throw new Error('since is required');
|
|
215
|
-
const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, EVENT_READ_LIMIT) : EVENT_READ_LIMIT;
|
|
216
|
-
const filters = { ...(outcome ? { outcome } : {}), ...(to ? { to } : {}) };
|
|
217
|
-
const [stored, lights] = await Promise.all([
|
|
218
|
-
EventModel.find({ at: { $gte: from }, ...(service ? { service } : {}), ...filters })
|
|
219
|
-
.sort({ at: 1, patientId: 1, service: 1, revision: 1 }).limit(bounded).lean(),
|
|
220
|
-
Model.aggregate([
|
|
221
|
-
{ $match: { ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } } },
|
|
222
|
-
{ $unwind: '$outbox' },
|
|
223
|
-
{ $match: { 'outbox.at': { $gte: from }, ...Object.fromEntries(Object.entries(filters).map(([field, value]) => [`outbox.${field}`, value])) } },
|
|
224
|
-
{ $sort: { 'outbox.at': 1, patientId: 1, service: 1, 'outbox.revision': 1 } },
|
|
225
|
-
{ $limit: bounded },
|
|
226
|
-
{ $project: { _id: 0, patientId: 1, service: 1, outbox: ['$outbox'] } },
|
|
227
|
-
]),
|
|
228
|
-
]);
|
|
229
|
-
return withOutboxEvents(stored, lights).sort(byTimeThenIdentity).slice(0, bounded);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
function chatReading(recommendation, decision) {
|
|
233
|
-
const color = decision[RISK_FIELD[decision.service]];
|
|
234
|
-
if (!color) return null;
|
|
235
|
-
const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
|
|
236
|
-
const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
|
|
237
|
-
return {
|
|
238
|
-
patientId: recommendation.patientId,
|
|
239
|
-
service: decision.service,
|
|
240
|
-
color,
|
|
241
|
-
source: 'ai',
|
|
242
|
-
reason,
|
|
243
|
-
evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
async function applyChatSupportReadings(recommendation, {
|
|
248
|
-
acceptedServices = null, isTurnLive = () => true, now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight,
|
|
249
|
-
} = {}) {
|
|
250
|
-
if (!isLive()) return [];
|
|
251
|
-
const results = [];
|
|
252
|
-
const decisions = (recommendation.decisions || []).filter((decision) => !acceptedServices || acceptedServices.includes(decision.service));
|
|
253
|
-
for (const decision of decisions) {
|
|
254
|
-
const reading = chatReading(recommendation, decision);
|
|
255
|
-
if (!reading) continue;
|
|
256
|
-
if (!isTurnLive()) break;
|
|
257
|
-
try {
|
|
258
|
-
const { light, outcome } = await apply({ ...reading, now });
|
|
259
|
-
results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
|
|
260
|
-
} catch (error) {
|
|
261
|
-
logger.error('[supportLight] chat reading not applied', {
|
|
262
|
-
code: recommendation.patientId, service: reading.service, error: error.message, stack: error.stack,
|
|
263
|
-
});
|
|
264
|
-
results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return results;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
193
|
module.exports = {
|
|
271
|
-
applyChatSupportReadings,
|
|
272
194
|
applySupportLight,
|
|
273
|
-
readSupportLightEvents,
|
|
274
195
|
readSupportLightBoard,
|
|
275
196
|
resolvePendingImprovement,
|
|
276
197
|
readSupportLights,
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const { ZodError } = require('zod');
|
|
2
2
|
|
|
3
3
|
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
-
const { applyChatSupportReadings } = require('../services/supportLightService');
|
|
5
4
|
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
6
5
|
|
|
7
6
|
const decisionProperties = {
|
|
@@ -44,7 +43,7 @@ const decisionProperties = {
|
|
|
44
43
|
|
|
45
44
|
const definition = {
|
|
46
45
|
name: 'submitSupportRoutingRecommendation',
|
|
47
|
-
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation.
|
|
46
|
+
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
48
47
|
strict: false,
|
|
49
48
|
parameters: {
|
|
50
49
|
type: 'object',
|
|
@@ -117,11 +116,6 @@ async function handler(args = {}, context = {}) {
|
|
|
117
116
|
});
|
|
118
117
|
if (!isRuntimeLive(runtime)) return inactiveTurn();
|
|
119
118
|
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
120
|
-
const lights = isRuntimeLive(runtime)
|
|
121
|
-
? await applyChatSupportReadings(recommendation, {
|
|
122
|
-
acceptedServices: candidates.map((candidate) => candidate.service), isTurnLive: () => isRuntimeLive(runtime),
|
|
123
|
-
})
|
|
124
|
-
: [];
|
|
125
119
|
runtime.trace?.setSignals?.({
|
|
126
120
|
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
127
121
|
});
|
|
@@ -134,7 +128,6 @@ async function handler(args = {}, context = {}) {
|
|
|
134
128
|
service: candidate.service,
|
|
135
129
|
disposition: candidate.disposition,
|
|
136
130
|
})),
|
|
137
|
-
lights,
|
|
138
131
|
invitation_sent: false,
|
|
139
132
|
},
|
|
140
133
|
});
|
|
@@ -12,6 +12,7 @@ const {
|
|
|
12
12
|
listEscalationReviews,
|
|
13
13
|
openEscalationReview,
|
|
14
14
|
recordDoctorDecision,
|
|
15
|
+
requestBotDraft,
|
|
15
16
|
sendApprovedIndications,
|
|
16
17
|
setReviewCases,
|
|
17
18
|
suggestDraft,
|
|
@@ -124,6 +125,16 @@ const suggestEscalationReviewDraftController = async (req, res) => {
|
|
|
124
125
|
}
|
|
125
126
|
};
|
|
126
127
|
|
|
128
|
+
const requestEscalationReviewDraftController = async (req, res) => {
|
|
129
|
+
try {
|
|
130
|
+
const { triggeredBy } = req.body || {};
|
|
131
|
+
const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
|
|
132
|
+
res.status(202).json({ success: true, review });
|
|
133
|
+
} catch (error) {
|
|
134
|
+
respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
127
138
|
const suggestEscalationReviewQuestionsController = async (req, res) => {
|
|
128
139
|
try {
|
|
129
140
|
const { triggeredBy } = req.body || {};
|
|
@@ -249,6 +260,7 @@ module.exports = {
|
|
|
249
260
|
closeEscalationReviewController,
|
|
250
261
|
getEscalationReviewController,
|
|
251
262
|
getReviewTimelineController,
|
|
263
|
+
requestEscalationReviewDraftController,
|
|
252
264
|
handOffEscalationReviewController,
|
|
253
265
|
listEscalationReviewsController,
|
|
254
266
|
listReviewBoardController,
|
package/lib/index.d.ts
CHANGED
|
@@ -1006,18 +1006,6 @@ declare module '@peopl-health/nexus' {
|
|
|
1006
1006
|
isPendingOnly?: boolean;
|
|
1007
1007
|
}, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
|
|
1008
1008
|
readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1009
|
-
readSupportLightEvents(filters: {
|
|
1010
|
-
since: Date | string;
|
|
1011
|
-
service?: SupportService | null;
|
|
1012
|
-
outcome?: SupportLightEventRecord['outcome'] | null;
|
|
1013
|
-
to?: SupportLightColor | null;
|
|
1014
|
-
}, options?: { limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1015
|
-
applyChatSupportReadings(recommendation: Pick<SupportRoutingRecommendationInput, 'patientId' | 'decisions'>, options?: { acceptedServices?: SupportService[] | null; isTurnLive?: () => boolean; now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
|
|
1016
|
-
service: SupportService;
|
|
1017
|
-
color: SupportLightColor;
|
|
1018
|
-
outcome: SupportLightOutcome | 'stale' | 'error';
|
|
1019
|
-
revision: number | null;
|
|
1020
|
-
}>>;
|
|
1021
1009
|
};
|
|
1022
1010
|
|
|
1023
1011
|
export const supportInvitability: {
|
|
@@ -7,11 +7,12 @@ const { logger } = require('../utils/logger');
|
|
|
7
7
|
const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
|
|
8
8
|
const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
|
|
9
9
|
const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
|
|
10
|
+
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
|
|
10
11
|
const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
11
12
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
12
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
13
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
14
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'direct_chat'];
|
|
15
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
15
16
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
16
17
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
17
18
|
|
|
@@ -168,6 +169,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
168
169
|
'sending',
|
|
169
170
|
'indications_queued',
|
|
170
171
|
'indications_sent',
|
|
172
|
+
'monitoring',
|
|
171
173
|
'closed',
|
|
172
174
|
'cancelled',
|
|
173
175
|
],
|
|
@@ -223,6 +225,7 @@ module.exports = {
|
|
|
223
225
|
DOCTOR_DECISIONS,
|
|
224
226
|
HANDOFF_MODES,
|
|
225
227
|
INTERRUPTED_STATUSES,
|
|
228
|
+
FOLLOWUP_STATUSES,
|
|
226
229
|
RETURN_REASONS,
|
|
227
230
|
URGENCY_RANK,
|
|
228
231
|
getEscalationReview,
|
package/lib/routes/index.js
CHANGED
|
@@ -127,6 +127,7 @@ const escalationReviewRouteDefinitions = {
|
|
|
127
127
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
128
128
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
129
129
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
130
|
+
'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
|
|
130
131
|
'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
|
|
131
132
|
'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
|
|
132
133
|
'POST /:id/drafts': 'addEscalationReviewDraftController',
|
|
@@ -299,6 +300,7 @@ const builtInControllers = {
|
|
|
299
300
|
listReviewBoardController: escalationReviewController.listReviewBoardController,
|
|
300
301
|
getEscalationReviewController: escalationReviewController.getEscalationReviewController,
|
|
301
302
|
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
303
|
+
requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
|
|
302
304
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
303
305
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
304
306
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|
|
@@ -14,6 +14,7 @@ const {
|
|
|
14
14
|
DOCTOR_DECISIONS,
|
|
15
15
|
HANDOFF_MODES,
|
|
16
16
|
INTERRUPTED_STATUSES,
|
|
17
|
+
FOLLOWUP_STATUSES,
|
|
17
18
|
RETURN_REASONS,
|
|
18
19
|
URGENCY_RANK,
|
|
19
20
|
getEscalationReview,
|
|
@@ -51,10 +52,11 @@ const DUPLICATE_KEY_ERROR = 11000;
|
|
|
51
52
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
52
53
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
53
54
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
54
|
-
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
|
|
55
|
+
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
|
|
55
56
|
const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
|
|
56
57
|
const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
57
|
-
const
|
|
58
|
+
const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
|
|
59
|
+
const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
|
|
58
60
|
const SETTLED_TRAJECTORIES = ['improving', 'stable'];
|
|
59
61
|
const ALERTED_URGENCIES = ['stat', 'asap'];
|
|
60
62
|
const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
|
|
@@ -93,7 +95,8 @@ const configured = (key) => {
|
|
|
93
95
|
return value;
|
|
94
96
|
};
|
|
95
97
|
|
|
96
|
-
const
|
|
98
|
+
const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
|
|
99
|
+
const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
|
|
97
100
|
|
|
98
101
|
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
99
102
|
? review.patientCaseRecordIds
|
|
@@ -580,7 +583,13 @@ async function openEscalationReview({
|
|
|
580
583
|
if (!patient) throw httpError(404, 'Patient not found');
|
|
581
584
|
|
|
582
585
|
const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
|
|
583
|
-
const fields = {
|
|
586
|
+
const fields = {
|
|
587
|
+
patientCode,
|
|
588
|
+
openedBy: operator,
|
|
589
|
+
patientCaseRecordIds: recordIds,
|
|
590
|
+
assistantPausedByReview: false,
|
|
591
|
+
draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS),
|
|
592
|
+
};
|
|
584
593
|
|
|
585
594
|
const EscalationReview = getEscalationReview();
|
|
586
595
|
let review;
|
|
@@ -616,6 +625,35 @@ async function openEscalationReview({
|
|
|
616
625
|
return { review, created: true };
|
|
617
626
|
}
|
|
618
627
|
|
|
628
|
+
async function requestBotDraft({ id, requestedBy, requestId = null } = {}) {
|
|
629
|
+
const reviewId = reviewIdOf(id);
|
|
630
|
+
const operator = requiredText(requestedBy, 'requestedBy');
|
|
631
|
+
const review = await loadReview(reviewId);
|
|
632
|
+
if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
633
|
+
if ((review.drafts ?? []).at(-1)?.writtenBy && review.drafts.at(-1).writtenBy !== DRAFT_OPERATOR) {
|
|
634
|
+
throw httpError(409, 'The latest draft was written by the team; edit it instead of asking for a new one');
|
|
635
|
+
}
|
|
636
|
+
const now = new Date();
|
|
637
|
+
if (review.draftDueAt && new Date(review.draftDueAt) > now) return review;
|
|
638
|
+
const scheduled = await getEscalationReview().findOneAndUpdate(
|
|
639
|
+
{
|
|
640
|
+
_id: reviewId,
|
|
641
|
+
status: { $in: DOCUMENTING_STATUSES },
|
|
642
|
+
drafts: { $size: (review.drafts ?? []).length },
|
|
643
|
+
$or: [{ draftDueAt: null }, { draftDueAt: { $lte: now } }],
|
|
644
|
+
},
|
|
645
|
+
{ $set: { draftDueAt: now, draftAttempts: 0 } },
|
|
646
|
+
{ new: true },
|
|
647
|
+
).lean();
|
|
648
|
+
if (!scheduled) {
|
|
649
|
+
const latest = await loadReview(reviewId);
|
|
650
|
+
if (latest.draftDueAt && new Date(latest.draftDueAt) > now) return latest;
|
|
651
|
+
throw httpError(409, STATUS_CONFLICT);
|
|
652
|
+
}
|
|
653
|
+
await audit(scheduled, operator, requestId, { action: 'draft_requested' });
|
|
654
|
+
return scheduled;
|
|
655
|
+
}
|
|
656
|
+
|
|
619
657
|
async function isEscalationApprover(operator) {
|
|
620
658
|
try {
|
|
621
659
|
return Boolean(await getEscalationApprover(operator));
|
|
@@ -709,34 +747,29 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
709
747
|
if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
|
|
710
748
|
|
|
711
749
|
const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
|
|
750
|
+
const casesChanged = {
|
|
751
|
+
$not: [{
|
|
752
|
+
$setEquals: [
|
|
753
|
+
{
|
|
754
|
+
$ifNull: [
|
|
755
|
+
'$patientCaseRecordIds',
|
|
756
|
+
{ $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
|
|
757
|
+
],
|
|
758
|
+
},
|
|
759
|
+
recordIds,
|
|
760
|
+
],
|
|
761
|
+
}],
|
|
762
|
+
};
|
|
763
|
+
const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
|
|
712
764
|
|
|
713
765
|
const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
|
|
714
766
|
$set: {
|
|
715
767
|
patientCaseRecordIds: recordIds,
|
|
716
|
-
status: {
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
{
|
|
722
|
-
$not: [{
|
|
723
|
-
$setEquals: [
|
|
724
|
-
{
|
|
725
|
-
$ifNull: [
|
|
726
|
-
'$patientCaseRecordIds',
|
|
727
|
-
{ $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
|
|
728
|
-
],
|
|
729
|
-
},
|
|
730
|
-
recordIds,
|
|
731
|
-
],
|
|
732
|
-
}],
|
|
733
|
-
},
|
|
734
|
-
],
|
|
735
|
-
},
|
|
736
|
-
'documenting',
|
|
737
|
-
'$status',
|
|
738
|
-
],
|
|
739
|
-
},
|
|
768
|
+
status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
|
|
769
|
+
...(isBotDraft && {
|
|
770
|
+
draftDueAt: { $cond: [casesChanged, new Date(Date.now() + DRAFT_DEBOUNCE_MS), '$draftDueAt'] },
|
|
771
|
+
draftAttempts: { $cond: [casesChanged, 0, '$draftAttempts'] },
|
|
772
|
+
}),
|
|
740
773
|
pendingCaseMirrors: {
|
|
741
774
|
$filter: {
|
|
742
775
|
input: { $ifNull: ['$pendingCaseMirrors', []] },
|
|
@@ -977,12 +1010,12 @@ const readingOf = (impression) => (['close', 'resolve_episode'].includes(impress
|
|
|
977
1010
|
async function followUpCasesOf(review, sinceMs) {
|
|
978
1011
|
const decisionNumber = (review.decisions ?? []).length;
|
|
979
1012
|
if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
|
|
980
|
-
const
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
1013
|
+
const caseIdsOfUpdates = (isBefore) => (review.updates ?? [])
|
|
1014
|
+
.filter((entry) => (new Date(entry.at).getTime() <= sinceMs) === isBefore)
|
|
1015
|
+
.flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean));
|
|
1016
|
+
let known = [...new Set([...(review.followUpCases ?? []), ...caseIdsOfUpdates(true)])];
|
|
1017
|
+
if (!known.length) known = [...new Set(caseIdsOfUpdates(false))];
|
|
1018
|
+
if (!known.length) return { review, known: new Set() };
|
|
986
1019
|
const stored = await getEscalationReview()
|
|
987
1020
|
.findOneAndUpdate(
|
|
988
1021
|
{ _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
|
|
@@ -1028,7 +1061,7 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
|
1028
1061
|
|
|
1029
1062
|
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
|
|
1030
1063
|
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1031
|
-
if (!settled || review.status
|
|
1064
|
+
if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1032
1065
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1033
1066
|
return review;
|
|
1034
1067
|
}
|
|
@@ -1382,11 +1415,13 @@ async function recordDoctorDecision({
|
|
|
1382
1415
|
}
|
|
1383
1416
|
|
|
1384
1417
|
const review = await loadReview(reviewId);
|
|
1385
|
-
|
|
1418
|
+
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
1419
|
+
const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
|
|
1420
|
+
if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
1386
1421
|
const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
|
|
1387
1422
|
const draftNumber = handoff?.draftNumber ?? review.drafts.length;
|
|
1388
1423
|
const draft = review.drafts[draftNumber - 1];
|
|
1389
|
-
if (!draft) throw httpError(409, STATUS_CONFLICT);
|
|
1424
|
+
if (!draft && !isDraftless) throw httpError(409, STATUS_CONFLICT);
|
|
1390
1425
|
if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
|
|
1391
1426
|
|
|
1392
1427
|
let approvedText = null;
|
|
@@ -1411,7 +1446,7 @@ async function recordDoctorDecision({
|
|
|
1411
1446
|
}
|
|
1412
1447
|
const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
|
|
1413
1448
|
|
|
1414
|
-
const updated = await updateReview(reviewId,
|
|
1449
|
+
const updated = await updateReview(reviewId, allowedStatuses, {
|
|
1415
1450
|
$push: {
|
|
1416
1451
|
decisions: {
|
|
1417
1452
|
decision,
|
|
@@ -1763,6 +1798,7 @@ module.exports = {
|
|
|
1763
1798
|
recordDoctorDecision,
|
|
1764
1799
|
sendScheduledDoctorAlert,
|
|
1765
1800
|
recordReviewUpdate,
|
|
1801
|
+
requestBotDraft,
|
|
1766
1802
|
sendApprovedIndications,
|
|
1767
1803
|
setReviewCases,
|
|
1768
1804
|
suggestDraft,
|
|
@@ -1,19 +1,15 @@
|
|
|
1
1
|
const { httpError } = require('../utils/httpErrorUtils');
|
|
2
|
-
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
2
|
+
const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
3
|
|
|
4
4
|
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
5
|
-
const RETURNED_STATUSES = ['returned'];
|
|
6
|
-
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
|
|
7
5
|
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
8
|
-
const BOARD_BUCKETS = ['pending', '
|
|
6
|
+
const BOARD_BUCKETS = ['pending', 'followup', 'done'];
|
|
9
7
|
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
10
8
|
|
|
11
9
|
const bucketQuery = (bucket, now) => {
|
|
12
10
|
switch (bucket) {
|
|
13
11
|
case 'pending':
|
|
14
|
-
return { closedAt: null, status: { $nin: [...
|
|
15
|
-
case 'returned':
|
|
16
|
-
return { closedAt: null, status: { $in: RETURNED_STATUSES } };
|
|
12
|
+
return { closedAt: null, status: { $nin: [...FOLLOWUP_STATUSES, ...DONE_STATUSES] } };
|
|
17
13
|
case 'followup':
|
|
18
14
|
return { closedAt: null, status: { $in: FOLLOWUP_STATUSES } };
|
|
19
15
|
case 'done':
|
package/package.json
CHANGED