@peopl-health/nexus 5.72.13 → 5.72.15
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/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +3 -2
- package/lib/clinical/providers/BaseLLMProvider.js +2 -1
- package/lib/controllers/patientController.js +2 -2
- package/lib/core/NexusMessaging.js +2 -1
- package/lib/fhir/constants/projectionSlugs.js +2 -0
- package/lib/fhir/index.js +2 -0
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/services/encounterService.js +10 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/models/threadModel.js +1 -0
- package/lib/services/conversationService.js +1 -0
- package/lib/services/escalationReviewService.js +1 -0
- package/lib/services/patientClinicalStatusService.js +60 -14
- package/package.json +1 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// The agent keeps answering an admitted patient; what it should do then lives in the preset, not here.
|
|
2
|
+
function withHospitalization(block, hospitalizedAt) {
|
|
3
|
+
if (!hospitalizedAt) return block;
|
|
4
|
+
const since = new Date(hospitalizedAt).toLocaleDateString('es-MX', { timeZone: 'UTC' });
|
|
5
|
+
return [block, `Situación actual: internado en el hospital desde el ${since} (registrado por el equipo).`].filter(Boolean).join('\n\n');
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
module.exports = { withHospitalization };
|
|
@@ -22,6 +22,7 @@ const { getRecordByFilter } = require('../../services/airtableService');
|
|
|
22
22
|
const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
|
|
23
23
|
const { getMessages, countMessages } = require('../../services/messageService');
|
|
24
24
|
const { hasInstructionInFlight } = require('../../services/instructionInFlightService');
|
|
25
|
+
const { isStaffSend } = require('../../helpers/staffSendHelper');
|
|
25
26
|
const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
|
|
26
27
|
const { CURRENT_TURN } = require('../promptPlacement');
|
|
27
28
|
|
|
@@ -214,8 +215,8 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
214
215
|
return label ? `${CAREGIVER_TURN_PREFIX.slice(0, -1)}: ${label}] ` : `${CAREGIVER_TURN_PREFIX} `;
|
|
215
216
|
}
|
|
216
217
|
if (msg.origin !== 'whatsapp_platform') return '';
|
|
217
|
-
//
|
|
218
|
-
return msg.triggeredBy ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
|
|
218
|
+
// Staff sign what they send with their email; anything else was an automation.
|
|
219
|
+
return isStaffSend(msg.triggeredBy) ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
|
|
219
220
|
}
|
|
220
221
|
|
|
221
222
|
async processResponse(response, thread) {
|
|
@@ -4,6 +4,7 @@ const { DefaultMemoryManager } = require('../memory/DefaultMemoryManager');
|
|
|
4
4
|
const { REFUSAL, isPurelyConversational } = require('../helpers/clinicalWorkflowGuard');
|
|
5
5
|
const { isToolFailure, toolRecoveryContract } = require('../helpers/toolResultHelper');
|
|
6
6
|
const { buildDateAnchor } = require('../helpers/dateAnchorHelper');
|
|
7
|
+
const { withHospitalization } = require('../helpers/hospitalizationContextHelper');
|
|
7
8
|
const { getConversationalTokens } = require('../services/clinicalExtractionService');
|
|
8
9
|
const { composePrompt, resolveTools } = require('../services/promptComposerService');
|
|
9
10
|
const { resolveSkillCatalog } = require('../services/skillService');
|
|
@@ -598,7 +599,7 @@ class BaseLLMProvider {
|
|
|
598
599
|
patientId: thread.code,
|
|
599
600
|
legacyBlock: promptVariables.clinical_context,
|
|
600
601
|
});
|
|
601
|
-
promptVariables.clinical_context = block;
|
|
602
|
+
promptVariables.clinical_context = withHospitalization(block, thread?.hospitalizedAt);
|
|
602
603
|
assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source });
|
|
603
604
|
|
|
604
605
|
const result = await this.runConversation({
|
|
@@ -131,8 +131,8 @@ const updatePatientTaskController = async (req, res) => {
|
|
|
131
131
|
const setPatientClinicalStatusController = async (req, res) => {
|
|
132
132
|
try {
|
|
133
133
|
const { code } = req.params;
|
|
134
|
-
const { status, deceasedOn, updatedBy, source } = req.body || {};
|
|
135
|
-
const result = await setPatientClinicalStatus({ code, status, deceasedOn, updatedBy, source, requestId: req.requestId });
|
|
134
|
+
const { status, deceasedOn, admittedOn, dischargedOn, updatedBy, source } = req.body || {};
|
|
135
|
+
const result = await setPatientClinicalStatus({ code, status, deceasedOn, admittedOn, dischargedOn, updatedBy, source, requestId: req.requestId });
|
|
136
136
|
res.status(200).json({ success: true, ...result });
|
|
137
137
|
} catch (error) {
|
|
138
138
|
logger.error('Error setting patient clinical status:', { error: error.message, code: req.params?.code });
|
|
@@ -22,6 +22,7 @@ const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper')
|
|
|
22
22
|
const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
23
23
|
const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
|
|
24
24
|
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
|
|
25
|
+
const { isStaffSend } = require('../helpers/staffSendHelper');
|
|
25
26
|
|
|
26
27
|
const { createMessagingProvider } = require('../adapters/registry');
|
|
27
28
|
const { ensureThreadExists } = require('../services/threadService');
|
|
@@ -378,7 +379,7 @@ class NexusMessaging {
|
|
|
378
379
|
|
|
379
380
|
async sendMessage(messageData) {
|
|
380
381
|
// Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
|
|
381
|
-
const operatorNow =
|
|
382
|
+
const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
|
|
382
383
|
if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
|
|
383
384
|
const claim = await acquireSendClaim(messageData);
|
|
384
385
|
if (!claim.acquired) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const PATIENT_SLUG = 'patient';
|
|
2
|
+
const ENCOUNTER_SLUG = 'encounter';
|
|
2
3
|
const CONTEXT_FACT_SLUG = 'context-fact';
|
|
3
4
|
const MENTION_SLUG = 'clinical-mention';
|
|
4
5
|
const RESULT_SLUG = 'patient-reported-result';
|
|
@@ -34,6 +35,7 @@ const PALLIATIVE_CAREPLAN_REC_SLUG = 'palliative-careplan-rec';
|
|
|
34
35
|
|
|
35
36
|
module.exports = {
|
|
36
37
|
PATIENT_SLUG,
|
|
38
|
+
ENCOUNTER_SLUG,
|
|
37
39
|
CONTEXT_FACT_SLUG,
|
|
38
40
|
MENTION_SLUG,
|
|
39
41
|
RESULT_SLUG,
|
package/lib/fhir/index.js
CHANGED
|
@@ -27,6 +27,7 @@ const {
|
|
|
27
27
|
} = require('./services/palliativeService');
|
|
28
28
|
const { storeTriage } = require('./services/triageService');
|
|
29
29
|
const { storePatient, storePatientDeceased, readPatient } = require('./services/patientService');
|
|
30
|
+
const { storeHospitalization } = require('./services/encounterService');
|
|
30
31
|
const {
|
|
31
32
|
storeContextFacts, readContextFacts, retractContextFacts, listContextFactPatients,
|
|
32
33
|
} = require('./services/clinicalContextService');
|
|
@@ -86,6 +87,7 @@ module.exports = {
|
|
|
86
87
|
storeTriage,
|
|
87
88
|
storePatient,
|
|
88
89
|
storePatientDeceased,
|
|
90
|
+
storeHospitalization,
|
|
89
91
|
readPatient,
|
|
90
92
|
storeContextFacts,
|
|
91
93
|
readContextFacts,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { fhirId } = require('../helpers/fhirHelper');
|
|
2
|
+
const { identifier, patientReference } = require('../helpers/elementHelper');
|
|
3
|
+
const { ENCOUNTER_SLUG } = require('../constants/projectionSlugs');
|
|
4
|
+
|
|
5
|
+
const INPATIENT_CLASS = {
|
|
6
|
+
coding: [{ system: 'http://terminology.hl7.org/CodeSystem/v3-ActCode', code: 'IMP', display: 'inpatient encounter' }],
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
class Encounter {
|
|
10
|
+
constructor(payload) {
|
|
11
|
+
Object.assign(this, payload);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// One hospital stay, keyed by the patient and the day of admission; a discharge day completes it.
|
|
15
|
+
static fromHospitalization({ patientId, admittedOn, dischargedOn = null }) {
|
|
16
|
+
if (!String(patientId ?? '').trim() || !admittedOn) throw new Error('Encounter requires a patientId and admittedOn');
|
|
17
|
+
const key = `${patientId}|${admittedOn}`;
|
|
18
|
+
return new Encounter({
|
|
19
|
+
resourceType: 'Encounter',
|
|
20
|
+
id: fhirId(key),
|
|
21
|
+
identifier: [identifier(ENCOUNTER_SLUG, key)],
|
|
22
|
+
status: dischargedOn ? 'completed' : 'in-progress',
|
|
23
|
+
class: [INPATIENT_CLASS],
|
|
24
|
+
subject: patientReference(patientId),
|
|
25
|
+
actualPeriod: { start: admittedOn, ...(dischargedOn && { end: dischargedOn }) },
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { Encounter };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const { Encounter } = require('../resources/Encounter');
|
|
2
|
+
const { storeResources } = require('./fhirService');
|
|
3
|
+
|
|
4
|
+
async function storeHospitalization({ patientId, admittedOn, dischargedOn = null }) {
|
|
5
|
+
const encounter = Encounter.fromHospitalization({ patientId, admittedOn, dischargedOn });
|
|
6
|
+
const { stored } = await storeResources([encounter]);
|
|
7
|
+
return { count: stored.length, ids: stored };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
module.exports = { storeHospitalization };
|
|
@@ -14,6 +14,7 @@ const threadSchema = new mongoose.Schema({
|
|
|
14
14
|
pausedAt: { type: Date, default: null },
|
|
15
15
|
deceasedAt: { type: Date, default: null },
|
|
16
16
|
programStatusBeforeDeath: { type: String, default: null },
|
|
17
|
+
hospitalizedAt: { type: Date, default: null },
|
|
17
18
|
doNotAlertThrough: { type: Date, default: null },
|
|
18
19
|
review: { type: Boolean, default: false },
|
|
19
20
|
version: { type: Number, default: null },
|
|
@@ -131,6 +131,7 @@ const processConversations = async (threads, airtableNameMap, openTaskMap, revie
|
|
|
131
131
|
version: thread?.version || null,
|
|
132
132
|
stopped: thread?.stopped ?? false,
|
|
133
133
|
deceasedAt: thread?.deceasedAt || null,
|
|
134
|
+
hospitalizedAt: thread?.hospitalizedAt || null,
|
|
134
135
|
review: thread?.review ?? false,
|
|
135
136
|
unreadCount: thread?.unreadCount || 0,
|
|
136
137
|
messageCount: thread?.messageCount || 0,
|
|
@@ -1018,6 +1018,7 @@ async function takenReason(review, since, timer, ownStart = null) {
|
|
|
1018
1018
|
const thread = await getThreadInfo(review.patientCode, { rethrow: true });
|
|
1019
1019
|
if (!thread) return 'thread_missing';
|
|
1020
1020
|
if (thread.stopped === true) return 'thread_paused';
|
|
1021
|
+
if (thread.hospitalizedAt) return 'patient_hospitalized';
|
|
1021
1022
|
// Staff write from the platform or act through add-instruction / add-msg, always under their email;
|
|
1022
1023
|
// automations (the timer itself included) sign with a name and never count.
|
|
1023
1024
|
const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
|
|
@@ -6,8 +6,8 @@ const { WHATSAPP_PATIENT_CODE } = require('../utils/sanitizerUtils');
|
|
|
6
6
|
|
|
7
7
|
const { Thread } = require('../models/threadModel');
|
|
8
8
|
const { CANCELLABLE_STATUSES } = require('../models/escalationReviewModel');
|
|
9
|
-
|
|
10
9
|
const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
10
|
+
|
|
11
11
|
const { requirePatientIdentity } = require('../clinical/services/patientIdentityService');
|
|
12
12
|
const { standDownAllPendingRows } = require('../clinical/services/clinicalAirtableService');
|
|
13
13
|
const { updateRecordByFilter } = require('./airtableService');
|
|
@@ -19,20 +19,25 @@ const { cancelEscalationReview, listEscalationReviews } = require('./escalationR
|
|
|
19
19
|
|
|
20
20
|
const DECEASED = 'deceased';
|
|
21
21
|
const ACTIVE = 'active';
|
|
22
|
-
const
|
|
22
|
+
const HOSPITALIZED = 'hospitalized';
|
|
23
|
+
const DISCHARGED = 'discharged';
|
|
24
|
+
const STATUSES = [DECEASED, ACTIVE, HOSPITALIZED, DISCHARGED];
|
|
25
|
+
const DECEASED_PROGRAM_STATUS = 'falleció';
|
|
23
26
|
const DECEASED_REASON = 'Paciente fallecido';
|
|
24
27
|
const ISO_DAY_RX = /^\d{4}-\d{2}-\d{2}$/;
|
|
25
28
|
|
|
26
|
-
function
|
|
29
|
+
function pastDayOf(value, field) {
|
|
27
30
|
const day = String(value ?? '').trim();
|
|
28
31
|
const date = new Date(`${day}T00:00:00Z`);
|
|
29
32
|
if (!ISO_DAY_RX.test(day) || Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== day) {
|
|
30
|
-
throw httpError(400,
|
|
33
|
+
throw httpError(400, `${field} must be a YYYY-MM-DD date`);
|
|
31
34
|
}
|
|
32
|
-
if (date.getTime() > Date.now()) throw httpError(400,
|
|
35
|
+
if (date.getTime() > Date.now()) throw httpError(400, `${field} cannot be in the future`);
|
|
33
36
|
return day;
|
|
34
37
|
}
|
|
35
38
|
|
|
39
|
+
const dayStart = (day) => new Date(`${day}T00:00:00Z`);
|
|
40
|
+
|
|
36
41
|
// Returns the program status the row had before this write.
|
|
37
42
|
async function writeProgramStatus(code, fields) {
|
|
38
43
|
const { recordId, record } = await requirePatientIdentity(Historial_Clinico_ID, code);
|
|
@@ -80,13 +85,19 @@ async function markThreadFields(code, fields) {
|
|
|
80
85
|
if (!matchedCount) throw new Error('the patient has no thread');
|
|
81
86
|
}
|
|
82
87
|
|
|
88
|
+
async function writeFhirHospitalization(code, stay) {
|
|
89
|
+
if (!patientResourceWriteLive()) return;
|
|
90
|
+
const { storeHospitalization } = require('../fhir');
|
|
91
|
+
await storeHospitalization({ patientId: code, ...stay });
|
|
92
|
+
}
|
|
93
|
+
|
|
83
94
|
async function markDeceased({ code, deceasedOn, updatedBy, source, requestId }) {
|
|
84
|
-
const previous = await writeProgramStatus(code, { actual_status_program:
|
|
95
|
+
const previous = await writeProgramStatus(code, { actual_status_program: DECEASED_PROGRAM_STATUS, fecha_fallecimiento: deceasedOn });
|
|
85
96
|
|
|
86
97
|
const failed = [];
|
|
87
98
|
// A repeated mark keeps the status the patient had before the first one.
|
|
88
|
-
const kept = previous ===
|
|
89
|
-
await attempt('mark_thread', failed, () => markThreadFields(code, { deceasedAt:
|
|
99
|
+
const kept = previous === DECEASED_PROGRAM_STATUS ? {} : { programStatusBeforeDeath: previous };
|
|
100
|
+
await attempt('mark_thread', failed, () => markThreadFields(code, { deceasedAt: dayStart(deceasedOn), ...kept }));
|
|
90
101
|
// Unread cases leave the review to close only what the team already saw, never everything it covers.
|
|
91
102
|
const caseIds = await attempt('read_cases', failed, () => openCaseIds(code));
|
|
92
103
|
// A cancelled review resumes the bot it paused, so the reviews go before the pause.
|
|
@@ -111,22 +122,57 @@ async function markActive({ code }) {
|
|
|
111
122
|
return { status: ACTIVE, failed };
|
|
112
123
|
}
|
|
113
124
|
|
|
114
|
-
|
|
125
|
+
// Only the 15-minute urgencias prompt stops while the patient is in hospital; everything else still reaches them.
|
|
126
|
+
async function markHospitalized({ code, admittedOn }) {
|
|
127
|
+
const thread = await Thread.findOne({ code }, { hospitalizedAt: 1 }).lean();
|
|
128
|
+
const current = thread?.hospitalizedAt?.toISOString().slice(0, 10);
|
|
129
|
+
if (current && current !== admittedOn) throw httpError(409, `The patient is already hospitalized since ${current}`);
|
|
130
|
+
await writeProgramStatus(code, { internado_desde: admittedOn });
|
|
131
|
+
const failed = [];
|
|
132
|
+
await attempt('mark_thread', failed, () => markThreadFields(code, { hospitalizedAt: dayStart(admittedOn) }));
|
|
133
|
+
await attempt('fhir_encounter', failed, () => writeFhirHospitalization(code, { admittedOn }));
|
|
134
|
+
return { status: HOSPITALIZED, admittedOn, failed };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function markDischarged({ code, dischargedOn }) {
|
|
138
|
+
const thread = await Thread.findOne({ code }, { hospitalizedAt: 1 }).lean();
|
|
139
|
+
if (!thread?.hospitalizedAt) throw httpError(409, 'The patient is not hospitalized');
|
|
140
|
+
const admittedOn = thread.hospitalizedAt.toISOString().slice(0, 10);
|
|
141
|
+
if (dischargedOn < admittedOn) throw httpError(400, 'dischargedOn cannot be before the admission');
|
|
142
|
+
|
|
143
|
+
await writeProgramStatus(code, { internado_desde: null });
|
|
144
|
+
const failed = [];
|
|
145
|
+
await attempt('clear_thread', failed, () => markThreadFields(code, { hospitalizedAt: null }));
|
|
146
|
+
await attempt('fhir_encounter', failed, () => writeFhirHospitalization(code, { admittedOn, dischargedOn }));
|
|
147
|
+
return { status: DISCHARGED, admittedOn, dischargedOn, failed };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function applyStatus({ code, status, deceasedOn, admittedOn, dischargedOn, updatedBy, source, requestId }) {
|
|
151
|
+
if (status === DECEASED) return markDeceased({ code, deceasedOn: pastDayOf(deceasedOn, 'deceasedOn'), updatedBy, source, requestId });
|
|
152
|
+
if (status === HOSPITALIZED) return markHospitalized({ code, admittedOn: pastDayOf(admittedOn, 'admittedOn') });
|
|
153
|
+
if (status === DISCHARGED) return markDischarged({ code, dischargedOn: pastDayOf(dischargedOn, 'dischargedOn') });
|
|
154
|
+
return markActive({ code });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function setPatientClinicalStatus({ code, status, deceasedOn, admittedOn, dischargedOn, updatedBy, source, requestId = null }) {
|
|
115
158
|
const whatsappId = String(code || '').trim();
|
|
116
159
|
if (!WHATSAPP_PATIENT_CODE.test(whatsappId)) throw httpError(400, 'A whatsapp:+<digits> patient code is required');
|
|
117
160
|
if (!updatedBy || !source) throw httpError(400, 'updatedBy and source are required');
|
|
118
|
-
if (!
|
|
161
|
+
if (!STATUSES.includes(status)) throw httpError(400, `Unknown status: ${status}`);
|
|
119
162
|
|
|
120
|
-
const result = status
|
|
121
|
-
? await markDeceased({ code: whatsappId, deceasedOn: deceasedDayOf(deceasedOn), updatedBy, source, requestId })
|
|
122
|
-
: await markActive({ code: whatsappId });
|
|
163
|
+
const result = await applyStatus({ code: whatsappId, status, deceasedOn, admittedOn, dischargedOn, updatedBy, source, requestId });
|
|
123
164
|
|
|
124
165
|
await logPatientChange({
|
|
125
166
|
code: whatsappId,
|
|
126
167
|
updatedBy,
|
|
127
168
|
source,
|
|
128
169
|
requestId,
|
|
129
|
-
changes: {
|
|
170
|
+
changes: {
|
|
171
|
+
clinicalStatus: status,
|
|
172
|
+
...(result.deceasedOn && { deceasedOn: result.deceasedOn }),
|
|
173
|
+
...(result.admittedOn && { admittedOn: result.admittedOn }),
|
|
174
|
+
...(result.dischargedOn && { dischargedOn: result.dischargedOn }),
|
|
175
|
+
},
|
|
130
176
|
status: result.failed.length ? 'partial' : 'success',
|
|
131
177
|
});
|
|
132
178
|
return result;
|