@peopl-health/nexus 5.72.0-dev.12926 → 5.72.0-dev.13735
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 +10 -0
- package/lib/clinical/helpers/chemoContextHelper.js +25 -9
- package/lib/clinical/helpers/clinicalContextHelper.js +4 -1
- package/lib/clinical/helpers/clinicalProfileHelper.js +18 -4
- package/lib/clinical/helpers/drugIdentityHelper.js +60 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +3 -3
- package/lib/clinical/helpers/triageCaseBaseHelper.js +16 -3
- package/lib/clinical/providers/BaseLLMProvider.js +27 -8
- package/lib/clinical/services/clinicalExtractionService.js +12 -5
- package/lib/clinical/services/clinicalPatternFloorService.js +3 -2
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/dispatcherService.js +11 -6
- package/lib/clinical/services/escalationDraftService.js +10 -4
- package/lib/clinical/services/gradeAnchorService.js +40 -18
- package/lib/clinical/services/gradeClaimService.js +15 -15
- package/lib/clinical/services/recommendationRankService.js +1 -1
- package/lib/clinical/services/regimenCloserService.js +125 -0
- package/lib/clinical/services/supportInvitability.js +6 -1
- package/lib/clinical/services/triageGateFloorService.js +1 -1
- package/lib/clinical/tools/extractClinicalInfoTool.js +27 -1
- package/lib/clinical/tools/openConditionTool.js +4 -2
- package/lib/clinical/tools/recordClinicalImpressionTool.js +11 -3
- package/lib/clinical/tools/reportMedicalEscalationTool.js +30 -8
- package/lib/clinical/tools/setContingencyPlanTool.js +3 -3
- package/lib/config/airtableConfig.js +2 -0
- package/lib/controllers/escalationReviewController.js +19 -16
- package/lib/core/NexusMessaging.js +60 -9
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/projectionSlugs.js +6 -0
- package/lib/fhir/index.js +2 -1
- package/lib/fhir/projections/contextFactProjection.js +1 -0
- package/lib/fhir/resources/CommunicationRequest.js +1 -1
- package/lib/fhir/resources/Task.js +42 -1
- package/lib/fhir/services/escalationService.js +13 -0
- package/lib/index.d.ts +72 -2
- package/lib/index.js +6 -0
- package/lib/models/escalationReviewModel.js +34 -2
- package/lib/services/escalationCaseTaskService.js +35 -0
- package/lib/services/escalationReviewService.js +284 -48
- package/lib/services/reviewAlertSweepService.js +7 -2
- package/lib/services/reviewBoardService.js +2 -0
- package/lib/services/threadService.js +2 -1
- package/lib/shared/dtos/DispatchedEscalation.js +1 -0
- package/lib/utils/dateUtils.js +4 -0
- package/lib/utils/retryUtils.js +1 -0
- package/package.json +1 -1
|
@@ -10,8 +10,14 @@ const {
|
|
|
10
10
|
const {
|
|
11
11
|
ESCALATION_SLUG,
|
|
12
12
|
ESCALATION_KIND_SLUG,
|
|
13
|
+
ESCALATION_CASE_SLUG,
|
|
14
|
+
ESCALATION_CASE_STATUS_SLUG,
|
|
15
|
+
ESCALATION_DECISION_SLUG,
|
|
13
16
|
} = require('../constants/projectionSlugs');
|
|
14
17
|
const { SEVERITY_TO_PRIORITY } = require('../constants/severityPriority');
|
|
18
|
+
const { caseStatusOf } = require('../constants/escalationCaseStatus');
|
|
19
|
+
|
|
20
|
+
const ESCALATION_CASE_CODE = 'escalation_case';
|
|
15
21
|
|
|
16
22
|
const TICKET_STATUS_TO_TASK_STATUS = {
|
|
17
23
|
queued: 'requested',
|
|
@@ -32,7 +38,7 @@ class Task {
|
|
|
32
38
|
identifier: [identifier(ESCALATION_SLUG, ticket.eventId)],
|
|
33
39
|
status: TICKET_STATUS_TO_TASK_STATUS[ticket.status],
|
|
34
40
|
intent: 'order',
|
|
35
|
-
priority: SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
|
|
41
|
+
priority: ticket.priority || SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
|
|
36
42
|
code: codeableConcept(ticket.kind, { code: ticket.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
|
|
37
43
|
for: patientReference(ticket.patientId),
|
|
38
44
|
authoredOn: toIso(ticket.createdAt),
|
|
@@ -48,6 +54,41 @@ class Task {
|
|
|
48
54
|
}
|
|
49
55
|
return new Task(payload);
|
|
50
56
|
}
|
|
57
|
+
|
|
58
|
+
// The operational case of an escalation review; its symptoms are the Conditions in `reason`.
|
|
59
|
+
static fromEscalationReview({ review, priority, conditionIds = [], deviceId }) {
|
|
60
|
+
const reviewId = String(review._id);
|
|
61
|
+
const { status, businessStatus, label } = caseStatusOf(review.status);
|
|
62
|
+
const payload = {
|
|
63
|
+
resourceType: 'Task',
|
|
64
|
+
id: fhirId(`escalation-case-${reviewId}`),
|
|
65
|
+
identifier: [identifier(ESCALATION_CASE_SLUG, reviewId)],
|
|
66
|
+
status,
|
|
67
|
+
businessStatus: codeableConcept(label, { code: businessStatus, system: codeSystemUrl(ESCALATION_CASE_STATUS_SLUG), display: label }),
|
|
68
|
+
intent: 'order',
|
|
69
|
+
priority: priority || 'routine',
|
|
70
|
+
code: codeableConcept(ESCALATION_CASE_CODE, { code: ESCALATION_CASE_CODE, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
|
|
71
|
+
for: patientReference(review.patientCode),
|
|
72
|
+
authoredOn: toIso(review.createdAt),
|
|
73
|
+
lastModified: toIso(review.updatedAt),
|
|
74
|
+
requester: reference('Device', deviceId),
|
|
75
|
+
executionPeriod: { start: toIso(review.createdAt), ...(review.closedAt ? { end: toIso(review.closedAt) } : {}) },
|
|
76
|
+
};
|
|
77
|
+
if (conditionIds.length) payload.reason = conditionIds.map((id) => ({ reference: reference('Condition', id) }));
|
|
78
|
+
// Only a code reaches FHIR: the operator's cancellation note is free text.
|
|
79
|
+
if (review.status === 'cancelled') {
|
|
80
|
+
const reasonCode = String(review.cancellationReason ?? '').startsWith('no_requiere') ? 'no_requiere' : 'cancelado_por_equipo';
|
|
81
|
+
payload.statusReason = { concept: codeableConcept(reasonCode) };
|
|
82
|
+
}
|
|
83
|
+
const decision = review.decisions?.at(-1)?.decision;
|
|
84
|
+
if (decision) {
|
|
85
|
+
payload.output = [{
|
|
86
|
+
type: codeableConcept('decision'),
|
|
87
|
+
valueCodeableConcept: codeableConcept(decision, { code: decision, system: codeSystemUrl(ESCALATION_DECISION_SLUG) }),
|
|
88
|
+
}];
|
|
89
|
+
}
|
|
90
|
+
return new Task(payload);
|
|
91
|
+
}
|
|
51
92
|
}
|
|
52
93
|
|
|
53
94
|
module.exports = { Task };
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
1
2
|
const { fhirId } = require('../helpers/fhirHelper');
|
|
2
3
|
const { ESCALATION_SLUG } = require('../constants/projectionSlugs');
|
|
3
4
|
const { getFhirStore } = require('../stores/fhirStore');
|
|
4
5
|
const { fromFhir } = require('../projections/dispatchedEscalationProjection');
|
|
6
|
+
const { Task } = require('../resources/Task');
|
|
7
|
+
const { storeResources } = require('./fhirService');
|
|
5
8
|
|
|
6
9
|
const RESOURCE_TYPES = ['Task', 'CommunicationRequest'];
|
|
7
10
|
|
|
@@ -31,6 +34,16 @@ async function readDispatchedEscalations({ patientId, since = null, limit = null
|
|
|
31
34
|
};
|
|
32
35
|
}
|
|
33
36
|
|
|
37
|
+
// Two syncs of the same review can finish out of order; the stored case never moves back to an older read.
|
|
38
|
+
const keepNewerCase = (prior, incoming) => (Date.parse(prior.lastModified) > Date.parse(incoming.lastModified) ? prior : incoming);
|
|
39
|
+
|
|
40
|
+
async function storeEscalationCase({ review, priority, conditionIds }) {
|
|
41
|
+
const task = Task.fromEscalationReview({ review, priority, conditionIds, deviceId: getDeviceId() });
|
|
42
|
+
const { stored } = await storeResources(task, { merge: keepNewerCase });
|
|
43
|
+
return { ids: stored };
|
|
44
|
+
}
|
|
45
|
+
|
|
34
46
|
module.exports = {
|
|
35
47
|
readDispatchedEscalations,
|
|
48
|
+
storeEscalationCase,
|
|
36
49
|
};
|
package/lib/index.d.ts
CHANGED
|
@@ -272,7 +272,7 @@ declare module '@peopl-health/nexus' {
|
|
|
272
272
|
getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
|
|
273
273
|
initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
|
|
274
274
|
getWorkflowRunner(): WorkflowRunner;
|
|
275
|
-
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string }): Promise<
|
|
275
|
+
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
276
276
|
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
|
|
277
277
|
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
|
|
278
278
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
@@ -475,6 +475,8 @@ declare module '@peopl-health/nexus' {
|
|
|
475
475
|
nextCheckAt: string | null;
|
|
476
476
|
/** Drafted patient-facing text. Present only on a dry run. */
|
|
477
477
|
draft?: string | null;
|
|
478
|
+
/** Why the out-of-window template would refuse the draft. Present only on a dry run. */
|
|
479
|
+
carrierRejection?: string | null;
|
|
478
480
|
/** Whether the provider accepted the fixed-template send. This is not proof of delivery. */
|
|
479
481
|
accepted?: boolean;
|
|
480
482
|
/** Whether the provider status is already terminal delivered/read. */
|
|
@@ -525,6 +527,72 @@ declare module '@peopl-health/nexus' {
|
|
|
525
527
|
source?: 'weekly' | 'patient_scope';
|
|
526
528
|
}): Promise<OutreachSweepResult>;
|
|
527
529
|
|
|
530
|
+
export interface ContextFactRow {
|
|
531
|
+
variableId: string;
|
|
532
|
+
value?: unknown;
|
|
533
|
+
status?: string | null;
|
|
534
|
+
validTime?: string | Date | null;
|
|
535
|
+
/** Set by currentRegimen on an oral fact over 90 days old: kept, but not confirmed as current. */
|
|
536
|
+
unconfirmed?: boolean;
|
|
537
|
+
[key: string]: any;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export interface UnitRegimen {
|
|
541
|
+
/** May be empty; each drug appears once. */
|
|
542
|
+
drugs: string[];
|
|
543
|
+
since: string | null;
|
|
544
|
+
lastApplication: string;
|
|
545
|
+
nextSession: string | null;
|
|
546
|
+
/** false when the unit's last application is over 100 days ago and no session is scheduled: the regimen is history, not treatment. */
|
|
547
|
+
current: boolean;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export interface ChemoContext {
|
|
551
|
+
ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
|
|
552
|
+
esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
|
|
553
|
+
inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
|
|
554
|
+
proximaSesion: { fecha: string; tipo: string; confirmada?: boolean } | null;
|
|
555
|
+
esquemaPrevio: { farmacos: string[]; hasta: string } | null;
|
|
556
|
+
[key: string]: any;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** The chemo unit's record for a patient: null when there is none, undefined when it cannot be read. */
|
|
560
|
+
export function readRecordedChemo(code: string): Promise<ChemoContext | null | undefined>;
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Narrows context-fact rows to the current treatment, preferring the chemo unit's regimen for infused drugs.
|
|
564
|
+
* `today` is a Mexico-time YYYY-MM-DD day. `source` is 'unreadable' when `chemo` is undefined; the facts are still narrowed.
|
|
565
|
+
* Oral facts are always kept (`unconfirmed` past 90 days). Without a unit record, infused and radiotherapy facts are kept within
|
|
566
|
+
* 60 days of the newest treatment fact of any kind. Statuses are not filtered: callers choose which to show.
|
|
567
|
+
*/
|
|
568
|
+
export function currentRegimen(input: { chemo: ChemoContext | null | undefined; facts: ContextFactRow[] | null | undefined; today?: string }): {
|
|
569
|
+
source: 'unit' | 'facts' | 'unreadable' | 'none';
|
|
570
|
+
unit: UnitRegimen | null;
|
|
571
|
+
facts: ContextFactRow[];
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
export interface RegimenClosure {
|
|
575
|
+
conceptKey: string;
|
|
576
|
+
drug: string;
|
|
577
|
+
status: string | null;
|
|
578
|
+
since: string;
|
|
579
|
+
proposedStatus: 'stopped';
|
|
580
|
+
endDate: string;
|
|
581
|
+
endFrom: 'esquemaPrevio' | 'inicioEsquema';
|
|
582
|
+
evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
|
|
586
|
+
export function dryRunRegimenClosures(options?: { today?: string }): Promise<{
|
|
587
|
+
ok: boolean;
|
|
588
|
+
dryRun: true;
|
|
589
|
+
closures: number;
|
|
590
|
+
unreadable: number;
|
|
591
|
+
reason?: string;
|
|
592
|
+
skipped: Record<string, number>;
|
|
593
|
+
patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
|
|
594
|
+
}>;
|
|
595
|
+
|
|
528
596
|
export const routes: any;
|
|
529
597
|
export function setupDefaultRoutes(app: any): void;
|
|
530
598
|
export function createRouter(routeDefinitions: Record<string, string>, controllers: Record<string, Function>): any;
|
|
@@ -940,7 +1008,7 @@ declare module '@peopl-health/nexus' {
|
|
|
940
1008
|
export type SupportLightColor = 'green' | 'yellow' | 'orange' | 'red' | 'unknown';
|
|
941
1009
|
export type SupportLightSource = 'ai' | 'human';
|
|
942
1010
|
export type SupportLightOutcome = 'applied' | 'pending' | 'withdrawn' | 'unchanged';
|
|
943
|
-
export type CollectiveRefusal = 'light_red' | 'light_orange' | 'light_unconfirmed' | 'invitation_paused'
|
|
1011
|
+
export type CollectiveRefusal = 'light_red' | 'light_orange' | 'light_unconfirmed' | 'invitation_paused' | 'individual_therapy'
|
|
944
1012
|
| 'already_invited_this_week' | 'weekly_limit' | 'no_capacity';
|
|
945
1013
|
|
|
946
1014
|
export interface SupportLightEvidence {
|
|
@@ -1042,6 +1110,8 @@ declare module '@peopl-health/nexus' {
|
|
|
1042
1110
|
hasInvitationThisWeek?: boolean;
|
|
1043
1111
|
collectivesThisWeek?: number;
|
|
1044
1112
|
hasCapacity?: boolean;
|
|
1113
|
+
isInIndividualTherapy?: boolean;
|
|
1114
|
+
psychologyColor?: SupportLightColor;
|
|
1045
1115
|
}): { allowed: boolean; reason: CollectiveRefusal | null };
|
|
1046
1116
|
supportWeek(date: Date | string): string | null;
|
|
1047
1117
|
};
|
package/lib/index.js
CHANGED
|
@@ -47,6 +47,9 @@ const { retractContentlessFacts } = require('./clinical/services/contextCleanupS
|
|
|
47
47
|
const { syncLegacyContext } = require('./clinical/services/legacyContextSyncService');
|
|
48
48
|
const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
|
|
49
49
|
const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
|
|
50
|
+
const { currentRegimen } = require('./clinical/services/currentRegimenService');
|
|
51
|
+
const { dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
|
|
52
|
+
const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
|
|
50
53
|
const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
|
|
51
54
|
const { MapCache } = require('./utils/MapCache');
|
|
52
55
|
const supportCandidateService = require('./clinical/services/supportCandidateService');
|
|
@@ -359,6 +362,9 @@ module.exports = {
|
|
|
359
362
|
routes,
|
|
360
363
|
syncClinicalContext,
|
|
361
364
|
runProactiveOutreachSweep,
|
|
365
|
+
currentRegimen,
|
|
366
|
+
dryRunRegimenClosures,
|
|
367
|
+
readRecordedChemo,
|
|
362
368
|
syncContextFacts,
|
|
363
369
|
retractContentlessFacts,
|
|
364
370
|
syncLegacyContext,
|
|
@@ -44,13 +44,14 @@ const impressionUpdateSchema = new mongoose.Schema({
|
|
|
44
44
|
}, { _id: false });
|
|
45
45
|
|
|
46
46
|
const doctorAlertSchema = new mongoose.Schema({
|
|
47
|
-
kind: { type: String, enum: ['initial', 'realert'], required: true },
|
|
47
|
+
kind: { type: String, enum: ['initial', 'realert', 'patient_prompt'], required: true },
|
|
48
48
|
urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
|
|
49
49
|
physicianEmail: { type: String, default: null },
|
|
50
50
|
transport: { type: String, default: null },
|
|
51
51
|
messageId: { type: String, default: null },
|
|
52
52
|
error: { type: String, default: null },
|
|
53
53
|
teamAlerted: { type: Boolean, default: false },
|
|
54
|
+
possiblyDelivered: { type: Boolean, default: false },
|
|
54
55
|
sentAt: { type: Date, required: true },
|
|
55
56
|
}, { _id: false });
|
|
56
57
|
|
|
@@ -198,8 +199,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
198
199
|
draftFailedAt: { type: Date, default: null },
|
|
199
200
|
doctorAlerts: { type: [doctorAlertSchema], default: [] },
|
|
200
201
|
doctorAlertDueAt: { type: Date, default: null },
|
|
201
|
-
doctorAlertKind: { type: String, enum: ['initial', 'realert', null], default: null },
|
|
202
|
+
doctorAlertKind: { type: String, enum: ['initial', 'realert', 'patient_prompt', null], default: null },
|
|
202
203
|
doctorAlertAttempts: { type: Number, default: 0 },
|
|
204
|
+
feverPromptStartedAt: { type: Date, default: null },
|
|
203
205
|
approverViewedAt: { type: Date, default: null },
|
|
204
206
|
previousReviewId: { type: String, default: null },
|
|
205
207
|
callLogs: { type: [callLogSchema], default: [] },
|
|
@@ -216,6 +218,33 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
216
218
|
cancellationReason: { type: String, default: null },
|
|
217
219
|
}, { timestamps: true });
|
|
218
220
|
|
|
221
|
+
// The fields the FHIR case Task is built from; a write that touches one tells the listeners.
|
|
222
|
+
const CASE_FIELDS = ['status', 'closedAt', 'cancellationReason', 'alarms', 'urgencyReclassifications', 'decisions', 'updates', 'followUpCases'];
|
|
223
|
+
const caseWriteListeners = [];
|
|
224
|
+
const onCaseWrite = (listener) => caseWriteListeners.push(listener);
|
|
225
|
+
// A listener failure is logged and never fails the review write that triggered it.
|
|
226
|
+
const notifyCaseWrite = (id) => {
|
|
227
|
+
if (!id) return;
|
|
228
|
+
caseWriteListeners.forEach((listener) => {
|
|
229
|
+
try {
|
|
230
|
+
listener(String(id));
|
|
231
|
+
} catch (error) {
|
|
232
|
+
logger.error('[EscalationReview] A case write listener failed', { escalationReviewId: String(id), error: error.message });
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
};
|
|
236
|
+
const touchesCase = (update = {}) => Array.isArray(update) || Object.entries(update)
|
|
237
|
+
.flatMap(([key, value]) => (key.startsWith('$') ? Object.keys(value ?? {}) : [key]))
|
|
238
|
+
.some((field) => CASE_FIELDS.includes(field.split('.')[0]));
|
|
239
|
+
|
|
240
|
+
escalationReviewSchema.post('save', (doc) => notifyCaseWrite(doc._id));
|
|
241
|
+
escalationReviewSchema.post('findOneAndUpdate', function notifyUpdated(doc) {
|
|
242
|
+
if (doc && touchesCase(this.getUpdate())) notifyCaseWrite(doc._id);
|
|
243
|
+
});
|
|
244
|
+
escalationReviewSchema.post('updateOne', function notifyUpdatedOne(result) {
|
|
245
|
+
if (result?.modifiedCount && touchesCase(this.getUpdate())) notifyCaseWrite(this.getFilter()._id);
|
|
246
|
+
});
|
|
247
|
+
|
|
219
248
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
220
249
|
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
221
250
|
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
@@ -243,4 +272,7 @@ module.exports = {
|
|
|
243
272
|
URGENCY_RANK,
|
|
244
273
|
getEscalationReview,
|
|
245
274
|
escalationReviewSchema,
|
|
275
|
+
notifyCaseWrite,
|
|
276
|
+
onCaseWrite,
|
|
277
|
+
touchesCase,
|
|
246
278
|
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { getEscalationReview, onCaseWrite } = require('../models/escalationReviewModel');
|
|
4
|
+
const { storeEscalationCase } = require('../fhir/services/escalationService');
|
|
5
|
+
const { effectiveUrgencyOf } = require('./reviewDeadlineService');
|
|
6
|
+
|
|
7
|
+
const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'false')).trim().toLowerCase() === 'true';
|
|
8
|
+
|
|
9
|
+
function conditionIdsOf(review) {
|
|
10
|
+
const impressed = (review.updates ?? []).flatMap((update) => (update.impressions ?? []).map((impression) => impression.caseId));
|
|
11
|
+
return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function syncCaseTask(id) {
|
|
15
|
+
const review = await getEscalationReview().findById(id).lean();
|
|
16
|
+
if (!review) return null;
|
|
17
|
+
return storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Syncs of one review run one after another, each reading the review fresh, so the last write carries the last state.
|
|
21
|
+
const inFlight = new Map();
|
|
22
|
+
|
|
23
|
+
function scheduleCaseSync(id) {
|
|
24
|
+
if (!caseTaskLive()) return null;
|
|
25
|
+
const next = (inFlight.get(id) ?? Promise.resolve())
|
|
26
|
+
.then(() => syncCaseTask(id))
|
|
27
|
+
.catch((error) => logger.error('[EscalationCaseTask] The FHIR case was not synced', { escalationReviewId: id, error: error.message }));
|
|
28
|
+
inFlight.set(id, next);
|
|
29
|
+
next.then(() => { if (inFlight.get(id) === next) inFlight.delete(id); }, () => {});
|
|
30
|
+
return next;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
onCaseWrite(scheduleCaseSync);
|
|
34
|
+
|
|
35
|
+
module.exports = { conditionIdsOf, scheduleCaseSync, syncCaseTask };
|