@peopl-health/nexus 5.71.23 → 5.71.25
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/helpers/drugIdentityHelper.js +12 -5
- package/lib/clinical/services/regimenCloserService.js +29 -10
- package/lib/controllers/escalationReviewController.js +19 -16
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/projectionSlugs.js +6 -0
- package/lib/fhir/helpers/terminologyHelper.js +1 -0
- package/lib/fhir/index.js +2 -1
- package/lib/fhir/projections/clinicalMentionProjection.js +3 -2
- package/lib/fhir/resources/Task.js +41 -0
- package/lib/fhir/services/escalationService.js +13 -0
- package/lib/models/escalationReviewModel.js +47 -0
- package/lib/services/escalationCaseTaskService.js +77 -0
- package/lib/services/escalationReviewService.js +5 -14
- package/lib/services/patientTaskService.js +3 -9
- package/lib/services/reviewBoardService.js +2 -0
- package/package.json +1 -1
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
const { foldAccents } = require('../../utils/formatUtils');
|
|
2
2
|
|
|
3
3
|
const MAX_ALIAS_WORDS = 4;
|
|
4
|
-
const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b)\s
|
|
4
|
+
const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b|\bm[aá]s\b|\bplus\b)\s*/i;
|
|
5
5
|
// a dose or a route left between separators ("100 MG / 20 ML en 500 ML glucosado", "IV/SC") names no drug
|
|
6
6
|
const DOSE_OR_ROUTE = /^(\d+|iv|sc|im|vo|po|ev|mg|ml|mcg|ui)(\s|$)/;
|
|
7
|
+
// beside a drug, only a dose, a route, or how it is formulated or scheduled says nothing about another drug
|
|
8
|
+
const DOSE_OR_ROUTE_WORD = /^(\d+(mg|ml|mcg|g|ui)?|iv|sc|im|vo|po|ev|mg|ml|mcg|ui|g)$/;
|
|
7
9
|
|
|
8
10
|
// one key for a brand, a Spanish and an English spelling: ciclofosfamida and cyclophosphamide meet
|
|
9
11
|
const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
|
|
@@ -14,6 +16,9 @@ const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
|
|
|
14
16
|
.replace(/\s+/g, ' ')
|
|
15
17
|
.trim();
|
|
16
18
|
|
|
19
|
+
const FORM_OR_SCHEDULE = new Set(['monodroga', 'semanal', 'liposomal', 'pegilada', 'lar', 'depot', 'pfs', 'jeringa'].map(drugKey));
|
|
20
|
+
const describesDose = (word) => DOSE_OR_ROUTE_WORD.test(word) || FORM_OR_SCHEDULE.has(word);
|
|
21
|
+
|
|
17
22
|
const lines = (text) => String(text ?? '').split(/[\n,;]+/).map((line) => line.trim()).filter(Boolean);
|
|
18
23
|
|
|
19
24
|
function buildDrugIdentity(catalog) {
|
|
@@ -34,24 +39,26 @@ function buildDrugIdentity(catalog) {
|
|
|
34
39
|
|
|
35
40
|
function genericsInPart(words, identity) {
|
|
36
41
|
const found = new Set();
|
|
42
|
+
let stray = false;
|
|
37
43
|
for (let at = 0; at < words.length;) {
|
|
38
44
|
let span = Math.min(MAX_ALIAS_WORDS, words.length - at);
|
|
39
45
|
for (; span > 0 && !identity.aliases.has(words.slice(at, at + span).join(' ')); span -= 1);
|
|
40
46
|
if (span) found.add(identity.aliases.get(words.slice(at, at + span).join(' ')));
|
|
47
|
+
else if (!describesDose(words[at])) stray = true;
|
|
41
48
|
at += span || 1;
|
|
42
49
|
}
|
|
43
|
-
return found;
|
|
50
|
+
return { found, stray };
|
|
44
51
|
}
|
|
45
52
|
|
|
46
|
-
// every drug the text names; unresolved when some part
|
|
53
|
+
// every drug the text names; unresolved when some part names none the catalog knows, or names one beside an unknown word
|
|
47
54
|
function drugsNamed(text, identity) {
|
|
48
55
|
const whole = identity.aliases.get(drugKey(text));
|
|
49
56
|
if (whole) return { drugs: [identity.generics.get(whole)], unresolved: false };
|
|
50
57
|
const keys = new Set();
|
|
51
58
|
let unresolved = false;
|
|
52
59
|
for (const part of String(text ?? '').split(PART_SEPARATORS).map(drugKey).filter(Boolean)) {
|
|
53
|
-
const found = genericsInPart(part.split(' '), identity);
|
|
54
|
-
if (
|
|
60
|
+
const { found, stray } = genericsInPart(part.split(' '), identity);
|
|
61
|
+
if (found.size ? stray : !DOSE_OR_ROUTE.test(part)) unresolved = true;
|
|
55
62
|
found.forEach((key) => keys.add(key));
|
|
56
63
|
}
|
|
57
64
|
return { drugs: [...keys].map((key) => identity.generics.get(key)), unresolved: unresolved || !keys.size };
|
|
@@ -6,27 +6,38 @@ const { Quimio_Ops_ID } = require('../../config/airtableConfig');
|
|
|
6
6
|
const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
|
|
7
7
|
const { readContextFacts, listContextFactPatients } = require('../../fhir');
|
|
8
8
|
const { mapConcurrent } = require('../../utils/concurrencyUtils');
|
|
9
|
-
const { mexicoDay } = require('../../utils/dateUtils');
|
|
9
|
+
const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
10
10
|
const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
|
|
11
11
|
const { logger } = require('../../utils/logger');
|
|
12
12
|
|
|
13
13
|
const CATALOG_TABLE = 'catalogo_farmacos';
|
|
14
14
|
const CATALOG_FIELDS = ['farmaco', 'variantes', 'generico', 'grupo'];
|
|
15
|
-
|
|
15
|
+
// the oncology sign-off of 2026-10-14 sets these windows and lists
|
|
16
|
+
const LAST_APPLICATION_DAYS = 60;
|
|
17
|
+
const REGIMEN_MIN_DAYS = 21;
|
|
18
|
+
// a checkpoint inhibitor is often given every 6 weeks, or held for an immune toxicity
|
|
19
|
+
const CHECKPOINT_REGIMEN_MIN_DAYS = 84;
|
|
16
20
|
const INJECTABLE_VARIABLE = 'injectable_onco_summary';
|
|
17
|
-
const CURRENT_STATUSES = new Set([null, 'taking', 'unknown'
|
|
21
|
+
const CURRENT_STATUSES = new Set([null, 'taking', 'unknown']);
|
|
18
22
|
const PROPOSED_STATUS = 'stopped';
|
|
19
23
|
// the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
|
|
20
24
|
const CLOSABLE_GROUP = 'Quimioterapia';
|
|
21
|
-
// in that group but oral, a hormone depot, or given outside the unit
|
|
25
|
+
// in that group but oral, a hormone depot, a rescue or protector, or given outside the unit
|
|
22
26
|
const NEVER_CLOSED = new Set([
|
|
23
|
-
'capecitabina', 'darolutamida', 'degarelix', 'fulvestrant', 'goserelina', 'leuprorelina', '
|
|
24
|
-
'octreotida', 'bacilo de Calmette-Guérin', 'ácido folínico',
|
|
27
|
+
'capecitabina', 'darolutamida', 'degarelix', 'fulvestrant', 'goserelina', 'leuprorelina', 'triptorelina',
|
|
28
|
+
'histrelina', 'buserelina', 'lanreotida', 'octreotida', 'pasireotida', 'bacilo de Calmette-Guérin', 'ácido folínico',
|
|
29
|
+
'levofolinato', 'mesna', 'dexrazoxano',
|
|
30
|
+
].map(drugKey));
|
|
31
|
+
const CHECKPOINT_INHIBITORS = new Set([
|
|
32
|
+
'pembrolizumab', 'nivolumab', 'atezolizumab', 'durvalumab', 'avelumab', 'cemiplimab', 'dostarlimab',
|
|
33
|
+
'tislelizumab', 'toripalimab', 'retifanlimab', 'sintilimab', 'camrelizumab', 'serplulimab', 'cosibelimab',
|
|
34
|
+
'ipilimumab', 'tremelimumab',
|
|
25
35
|
].map(drugKey));
|
|
26
36
|
const DEFAULT_PATIENT_CONCURRENCY = 10;
|
|
27
37
|
|
|
28
38
|
// a co-formulation such as pertuzumab/trastuzumab is each of its drugs
|
|
29
39
|
const keysOf = (drug) => drug.generic.split('/').map(drugKey);
|
|
40
|
+
const isCheckpoint = (key) => CHECKPOINT_INHIBITORS.has(key);
|
|
30
41
|
const closable = (drug) => drug.group === CLOSABLE_GROUP && !NEVER_CLOSED.has(drugKey(drug.generic));
|
|
31
42
|
// the day as stated: a date-only report is stored at UTC midnight, which Mexico time would move to the day before
|
|
32
43
|
const dayOf = (row) => {
|
|
@@ -39,13 +50,15 @@ async function loadDrugIdentity() {
|
|
|
39
50
|
return catalog?.length ? buildDrugIdentity(catalog) : null;
|
|
40
51
|
}
|
|
41
52
|
|
|
42
|
-
function skipReason(row, { chemo, identity, regimen }) {
|
|
53
|
+
function skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass }) {
|
|
43
54
|
const named = drugsNamed(row.concept ?? row.value, identity);
|
|
44
55
|
if (named.unresolved) return 'unresolved';
|
|
45
56
|
if (named.drugs.flatMap(keysOf).some((key) => regimen.has(key))) return 'in-regimen';
|
|
46
57
|
if (!named.drugs.every(closable)) return 'never-closed';
|
|
47
58
|
const since = dayOf(row);
|
|
48
59
|
if (!since || since >= chemo.inicioEsquema.fecha) return 'not-before-regimen';
|
|
60
|
+
const checkpoint = named.drugs.flatMap(keysOf).some(isCheckpoint);
|
|
61
|
+
if (checkpoint && !replacedInClass && regimenDays < CHECKPOINT_REGIMEN_MIN_DAYS) return 'checkpoint-too-recent';
|
|
49
62
|
return null;
|
|
50
63
|
}
|
|
51
64
|
|
|
@@ -62,10 +75,15 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
|
|
|
62
75
|
const none = (reason) => ({ closures: [], skipped: { [reason]: 1 } });
|
|
63
76
|
if (chemo === undefined) return none('chemo-unreadable');
|
|
64
77
|
if (!chemo?.inicioEsquema) return none('no-regimen-start');
|
|
65
|
-
const status = chemoStatus(chemo, today,
|
|
78
|
+
const status = chemoStatus(chemo, today, LAST_APPLICATION_DAYS);
|
|
66
79
|
if (!status.active) return none('inactive');
|
|
67
80
|
// a scheduled session keeps a regimen active, but an old last application is no evidence of what it is now
|
|
68
|
-
if (status.days >
|
|
81
|
+
if (status.days > LAST_APPLICATION_DAYS) return none('stale-regimen');
|
|
82
|
+
// a drug given on day 8 or every three weeks may not have come up yet in a younger regimen
|
|
83
|
+
const regimenDays = daysBetween(chemo.inicioEsquema.fecha, today);
|
|
84
|
+
if (regimenDays < REGIMEN_MIN_DAYS) return none('regimen-too-recent');
|
|
85
|
+
// without a previous regimen the start is only the first recorded session, so a second one must show the regimen
|
|
86
|
+
if (!chemo.esquemaPrevio && !(chemo.ultimaAplicacion.fecha > chemo.inicioEsquema.fecha)) return none('single-session-regimen');
|
|
69
87
|
const named = chemo.esquema.map((entry) => drugsNamed(entry.farmaco, identity));
|
|
70
88
|
// a drug of the regimen the catalog cannot name could be the very drug of a slot
|
|
71
89
|
if (named.some((entry) => entry.unresolved)) return none('unresolved-regimen');
|
|
@@ -73,11 +91,12 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
|
|
|
73
91
|
// a depot or support visit is no evidence the antineoplastic line changed
|
|
74
92
|
if (!regimenDrugs.some(closable)) return none('no-closable-regimen');
|
|
75
93
|
const regimen = new Set(regimenDrugs.flatMap(keysOf));
|
|
94
|
+
const replacedInClass = [...regimen].some(isCheckpoint);
|
|
76
95
|
const closures = [];
|
|
77
96
|
const skipped = {};
|
|
78
97
|
for (const row of facts) {
|
|
79
98
|
if (row.variableId !== INJECTABLE_VARIABLE || !CURRENT_STATUSES.has(row.status ?? null)) continue;
|
|
80
|
-
const reason = skipReason(row, { chemo, identity, regimen });
|
|
99
|
+
const reason = skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass });
|
|
81
100
|
if (reason) {
|
|
82
101
|
skipped[reason] = (skipped[reason] ?? 0) + 1;
|
|
83
102
|
continue;
|
|
@@ -22,6 +22,7 @@ const {
|
|
|
22
22
|
syncEscalationReviewCase,
|
|
23
23
|
} = require('../services/escalationReviewService');
|
|
24
24
|
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
25
|
+
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
25
26
|
|
|
26
27
|
const respondWithError = (res, error, action, context) => {
|
|
27
28
|
logger.error(`Error ${action}:`, {
|
|
@@ -32,6 +33,8 @@ const respondWithError = (res, error, action, context) => {
|
|
|
32
33
|
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
33
34
|
};
|
|
34
35
|
|
|
36
|
+
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
37
|
+
|
|
35
38
|
const openEscalationReviewController = async (req, res) => {
|
|
36
39
|
try {
|
|
37
40
|
const { code, patientCaseRecordId = null, patientCaseRecordIds = null, triggeredBy } = req.body || {};
|
|
@@ -42,7 +45,7 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
42
45
|
openedBy: triggeredBy,
|
|
43
46
|
requestId: req.requestId,
|
|
44
47
|
});
|
|
45
|
-
res.status(created ? 201 : 200).json({ success: true, review });
|
|
48
|
+
res.status(created ? 201 : 200).json({ success: true, review: withCaseStatus(review) });
|
|
46
49
|
} catch (error) {
|
|
47
50
|
respondWithError(res, error, 'opening escalation review', { code: redactDirectIdentifiers(String(req.body?.code || '')) });
|
|
48
51
|
}
|
|
@@ -51,7 +54,7 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
51
54
|
const getEscalationReviewController = async (req, res) => {
|
|
52
55
|
try {
|
|
53
56
|
const { review, isApprover, responseDeadline } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
54
|
-
res.status(200).json({ success: true, review, isApprover, responseDeadline });
|
|
57
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline });
|
|
55
58
|
} catch (error) {
|
|
56
59
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
57
60
|
}
|
|
@@ -69,7 +72,7 @@ const getReviewTimelineController = async (req, res) => {
|
|
|
69
72
|
const listEscalationReviewsController = async (req, res) => {
|
|
70
73
|
try {
|
|
71
74
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
72
|
-
res.status(200).json({ success: true, reviews });
|
|
75
|
+
res.status(200).json({ success: true, reviews: reviews.map(withCaseStatus) });
|
|
73
76
|
} catch (error) {
|
|
74
77
|
respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
|
|
75
78
|
}
|
|
@@ -88,7 +91,7 @@ const setEscalationReviewCasesController = async (req, res) => {
|
|
|
88
91
|
try {
|
|
89
92
|
const { patientCaseRecordIds, triggeredBy } = req.body || {};
|
|
90
93
|
const review = await setReviewCases({ id: req.params.id, patientCaseRecordIds, updatedBy: triggeredBy, requestId: req.requestId });
|
|
91
|
-
res.status(200).json({ success: true, review });
|
|
94
|
+
res.status(200).json({ success: true, review: withCaseStatus(review) });
|
|
92
95
|
} catch (error) {
|
|
93
96
|
respondWithError(res, error, 'selecting escalation review cases', { reviewId: req.params?.id });
|
|
94
97
|
}
|
|
@@ -98,7 +101,7 @@ const addEscalationReviewCallLogController = async (req, res) => {
|
|
|
98
101
|
try {
|
|
99
102
|
const { outcome, notes, calledAt, triggeredBy } = req.body || {};
|
|
100
103
|
const review = await addCallLog({ id: req.params.id, outcome, notes, calledAt, loggedBy: triggeredBy, requestId: req.requestId });
|
|
101
|
-
res.status(201).json({ success: true, review });
|
|
104
|
+
res.status(201).json({ success: true, review: withCaseStatus(review) });
|
|
102
105
|
} catch (error) {
|
|
103
106
|
respondWithError(res, error, 'logging escalation review call', { reviewId: req.params?.id });
|
|
104
107
|
}
|
|
@@ -110,7 +113,7 @@ const confirmEscalationReviewNoteFactsController = async (req, res) => {
|
|
|
110
113
|
const review = await confirmNoteFacts({
|
|
111
114
|
id: req.params.id, accepted, declined, confirmedBy: triggeredBy, requestId: req.requestId,
|
|
112
115
|
});
|
|
113
|
-
res.status(200).json({ success: true, review });
|
|
116
|
+
res.status(200).json({ success: true, review: withCaseStatus(review) });
|
|
114
117
|
} catch (error) {
|
|
115
118
|
respondWithError(res, error, 'confirming escalation review note facts', { reviewId: req.params?.id });
|
|
116
119
|
}
|
|
@@ -130,7 +133,7 @@ const requestEscalationReviewDraftController = async (req, res) => {
|
|
|
130
133
|
try {
|
|
131
134
|
const { triggeredBy } = req.body || {};
|
|
132
135
|
const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
|
|
133
|
-
res.status(202).json({ success: true, review });
|
|
136
|
+
res.status(202).json({ success: true, review: withCaseStatus(review) });
|
|
134
137
|
} catch (error) {
|
|
135
138
|
respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
|
|
136
139
|
}
|
|
@@ -150,7 +153,7 @@ const addEscalationReviewDraftController = async (req, res) => {
|
|
|
150
153
|
try {
|
|
151
154
|
const { doctorText, patientMessage, triggeredBy } = req.body || {};
|
|
152
155
|
const review = await addDraft({ id: req.params.id, doctorText, patientMessage, writtenBy: triggeredBy, requestId: req.requestId });
|
|
153
|
-
res.status(201).json({ success: true, review });
|
|
156
|
+
res.status(201).json({ success: true, review: withCaseStatus(review) });
|
|
154
157
|
} catch (error) {
|
|
155
158
|
respondWithError(res, error, 'saving escalation review draft', { reviewId: req.params?.id });
|
|
156
159
|
}
|
|
@@ -160,7 +163,7 @@ const handOffEscalationReviewController = async (req, res) => {
|
|
|
160
163
|
try {
|
|
161
164
|
const { mode, physicianEmail = null, triggeredBy } = req.body || {};
|
|
162
165
|
const { review, caseMirror, caseMirrors } = await handOffToDoctor({ id: req.params.id, mode, physicianEmail, sentBy: triggeredBy, requestId: req.requestId });
|
|
163
|
-
res.status(201).json({ success: true, review, caseMirror, caseMirrors });
|
|
166
|
+
res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
164
167
|
} catch (error) {
|
|
165
168
|
respondWithError(res, error, 'handing escalation review to doctor', { reviewId: req.params?.id });
|
|
166
169
|
}
|
|
@@ -192,7 +195,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
192
195
|
recordedBy: triggeredBy,
|
|
193
196
|
requestId: req.requestId,
|
|
194
197
|
});
|
|
195
|
-
res.status(201).json({ success: true, review });
|
|
198
|
+
res.status(201).json({ success: true, review: withCaseStatus(review) });
|
|
196
199
|
} catch (error) {
|
|
197
200
|
respondWithError(res, error, 'recording escalation review decision', { reviewId: req.params?.id });
|
|
198
201
|
}
|
|
@@ -202,7 +205,7 @@ const sendEscalationReviewIndicationsController = async (req, res) => {
|
|
|
202
205
|
try {
|
|
203
206
|
const { outsideWindowRoute = null, triggeredBy } = req.body || {};
|
|
204
207
|
const { review, caseMirror, caseMirrors } = await sendApprovedIndications({ id: req.params.id, outsideWindowRoute, sentBy: triggeredBy, requestId: req.requestId });
|
|
205
|
-
res.status(201).json({ success: true, review, caseMirror, caseMirrors });
|
|
208
|
+
res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
206
209
|
} catch (error) {
|
|
207
210
|
respondWithError(res, error, 'sending escalation review indications', { reviewId: req.params?.id });
|
|
208
211
|
}
|
|
@@ -218,7 +221,7 @@ const closeEscalationReviewController = async (req, res) => {
|
|
|
218
221
|
interruptionNotes,
|
|
219
222
|
requestId: req.requestId,
|
|
220
223
|
});
|
|
221
|
-
res.status(200).json({ success: true, review, caseMirror, caseMirrors });
|
|
224
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
222
225
|
} catch (error) {
|
|
223
226
|
respondWithError(res, error, 'closing escalation review', { reviewId: req.params?.id });
|
|
224
227
|
}
|
|
@@ -234,7 +237,7 @@ const reclassifyEscalationReviewUrgencyController = async (req, res) => {
|
|
|
234
237
|
reclassifiedBy: triggeredBy,
|
|
235
238
|
requestId: req.requestId,
|
|
236
239
|
});
|
|
237
|
-
res.status(200).json({ success: true, review, responseDeadline });
|
|
240
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), responseDeadline });
|
|
238
241
|
} catch (error) {
|
|
239
242
|
respondWithError(res, error, 'reclassifying escalation review urgency', { reviewId: req.params?.id });
|
|
240
243
|
}
|
|
@@ -249,7 +252,7 @@ const cancelEscalationReviewController = async (req, res) => {
|
|
|
249
252
|
reason,
|
|
250
253
|
requestId: req.requestId,
|
|
251
254
|
});
|
|
252
|
-
res.status(200).json({ success: true, review, caseMirror, caseMirrors });
|
|
255
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
253
256
|
} catch (error) {
|
|
254
257
|
respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
|
|
255
258
|
}
|
|
@@ -260,10 +263,10 @@ const syncEscalationReviewCaseController = async (req, res) => {
|
|
|
260
263
|
const { triggeredBy } = req.body || {};
|
|
261
264
|
const { review, caseMirror, caseMirrors } = await syncEscalationReviewCase({ id: req.params.id, syncedBy: triggeredBy, requestId: req.requestId });
|
|
262
265
|
if (caseMirror === 'failed' || caseMirror === 'partial') {
|
|
263
|
-
res.status(502).json({ success: false, error: 'The patient case could not be updated', review, caseMirror, caseMirrors });
|
|
266
|
+
res.status(502).json({ success: false, error: 'The patient case could not be updated', review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
264
267
|
return;
|
|
265
268
|
}
|
|
266
|
-
res.status(200).json({ success: true, review, caseMirror, caseMirrors });
|
|
269
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
267
270
|
} catch (error) {
|
|
268
271
|
respondWithError(res, error, 'syncing escalation review case', { reviewId: req.params?.id });
|
|
269
272
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const CASE = (status, businessStatus, label) => ({ status, businessStatus, label });
|
|
2
|
+
|
|
3
|
+
const POR_REVISAR = CASE('requested', 'por-revisar', 'Por revisar');
|
|
4
|
+
const EN_EVALUACION = CASE('in-progress', 'en-evaluacion', 'En evaluación');
|
|
5
|
+
const CON_MEDICO = CASE('in-progress', 'con-medico', 'Con el médico');
|
|
6
|
+
const POR_ENVIAR = CASE('in-progress', 'indicacion-por-enviar', 'Indicación por enviar');
|
|
7
|
+
|
|
8
|
+
const CASE_STATUS_BY_REVIEW_STATUS = Object.freeze({
|
|
9
|
+
open: POR_REVISAR,
|
|
10
|
+
documenting: EN_EVALUACION,
|
|
11
|
+
draft_ready: EN_EVALUACION,
|
|
12
|
+
returned: EN_EVALUACION,
|
|
13
|
+
handing_off: CON_MEDICO,
|
|
14
|
+
awaiting_doctor: CON_MEDICO,
|
|
15
|
+
approved: POR_ENVIAR,
|
|
16
|
+
sending: POR_ENVIAR,
|
|
17
|
+
needs_intervention: CASE('in-progress', 'requiere-valoracion', 'Requiere valoración'),
|
|
18
|
+
indications_queued: CASE('on-hold', 'esperando-paciente', 'Esperando paciente'),
|
|
19
|
+
indications_sent: CASE('in-progress', 'indicaciones-dadas', 'Indicaciones dadas'),
|
|
20
|
+
monitoring: CASE('in-progress', 'en-vigilancia', 'En vigilancia'),
|
|
21
|
+
closed: CASE('completed', 'cerrado', 'Cerrado'),
|
|
22
|
+
cancelled: CASE('cancelled', 'no-requiere', 'No requiere'),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function caseStatusOf(reviewStatus) {
|
|
26
|
+
const caseStatus = CASE_STATUS_BY_REVIEW_STATUS[reviewStatus];
|
|
27
|
+
if (!caseStatus) throw new Error(`no case status for review status ${reviewStatus}`);
|
|
28
|
+
return caseStatus;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = { CASE_STATUS_BY_REVIEW_STATUS, caseStatusOf };
|
|
@@ -4,6 +4,9 @@ const MENTION_SLUG = 'clinical-mention';
|
|
|
4
4
|
const RESULT_SLUG = 'patient-reported-result';
|
|
5
5
|
const ESCALATION_SLUG = 'dispatched-escalation';
|
|
6
6
|
const ESCALATION_KIND_SLUG = 'escalation-kind';
|
|
7
|
+
const ESCALATION_CASE_SLUG = 'escalation-case';
|
|
8
|
+
const ESCALATION_CASE_STATUS_SLUG = 'escalation-case-status';
|
|
9
|
+
const ESCALATION_DECISION_SLUG = 'escalation-decision';
|
|
7
10
|
const REMINDER_SLUG = 'reminder';
|
|
8
11
|
const REMINDER_KIND_SLUG = 'reminder-kind';
|
|
9
12
|
const COMMUNICATION_CHANNEL_SLUG = 'communication-channel';
|
|
@@ -36,6 +39,9 @@ module.exports = {
|
|
|
36
39
|
RESULT_SLUG,
|
|
37
40
|
ESCALATION_SLUG,
|
|
38
41
|
ESCALATION_KIND_SLUG,
|
|
42
|
+
ESCALATION_CASE_SLUG,
|
|
43
|
+
ESCALATION_CASE_STATUS_SLUG,
|
|
44
|
+
ESCALATION_DECISION_SLUG,
|
|
39
45
|
REMINDER_SLUG,
|
|
40
46
|
REMINDER_KIND_SLUG,
|
|
41
47
|
COMMUNICATION_CHANNEL_SLUG,
|
package/lib/fhir/index.js
CHANGED
|
@@ -15,7 +15,7 @@ const {
|
|
|
15
15
|
recordRecommendationReview,
|
|
16
16
|
} = require('./services/recommendationService');
|
|
17
17
|
const { storeContingency, readContingencies } = require('./services/contingencyService');
|
|
18
|
-
const { readDispatchedEscalations } = require('./services/escalationService');
|
|
18
|
+
const { readDispatchedEscalations, storeEscalationCase } = require('./services/escalationService');
|
|
19
19
|
const { storeIntervention, readInterventions } = require('./services/interventionService');
|
|
20
20
|
const { storeCluster, readClusters } = require('./services/clusterService');
|
|
21
21
|
const { storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
|
|
@@ -70,6 +70,7 @@ module.exports = {
|
|
|
70
70
|
storeContingency,
|
|
71
71
|
readContingencies,
|
|
72
72
|
readDispatchedEscalations,
|
|
73
|
+
storeEscalationCase,
|
|
73
74
|
storeIntervention,
|
|
74
75
|
readInterventions,
|
|
75
76
|
storeCluster,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { getDeviceId, getOrganizationId, getSystems } = require('../config/fhirConfig');
|
|
2
2
|
const { stringifyValue } = require('../utils/normalizeUtils');
|
|
3
|
-
const { fhirId } = require('../helpers/fhirHelper');
|
|
3
|
+
const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
|
|
4
|
+
const { ctcaeSlug } = require('../helpers/terminologyHelper');
|
|
4
5
|
const { reference, patientReference, codeableConcept, extension, toInstant } = require('../helpers/elementHelper');
|
|
5
6
|
const { baseResource, problemListCategory, observationCategory } = require('../helpers/resourceHelper');
|
|
6
7
|
const { MENTION_SLUG } = require('../constants/projectionSlugs');
|
|
@@ -48,7 +49,7 @@ function primaryResource(mention) {
|
|
|
48
49
|
|
|
49
50
|
function mentionCode(fact) {
|
|
50
51
|
return fact.ctcaeTerm
|
|
51
|
-
? codeableConcept(fact.canonicalTerm, { code: fact.ctcaeTerm, system:
|
|
52
|
+
? codeableConcept(fact.canonicalTerm, { code: ctcaeSlug(fact.ctcaeTerm), system: codeSystemUrl('ctcae-v5-term'), display: fact.ctcaeTerm })
|
|
52
53
|
: codeableConcept(fact.canonicalTerm);
|
|
53
54
|
}
|
|
54
55
|
|
|
@@ -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',
|
|
@@ -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
|
};
|
|
@@ -216,14 +216,56 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
216
216
|
closedBy: { type: String, default: null },
|
|
217
217
|
closedAt: { type: Date, default: null },
|
|
218
218
|
cancellationReason: { type: String, default: null },
|
|
219
|
+
caseStatusMirror: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
219
220
|
}, { timestamps: true });
|
|
220
221
|
|
|
222
|
+
// The fields the FHIR case Task is built from; a write that touches one tells the listeners.
|
|
223
|
+
const CASE_FIELDS = ['status', 'closedAt', 'cancellationReason', 'alarms', 'urgencyReclassifications', 'decisions', 'updates', 'followUpCases'];
|
|
224
|
+
const caseWriteListeners = [];
|
|
225
|
+
const onCaseWrite = (listener) => caseWriteListeners.push(listener);
|
|
226
|
+
// A listener failure is logged and never fails the review write that triggered it.
|
|
227
|
+
const notifyCaseWrite = (id) => {
|
|
228
|
+
if (!id) return;
|
|
229
|
+
caseWriteListeners.forEach((listener) => {
|
|
230
|
+
try {
|
|
231
|
+
listener(String(id));
|
|
232
|
+
} catch (error) {
|
|
233
|
+
logger.error('[EscalationReview] A case write listener failed', { escalationReviewId: String(id), error: error.message });
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
};
|
|
237
|
+
const touchesCase = (update = {}) => Array.isArray(update) || Object.entries(update)
|
|
238
|
+
.flatMap(([key, value]) => (key.startsWith('$') ? Object.keys(value ?? {}) : [key]))
|
|
239
|
+
.some((field) => CASE_FIELDS.includes(field.split('.')[0]));
|
|
240
|
+
|
|
241
|
+
escalationReviewSchema.post('save', (doc) => notifyCaseWrite(doc._id));
|
|
242
|
+
escalationReviewSchema.post('findOneAndUpdate', function notifyUpdated(doc) {
|
|
243
|
+
if (doc && touchesCase(this.getUpdate())) notifyCaseWrite(doc._id);
|
|
244
|
+
});
|
|
245
|
+
escalationReviewSchema.post('updateOne', function notifyUpdatedOne(result) {
|
|
246
|
+
if (result?.modifiedCount && touchesCase(this.getUpdate())) notifyCaseWrite(this.getFilter()._id);
|
|
247
|
+
});
|
|
248
|
+
|
|
221
249
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
222
250
|
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
223
251
|
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
224
252
|
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
225
253
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
226
254
|
|
|
255
|
+
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
256
|
+
? review.patientCaseRecordIds
|
|
257
|
+
: (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
|
|
258
|
+
|
|
259
|
+
// A closed review leaves the cases the patient's open review now holds to that review.
|
|
260
|
+
async function supersededCaseIds(EscalationReview, review) {
|
|
261
|
+
if (!review.closedAt) return new Set();
|
|
262
|
+
const owner = await EscalationReview
|
|
263
|
+
.findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
|
|
264
|
+
.lean();
|
|
265
|
+
if (!owner || String(owner._id) === String(review._id)) return new Set();
|
|
266
|
+
return new Set(caseIdsOf(owner));
|
|
267
|
+
}
|
|
268
|
+
|
|
227
269
|
const getEscalationReview = () => {
|
|
228
270
|
const dbName = getModelDatabase('EscalationReview');
|
|
229
271
|
const db = dbName ? getDb(dbName) : mongoose;
|
|
@@ -245,4 +287,9 @@ module.exports = {
|
|
|
245
287
|
URGENCY_RANK,
|
|
246
288
|
getEscalationReview,
|
|
247
289
|
escalationReviewSchema,
|
|
290
|
+
notifyCaseWrite,
|
|
291
|
+
onCaseWrite,
|
|
292
|
+
touchesCase,
|
|
293
|
+
caseIdsOf,
|
|
294
|
+
supersededCaseIds,
|
|
248
295
|
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { isShadowRun } = require('../utils/shadowScope');
|
|
4
|
+
const { caseIdsOf, getEscalationReview, onCaseWrite, supersededCaseIds } = require('../models/escalationReviewModel');
|
|
5
|
+
const { storeEscalationCase } = require('../fhir/services/escalationService');
|
|
6
|
+
const { caseStatusOf } = require('../fhir/constants/escalationCaseStatus');
|
|
7
|
+
const { effectiveUrgencyOf } = require('./reviewDeadlineService');
|
|
8
|
+
const { updatePatientTask } = require('./patientTaskService');
|
|
9
|
+
|
|
10
|
+
const MIRROR_OPERATOR = 'bot:escalationCase';
|
|
11
|
+
const MIRROR_SOURCE = 'escalation_case';
|
|
12
|
+
|
|
13
|
+
const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'false')).trim().toLowerCase() === 'true';
|
|
14
|
+
|
|
15
|
+
function conditionIdsOf(review) {
|
|
16
|
+
const impressed = (review.updates ?? []).flatMap((update) => (update.impressions ?? []).map((impression) => impression.caseId));
|
|
17
|
+
return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// The linked Airtable cases show the stored Task's status in status_operaciones; only a change is written.
|
|
21
|
+
async function mirrorToCases(review) {
|
|
22
|
+
const { businessStatus, label } = caseStatusOf(review.status);
|
|
23
|
+
const superseded = await supersededCaseIds(getEscalationReview(), review);
|
|
24
|
+
const recordIds = caseIdsOf(review).filter((recordId) => !superseded.has(recordId));
|
|
25
|
+
const mirrored = review.caseStatusMirror;
|
|
26
|
+
const pending = recordIds.filter((recordId) => mirrored?.businessStatus !== businessStatus || !mirrored.recordIds?.includes(recordId));
|
|
27
|
+
if (!pending.length) return;
|
|
28
|
+
const settled = [];
|
|
29
|
+
for (const recordId of pending) {
|
|
30
|
+
try {
|
|
31
|
+
await updatePatientTask({
|
|
32
|
+
code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
|
|
33
|
+
});
|
|
34
|
+
settled.push(recordId);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// A case of another patient or program is never written; it is settled rather than retried on every sync.
|
|
37
|
+
if (error?.statusCode === 404) {
|
|
38
|
+
logger.warn('[EscalationCaseTask] The linked case is not this patient\'s program case; it is left as is', { escalationReviewId: String(review._id), recordId });
|
|
39
|
+
settled.push(recordId);
|
|
40
|
+
} else {
|
|
41
|
+
logger.error('[EscalationCaseTask] The case status did not reach the Airtable case', { escalationReviewId: String(review._id), recordId, error: error.message });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!settled.length) return;
|
|
46
|
+
const kept = mirrored?.businessStatus === businessStatus ? mirrored.recordIds ?? [] : [];
|
|
47
|
+
await getEscalationReview().updateOne(
|
|
48
|
+
{ _id: review._id },
|
|
49
|
+
{ $set: { caseStatusMirror: { businessStatus, recordIds: [...new Set([...kept, ...settled])] } } },
|
|
50
|
+
{ timestamps: false },
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function syncCaseTask(id) {
|
|
55
|
+
const review = await getEscalationReview().findById(id).lean();
|
|
56
|
+
if (!review) return null;
|
|
57
|
+
const stored = await storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
|
|
58
|
+
await mirrorToCases(review);
|
|
59
|
+
return stored;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Syncs of one review run one after another, each reading the review fresh, so the last write carries the last state.
|
|
63
|
+
const inFlight = new Map();
|
|
64
|
+
|
|
65
|
+
function scheduleCaseSync(id) {
|
|
66
|
+
if (!caseTaskLive() || isShadowRun()) return null;
|
|
67
|
+
const next = (inFlight.get(id) ?? Promise.resolve())
|
|
68
|
+
.then(() => syncCaseTask(id))
|
|
69
|
+
.catch((error) => logger.error('[EscalationCaseTask] The FHIR case was not synced', { escalationReviewId: id, error: error.message }));
|
|
70
|
+
inFlight.set(id, next);
|
|
71
|
+
next.then(() => { if (inFlight.get(id) === next) inFlight.delete(id); }, () => {});
|
|
72
|
+
return next;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
onCaseWrite(scheduleCaseSync);
|
|
76
|
+
|
|
77
|
+
module.exports = { caseTaskLive, conditionIdsOf, scheduleCaseSync, syncCaseTask };
|
|
@@ -18,7 +18,9 @@ const {
|
|
|
18
18
|
RETURN_REASONS,
|
|
19
19
|
URGENCY_LEVELS,
|
|
20
20
|
URGENCY_RANK,
|
|
21
|
+
caseIdsOf,
|
|
21
22
|
getEscalationReview,
|
|
23
|
+
supersededCaseIds,
|
|
22
24
|
} = require('../models/escalationReviewModel');
|
|
23
25
|
const { getPatientAuditLog } = require('../models/patientAuditLogModel');
|
|
24
26
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
@@ -48,6 +50,7 @@ const { countMessages } = require('./messageService');
|
|
|
48
50
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
49
51
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
50
52
|
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
53
|
+
const { caseTaskLive } = require('./escalationCaseTaskService');
|
|
51
54
|
|
|
52
55
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
53
56
|
|
|
@@ -124,10 +127,6 @@ const configured = (key) => {
|
|
|
124
127
|
const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
|
|
125
128
|
const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
|
|
126
129
|
|
|
127
|
-
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
128
|
-
? review.patientCaseRecordIds
|
|
129
|
-
: (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
|
|
130
|
-
|
|
131
130
|
const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
|
|
132
131
|
|
|
133
132
|
const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
|
|
@@ -222,15 +221,6 @@ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus
|
|
|
222
221
|
throw httpError(409, STATUS_CONFLICT);
|
|
223
222
|
}
|
|
224
223
|
|
|
225
|
-
async function supersededCaseIds(EscalationReview, review) {
|
|
226
|
-
if (!review.closedAt) return new Set();
|
|
227
|
-
const owner = await EscalationReview
|
|
228
|
-
.findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
|
|
229
|
-
.lean();
|
|
230
|
-
if (!owner || String(owner._id) === String(review._id)) return new Set();
|
|
231
|
-
return new Set(caseIdsOf(owner));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
224
|
const summarise = (outcomes) => {
|
|
235
225
|
if (!outcomes.length) return 'skipped';
|
|
236
226
|
if (outcomes.every((outcome) => outcome.status === 'superseded')) return 'superseded';
|
|
@@ -1633,7 +1623,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
1633
1623
|
$addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
|
|
1634
1624
|
$unset: { identityBlock: '' },
|
|
1635
1625
|
};
|
|
1636
|
-
|
|
1626
|
+
// With the case Task live, the case's operations status comes from the Task; the clinical status stays clinical.
|
|
1627
|
+
const recordUpdate = caseTaskLive() ? handoff : withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
|
|
1637
1628
|
updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
|
|
1638
1629
|
} catch (error) {
|
|
1639
1630
|
await releaseReview(reviewId, 'handing_off', review.status, claim);
|
|
@@ -18,6 +18,7 @@ const {
|
|
|
18
18
|
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
|
|
19
19
|
const { logPatientChange } = require('../services/patientService');
|
|
20
20
|
const { clearOpenTaskSummary } = require('../services/patientTaskSummaryService');
|
|
21
|
+
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
21
22
|
|
|
22
23
|
const MAX_ROWS = 50;
|
|
23
24
|
const MAX_NOTE_LENGTH = 5000;
|
|
@@ -58,15 +59,8 @@ const CASE_STATUSES = [
|
|
|
58
59
|
'radioterapia_revisión',
|
|
59
60
|
'internado',
|
|
60
61
|
];
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
'coordinación médica',
|
|
64
|
-
'síntoma marcado',
|
|
65
|
-
'pendiente',
|
|
66
|
-
'notificado ops',
|
|
67
|
-
'notificado medical',
|
|
68
|
-
'sin caracterizar',
|
|
69
|
-
];
|
|
62
|
+
// The operations status of a case is its FHIR case Task status, the same vocabulary nexus mirrors.
|
|
63
|
+
const OPERATIONS_STATUSES = [...new Set(Object.values(CASE_STATUS_BY_REVIEW_STATUS).map(({ label }) => label))];
|
|
70
64
|
|
|
71
65
|
const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
|
|
72
66
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { httpError } = require('../utils/httpErrorUtils');
|
|
2
2
|
const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
3
|
|
|
4
|
+
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
4
5
|
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
5
6
|
|
|
6
7
|
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -31,6 +32,7 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
|
31
32
|
patientCode: review.patientCode,
|
|
32
33
|
bucket,
|
|
33
34
|
status: review.status,
|
|
35
|
+
caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null,
|
|
34
36
|
urgency: lead?.urgency || null,
|
|
35
37
|
symptom: lead?.symptom || null,
|
|
36
38
|
alarmCount: alarms.length,
|