@peopl-health/nexus 6.0.0-dev.16255 → 6.0.0-dev.16334
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 +1 -0
- package/lib/clinical/providers/BaseLLMProvider.js +13 -7
- package/lib/clinical/services/outreachCarrierService.js +2 -1
- package/lib/clinical/services/outreachSweepService.js +1 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +4 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +3 -0
- package/lib/core/NexusMessaging.js +2 -0
- package/lib/index.d.ts +1 -1
- package/lib/services/escalationReviewService.js +3 -2
- package/lib/services/reviewDeadlineService.js +12 -6
- package/lib/services/teamAlertService.js +57 -7
- package/lib/services/untakenAlertService.js +20 -8
- package/package.json +1 -1
|
@@ -108,6 +108,7 @@ class AssistantProcessor {
|
|
|
108
108
|
if (ctx) {
|
|
109
109
|
ctx.outreachReminderType = runOptions.outreachCarrier?.reminderType || null;
|
|
110
110
|
ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
|
|
111
|
+
ctx.outreachAllowsFollowUp = runOptions.outreachAllowsFollowUp !== false;
|
|
111
112
|
ctx.checkInOtherPlans = runOptions.outreachBrief?.checkIn?.otherPlans ?? null;
|
|
112
113
|
}
|
|
113
114
|
if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
|
|
@@ -164,14 +164,15 @@ class BaseLLMProvider {
|
|
|
164
164
|
const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
|
|
165
165
|
const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
|
|
166
166
|
const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
|
|
167
|
+
const allowFollowUp = assistant?.toolRuntimeContext?.outreachAllowsFollowUp !== false;
|
|
167
168
|
const auditedPrompt = [
|
|
168
169
|
devContent,
|
|
169
170
|
catalogBlock,
|
|
170
171
|
additionalInstructions ? this._operatorInstructionTurn(additionalInstructions, modelConfig).content : '',
|
|
171
|
-
isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
|
|
172
|
+
isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds, allowFollowUp })[0]?.content || '') : '',
|
|
172
173
|
ruleBlock,
|
|
173
174
|
].filter(Boolean).join('\n\n');
|
|
174
|
-
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
|
|
175
|
+
const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null, allowFollowUp });
|
|
175
176
|
|
|
176
177
|
if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
|
|
177
178
|
trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
|
|
@@ -306,7 +307,7 @@ class BaseLLMProvider {
|
|
|
306
307
|
return { role: 'developer', content: `[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}` };
|
|
307
308
|
}
|
|
308
309
|
|
|
309
|
-
_buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null }) {
|
|
310
|
+
_buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null, allowFollowUp = true }) {
|
|
310
311
|
let messages = this._convertItemsToApiFormat(context || []);
|
|
311
312
|
if (Array.isArray(prePromptResult?.additionalMessages) && prePromptResult.additionalMessages.length > 0) {
|
|
312
313
|
messages = [...messages, ...this._convertItemsToApiFormat(prePromptResult.additionalMessages)];
|
|
@@ -325,7 +326,7 @@ class BaseLLMProvider {
|
|
|
325
326
|
...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
|
|
326
327
|
...this._buildClockMessage(promptVariables, interpolatedVariables),
|
|
327
328
|
...messages,
|
|
328
|
-
...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
|
|
329
|
+
...this._buildOutreachBriefMessage({ outreachBrief, toolIds, allowFollowUp }),
|
|
329
330
|
...this._buildContingencyRuleMessage({ toolIds, promptVariables }),
|
|
330
331
|
]);
|
|
331
332
|
}
|
|
@@ -347,7 +348,7 @@ class BaseLLMProvider {
|
|
|
347
348
|
|
|
348
349
|
// Rides as a turn-scoped developer block, never as a stored message: a proactive brief is true for
|
|
349
350
|
// this morning only, and anything persisted into history would still read as a standing rule weeks later.
|
|
350
|
-
_buildOutreachBriefMessage({ outreachBrief = null, toolIds = [] }) {
|
|
351
|
+
_buildOutreachBriefMessage({ outreachBrief = null, toolIds = [], allowFollowUp = true }) {
|
|
351
352
|
if (!outreachBrief || typeof outreachBrief !== 'object') return [];
|
|
352
353
|
if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
|
|
353
354
|
|
|
@@ -381,8 +382,13 @@ class BaseLLMProvider {
|
|
|
381
382
|
if (since.length) parts.push('', '## Qué ha pasado desde entonces', ...since);
|
|
382
383
|
parts.push(
|
|
383
384
|
'',
|
|
384
|
-
|
|
385
|
-
|
|
385
|
+
...(allowFollowUp ? [
|
|
386
|
+
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
|
|
387
|
+
'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
|
|
388
|
+
] : [
|
|
389
|
+
`Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora o sostener.`,
|
|
390
|
+
'En este turno no programes seguimientos ni recordatorios, aunque otras reglas lo pidan: si te responde, la conversación decide lo que sigue. Si sostienes, deja next_check_at en null.',
|
|
391
|
+
]),
|
|
386
392
|
'',
|
|
387
393
|
'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
|
|
388
394
|
'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
|
|
@@ -3,6 +3,7 @@ const { escapeRegExp } = require('../../utils/textMatchUtils');
|
|
|
3
3
|
|
|
4
4
|
const MAX_CARRIER_TEXT_LENGTH = 600;
|
|
5
5
|
const MAX_HYDRATED_BODY_LENGTH = 1024;
|
|
6
|
+
const GRAPHEME_SEGMENTER = new Intl.Segmenter('es', { granularity: 'grapheme' });
|
|
6
7
|
const FOLLOW_UP_TYPES = new Set(['seguimiento']);
|
|
7
8
|
const CONTINGENCY_TYPES = new Set(['contingencia']);
|
|
8
9
|
const REMINDER_TYPES = new Set(['cita', 'examen', 'medicamento', 'otros']);
|
|
@@ -50,7 +51,7 @@ function validateAgentText(messageText, firstName) {
|
|
|
50
51
|
throw new Error('OUTREACH_CARRIER_TEXT_REPEATS_NAME');
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
const emojiCount = [...text.
|
|
54
|
+
const emojiCount = [...GRAPHEME_SEGMENTER.segment(text)].filter(({ segment }) => /\p{Extended_Pictographic}/u.test(segment)).length;
|
|
54
55
|
if (emojiCount > 1) throw new Error('OUTREACH_CARRIER_TEXT_TOO_MANY_EMOJI');
|
|
55
56
|
return { text, name };
|
|
56
57
|
}
|
|
@@ -583,6 +583,7 @@ async function runOutreachSweep({
|
|
|
583
583
|
dryRun,
|
|
584
584
|
reminderType: 'seguimiento',
|
|
585
585
|
reminderPrefix: mode === 'monday_triage_recovery' ? 'recovery' : null,
|
|
586
|
+
allowFollowUp: mode === 'monday_triage_recovery',
|
|
586
587
|
triggeredBy: `seguimiento:${candidate.recordId}`,
|
|
587
588
|
});
|
|
588
589
|
counts.run++;
|
|
@@ -59,6 +59,7 @@ const MAX_PAUSE_DAYS = 30;
|
|
|
59
59
|
const ROUTINE_OUTREACH_START_HOUR = 11;
|
|
60
60
|
const ROUTINE_OUTREACH_END_HOUR = 21;
|
|
61
61
|
const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
|
|
62
|
+
const NO_FOLLOW_UP_ERROR = 'follow_up_not_allowed — this proactive contact cannot schedule a reminder: if she replies, the conversation decides what comes next. Close with write, or hold with next_check_at null.';
|
|
62
63
|
|
|
63
64
|
const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?$/;
|
|
64
65
|
const FIRE_AT_FORMATS = ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm'];
|
|
@@ -88,6 +89,9 @@ async function handler(args = {}, context = {}) {
|
|
|
88
89
|
const requestedAction = (args?.reminder_action_type || '').toLowerCase();
|
|
89
90
|
if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
|
|
90
91
|
if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
|
|
92
|
+
if (runtime.outreachAllowsFollowUp === false) {
|
|
93
|
+
return JSON.stringify({ success: false, error: NO_FOLLOW_UP_ERROR, data: {} });
|
|
94
|
+
}
|
|
91
95
|
|
|
92
96
|
const reminderDate = (args?.reminder_date || '').trim();
|
|
93
97
|
const description = sanitizeVariable(args?.reminder_description || '');
|
|
@@ -87,6 +87,9 @@ async function handler(args = {}, context = {}) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
|
|
90
|
+
if (rawDecision === 'hold' && nextCheckAt && runtime.outreachAllowsFollowUp === false) {
|
|
91
|
+
return JSON.stringify({ success: false, error: 'next_check_at must be null: this proactive contact cannot plan a later check. Write now, or hold with next_check_at null.', data: {} });
|
|
92
|
+
}
|
|
90
93
|
if (holdReason === 'contingency_already_armed' && !nextCheckAt && runtime.checkInOtherPlans === 0) {
|
|
91
94
|
return JSON.stringify({ success: false, error: 'contingency_already_armed needs another active net or pending seguimiento, and this check-in has none: write now, or schedule a seguimiento and hold with rescheduled_for_cadence.', data: {} });
|
|
92
95
|
}
|
|
@@ -1038,6 +1038,7 @@ class NexusMessaging {
|
|
|
1038
1038
|
reminderType = 'seguimiento',
|
|
1039
1039
|
reminderPrefix = null,
|
|
1040
1040
|
replyToContact = false,
|
|
1041
|
+
allowFollowUp = true,
|
|
1041
1042
|
dryRun = false,
|
|
1042
1043
|
} = {}) {
|
|
1043
1044
|
const outreachStartedAt = new Date().toISOString();
|
|
@@ -1069,6 +1070,7 @@ class NexusMessaging {
|
|
|
1069
1070
|
outreachBrief: brief,
|
|
1070
1071
|
preemptiveWindowRoute: true,
|
|
1071
1072
|
outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
|
|
1073
|
+
outreachAllowsFollowUp: allowFollowUp,
|
|
1072
1074
|
outreachStartedAt,
|
|
1073
1075
|
// Stamped on the outbound so a delivered message joins back to the row that surfaced her.
|
|
1074
1076
|
triggeredBy: triggeredBy || null,
|
package/lib/index.d.ts
CHANGED
|
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
|
|
|
274
274
|
getWorkflowRunner(): WorkflowRunner;
|
|
275
275
|
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 }>;
|
|
276
276
|
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
|
|
277
|
-
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean }): Promise<OutreachDecision>;
|
|
277
|
+
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
|
|
278
278
|
processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
|
|
279
279
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|
|
280
280
|
isConnected(): boolean;
|
|
@@ -964,7 +964,7 @@ async function patientTimerOf(review, level, now, { firing = false } = {}) {
|
|
|
964
964
|
return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
|
|
965
965
|
}
|
|
966
966
|
if (levelTimer) {
|
|
967
|
-
return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes() * 60 * 1000 }, gap };
|
|
967
|
+
return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes(level) * 60 * 1000 }, gap };
|
|
968
968
|
}
|
|
969
969
|
return { timer: null, gap };
|
|
970
970
|
}
|
|
@@ -1300,7 +1300,7 @@ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel
|
|
|
1300
1300
|
try {
|
|
1301
1301
|
review = await loadReview(reviewIdOf(reviewId));
|
|
1302
1302
|
// Airtable alerts the team only once its emergencies row exists; a team notice that reached no one falls back to one phone.
|
|
1303
|
-
delivery = (teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
|
|
1303
|
+
delivery = (await teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
|
|
1304
1304
|
|| await alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId);
|
|
1305
1305
|
} catch (error) {
|
|
1306
1306
|
delivery = { error: redactedError(error) };
|
|
@@ -2145,6 +2145,7 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
|
|
|
2145
2145
|
module.exports = {
|
|
2146
2146
|
BOOKKEEPING,
|
|
2147
2147
|
DOCUMENTING_STATUSES,
|
|
2148
|
+
FEVER_CATEGORY,
|
|
2148
2149
|
MAX_ALERT_ATTEMPTS,
|
|
2149
2150
|
PRE_DECISION_STATUSES,
|
|
2150
2151
|
_resetEscalationReviewIndexes,
|
|
@@ -8,7 +8,9 @@ const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
|
|
|
8
8
|
const TEAM_TIMEZONE = 'America/Mexico_City';
|
|
9
9
|
const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 20 };
|
|
10
10
|
const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
|
|
11
|
-
const DEFAULT_PATIENT_TIMER_MINUTES = 15;
|
|
11
|
+
const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20 };
|
|
12
|
+
const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES' };
|
|
13
|
+
const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
|
|
12
14
|
|
|
13
15
|
const rankOf = (level) => URGENCY_RANK[level] || 0;
|
|
14
16
|
const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
|
|
@@ -64,15 +66,19 @@ function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level])
|
|
|
64
66
|
return new Date(timeOf(from) + minutes * 60 * 1000);
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
const
|
|
68
|
-
const minutes = Number(runtimeConfig.get(
|
|
69
|
-
return Number.isFinite(minutes) && minutes > 0 ? minutes :
|
|
69
|
+
const positiveMinutes = (key, fallback) => {
|
|
70
|
+
const minutes = Number(runtimeConfig.get(key, fallback));
|
|
71
|
+
return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
|
|
70
72
|
};
|
|
71
73
|
|
|
72
|
-
//
|
|
74
|
+
// asap leaves the team its early alert before the patient gets the numbers to call.
|
|
75
|
+
const patientTimerMinutes = (level) => positiveMinutes(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
|
|
76
|
+
const untakenEarlyMinutes = () => positiveMinutes('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
|
|
77
|
+
|
|
78
|
+
// Untaken alerts: asap early, asap and urgent at half the response time, and every level at the deadline.
|
|
73
79
|
function untakenStagesOf(level, since, policy) {
|
|
74
80
|
const total = policy.responseMinutes[level];
|
|
75
|
-
const minutesOf = { early:
|
|
81
|
+
const minutesOf = { early: untakenEarlyMinutes(), half: total / 2, deadline: total };
|
|
76
82
|
return (UNTAKEN_STAGES[level] ?? [])
|
|
77
83
|
.filter((stage) => stage !== 'early' || minutesOf.early < minutesOf.half)
|
|
78
84
|
.map((stage) => ({ stage, minutes: minutesOf[stage], totalMinutes: total, dueAt: dueAtFor(since, level, policy, minutesOf[stage]) }));
|
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
const axios = require('axios');
|
|
2
2
|
|
|
3
3
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
5
6
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
7
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
8
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
9
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
8
10
|
|
|
11
|
+
const airtableService = require('./airtableService');
|
|
12
|
+
|
|
9
13
|
const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
|
|
10
14
|
const REQUEST_TIMEOUT_MS = 15000;
|
|
11
15
|
const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
|
|
12
16
|
const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
|
|
17
|
+
const ROSTER_TABLE = 'equipo_guardia';
|
|
18
|
+
const ROSTER_FIELDS = ['whatsapp', 'sin_tomar'];
|
|
19
|
+
const ROSTER_TTL_MS = 5 * 60 * 1000;
|
|
20
|
+
const ROSTER_READ_TIMEOUT_MS = 5000;
|
|
13
21
|
|
|
14
22
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
15
23
|
|
|
@@ -17,7 +25,11 @@ const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').repla
|
|
|
17
25
|
|
|
18
26
|
const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
|
|
19
27
|
|
|
20
|
-
|
|
28
|
+
let roster = { members: null, readAt: 0 };
|
|
29
|
+
let reading = null;
|
|
30
|
+
|
|
31
|
+
// Used when the roster is unreadable or has no active phone; it ignores levels.
|
|
32
|
+
function configuredPhones() {
|
|
21
33
|
return String(runtimeConfig.get('ESCALATION_TEAM_ALERT_PHONES', '') ?? '')
|
|
22
34
|
.split(',')
|
|
23
35
|
.map((phone) => phone.trim())
|
|
@@ -26,6 +38,45 @@ function teamPhones() {
|
|
|
26
38
|
.filter((code) => PATIENT_CODE.test(code));
|
|
27
39
|
}
|
|
28
40
|
|
|
41
|
+
async function readRoster() {
|
|
42
|
+
const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, '{activo}', null, ROSTER_FIELDS);
|
|
43
|
+
if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
|
|
44
|
+
return rows
|
|
45
|
+
.map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [] }))
|
|
46
|
+
.filter((member) => PATIENT_CODE.test(member.code));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function refreshRoster(now) {
|
|
50
|
+
try {
|
|
51
|
+
const members = await withTimeout(readRoster(), ROSTER_READ_TIMEOUT_MS, 'on-call roster read');
|
|
52
|
+
roster = { members: members.length ? members : null, readAt: now };
|
|
53
|
+
if (!members.length) logger.warn('[TeamAlert] The on-call roster has no active phone; using ESCALATION_TEAM_ALERT_PHONES');
|
|
54
|
+
} catch (error) {
|
|
55
|
+
roster = { ...roster, readAt: now };
|
|
56
|
+
logger.error('[TeamAlert] The on-call roster could not be read; using the last one read', { error: redacted(error) });
|
|
57
|
+
}
|
|
58
|
+
return roster.members;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The Airtable roster, read at most every 5 min by one read at a time; a failed read keeps the last one and waits as long to retry.
|
|
62
|
+
async function rosterMembers(now = Date.now()) {
|
|
63
|
+
if (roster.readAt && now - roster.readAt < ROSTER_TTL_MS) return roster.members;
|
|
64
|
+
if (!reading) reading = refreshRoster(now).finally(() => { reading = null; });
|
|
65
|
+
return reading;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// With a level, only the members who take that level's untaken alerts; without one, every active member.
|
|
69
|
+
async function teamPhones(level = null) {
|
|
70
|
+
const members = await rosterMembers();
|
|
71
|
+
if (!members) return configuredPhones();
|
|
72
|
+
return members.filter((member) => !level || member.levels.includes(level)).map((member) => member.code);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const _resetRoster = () => {
|
|
76
|
+
roster = { members: null, readAt: 0 };
|
|
77
|
+
reading = null;
|
|
78
|
+
};
|
|
79
|
+
|
|
29
80
|
// Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
|
|
30
81
|
async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
31
82
|
const inWindow = await isWithin24HourWindow(code);
|
|
@@ -42,7 +93,7 @@ async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
|
42
93
|
|
|
43
94
|
const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
|
|
44
95
|
|
|
45
|
-
const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
|
|
96
|
+
const teamChannelConfigured = async () => groupConfigured() || (await teamPhones()).length > 0;
|
|
46
97
|
|
|
47
98
|
async function postToGroup(body, quoted) {
|
|
48
99
|
const res = await axios({
|
|
@@ -68,13 +119,12 @@ async function sendToGroup(body, quoted = null) {
|
|
|
68
119
|
}
|
|
69
120
|
}
|
|
70
121
|
|
|
71
|
-
// Alerts the
|
|
72
|
-
|
|
73
|
-
async function sendTeamAlert({ message, operator, notice = false, quoted = null }) {
|
|
122
|
+
// Alerts the group and the on-call phones for `level` (all without one); one failed recipient never stops the others and nothing throws.
|
|
123
|
+
async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null }) {
|
|
74
124
|
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
75
125
|
const group = await sendToGroup(message.body, quoted);
|
|
76
126
|
const phones = [];
|
|
77
|
-
for (const code of teamPhones()) {
|
|
127
|
+
for (const code of await teamPhones(level)) {
|
|
78
128
|
try {
|
|
79
129
|
phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
|
|
80
130
|
} catch (error) {
|
|
@@ -86,4 +136,4 @@ async function sendTeamAlert({ message, operator, notice = false, quoted = null
|
|
|
86
136
|
return { group, phones, delivered };
|
|
87
137
|
}
|
|
88
138
|
|
|
89
|
-
module.exports = { groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
139
|
+
module.exports = { _resetRoster, groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
@@ -3,11 +3,11 @@ const { logger } = require('../utils/logger');
|
|
|
3
3
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
4
|
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
5
|
const { conversationLink, readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
6
|
-
const { escalationGravePendingShadow, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
6
|
+
const { escalationGravePendingShadow, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
7
7
|
|
|
8
8
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
9
9
|
const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
|
|
10
|
-
const { BOOKKEEPING, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
|
|
10
|
+
const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
|
|
11
11
|
const { recordGraveMissing } = require('./gravePendingService');
|
|
12
12
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
13
13
|
|
|
@@ -84,6 +84,16 @@ function pendingQuestionOf(review, clock) {
|
|
|
84
84
|
return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
// The early asap alert says when the armed prompt gives the patient the numbers; a fever prompt keeps its own wording.
|
|
88
|
+
function patientPromptNote(review, stage, now) {
|
|
89
|
+
if (stage.stage !== 'early' || !escalationPatientTimerLive()) return null;
|
|
90
|
+
if (currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY)) return null;
|
|
91
|
+
// A leased or retried slot (attempts above 0) is already being sent.
|
|
92
|
+
if (review.doctorAlertKind !== 'patient_prompt' || (review.doctorAlertAttempts ?? 0) !== 0 || !review.doctorAlertDueAt) return null;
|
|
93
|
+
const lead = Math.round((new Date(review.doctorAlertDueAt).getTime() - now.getTime()) / 60000);
|
|
94
|
+
return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
87
97
|
async function identityOf(review) {
|
|
88
98
|
try {
|
|
89
99
|
return doctorIdentity(await getPatientInformation(review.patientCode));
|
|
@@ -95,7 +105,7 @@ async function identityOf(review) {
|
|
|
95
105
|
}
|
|
96
106
|
}
|
|
97
107
|
|
|
98
|
-
async function untakenMessage(review, clock, stage) {
|
|
108
|
+
async function untakenMessage(review, clock, stage, now) {
|
|
99
109
|
const { patientName, treatingDoctor } = await identityOf(review);
|
|
100
110
|
const patient = patientName || NO_NAME;
|
|
101
111
|
const doctor = treatingDoctor || NO_DOCTOR;
|
|
@@ -104,11 +114,13 @@ async function untakenMessage(review, clock, stage) {
|
|
|
104
114
|
const level = LEVEL_LABELS[clock.level];
|
|
105
115
|
const action = ACTIONS[clock.level];
|
|
106
116
|
const question = pendingQuestionOf(review, clock);
|
|
117
|
+
const note = patientPromptNote(review, stage, now);
|
|
107
118
|
return {
|
|
108
119
|
body: [
|
|
109
120
|
`⏰ ${level} sin tomar · ${deadline}`,
|
|
110
121
|
[`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
|
|
111
122
|
question && `Falta saber: ${question}`,
|
|
123
|
+
note,
|
|
112
124
|
`Qué hacer: ${action}`,
|
|
113
125
|
link,
|
|
114
126
|
].filter(Boolean).join('\n'),
|
|
@@ -116,7 +128,7 @@ async function untakenMessage(review, clock, stage) {
|
|
|
116
128
|
1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
|
|
117
129
|
2: patient,
|
|
118
130
|
3: doctor,
|
|
119
|
-
4: question
|
|
131
|
+
4: [question && `Falta saber: ${question}`, action, note].filter(Boolean).join(' · '),
|
|
120
132
|
5: link,
|
|
121
133
|
},
|
|
122
134
|
};
|
|
@@ -147,11 +159,11 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
147
159
|
await claimStage(review, clock, stage, now, taken);
|
|
148
160
|
return false;
|
|
149
161
|
}
|
|
150
|
-
const message = await untakenMessage(review, clock, stage);
|
|
162
|
+
const message = await untakenMessage(review, clock, stage, now);
|
|
151
163
|
// Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
|
|
152
164
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
153
165
|
if (!await claimStage(review, clock, stage, now)) return false;
|
|
154
|
-
const result = await sendTeamAlert({ message, operator: OPERATOR, quoted });
|
|
166
|
+
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted });
|
|
155
167
|
const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
|
|
156
168
|
await getEscalationReview().updateOne(
|
|
157
169
|
{ _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
|
|
@@ -170,7 +182,7 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
170
182
|
return true;
|
|
171
183
|
}
|
|
172
184
|
|
|
173
|
-
// Alerts the whole team at each stage of a case nobody took (asap also
|
|
185
|
+
// Alerts the whole team at each stage of a case nobody took (asap also early); being with the doctor is not taken.
|
|
174
186
|
async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
175
187
|
const alerts = escalationUntakenAlertsLive();
|
|
176
188
|
const graveShadow = escalationGravePendingShadow();
|
|
@@ -180,7 +192,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
180
192
|
closedAt: null,
|
|
181
193
|
status: { $in: PRE_DECISION_STATUSES },
|
|
182
194
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
183
|
-
}, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, 'updates.at': 1,
|
|
195
|
+
}, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
184
196
|
'drafts.createdAt': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
185
197
|
})
|
|
186
198
|
.sort({ _id: -1 })
|