@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20074
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/AssistantProcessor.js +3 -1
- package/lib/clinical/config/planTextsConfig.js +41 -0
- package/lib/clinical/flags/escalationFlags.js +15 -0
- package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +72 -2
- package/lib/clinical/helpers/legacyContextHelper.js +6 -2
- package/lib/clinical/helpers/planTextHelper.js +9 -2
- package/lib/clinical/protocols/treatmentFormulary.js +3 -3
- package/lib/clinical/services/bridgeService.js +2 -2
- package/lib/clinical/services/checkInDueService.js +3 -2
- package/lib/clinical/services/clinicalAirtableService.js +3 -2
- package/lib/clinical/services/clinicalExtractionService.js +9 -2
- package/lib/clinical/services/contingencyDispatchService.js +8 -4
- package/lib/clinical/services/doctorPlanService.js +27 -11
- package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
- package/lib/config/awsConfig.js +1 -1
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/escalationReviewController.js +16 -3
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +16 -18
- package/lib/fhir/constants/escalationCaseStatus.js +1 -1
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/helpers/templateFlowControllerHelper.js +9 -48
- package/lib/index.d.ts +3 -3
- package/lib/models/escalationReviewModel.js +32 -2
- package/lib/services/assistantMessageService.js +11 -6
- package/lib/services/caseFollowUpService.js +226 -0
- package/lib/services/caseFollowUpSweepService.js +89 -0
- package/lib/services/characterizationOutcomeService.js +27 -15
- package/lib/services/escalationCaseStateService.js +68 -0
- package/lib/services/escalationReviewService.js +123 -37
- package/lib/services/flowDataExchangeService.js +6 -35
- package/lib/services/reviewAlertSweepService.js +19 -1
- package/lib/services/reviewBoardService.js +24 -6
- package/lib/services/reviewDeadlineService.js +1 -1
- package/lib/services/untakenAlertService.js +9 -7
- package/lib/services/watchExpiryService.js +162 -0
- package/lib/utils/coercionUtils.js +5 -1
- package/lib/utils/textMatchUtils.js +52 -18
- package/package.json +1 -1
|
@@ -9,7 +9,7 @@ const EMPTY_OUTBOUND_FALLBACK = 'Recibí tu mensaje. Si quieres contarme más o
|
|
|
9
9
|
const definition = {
|
|
10
10
|
name: 'DeliverPatientMessage',
|
|
11
11
|
replayArgs: ['message_text', 'purpose'],
|
|
12
|
-
description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`
|
|
12
|
+
description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`Indicación en cola`, `Indicaciones dadas`, `En vigilancia`).\n\n**When you relay what a doctor indicated:** name the doctor the team instruction names, even when it is not the `Médico tratante` of the clinical context. Saying the treating doctor reviewed the case when another doctor did tells the patient something false.\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
|
|
13
13
|
strict: false,
|
|
14
14
|
parameters: {
|
|
15
15
|
type: 'object',
|
|
@@ -5,7 +5,7 @@ const { logger } = require('../../utils/logger');
|
|
|
5
5
|
|
|
6
6
|
const definition = {
|
|
7
7
|
name: 'getPatientRiskAssessment',
|
|
8
|
-
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `
|
|
8
|
+
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Indicación en cola`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `plan_approved` = the doctor gave a structured plan, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**How to use:** read `turn_focus.current_concerns`, then each `relevant_risks[].checks_now` and `escalation_threshold`. It preserves concurrent symptoms. Any `selection` containing `fallback` marks a precaution to check, not a confirmed explanation. When `selection` is `no_current_concerns` the patient reported no current symptom this turn. Use `profile` only for supporting detail.\n\n**`profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `turn_focus.current_concerns`.\n\n**Returns:** `status` — `final` when an assessment exists and carries findings, `no_signal` when one exists but the synthesis found nothing usable, or `not_generated`; `turn_focus`, always present; and the full `profile` (`predicted_aes[]`, `disease_risks[]`, `comorbidity_amplifiers[]`, lifecycle and missing-information fields). `profile` is null when not yet generated.',
|
|
9
9
|
strict: false,
|
|
10
10
|
replayScope: 'turn',
|
|
11
11
|
parameters: {
|
|
@@ -10,7 +10,7 @@ const REQUIRED_SECTION = 'risk';
|
|
|
10
10
|
|
|
11
11
|
const definition = {
|
|
12
12
|
name: 'getRouterContextBundle',
|
|
13
|
-
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `
|
|
13
|
+
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Indicación en cola`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `plan_approved` = the doctor gave a structured plan, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
|
|
14
14
|
strict: false,
|
|
15
15
|
replayScope: 'turn',
|
|
16
16
|
parameters: {
|
|
@@ -9,6 +9,7 @@ const { logger } = require('../../utils/logger');
|
|
|
9
9
|
const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
|
|
10
10
|
const { botIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
11
11
|
const { setCheckInsPausedUntil, checkInsPausedUntil } = require('../../services/threadService');
|
|
12
|
+
const { caseFollowUpMoveRefusal, isCaseFollowUpId, recordCaseFollowUpMoved } = require('../../services/caseFollowUpService');
|
|
12
13
|
|
|
13
14
|
const definition = {
|
|
14
15
|
name: 'schedulePatientReminder',
|
|
@@ -152,6 +153,10 @@ async function handler(args = {}, context = {}) {
|
|
|
152
153
|
if (actionType === 'update' && targetId && runtime.patientCode && !await isReminderPending({ code: runtime.patientCode, reminderId: targetId })) {
|
|
153
154
|
return JSON.stringify({ success: false, error: 'reminder_not_active — that reminder already went out or was stood down, so it cannot be updated. If a check is still needed, create a new one.', data: { reminder_id: targetId } });
|
|
154
155
|
}
|
|
156
|
+
if (actionType === 'update' && targetId && isCaseFollowUpId(targetId) && runtime.patientCode) {
|
|
157
|
+
const refusal = await caseFollowUpMoveRefusal({ code: runtime.patientCode, reminderId: targetId, fireAt: fireMoment.toDate() });
|
|
158
|
+
if (refusal) return JSON.stringify({ success: false, error: refusal, data: { reminder_id: targetId } });
|
|
159
|
+
}
|
|
155
160
|
if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
|
|
156
161
|
if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
|
|
157
162
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
@@ -215,6 +220,7 @@ async function handler(args = {}, context = {}) {
|
|
|
215
220
|
}
|
|
216
221
|
return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
|
|
217
222
|
}
|
|
223
|
+
if (actionType === 'update' && isCaseFollowUpId(reminderId)) await recordCaseFollowUpMoved({ code: runtime.patientCode, reminderId, dueAt: fireMoment.toDate() });
|
|
218
224
|
}
|
|
219
225
|
|
|
220
226
|
trace.setSignals({ reminderIntents: [...existing, intent] });
|
|
@@ -258,7 +264,7 @@ async function pauseCheckIns(args, runtime) {
|
|
|
258
264
|
}
|
|
259
265
|
if (patientCode && !isShadowRun()) {
|
|
260
266
|
await setCheckInsPausedUntil(patientCode, until.toDate());
|
|
261
|
-
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused' })) {
|
|
267
|
+
if (!await cancelPendingFollowUps({ code: patientCode, trace, reason: 'patient_paused', includeCaseFollowUp: true })) {
|
|
262
268
|
logger.warn('[schedulePatientReminder] pending seguimientos were not retired on pause', { patientCode });
|
|
263
269
|
}
|
|
264
270
|
}
|
|
@@ -274,6 +280,9 @@ async function cancelSeguimiento(args, runtime) {
|
|
|
274
280
|
}
|
|
275
281
|
const { patientCode, trace } = runtime;
|
|
276
282
|
const notPending = () => JSON.stringify({ success: false, error: 'not_pending — only a pending seguimiento listed under «Seguimientos ya programados» can be cancelled.', data: { reminder_id: reminderId } });
|
|
283
|
+
if (isCaseFollowUpId(reminderId)) {
|
|
284
|
+
return JSON.stringify({ success: false, error: 'case_follow_up — this seguimiento follows up the doctor\'s indications and ends when the case closes, not when the patient replies. If she asked to be written at another time, move it with update.', data: { reminder_id: reminderId } });
|
|
285
|
+
}
|
|
277
286
|
if (!reminderId.startsWith('followup_')) return notPending();
|
|
278
287
|
if (patientCode) {
|
|
279
288
|
const pending = await readPendingFollowUpsForPatient({ code: patientCode });
|
package/lib/config/awsConfig.js
CHANGED
|
@@ -91,7 +91,7 @@ async function generatePresignedUrl(bucketName, key, expiration = 3000) {
|
|
|
91
91
|
|
|
92
92
|
try {
|
|
93
93
|
const url = await s3.getSignedUrlPromise('getObject', params);
|
|
94
|
-
logger.info(
|
|
94
|
+
logger.info('Presigned URL generated');
|
|
95
95
|
return url;
|
|
96
96
|
} catch (error) {
|
|
97
97
|
logger.error(`Error generating presigned URL: ${error.message}`);
|
|
@@ -4,6 +4,7 @@ const { DUPLICATE_INSTRUCTION_WINDOW_MS } = require('../config/instructionConfig
|
|
|
4
4
|
|
|
5
5
|
const { logger } = require('../utils/logger');
|
|
6
6
|
const { isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
7
|
+
const { registeredCaregiverCode } = require('../helpers/caregiverHelper');
|
|
7
8
|
const { AssistantMessageError, injectAssistantMessages } = require('../services/assistantMessageService');
|
|
8
9
|
|
|
9
10
|
const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
|
|
@@ -60,11 +61,13 @@ const doNotAlertController = async (req, res) => {
|
|
|
60
61
|
};
|
|
61
62
|
|
|
62
63
|
const addInsAssistantController = async (req, res) => {
|
|
63
|
-
const { code, instruction, triggeredBy } = req.body;
|
|
64
|
+
const { code, instruction, triggeredBy, contactCode } = req.body;
|
|
64
65
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
65
66
|
|
|
66
67
|
try {
|
|
67
|
-
const
|
|
68
|
+
const caregiverCode = contactCode ? await registeredCaregiverCode(code, contactCode) : null;
|
|
69
|
+
if (contactCode && !caregiverCode) return res.status(400).json({ success: false, error: 'contactCode is not a registered caregiver of this patient' });
|
|
70
|
+
const result = await processInstruction(code, instruction, 'developer', { triggeredBy, dedupeWithinMs: DUPLICATE_INSTRUCTION_WINDOW_MS, ...(caregiverCode && { contactCode: caregiverCode }) });
|
|
68
71
|
if (result?.outcome === 'duplicate') {
|
|
69
72
|
return res.status(200).json({ success: true, duplicate: true, message: 'Instruction already answered' });
|
|
70
73
|
}
|
|
@@ -23,6 +23,8 @@ const {
|
|
|
23
23
|
syncEscalationReviewCase,
|
|
24
24
|
} = require('../services/escalationReviewService');
|
|
25
25
|
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
26
|
+
const { caseStateOf } = require('../services/escalationCaseStateService');
|
|
27
|
+
const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
|
|
26
28
|
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
27
29
|
|
|
28
30
|
const respondWithError = (res, error, action, context) => {
|
|
@@ -34,6 +36,12 @@ const respondWithError = (res, error, action, context) => {
|
|
|
34
36
|
res.status(error.statusCode || 500).json({ success: false, error: error.message, ...(error.errorCode && { errorCode: error.errorCode }) });
|
|
35
37
|
};
|
|
36
38
|
|
|
39
|
+
// The review still reads when its case state cannot be worked out.
|
|
40
|
+
const safeCaseStateOf = (review) => caseStateOf(review, { policy: responseDeadlinePolicy() }).catch((error) => {
|
|
41
|
+
logger.warn('[EscalationReview] Could not read the case state', { escalationReviewId: String(review?._id), error: redactDirectIdentifiers(String(error?.message || error)) });
|
|
42
|
+
return null;
|
|
43
|
+
});
|
|
44
|
+
|
|
37
45
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
38
46
|
|
|
39
47
|
const openEscalationReviewController = async (req, res) => {
|
|
@@ -55,7 +63,8 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
55
63
|
const getEscalationReviewController = async (req, res) => {
|
|
56
64
|
try {
|
|
57
65
|
const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
58
|
-
|
|
66
|
+
const caseState = await safeCaseStateOf(review);
|
|
67
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers });
|
|
59
68
|
} catch (error) {
|
|
60
69
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
61
70
|
}
|
|
@@ -63,7 +72,7 @@ const getEscalationReviewController = async (req, res) => {
|
|
|
63
72
|
|
|
64
73
|
const previewEscalationReviewPlanController = async (req, res) => {
|
|
65
74
|
try {
|
|
66
|
-
const instructions = previewPlanInstructions({ id: req.params.id, plan: req.body?.plan });
|
|
75
|
+
const instructions = await previewPlanInstructions({ id: req.params.id, plan: req.body?.plan });
|
|
67
76
|
res.status(200).json({ success: true, instructions });
|
|
68
77
|
} catch (error) {
|
|
69
78
|
respondWithError(res, error, 'previewing the plan instructions', { reviewId: req.params?.id });
|
|
@@ -82,7 +91,11 @@ const getReviewTimelineController = async (req, res) => {
|
|
|
82
91
|
const listEscalationReviewsController = async (req, res) => {
|
|
83
92
|
try {
|
|
84
93
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
85
|
-
|
|
94
|
+
// Only the open review gets its state, so the panel's poll stays fresh without reading the review as seen.
|
|
95
|
+
const listed = await Promise.all(reviews.map(async (review) => (review.closedAt
|
|
96
|
+
? withCaseStatus(review)
|
|
97
|
+
: { ...withCaseStatus(review), caseState: await safeCaseStateOf(review) })));
|
|
98
|
+
res.status(200).json({ success: true, reviews: listed });
|
|
86
99
|
} catch (error) {
|
|
87
100
|
respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
|
|
88
101
|
}
|
|
@@ -9,9 +9,9 @@ const { ScheduledMessage } = require('../models/agendaMessageModel.js');
|
|
|
9
9
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
|
|
10
10
|
const { FlowRouting } = require('../models/flowRoutingModel.js');
|
|
11
11
|
|
|
12
|
-
const { ensureWhatsAppFormat,
|
|
12
|
+
const { ensureWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twilioHelper');
|
|
13
13
|
const { ensureFlowTokenInVariables } = require('../helpers/templateFlowControllerHelper');
|
|
14
|
-
const { CAREGIVER_ROLE,
|
|
14
|
+
const { CAREGIVER_ROLE, registeredCaregiverCode } = require('../helpers/caregiverHelper');
|
|
15
15
|
|
|
16
16
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
17
17
|
const { getMessages } = require('../services/messageService');
|
|
@@ -105,12 +105,11 @@ const sendMessageController = async (req, res) => {
|
|
|
105
105
|
if (sendTime) {
|
|
106
106
|
return res.status(400).json({ success: false, error: 'contactCode cannot be combined with sendTime' });
|
|
107
107
|
}
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
if (!caregiver || stripWhatsAppFormat(caregiver.patientCode) !== stripWhatsAppFormat(formattedCode)) {
|
|
108
|
+
const caregiverCode = await registeredCaregiverCode(formattedCode, contactCode);
|
|
109
|
+
if (!caregiverCode) {
|
|
111
110
|
return res.status(400).json({ success: false, error: 'contactCode is not a registered caregiver of this patient' });
|
|
112
111
|
}
|
|
113
|
-
contact = { contactCode:
|
|
112
|
+
contact = { contactCode: caregiverCode, contactRole: CAREGIVER_ROLE };
|
|
114
113
|
}
|
|
115
114
|
|
|
116
115
|
const finalVariables = contentSid ? await ensureFlowTokenInVariables(contentSid, variables) : variables;
|
|
@@ -18,7 +18,7 @@ const { Thread } = require('../models/threadModel');
|
|
|
18
18
|
|
|
19
19
|
const { storeRunMetrics } = require('../helpers/metricsHelper');
|
|
20
20
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
21
|
-
const { maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
|
|
21
|
+
const { CAREGIVER_ROLE, maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
|
|
22
22
|
const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
|
|
23
23
|
const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
24
24
|
const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
|
|
@@ -519,10 +519,6 @@ class NexusMessaging {
|
|
|
519
519
|
|
|
520
520
|
async sendAssistantReply(messageData) {
|
|
521
521
|
if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
|
|
522
|
-
if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
|
|
523
|
-
const contact = await replyContactFor(messageData.code);
|
|
524
|
-
if (contact) messageData = { ...messageData, ...contact };
|
|
525
|
-
}
|
|
526
522
|
if (messageData.outreachStartedAt) {
|
|
527
523
|
const patientActivity = await getMessages({
|
|
528
524
|
numero: messageData.code,
|
|
@@ -740,7 +736,7 @@ class NexusMessaging {
|
|
|
740
736
|
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
741
737
|
|
|
742
738
|
try {
|
|
743
|
-
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
|
|
739
|
+
const result = await this._processMessages(from, async () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true, ...(await replyContactFor(from)) } }));
|
|
744
740
|
await this.assistantProcessor.sendResponse(from, result);
|
|
745
741
|
} catch (error) {
|
|
746
742
|
logger.error('Error in handleMessageWithAssistant', { error: error.message });
|
|
@@ -753,7 +749,7 @@ class NexusMessaging {
|
|
|
753
749
|
if (this.batchingManager.isDraining()) return { deferred: true, reason: 'draining' };
|
|
754
750
|
|
|
755
751
|
try {
|
|
756
|
-
const result = await this._processMessages(from, () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true } }));
|
|
752
|
+
const result = await this._processMessages(from, async () => this.assistantProcessor.process({ code: from, runOptions: { patientTurn: true, ...(await replyContactFor(from)) } }));
|
|
757
753
|
await this.assistantProcessor.sendResponse(from, result);
|
|
758
754
|
} catch (error) {
|
|
759
755
|
logger.error('Error in handleMediaWithAssistant', { error: error.message });
|
|
@@ -858,7 +854,7 @@ class NexusMessaging {
|
|
|
858
854
|
|
|
859
855
|
const result = await this.assistantProcessor.executeLLM(
|
|
860
856
|
resolved.thread, resolved.assistant,
|
|
861
|
-
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
857
|
+
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId), ...(await replyContactFor(chatId)) },
|
|
862
858
|
preProcessed.messages[0]
|
|
863
859
|
);
|
|
864
860
|
|
|
@@ -886,8 +882,8 @@ class NexusMessaging {
|
|
|
886
882
|
* batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
|
|
887
883
|
* run behind its own gate.
|
|
888
884
|
*/
|
|
889
|
-
async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0 } = {}) {
|
|
890
|
-
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs)) {
|
|
885
|
+
async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null, dedupeWithinMs = 0, contactCode = null } = {}) {
|
|
886
|
+
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, null, contactCode)) {
|
|
891
887
|
logger.info('[processInstruction] Identical instruction already answered; skipping the resend', { code, triggeredBy: triggeredBy || null });
|
|
892
888
|
return { outcome: 'duplicate' };
|
|
893
889
|
}
|
|
@@ -903,6 +899,7 @@ class NexusMessaging {
|
|
|
903
899
|
raw: beforeRun ? { role, gated: true } : { role },
|
|
904
900
|
triggeredBy: triggeredBy || null,
|
|
905
901
|
silent: true,
|
|
902
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
906
903
|
};
|
|
907
904
|
|
|
908
905
|
beginInstruction(code);
|
|
@@ -950,13 +947,13 @@ class NexusMessaging {
|
|
|
950
947
|
return null;
|
|
951
948
|
}
|
|
952
949
|
}
|
|
953
|
-
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id)) {
|
|
950
|
+
if (dedupeWithinMs > 0 && await this._instructionAnsweredRecently(code, instruction, dedupeWithinMs, _id, contactCode)) {
|
|
954
951
|
logger.info('[processInstruction] Identical instruction answered while this one waited; skipping it', { code, triggeredBy: triggeredBy || null });
|
|
955
952
|
duplicate = true;
|
|
956
953
|
await markOwnProcessed();
|
|
957
954
|
return null;
|
|
958
955
|
}
|
|
959
|
-
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
|
|
956
|
+
const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt, contactCode);
|
|
960
957
|
if (!batch.length) {
|
|
961
958
|
logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
|
|
962
959
|
alreadyAnswered = true;
|
|
@@ -970,6 +967,7 @@ class NexusMessaging {
|
|
|
970
967
|
additionalInstructions: batch.map(m => m.body).join('\n\n'),
|
|
971
968
|
toolChoice: 'none',
|
|
972
969
|
turnKind: TURN_KIND.OPERATOR_INSTRUCTION,
|
|
970
|
+
...(contactCode && { contactCode, contactRole: CAREGIVER_ROLE }),
|
|
973
971
|
runId,
|
|
974
972
|
shouldContinue,
|
|
975
973
|
signal: this.batchingManager.getAbortSignal(runId),
|
|
@@ -1020,7 +1018,7 @@ class NexusMessaging {
|
|
|
1020
1018
|
}
|
|
1021
1019
|
}
|
|
1022
1020
|
|
|
1023
|
-
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null) {
|
|
1021
|
+
async _instructionAnsweredRecently(code, instruction, windowMs, ownId = null, contactCode = null) {
|
|
1024
1022
|
try {
|
|
1025
1023
|
const rows = await getMessages(
|
|
1026
1024
|
{
|
|
@@ -1028,6 +1026,7 @@ class NexusMessaging {
|
|
|
1028
1026
|
origin: 'instruction',
|
|
1029
1027
|
message_id: /^instruction_/,
|
|
1030
1028
|
plainBody: instruction,
|
|
1029
|
+
contact_code: contactCode,
|
|
1031
1030
|
processed: true,
|
|
1032
1031
|
'raw.gated': { $ne: true },
|
|
1033
1032
|
createdAt: { $gte: new Date(Date.now() - windowMs) },
|
|
@@ -1042,7 +1041,7 @@ class NexusMessaging {
|
|
|
1042
1041
|
}
|
|
1043
1042
|
}
|
|
1044
1043
|
|
|
1045
|
-
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt) {
|
|
1044
|
+
async _pendingInstructionBatch(code, ownId, ownBody, receivedAt, contactCode = null) {
|
|
1046
1045
|
if (!ownId) return [{ _id: null, body: ownBody }];
|
|
1047
1046
|
try {
|
|
1048
1047
|
const rows = await getMessages(
|
|
@@ -1050,7 +1049,7 @@ class NexusMessaging {
|
|
|
1050
1049
|
numero: code,
|
|
1051
1050
|
origin: 'instruction',
|
|
1052
1051
|
message_id: /^instruction_/,
|
|
1053
|
-
$or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
1052
|
+
$or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, contact_code: contactCode, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
|
|
1054
1053
|
},
|
|
1055
1054
|
{ sort: { _id: 1 }, select: '_id body processed' },
|
|
1056
1055
|
);
|
|
@@ -1078,7 +1077,6 @@ class NexusMessaging {
|
|
|
1078
1077
|
firstName = null,
|
|
1079
1078
|
reminderType = 'seguimiento',
|
|
1080
1079
|
reminderPrefix = null,
|
|
1081
|
-
replyToContact = false,
|
|
1082
1080
|
allowFollowUp = true,
|
|
1083
1081
|
dryRun = false,
|
|
1084
1082
|
} = {}) {
|
|
@@ -1112,7 +1110,7 @@ class NexusMessaging {
|
|
|
1112
1110
|
turnKind: TURN_KIND.PROACTIVE_OUTREACH,
|
|
1113
1111
|
outreachBrief: brief,
|
|
1114
1112
|
preemptiveWindowRoute: true,
|
|
1115
|
-
outreachCarrier: { reminderType, reminderPrefix, firstName
|
|
1113
|
+
outreachCarrier: { reminderType, reminderPrefix, firstName },
|
|
1116
1114
|
outreachAllowsFollowUp: allowFollowUp,
|
|
1117
1115
|
outreachStartedAt,
|
|
1118
1116
|
// Stamped on the outbound so a delivered message joins back to the row that surfaced her.
|
|
@@ -1250,7 +1248,7 @@ class NexusMessaging {
|
|
|
1250
1248
|
const sent = outcome === 'sent' || outcome === 'unknown';
|
|
1251
1249
|
result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
|
|
1252
1250
|
} else {
|
|
1253
|
-
const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName
|
|
1251
|
+
const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName });
|
|
1254
1252
|
result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
|
|
1255
1253
|
}
|
|
1256
1254
|
|
|
@@ -15,7 +15,7 @@ const CASE_STATUS_BY_REVIEW_STATUS = Object.freeze({
|
|
|
15
15
|
approved: POR_ENVIAR,
|
|
16
16
|
sending: POR_ENVIAR,
|
|
17
17
|
needs_intervention: CASE('in-progress', 'requiere-valoracion', 'Requiere valoración'),
|
|
18
|
-
indications_queued: CASE('on-hold', '
|
|
18
|
+
indications_queued: CASE('on-hold', 'indicacion-en-cola', 'Indicación en cola'),
|
|
19
19
|
indications_sent: CASE('in-progress', 'indicaciones-dadas', 'Indicaciones dadas'),
|
|
20
20
|
monitoring: CASE('in-progress', 'en-vigilancia', 'En vigilancia'),
|
|
21
21
|
closed: CASE('completed', 'cerrado', 'Cerrado'),
|
|
@@ -79,6 +79,13 @@ async function resolveCaregiver(code, { strict = false } = {}) {
|
|
|
79
79
|
return resolved;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
async function registeredCaregiverCode(patientCode, contactCode) {
|
|
83
|
+
const formatted = ensureWhatsAppFormat(contactCode);
|
|
84
|
+
const caregiver = await resolveCaregiver(formatted, { strict: true });
|
|
85
|
+
if (!caregiver || stripWhatsAppFormat(caregiver.patientCode) !== stripWhatsAppFormat(patientCode)) return null;
|
|
86
|
+
return formatted;
|
|
87
|
+
}
|
|
88
|
+
|
|
82
89
|
async function remapCaregiverSender(messageData) {
|
|
83
90
|
if (!messageData?.code || messageData.fromMe !== false || messageData.contactCode) return messageData;
|
|
84
91
|
const caregiver = await resolveCaregiver(messageData.code);
|
|
@@ -129,6 +136,7 @@ module.exports = {
|
|
|
129
136
|
contactOf,
|
|
130
137
|
listedCaregivers,
|
|
131
138
|
maskCaregiverLabel,
|
|
139
|
+
registeredCaregiverCode,
|
|
132
140
|
remapCaregiverSender,
|
|
133
141
|
replyContactFor,
|
|
134
142
|
resolveCaregiver,
|
|
@@ -38,21 +38,6 @@ const storeFlowConditionalRules = async (flowId, contentSid, flowFirstPageId, ru
|
|
|
38
38
|
}
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
-
const getAnyFlowConditionalRules = async () => {
|
|
42
|
-
const iter = flowConditionalRules.values().next();
|
|
43
|
-
if (!iter.done) return iter.value;
|
|
44
|
-
try {
|
|
45
|
-
const doc = await FlowRouting.findOne({}, {}, { sort: { updatedAt: -1 } }).lean();
|
|
46
|
-
if (doc) {
|
|
47
|
-
flowConditionalRules.set(doc.flowId, doc);
|
|
48
|
-
return doc;
|
|
49
|
-
}
|
|
50
|
-
} catch (err) {
|
|
51
|
-
console.warn('[FlowRouting] Failed to load latest rules', err.message);
|
|
52
|
-
}
|
|
53
|
-
return null;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
41
|
const getFlowConditionalRules = async (flowId) => {
|
|
57
42
|
if (!flowId) return null;
|
|
58
43
|
if (flowConditionalRules.has(flowId)) return flowConditionalRules.get(flowId);
|
|
@@ -68,35 +53,13 @@ const getFlowConditionalRules = async (flowId) => {
|
|
|
68
53
|
return null;
|
|
69
54
|
};
|
|
70
55
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (doc) {
|
|
79
|
-
flowConditionalRules.set(doc.flowId, doc);
|
|
80
|
-
return doc;
|
|
81
|
-
}
|
|
82
|
-
} catch (err) {
|
|
83
|
-
console.warn('[FlowRouting] Failed to load rules by flowToken', err.message);
|
|
84
|
-
}
|
|
85
|
-
return null;
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
const attachFlowToken = async (flowId, flowToken) => {
|
|
89
|
-
if (!flowId || !flowToken) return;
|
|
90
|
-
const cached = flowConditionalRules.get(flowId);
|
|
91
|
-
if (cached) {
|
|
92
|
-
cached.flowToken = flowToken;
|
|
93
|
-
flowConditionalRules.set(flowId, cached);
|
|
94
|
-
}
|
|
95
|
-
try {
|
|
96
|
-
await FlowRouting.findOneAndUpdate({ flowId }, { flowToken }, { new: true });
|
|
97
|
-
} catch (err) {
|
|
98
|
-
console.warn('[FlowRouting] Failed to attach flowToken', err.message);
|
|
99
|
-
}
|
|
56
|
+
// Tokens are minted as `<flowId>:<uuid>` so the answer routes back to its own flow without a lookup table.
|
|
57
|
+
const FLOW_TOKEN_SEPARATOR = ':';
|
|
58
|
+
const buildFlowToken = (flowId) => `${flowId}${FLOW_TOKEN_SEPARATOR}${uuidv4()}`;
|
|
59
|
+
const flowIdFromToken = (flowToken) => {
|
|
60
|
+
if (typeof flowToken !== 'string') return null;
|
|
61
|
+
const index = flowToken.indexOf(FLOW_TOKEN_SEPARATOR);
|
|
62
|
+
return index > 0 ? flowToken.slice(0, index) : null;
|
|
100
63
|
};
|
|
101
64
|
|
|
102
65
|
const deleteFlowConditionalRules = (contentSid) => {
|
|
@@ -152,7 +115,7 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
|
|
|
152
115
|
const flowRouting = await FlowRouting.findOne({ contentSid }).lean();
|
|
153
116
|
if (!flowRouting) return existingVariables;
|
|
154
117
|
|
|
155
|
-
const flowToken =
|
|
118
|
+
const flowToken = buildFlowToken(flowRouting.flowId);
|
|
156
119
|
logger.info('[ensureFlowTokenInVariables] Meta Flow template detected', {
|
|
157
120
|
contentSid,
|
|
158
121
|
flowId: flowRouting.flowId,
|
|
@@ -170,10 +133,8 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
|
|
|
170
133
|
|
|
171
134
|
module.exports = {
|
|
172
135
|
storeFlowConditionalRules,
|
|
173
|
-
getAnyFlowConditionalRules,
|
|
174
136
|
getFlowConditionalRules,
|
|
175
|
-
|
|
176
|
-
attachFlowToken,
|
|
137
|
+
flowIdFromToken,
|
|
177
138
|
deleteFlowConditionalRules,
|
|
178
139
|
buildFlowTemplatePayload,
|
|
179
140
|
generateUniqueFriendlyName,
|
package/lib/index.d.ts
CHANGED
|
@@ -275,9 +275,9 @@ declare module '@peopl-health/nexus' {
|
|
|
275
275
|
getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
|
|
276
276
|
initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
|
|
277
277
|
getWorkflowRunner(): WorkflowRunner;
|
|
278
|
-
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
279
|
-
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
|
|
280
|
-
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean;
|
|
278
|
+
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number; contactCode?: string | null }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
279
|
+
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean; contactCode?: string | null }): Promise<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
|
|
280
|
+
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
|
|
281
281
|
processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
|
|
282
282
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
283
283
|
isConnected(): boolean;
|
|
@@ -13,7 +13,8 @@ const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
|
13
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
14
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
15
15
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
16
|
-
const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
|
|
16
|
+
const PLAN_FOLLOW_UPS = ['none', 'auto', 'check_in', 'vigilancia'];
|
|
17
|
+
const PLAN_DURATIONS = Object.freeze(['days', 'as_needed', 'continuous', 'unspecified']);
|
|
17
18
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
18
19
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
19
20
|
|
|
@@ -31,6 +32,7 @@ const alarmSchema = new mongoose.Schema({
|
|
|
31
32
|
clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
32
33
|
emergencyRecordId: { type: String, default: null },
|
|
33
34
|
appliedLevel: { type: String, default: null },
|
|
35
|
+
isHeldInFollowUp: { type: Boolean, default: undefined },
|
|
34
36
|
raisedAt: { type: Date, required: true },
|
|
35
37
|
}, { _id: false });
|
|
36
38
|
|
|
@@ -91,6 +93,16 @@ const quietReminderSchema = new mongoose.Schema({
|
|
|
91
93
|
delivered: { type: Boolean, default: null },
|
|
92
94
|
}, { _id: false });
|
|
93
95
|
|
|
96
|
+
const watchNoticeSchema = new mongoose.Schema({
|
|
97
|
+
until: { type: Date, required: true },
|
|
98
|
+
kind: { type: String, enum: ['reminder', 'team'], required: true },
|
|
99
|
+
sentAt: { type: Date, required: true },
|
|
100
|
+
skippedReason: { type: String, default: null },
|
|
101
|
+
// sent | queued (recovery template) | not_sent | skipped | failed (team, tried again); null while in flight.
|
|
102
|
+
outcome: { type: String, default: null },
|
|
103
|
+
status: { type: String, default: null },
|
|
104
|
+
}, { _id: false });
|
|
105
|
+
|
|
94
106
|
const blockingAskSchema = new mongoose.Schema({
|
|
95
107
|
draftAt: { type: Date, required: true },
|
|
96
108
|
question: { type: String, default: null },
|
|
@@ -199,7 +211,8 @@ const planItemSchema = new mongoose.Schema({
|
|
|
199
211
|
strength: { type: String, default: null },
|
|
200
212
|
dose: { type: String, required: true },
|
|
201
213
|
frequency: { type: String, required: true },
|
|
202
|
-
|
|
214
|
+
duration: { type: String, enum: PLAN_DURATIONS, default: 'days' },
|
|
215
|
+
days: { type: Number, default: null },
|
|
203
216
|
position: { type: String, default: null },
|
|
204
217
|
reason: { type: String, default: null },
|
|
205
218
|
formularyKey: { type: String, default: null },
|
|
@@ -285,6 +298,18 @@ const identityBlockSchema = new mongoose.Schema({
|
|
|
285
298
|
blockedBy: { type: String, required: true },
|
|
286
299
|
}, { _id: false });
|
|
287
300
|
|
|
301
|
+
const caseFollowUpSchema = new mongoose.Schema({
|
|
302
|
+
decisionNumber: { type: Number, required: true },
|
|
303
|
+
kind: { type: String, enum: ['auto', 'check_in', 'vigilancia'], required: true },
|
|
304
|
+
attempt: { type: Number, required: true },
|
|
305
|
+
reminderId: { type: String, required: true },
|
|
306
|
+
dueAt: { type: Date, required: true },
|
|
307
|
+
isWritten: { type: Boolean, default: true },
|
|
308
|
+
firstDueAt: { type: Date, required: true },
|
|
309
|
+
nextCheckAt: { type: Date, default: null },
|
|
310
|
+
unansweredAt: { type: Date, default: null },
|
|
311
|
+
}, { _id: false });
|
|
312
|
+
|
|
288
313
|
const escalationReviewSchema = new mongoose.Schema({
|
|
289
314
|
patientCode: { type: String, required: true },
|
|
290
315
|
patientCaseRecordId: { type: String, default: null },
|
|
@@ -333,6 +358,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
333
358
|
digestClaimedAt: { type: Date, default: null },
|
|
334
359
|
digestSentAt: { type: Date, default: null },
|
|
335
360
|
quietReminders: { type: [quietReminderSchema], default: [] },
|
|
361
|
+
monitoringUntil: { type: Date, default: null },
|
|
362
|
+
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
363
|
+
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
336
364
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
337
365
|
feverPromptStartedAt: { type: Date, default: null },
|
|
338
366
|
approverViewedAt: { type: Date, default: null },
|
|
@@ -385,6 +413,7 @@ escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
|
385
413
|
escalationReviewSchema.index({ status: 1, closedAt: -1 });
|
|
386
414
|
escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { draftDueAt: { $type: 'date' } } });
|
|
387
415
|
escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
|
|
416
|
+
escalationReviewSchema.index({ 'caseFollowUp.nextCheckAt': 1 }, { partialFilterExpression: { 'caseFollowUp.nextCheckAt': { $type: 'date' } } });
|
|
388
417
|
escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
|
|
389
418
|
|
|
390
419
|
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
@@ -416,6 +445,7 @@ module.exports = {
|
|
|
416
445
|
DOCTOR_DECISIONS,
|
|
417
446
|
HANDOFF_MODES,
|
|
418
447
|
INTERRUPTED_STATUSES,
|
|
448
|
+
PLAN_DURATIONS,
|
|
419
449
|
PLAN_FOLLOW_UPS,
|
|
420
450
|
FOLLOWUP_STATUSES,
|
|
421
451
|
RETURN_REASONS,
|