@peopl-health/nexus 5.61.0-dev.11231 → 5.61.0-dev.11233
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 +16 -0
- package/lib/clinical/config/subAgentsConfig.js +1 -7
- package/lib/clinical/helpers/reviewUpdateHelper.js +74 -0
- package/lib/clinical/models/supportLightModel.js +1 -19
- package/lib/clinical/services/escalationDraftService.js +17 -3
- package/lib/clinical/services/treatmentProposalService.js +7 -2
- package/lib/clinical/tools/reportMedicalEscalationTool.js +3 -0
- package/lib/config/lifecycle.js +5 -1
- package/lib/controllers/conversationController.js +2 -2
- package/lib/controllers/escalationReviewController.js +26 -0
- package/lib/controllers/messageController.js +21 -1
- package/lib/index.d.ts +14 -33
- package/lib/index.js +20 -2
- package/lib/models/escalationReviewModel.js +68 -2
- package/lib/routes/index.js +4 -0
- package/lib/services/conversationService.js +40 -13
- package/lib/services/escalationReviewService.js +640 -45
- package/lib/services/patientTaskService.js +1 -0
- package/lib/services/reviewAlertSweepService.js +90 -0
- package/lib/services/reviewBoardService.js +78 -0
- package/lib/services/reviewDraftSweepService.js +80 -0
- package/package.json +1 -1
- package/lib/clinical/services/supportLightEvaluationService.js +0 -159
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
3
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
4
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
|
+
|
|
6
|
+
const { BOOKKEEPING, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
|
|
7
|
+
|
|
8
|
+
const SWEEP_LIMIT = 10;
|
|
9
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
10
|
+
const LEASE_MS = 5 * 60 * 1000;
|
|
11
|
+
// Well inside the lease: an alert never outlives its claim, so two sweeps never send the same one.
|
|
12
|
+
const SEND_TIMEOUT_MS = 2 * 60 * 1000;
|
|
13
|
+
const MAX_ALERT_ATTEMPTS = 3;
|
|
14
|
+
const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
|
|
15
|
+
const ALERTED_URGENCIES = ['stat', 'asap'];
|
|
16
|
+
|
|
17
|
+
// Due alerts, plus a recent stat/asap review still waiting on a decision that never got its first
|
|
18
|
+
// alert because scheduling it failed after the alarm was written.
|
|
19
|
+
const dueQuery = (now) => ({
|
|
20
|
+
closedAt: null,
|
|
21
|
+
$or: [
|
|
22
|
+
{ doctorAlertDueAt: { $lte: now } },
|
|
23
|
+
{
|
|
24
|
+
doctorAlertDueAt: null,
|
|
25
|
+
status: { $in: PRE_DECISION_STATUSES },
|
|
26
|
+
'doctorAlerts.0': { $exists: false },
|
|
27
|
+
alarms: { $elemMatch: { urgencyLevel: { $in: ALERTED_URGENCIES }, raisedAt: { $gte: new Date(now.getTime() - SELF_HEAL_WINDOW_MS) } } },
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
async function sweepDoctorAlerts({ now = new Date(), clock = () => new Date() } = {}) {
|
|
33
|
+
const EscalationReview = getEscalationReview();
|
|
34
|
+
const due = await EscalationReview
|
|
35
|
+
.find(dueQuery(now), { _id: 1, doctorAlertDueAt: 1, doctorAlertKind: 1, doctorAlertAttempts: 1 })
|
|
36
|
+
.sort({ doctorAlertDueAt: 1 })
|
|
37
|
+
.limit(SWEEP_LIMIT)
|
|
38
|
+
.lean();
|
|
39
|
+
|
|
40
|
+
let sent = 0;
|
|
41
|
+
for (const { _id: reviewId, doctorAlertDueAt = null, doctorAlertKind, doctorAlertAttempts = 0 } of due) {
|
|
42
|
+
const kind = doctorAlertKind || 'initial';
|
|
43
|
+
// Each claim starts its own clock: a slow alert earlier in the pass must not shorten the next lease.
|
|
44
|
+
const claimedAt = clock();
|
|
45
|
+
try {
|
|
46
|
+
if (doctorAlertAttempts >= MAX_ALERT_ATTEMPTS) {
|
|
47
|
+
logger.error('[ReviewAlertSweep] The doctor alert failed on every attempt; it is dropped', {
|
|
48
|
+
escalationReviewId: String(reviewId), kind, attempts: doctorAlertAttempts,
|
|
49
|
+
});
|
|
50
|
+
// The drop is on the record, so the recovery of never-sent first alerts does not pick it up again.
|
|
51
|
+
await EscalationReview.updateOne(
|
|
52
|
+
{ _id: reviewId, doctorAlertDueAt },
|
|
53
|
+
{
|
|
54
|
+
$set: { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 },
|
|
55
|
+
$push: { doctorAlerts: { kind, urgencyLevel: null, error: `dropped after ${doctorAlertAttempts} attempts`, sentAt: claimedAt } },
|
|
56
|
+
},
|
|
57
|
+
BOOKKEEPING,
|
|
58
|
+
);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
// Claiming turns the due time into a short lease: a pass that dies or throws leaves the alert
|
|
62
|
+
// due again once it expires, and the sender only touches the schedule while the lease is its own.
|
|
63
|
+
const lease = new Date(claimedAt.getTime() + LEASE_MS);
|
|
64
|
+
const claimed = await EscalationReview
|
|
65
|
+
.findOneAndUpdate(
|
|
66
|
+
{ _id: reviewId, doctorAlertDueAt },
|
|
67
|
+
{ $set: { doctorAlertDueAt: lease, doctorAlertKind: kind }, $inc: { doctorAlertAttempts: 1 } },
|
|
68
|
+
{ ...BOOKKEEPING, new: true, projection: { _id: 1 } },
|
|
69
|
+
)
|
|
70
|
+
.lean();
|
|
71
|
+
if (!claimed) continue;
|
|
72
|
+
const alert = sendScheduledDoctorAlert({ id: String(reviewId), kind, lease, now: claimedAt });
|
|
73
|
+
if (await withTimeout(alert, SEND_TIMEOUT_MS, 'doctor alert')) sent += 1;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
logger.error('[ReviewAlertSweep] Could not alert the doctor for a review', { escalationReviewId: String(reviewId), error: error.message });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return sent;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const sweeper = createIntervalSweeper({
|
|
82
|
+
label: '[ReviewAlertSweep]',
|
|
83
|
+
sweep: () => sweepDoctorAlerts(),
|
|
84
|
+
defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const startReviewAlertSweep = (options) => sweeper.start(options);
|
|
88
|
+
const stopReviewAlertSweep = () => sweeper.stop();
|
|
89
|
+
|
|
90
|
+
module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const { httpError } = require('../utils/httpErrorUtils');
|
|
2
|
+
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
|
+
|
|
4
|
+
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
5
|
+
const RETURNED_STATUSES = ['returned'];
|
|
6
|
+
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
|
|
7
|
+
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
8
|
+
const BOARD_BUCKETS = ['pending', 'returned', 'followup', 'done'];
|
|
9
|
+
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
10
|
+
|
|
11
|
+
const bucketQuery = (bucket, now) => {
|
|
12
|
+
switch (bucket) {
|
|
13
|
+
case 'pending':
|
|
14
|
+
return { closedAt: null, status: { $nin: [...RETURNED_STATUSES, ...FOLLOWUP_STATUSES, ...DONE_STATUSES] } };
|
|
15
|
+
case 'returned':
|
|
16
|
+
return { closedAt: null, status: { $in: RETURNED_STATUSES } };
|
|
17
|
+
case 'followup':
|
|
18
|
+
return { closedAt: null, status: { $in: FOLLOWUP_STATUSES } };
|
|
19
|
+
case 'done':
|
|
20
|
+
return { status: { $in: DONE_STATUSES }, closedAt: { $gte: new Date(now.getTime() - DONE_WINDOW_MS) } };
|
|
21
|
+
default:
|
|
22
|
+
throw httpError(400, `bucket must be one of: ${BOARD_BUCKETS.join(', ')}`);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const rankOf = (alarm) => URGENCY_RANK[alarm?.urgencyLevel] || 0;
|
|
27
|
+
|
|
28
|
+
const leadingAlarm = (alarms) => alarms.reduce((lead, alarm) => (
|
|
29
|
+
!lead || rankOf(alarm) > rankOf(lead) || (rankOf(alarm) === rankOf(lead) && alarm.raisedAt > lead.raisedAt) ? alarm : lead
|
|
30
|
+
), null);
|
|
31
|
+
|
|
32
|
+
const boardRowOf = (review, bucket) => {
|
|
33
|
+
const alarms = review.alarms || [];
|
|
34
|
+
const lead = leadingAlarm(alarms);
|
|
35
|
+
const raised = alarms.map((alarm) => alarm.raisedAt).filter(Boolean);
|
|
36
|
+
const since = raised.length ? new Date(Math.min(...raised.map(Number))) : review.createdAt;
|
|
37
|
+
return {
|
|
38
|
+
reviewId: String(review._id),
|
|
39
|
+
patientCode: review.patientCode,
|
|
40
|
+
bucket,
|
|
41
|
+
status: review.status,
|
|
42
|
+
urgency: lead?.urgencyLevel || null,
|
|
43
|
+
symptom: lead?.symptom || null,
|
|
44
|
+
alarmCount: alarms.length,
|
|
45
|
+
since,
|
|
46
|
+
closedAt: review.closedAt || null,
|
|
47
|
+
updatedSinceSeen: review.updatedSinceSeen === true,
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const byUrgencyThenAge = (a, b) => (URGENCY_RANK[b.urgency] || 0) - (URGENCY_RANK[a.urgency] || 0)
|
|
52
|
+
|| new Date(a.since) - new Date(b.since);
|
|
53
|
+
|
|
54
|
+
const byMostRecentlyClosed = (a, b) => new Date(b.closedAt) - new Date(a.closedAt);
|
|
55
|
+
|
|
56
|
+
async function listReviewBoard({ bucket, now = new Date() } = {}) {
|
|
57
|
+
const reviews = await getEscalationReview()
|
|
58
|
+
.find(bucketQuery(bucket, now), {
|
|
59
|
+
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
60
|
+
})
|
|
61
|
+
.lean();
|
|
62
|
+
const rows = reviews.map((review) => boardRowOf(review, bucket))
|
|
63
|
+
.sort(bucket === 'done' ? byMostRecentlyClosed : byUrgencyThenAge);
|
|
64
|
+
const seen = new Set();
|
|
65
|
+
return rows.filter((row) => !seen.has(row.patientCode) && seen.add(row.patientCode));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const boardBucketOfFilter = (filter) => {
|
|
69
|
+
if (typeof filter !== 'string' || !filter.startsWith(BOARD_FILTER_PREFIX)) return null;
|
|
70
|
+
const bucket = filter.slice(BOARD_FILTER_PREFIX.length);
|
|
71
|
+
return BOARD_BUCKETS.includes(bucket) ? bucket : null;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
module.exports = {
|
|
75
|
+
BOARD_BUCKETS,
|
|
76
|
+
boardBucketOfFilter,
|
|
77
|
+
listReviewBoard,
|
|
78
|
+
};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
3
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
4
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
|
+
|
|
6
|
+
const { BOOKKEEPING, generateBotDraft } = require('./escalationReviewService');
|
|
7
|
+
|
|
8
|
+
// One review per pass keeps a pass inside the sweeper's pass timeout, so shutdown always waits for it.
|
|
9
|
+
const SWEEP_LIMIT = 1;
|
|
10
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
11
|
+
const RETRY_DELAY_MS = 5 * 60 * 1000;
|
|
12
|
+
const MAX_DRAFT_ATTEMPTS = 3;
|
|
13
|
+
const LEASE_MS = 10 * 60 * 1000;
|
|
14
|
+
// Well inside the lease: a run never outlives its claim, so two runs never draft the same review.
|
|
15
|
+
const GENERATION_TIMEOUT_MS = 4 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts = 0 }, now) {
|
|
18
|
+
// Claiming moves draftDueAt to a lease deadline: a worker that dies mid-draft leaves the review due
|
|
19
|
+
// again once the lease expires, and an alarm or update that lands meanwhile replaces the lease.
|
|
20
|
+
const lease = new Date(now.getTime() + LEASE_MS);
|
|
21
|
+
const claimed = await EscalationReview
|
|
22
|
+
.findOneAndUpdate({ _id, draftDueAt }, { $set: { draftDueAt: lease } }, { ...BOOKKEEPING, new: true, projection: { _id: 1 } })
|
|
23
|
+
.lean();
|
|
24
|
+
if (!claimed) return false;
|
|
25
|
+
|
|
26
|
+
let outcome;
|
|
27
|
+
try {
|
|
28
|
+
outcome = await withTimeout(generateBotDraft({ id: String(_id), lease }), GENERATION_TIMEOUT_MS, 'automatic draft generation');
|
|
29
|
+
} catch (error) {
|
|
30
|
+
logger.error('[ReviewDraftSweep] The automatic draft threw', { escalationReviewId: String(_id), error: error.message });
|
|
31
|
+
outcome = { review: null, retry: true };
|
|
32
|
+
}
|
|
33
|
+
const { review, retry } = outcome;
|
|
34
|
+
if (review) return true;
|
|
35
|
+
const willRetry = retry && draftAttempts + 1 < MAX_DRAFT_ATTEMPTS;
|
|
36
|
+
if (retry && !willRetry) {
|
|
37
|
+
logger.error('[ReviewDraftSweep] The automatic draft failed on every attempt; it waits for new material', {
|
|
38
|
+
escalationReviewId: String(_id), attempts: draftAttempts + 1,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
// Releases the lease, unless new material replaced it meanwhile.
|
|
42
|
+
await EscalationReview.updateOne(
|
|
43
|
+
{ _id, draftDueAt: lease },
|
|
44
|
+
willRetry
|
|
45
|
+
? { $set: { draftDueAt: new Date(Date.now() + RETRY_DELAY_MS) }, $inc: { draftAttempts: 1 } }
|
|
46
|
+
: { $set: { draftDueAt: null } },
|
|
47
|
+
BOOKKEEPING,
|
|
48
|
+
);
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function sweepReviewDrafts({ now = new Date() } = {}) {
|
|
53
|
+
const EscalationReview = getEscalationReview();
|
|
54
|
+
const due = await EscalationReview
|
|
55
|
+
.find({ closedAt: null, draftDueAt: { $lte: now } }, { _id: 1, draftDueAt: 1, draftAttempts: 1 })
|
|
56
|
+
.sort({ draftDueAt: 1 })
|
|
57
|
+
.limit(SWEEP_LIMIT)
|
|
58
|
+
.lean();
|
|
59
|
+
|
|
60
|
+
let written = 0;
|
|
61
|
+
for (const entry of due) {
|
|
62
|
+
try {
|
|
63
|
+
if (await draftReview(EscalationReview, entry, now)) written += 1;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
logger.error('[ReviewDraftSweep] Could not draft a review', { escalationReviewId: String(entry._id), error: error.message });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return written;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const sweeper = createIntervalSweeper({
|
|
72
|
+
label: '[ReviewDraftSweep]',
|
|
73
|
+
sweep: () => sweepReviewDrafts(),
|
|
74
|
+
defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const startReviewDraftSweep = (options) => sweeper.start(options);
|
|
78
|
+
const stopReviewDraftSweep = () => sweeper.stop();
|
|
79
|
+
|
|
80
|
+
module.exports = { startReviewDraftSweep, stopReviewDraftSweep, sweepReviewDrafts };
|
package/package.json
CHANGED
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
const { requireGatewayProvider } = require('../config/llmConfig');
|
|
2
|
-
const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
|
|
3
|
-
const { getSupportLightSweepModel } = require('../models/supportLightModel');
|
|
4
|
-
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
5
|
-
const { getMessages, aggregateMessages } = require('../../services/messageService');
|
|
6
|
-
const { safeParse } = require('../../utils/jsonUtils');
|
|
7
|
-
const { logger } = require('../../utils/logger');
|
|
8
|
-
const { LIGHT_SCALE } = require('./supportInvitability');
|
|
9
|
-
const { applySupportLight } = require('./supportLightService');
|
|
10
|
-
|
|
11
|
-
const HOUR_MS = 60 * 60 * 1000;
|
|
12
|
-
const DAY_MS = 24 * HOUR_MS;
|
|
13
|
-
const DEFAULT_CADENCE_HOURS = 48;
|
|
14
|
-
const RETRY_HOURS = 6;
|
|
15
|
-
const DEFAULT_WINDOW_DAYS = 14;
|
|
16
|
-
const MAX_MESSAGES = 60;
|
|
17
|
-
const MAX_PATIENT_MESSAGES = 20;
|
|
18
|
-
const CANDIDATE_PAGE = 200;
|
|
19
|
-
const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
|
|
20
|
-
const MAX_REASON_CHARS = 500;
|
|
21
|
-
const MAX_EVIDENCE = 5;
|
|
22
|
-
const INTERNAL_ORIGINS = ['system', 'instruction'];
|
|
23
|
-
const SERVICES = Object.keys(LIGHT_SCALE);
|
|
24
|
-
|
|
25
|
-
function transcriptOf(messages) {
|
|
26
|
-
return messages.map((message, index) => {
|
|
27
|
-
const at = new Date(message.createdAt).toISOString().slice(0, 16).replace('T', ' ');
|
|
28
|
-
return `[${index}] ${at} ${message.from_me ? 'Equipo' : 'Paciente'}: ${String(message.body || '').trim()}`;
|
|
29
|
-
}).join('\n');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function readingFor(service, raw, messages) {
|
|
33
|
-
const color = raw?.color;
|
|
34
|
-
if (color !== 'unknown' && !LIGHT_SCALE[service].includes(color)) return null;
|
|
35
|
-
const evidence = (Array.isArray(raw?.evidence) ? raw.evidence : [])
|
|
36
|
-
.filter((item) => Number.isInteger(item?.message_index) && messages[item.message_index] && typeof item.summary === 'string')
|
|
37
|
-
.slice(0, MAX_EVIDENCE)
|
|
38
|
-
.map((item) => ({ source: 'sweep', sourceId: String(messages[item.message_index]._id), summary: item.summary.slice(0, MAX_REASON_CHARS) }));
|
|
39
|
-
const reason = typeof raw?.reason === 'string' ? raw.reason.slice(0, MAX_REASON_CHARS) : null;
|
|
40
|
-
return { color, reason, evidence };
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
async function readRecentMessages(patientId, { now, windowDays, readMessages }) {
|
|
44
|
-
const query = {
|
|
45
|
-
numero: patientId,
|
|
46
|
-
createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
|
|
47
|
-
origin: { $nin: INTERNAL_ORIGINS },
|
|
48
|
-
body: { $regex: '\\S' },
|
|
49
|
-
};
|
|
50
|
-
const options = { sort: { createdAt: -1 }, select: '_id body from_me createdAt' };
|
|
51
|
-
const [recent, fromPatient] = await Promise.all([
|
|
52
|
-
readMessages(query, { ...options, limit: MAX_MESSAGES }),
|
|
53
|
-
readMessages({ ...query, from_me: false }, { ...options, limit: MAX_PATIENT_MESSAGES }),
|
|
54
|
-
]);
|
|
55
|
-
const byId = new Map([...(recent || []), ...(fromPatient || [])].map((message) => [String(message._id), message]));
|
|
56
|
-
return [...byId.values()].sort((left, right) => new Date(left.createdAt) - new Date(right.createdAt));
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async function evaluatePatientSupport({
|
|
60
|
-
patientId, now = new Date(), windowDays = DEFAULT_WINDOW_DAYS,
|
|
61
|
-
}, {
|
|
62
|
-
provider = null, getConfig = getSupportLightEvaluator, readMessages = getMessages, applyLight = applySupportLight,
|
|
63
|
-
} = {}) {
|
|
64
|
-
const { presetId } = await getConfig();
|
|
65
|
-
if (!presetId) return { outcome: 'not_configured' };
|
|
66
|
-
const messages = await readRecentMessages(patientId, { now, windowDays, readMessages });
|
|
67
|
-
if (!messages.some((message) => !message.from_me)) return { outcome: 'no_messages' };
|
|
68
|
-
|
|
69
|
-
const result = await (provider || requireGatewayProvider()).runStructured({
|
|
70
|
-
presetId,
|
|
71
|
-
input: [{ role: 'user', content: transcriptOf(messages) }],
|
|
72
|
-
metadata: { subAgent: 'support-light' },
|
|
73
|
-
});
|
|
74
|
-
if (result?.status && result.status !== 'completed') return { outcome: 'incomplete' };
|
|
75
|
-
const parsed = safeParse(readStructuredText(result), null);
|
|
76
|
-
if (!parsed || typeof parsed !== 'object') return { outcome: 'unparseable' };
|
|
77
|
-
|
|
78
|
-
const changes = [];
|
|
79
|
-
let isPartial = false;
|
|
80
|
-
for (const service of SERVICES) {
|
|
81
|
-
const reading = readingFor(service, parsed[service], messages);
|
|
82
|
-
if (!reading) {
|
|
83
|
-
isPartial = true;
|
|
84
|
-
logger.warn('[supportLightEvaluation] reading skipped: missing or invalid colour', { code: patientId, service });
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
const { light, outcome } = await applyLight({ patientId, service, source: 'ai', now, ...reading });
|
|
88
|
-
if (outcome !== 'unchanged') changes.push({ service, outcome, color: reading.color, revision: light?.revision ?? null });
|
|
89
|
-
}
|
|
90
|
-
return { outcome: isPartial ? 'partial' : 'evaluated', changes };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
|
|
94
|
-
const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
|
|
95
|
-
const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
|
|
96
|
-
const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
|
|
97
|
-
const selected = [];
|
|
98
|
-
for (let page = 0; selected.length < limit; page += 1) {
|
|
99
|
-
const active = await aggregateMessages([
|
|
100
|
-
{ $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
|
|
101
|
-
{ $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
|
|
102
|
-
{ $sort: { lastInboundAt: -1, _id: 1 } },
|
|
103
|
-
{ $skip: page * CANDIDATE_PAGE },
|
|
104
|
-
{ $limit: CANDIDATE_PAGE },
|
|
105
|
-
]);
|
|
106
|
-
const ids = (active || []).map((row) => row._id);
|
|
107
|
-
if (!ids.length) break;
|
|
108
|
-
const recent = await SweepModel.find({
|
|
109
|
-
patientId: { $in: ids },
|
|
110
|
-
$or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }],
|
|
111
|
-
}).select('patientId').lean();
|
|
112
|
-
const done = new Set(recent.map((row) => row.patientId));
|
|
113
|
-
selected.push(...ids.filter((id) => !done.has(id)));
|
|
114
|
-
if (ids.length < CANDIDATE_PAGE) break;
|
|
115
|
-
}
|
|
116
|
-
return selected.slice(0, limit);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function validPatientIds(ids) {
|
|
120
|
-
return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function sweepState(outcome, now) {
|
|
124
|
-
return { lastAttemptAt: now, lastOutcome: outcome, ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}) };
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async function runSupportLightSweep({
|
|
128
|
-
now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
|
|
129
|
-
} = {}, { SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, ...deps } = {}) {
|
|
130
|
-
const candidates = Array.isArray(patientIds)
|
|
131
|
-
? validPatientIds(patientIds).slice(0, limit)
|
|
132
|
-
: await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
|
|
133
|
-
const summary = { evaluated: 0, skipped: 0, failed: 0, changes: [] };
|
|
134
|
-
for (const patientId of candidates) {
|
|
135
|
-
let outcome = 'error';
|
|
136
|
-
try {
|
|
137
|
-
const result = await evaluate({ patientId, now, windowDays }, deps);
|
|
138
|
-
if (result.outcome === 'not_configured') return { ...summary, outcome: 'not_configured' };
|
|
139
|
-
outcome = result.outcome;
|
|
140
|
-
if (outcome === 'evaluated' || outcome === 'partial') {
|
|
141
|
-
summary.evaluated += 1;
|
|
142
|
-
summary.changes.push(...result.changes.map((change) => ({ patientId, ...change })));
|
|
143
|
-
} else {
|
|
144
|
-
summary.skipped += 1;
|
|
145
|
-
}
|
|
146
|
-
} catch (error) {
|
|
147
|
-
summary.failed += 1;
|
|
148
|
-
logger.error('[supportLightEvaluation] patient evaluation failed', { code: patientId, error: error.message, stack: error.stack });
|
|
149
|
-
}
|
|
150
|
-
try {
|
|
151
|
-
await SweepModel.updateOne({ patientId }, { $set: sweepState(outcome, now) }, { upsert: true });
|
|
152
|
-
} catch (stateError) {
|
|
153
|
-
logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return { ...summary, outcome: 'completed' };
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
module.exports = { evaluatePatientSupport, runSupportLightSweep };
|