@peopl-health/nexus 5.51.0-dev.7633 → 5.51.0-dev.7635
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/README.md +21 -0
- package/lib/clinical/AssistantProcessor.js +156 -12
- package/lib/clinical/context/ToolRuntimeContext.js +39 -1
- package/lib/clinical/context/turnContext.js +10 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +28 -0
- package/lib/clinical/providers/BaseLLMProvider.js +45 -5
- package/lib/clinical/services/clinicalAirtableService.js +8 -5
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/divergenceService.js +9 -2
- package/lib/clinical/services/supportActionService.js +129 -0
- package/lib/clinical/services/supportCandidateService.js +532 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/triageRecommendationService.js +453 -251
- package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
- package/lib/clinical/tools/registerClinicalTools.js +2 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +142 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/controllers/escalationReviewController.js +0 -12
- package/lib/core/BatchingManager.js +20 -9
- package/lib/core/NexusMessaging.js +25 -6
- package/lib/core/ProcessingPipeline.js +32 -3
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/index.d.ts +334 -6
- package/lib/index.js +22 -0
- package/lib/models/escalationReviewModel.js +0 -4
- package/lib/routes/index.js +0 -2
- package/lib/services/airtableService.js +8 -1
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +30 -3
- package/lib/services/escalationReviewService.js +4 -36
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/package.json +1 -1
|
@@ -6,6 +6,8 @@ const { logger } = require('../../utils/logger');
|
|
|
6
6
|
|
|
7
7
|
const { runClinicalAgent } = require('./clinicalAgentService');
|
|
8
8
|
|
|
9
|
+
const ORACLE_UNSUPPORTED_TOOLS = new Set(['submitSupportRoutingRecommendation']);
|
|
10
|
+
|
|
9
11
|
async function runDivergence({ request, connection, trace, actualMessage }) {
|
|
10
12
|
let post;
|
|
11
13
|
const startedAt = Date.now();
|
|
@@ -23,7 +25,12 @@ async function runDivergence({ request, connection, trace, actualMessage }) {
|
|
|
23
25
|
const expected = { ...expectedTurn, tools_invoked: oracleToolsInvoked(expectedTurn, request.enabledTools) };
|
|
24
26
|
const expectedMessage = post.body?.response || '';
|
|
25
27
|
|
|
26
|
-
const
|
|
28
|
+
const enabledTools = new Set(request.enabledTools);
|
|
29
|
+
const rawActual = trace.toDecision();
|
|
30
|
+
const actual = {
|
|
31
|
+
...rawActual,
|
|
32
|
+
tools_invoked: (rawActual.tools_invoked || []).filter((name) => enabledTools.has(name)),
|
|
33
|
+
};
|
|
27
34
|
const outcome = await classify({
|
|
28
35
|
expected, actual, expectedMessage, actualMessage,
|
|
29
36
|
});
|
|
@@ -56,7 +63,7 @@ async function diverge({ shadow, runId }) {
|
|
|
56
63
|
clinicalData: inputs.clinicalData,
|
|
57
64
|
input: inputs.input || [],
|
|
58
65
|
model: inputs.model,
|
|
59
|
-
enabledTools: inputs.toolIds || [],
|
|
66
|
+
enabledTools: (inputs.toolIds || []).filter((name) => !ORACLE_UNSUPPORTED_TOOLS.has(name)),
|
|
60
67
|
additionalInstructions: inputs.additionalInstructions || null,
|
|
61
68
|
};
|
|
62
69
|
logger.debug('[divergence] oracle request', { runId, code, model: request.model, inputLen: request.input.length, tools: request.enabledTools.length });
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const { SupportAction } = require('../../shared/dtos/SupportAction');
|
|
2
|
+
const { logger } = require('../../utils/logger');
|
|
3
|
+
const { claimInvitation, recordEngagement, updateSupportOperationalReview } = require('./supportCandidateService');
|
|
4
|
+
|
|
5
|
+
const TEMPLATE_VERSION = 'support-card-v1';
|
|
6
|
+
const URGENT_NUTRITION_TARGET = 'nutrition.urgent_intake';
|
|
7
|
+
|
|
8
|
+
function isSafeGroupCandidate(candidate) {
|
|
9
|
+
if (!candidate.groupEligible) return false;
|
|
10
|
+
return candidate.service === 'nutrition'
|
|
11
|
+
? (candidate.nutritionRisk === 'green' && candidate.disposition === 'group')
|
|
12
|
+
|| (candidate.nutritionRisk === 'yellow' && candidate.disposition === 'individual')
|
|
13
|
+
: candidate.disposition === 'group' && candidate.psychologyRisk === 'green';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function isUrgentNutritionCandidate(candidate) {
|
|
17
|
+
return candidate.service === 'nutrition'
|
|
18
|
+
&& candidate.nutritionRisk === 'yellow'
|
|
19
|
+
&& candidate.urgentIntakeEligible === true
|
|
20
|
+
&& candidate.disposition === 'individual';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function groupContextFor(candidate, deliveryContext) {
|
|
24
|
+
const invitationClass = deliveryContext?.invitationClassByService?.[candidate.service];
|
|
25
|
+
const targetKey = deliveryContext?.targetKeyByService?.[candidate.service];
|
|
26
|
+
if (!['first', 'followup'].includes(invitationClass)) return null;
|
|
27
|
+
if (typeof targetKey !== 'string' || !targetKey.trim()) return null;
|
|
28
|
+
return { invitationClass, targetKey };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function urgentNutritionAction(candidate) {
|
|
32
|
+
return {
|
|
33
|
+
candidateId: candidate.candidateId,
|
|
34
|
+
service: 'nutrition',
|
|
35
|
+
type: 'urgent_nutrition_intake',
|
|
36
|
+
invitationClass: null,
|
|
37
|
+
targetKey: URGENT_NUTRITION_TARGET,
|
|
38
|
+
priority: candidate.priority,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function updateActionReview(review, options) {
|
|
43
|
+
try {
|
|
44
|
+
await updateSupportOperationalReview(review, options);
|
|
45
|
+
} catch (_error) {
|
|
46
|
+
logger.warn('[supportAction] review persistence failed', { sourceId: review.sourceId, service: review.service, reasonCode: review.reasonCode });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function prepareSupportAction({ patientId, sourceId, candidates = [], resolveDeliveryContext, now = new Date() }, options = {}) {
|
|
51
|
+
const patientCandidates = candidates.filter((candidate) => candidate.patientId === patientId);
|
|
52
|
+
const urgentActions = patientCandidates
|
|
53
|
+
.filter(isUrgentNutritionCandidate)
|
|
54
|
+
.map(urgentNutritionAction);
|
|
55
|
+
const groupCandidates = patientCandidates.filter(isSafeGroupCandidate);
|
|
56
|
+
|
|
57
|
+
if (!groupCandidates.length) {
|
|
58
|
+
return urgentActions.length
|
|
59
|
+
? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions: urgentActions })
|
|
60
|
+
: null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let deliveryContext;
|
|
64
|
+
try {
|
|
65
|
+
deliveryContext = await resolveDeliveryContext({ patientId, candidates: groupCandidates });
|
|
66
|
+
} catch (_error) {
|
|
67
|
+
for (const candidate of groupCandidates) await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
|
|
68
|
+
return urgentActions.length
|
|
69
|
+
? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions: urgentActions })
|
|
70
|
+
: null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const claimedActions = [];
|
|
74
|
+
const invitationCycle = new Date(now).toISOString().slice(0, 10);
|
|
75
|
+
for (const candidate of groupCandidates) {
|
|
76
|
+
const context = groupContextFor(candidate, deliveryContext);
|
|
77
|
+
if (!context) {
|
|
78
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
let claimed;
|
|
82
|
+
try {
|
|
83
|
+
const evidence = deliveryContext.attendanceEvidenceByService?.[candidate.service];
|
|
84
|
+
if (context.invitationClass === 'followup') {
|
|
85
|
+
if (!evidence || evidence.patientId !== patientId || evidence.service !== candidate.service
|
|
86
|
+
|| typeof evidence.evidenceId !== 'string' || !evidence.evidenceId.trim()) {
|
|
87
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const recorded = await recordEngagement({
|
|
91
|
+
patientId, service: candidate.service, state: 'attended',
|
|
92
|
+
evidenceId: evidence.evidenceId, occurredAt: null,
|
|
93
|
+
}, { ...options, historicalAttendance: true });
|
|
94
|
+
if (!recorded) {
|
|
95
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
claimed = await claimInvitation({
|
|
100
|
+
candidateId: candidate.candidateId,
|
|
101
|
+
invitationClass: context.invitationClass,
|
|
102
|
+
invitationCycle,
|
|
103
|
+
templateVersion: TEMPLATE_VERSION,
|
|
104
|
+
now,
|
|
105
|
+
}, options);
|
|
106
|
+
if (!claimed) continue;
|
|
107
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable', resolved: true }, options);
|
|
108
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed', resolved: true }, options);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
logger.warn('[supportAction] invitation claim failed', { candidateId: candidate.candidateId, error: error?.message });
|
|
111
|
+
await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed' }, options);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
claimedActions.push({
|
|
115
|
+
candidateId: candidate.candidateId,
|
|
116
|
+
service: candidate.service,
|
|
117
|
+
type: 'group_registration',
|
|
118
|
+
invitationClass: context.invitationClass,
|
|
119
|
+
idempotencyKey: claimed.activeInvitationKey,
|
|
120
|
+
targetKey: context.targetKey,
|
|
121
|
+
priority: candidate.priority,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const actions = [...urgentActions, ...claimedActions];
|
|
126
|
+
return actions.length ? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions }) : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = { prepareSupportAction };
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
const { v4: uuidv4 } = require('uuid');
|
|
2
|
+
|
|
3
|
+
const { getSupportCandidateModel } = require('../models/supportCandidateModel');
|
|
4
|
+
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
5
|
+
|
|
6
|
+
const COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000;
|
|
7
|
+
const DELIVERY_STATUSES = ['sent', 'delivered', 'read', 'failed', 'unknown'];
|
|
8
|
+
const INVITATION_CLASSES = ['first', 'followup'];
|
|
9
|
+
const ENGAGEMENT_STATES = ['notInvited', 'invited', 'registered', 'attended', 'declined'];
|
|
10
|
+
const OPERATIONAL_REASONS = ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'];
|
|
11
|
+
const OPERATIONAL_PLACEHOLDER_VERSION = 'operational-review-v1';
|
|
12
|
+
|
|
13
|
+
function evidenceKey(item) {
|
|
14
|
+
return `${item.source}:${item.sourceId}:${item.code}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalizeEvidence(items = []) {
|
|
18
|
+
const byKey = new Map();
|
|
19
|
+
for (const item of items) byKey.set(evidenceKey(item), { key: evidenceKey(item), ...item });
|
|
20
|
+
return [...byKey.values()];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function initialState(decision) {
|
|
24
|
+
return decision.disposition;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function nextState(existing, decision) {
|
|
28
|
+
if (decision.disposition === 'escalated' || existing?.disposition === 'escalated') return 'escalated';
|
|
29
|
+
return initialState(decision);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function candidatePatch(existing, recommendation, decision) {
|
|
33
|
+
const priorEvidence = normalizeEvidence(existing?.evidence || []);
|
|
34
|
+
const mergedEvidence = normalizeEvidence([...priorEvidence, ...decision.evidence]);
|
|
35
|
+
return {
|
|
36
|
+
disposition: nextState(existing, decision),
|
|
37
|
+
...(decision.disposition === 'escalated' && existing?.disposition !== 'escalated' ? {
|
|
38
|
+
escalation: { risk: decision.psychologyRisk || decision.nutritionRisk, sourceId: recommendation.sourceId, origin: recommendation.origin, detectedAt: new Date(recommendation.createdAt), clearedAt: null },
|
|
39
|
+
} : {}),
|
|
40
|
+
groupEligible: decision.groupEligible,
|
|
41
|
+
urgentIntakeEligible: decision.service === 'nutrition' ? decision.urgentIntakeEligible : false,
|
|
42
|
+
priority: decision.priority,
|
|
43
|
+
confidence: decision.confidence,
|
|
44
|
+
nutritionRisk: decision.service === 'nutrition' ? decision.nutritionRisk : null,
|
|
45
|
+
psychologyRisk: decision.service === 'psychology' ? decision.psychologyRisk : null,
|
|
46
|
+
reasonCodes: [...new Set([...(existing?.reasonCodes || []), ...decision.reasonCodes])],
|
|
47
|
+
evidence: mergedEvidence,
|
|
48
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
|
|
49
|
+
latestSourceId: recommendation.sourceId,
|
|
50
|
+
latestOrigin: recommendation.origin,
|
|
51
|
+
decisionVersion: recommendation.decisionVersion,
|
|
52
|
+
lastEvaluatedAt: new Date(recommendation.createdAt),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isStaleRecommendation(existing, recommendation) {
|
|
57
|
+
if (!existing?.lastEvaluatedAt || existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION) return false;
|
|
58
|
+
return new Date(recommendation.createdAt).getTime() < new Date(existing.lastEvaluatedAt).getTime();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function historicalEvidencePatch(existing, recommendation, decision) {
|
|
62
|
+
return {
|
|
63
|
+
evidence: normalizeEvidence([...(existing?.evidence || []), ...decision.evidence]),
|
|
64
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function upsertDecision(recommendation, decision, options = {}) {
|
|
69
|
+
const Model = options.Model || getSupportCandidateModel();
|
|
70
|
+
const query = { patientId: recommendation.patientId, service: decision.service };
|
|
71
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
72
|
+
const existing = await Model.findOne(query).lean();
|
|
73
|
+
const stale = isStaleRecommendation(existing, recommendation);
|
|
74
|
+
const compareAndSet = existing
|
|
75
|
+
? {
|
|
76
|
+
...query,
|
|
77
|
+
...(existing.revision == null
|
|
78
|
+
? { $or: [{ revision: 0 }, { revision: { $exists: false } }] }
|
|
79
|
+
: { revision: existing.revision }),
|
|
80
|
+
}
|
|
81
|
+
: { ...query, candidateId: { $exists: false } };
|
|
82
|
+
try {
|
|
83
|
+
const updated = await Model.findOneAndUpdate(compareAndSet, {
|
|
84
|
+
$set: stale
|
|
85
|
+
? historicalEvidencePatch(existing, recommendation, decision)
|
|
86
|
+
: candidatePatch(existing, recommendation, decision),
|
|
87
|
+
$setOnInsert: {
|
|
88
|
+
candidateId: uuidv4(),
|
|
89
|
+
patientId: recommendation.patientId,
|
|
90
|
+
service: decision.service,
|
|
91
|
+
},
|
|
92
|
+
$inc: { revision: 1 },
|
|
93
|
+
}, { new: true, upsert: !existing, setDefaultsOnInsert: true });
|
|
94
|
+
if (updated) return stale ? null : updated;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error?.code !== 11000) throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
throw new Error('support candidate changed repeatedly during routing update');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function recordSupportRoutingRecommendation(rawRecommendation, options = {}) {
|
|
103
|
+
const recommendation = rawRecommendation instanceof SupportRoutingRecommendation
|
|
104
|
+
? rawRecommendation
|
|
105
|
+
: new SupportRoutingRecommendation(rawRecommendation);
|
|
106
|
+
const candidates = [];
|
|
107
|
+
for (const decision of recommendation.decisions) {
|
|
108
|
+
const candidate = await upsertDecision(recommendation, decision, options);
|
|
109
|
+
if (candidate) candidates.push(candidate);
|
|
110
|
+
}
|
|
111
|
+
return candidates;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function updateSupportOperationalReview({ patientId, service, reasonCode, sourceId, resolved = false, noClinicalDecision = false, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
115
|
+
if (typeof patientId !== 'string' || !patientId.trim() || !['nutrition', 'psychology'].includes(service)
|
|
116
|
+
|| !OPERATIONAL_REASONS.includes(reasonCode) || typeof sourceId !== 'string' || !sourceId.trim() || sourceId.length > 256) {
|
|
117
|
+
throw new Error('Valid support operational review identity is required');
|
|
118
|
+
}
|
|
119
|
+
const query = { patientId, service };
|
|
120
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
121
|
+
const existing = await Model.findOne(query).lean();
|
|
122
|
+
const reviews = existing?.operationalReviews || [];
|
|
123
|
+
const matches = (review) => review.reasonCode === reasonCode && review.sourceId === sourceId;
|
|
124
|
+
if (resolved && !reviews.some(matches)) return existing;
|
|
125
|
+
const updatedReviews = resolved ? reviews.filter((review) => !matches(review))
|
|
126
|
+
: reviews.some(matches) ? reviews : [...reviews, { reasonCode, sourceId, detectedAt: new Date(now) }];
|
|
127
|
+
const patch = { operationalReviews: updatedReviews.slice(0, 20) };
|
|
128
|
+
if (!resolved) Object.assign(patch, {
|
|
129
|
+
operationalReviewOverflow: existing?.operationalReviewOverflow === true || updatedReviews.length > 20,
|
|
130
|
+
evidence: normalizeEvidence([...(existing?.evidence || []), { source: 'triage', sourceId, code: `support_operational_${reasonCode}`, summary: null, confidence: null }]),
|
|
131
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), sourceId])],
|
|
132
|
+
});
|
|
133
|
+
if (resolved && noClinicalDecision && reasonCode === 'classification_failed'
|
|
134
|
+
&& existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION && !updatedReviews.length && !existing.operationalReviewOverflow) {
|
|
135
|
+
patch.disposition = 'none';
|
|
136
|
+
}
|
|
137
|
+
const owner = existing ? { ...query, revision: existing.revision == null ? { $in: [0, null] } : existing.revision }
|
|
138
|
+
: { ...query, candidateId: { $exists: false } };
|
|
139
|
+
try {
|
|
140
|
+
const updated = await Model.findOneAndUpdate(owner, {
|
|
141
|
+
$set: patch,
|
|
142
|
+
...(!existing ? { $setOnInsert: {
|
|
143
|
+
candidateId: uuidv4(), patientId, service, disposition: 'reviewRequired',
|
|
144
|
+
// Review placeholders must remain ineligible even if the schema default changes.
|
|
145
|
+
groupEligible: false, urgentIntakeEligible: false, confidence: 0,
|
|
146
|
+
decisionVersion: OPERATIONAL_PLACEHOLDER_VERSION, latestSourceId: sourceId,
|
|
147
|
+
latestOrigin: 'triage', lastEvaluatedAt: new Date(now),
|
|
148
|
+
} } : {}),
|
|
149
|
+
$inc: { revision: 1 },
|
|
150
|
+
}, { new: true, upsert: !existing, setDefaultsOnInsert: true });
|
|
151
|
+
if (updated) return updated;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error?.code !== 11000) throw error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
throw new Error('support operational review changed repeatedly');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function requireGroupReview(reviewedRevision, reviewedRisk) {
|
|
160
|
+
if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
|
|
161
|
+
if (!['green', 'yellow'].includes(reviewedRisk)) throw new Error('reviewedRisk must be safe for group approval');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function reviewedGroupPatch(service, reviewedRisk, reviewedAt) {
|
|
165
|
+
return {
|
|
166
|
+
disposition: service === 'nutrition' && reviewedRisk === 'yellow' ? 'individual' : 'group',
|
|
167
|
+
groupEligible: true,
|
|
168
|
+
specialistClearedAt: reviewedAt,
|
|
169
|
+
[service === 'nutrition' ? 'nutritionRisk' : 'psychologyRisk']: reviewedRisk,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function approveCandidate(candidateId, {
|
|
174
|
+
reviewedRevision, reviewedRisk, Model = getSupportCandidateModel(),
|
|
175
|
+
} = {}) {
|
|
176
|
+
requireGroupReview(reviewedRevision, reviewedRisk);
|
|
177
|
+
const reviewedAt = new Date();
|
|
178
|
+
const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
|
|
179
|
+
for (const service of services) {
|
|
180
|
+
const approved = await Model.findOneAndUpdate(
|
|
181
|
+
{ candidateId, service, disposition: 'reviewRequired', revision: reviewedRevision },
|
|
182
|
+
{ $set: reviewedGroupPatch(service, reviewedRisk, reviewedAt), $inc: { revision: 1 } },
|
|
183
|
+
{ new: true },
|
|
184
|
+
);
|
|
185
|
+
if (approved) return approved;
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion }) {
|
|
191
|
+
return `${candidateId}:${invitationClass}:${invitationCycle}:${templateVersion}`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function claimEligibility({ candidateId, invitationClass, now }) {
|
|
195
|
+
return {
|
|
196
|
+
candidateId,
|
|
197
|
+
groupEligible: true,
|
|
198
|
+
$and: [{ $or: [
|
|
199
|
+
{ service: 'nutrition', disposition: { $in: ['group', 'individual'] } },
|
|
200
|
+
{ service: 'psychology', disposition: 'group', psychologyRisk: 'green' },
|
|
201
|
+
] }],
|
|
202
|
+
activeInvitationKey: null,
|
|
203
|
+
'engagement.state': { $in: ['notInvited', 'invited', 'registered', 'attended'] },
|
|
204
|
+
'engagement.attendanceEvidenceId': invitationClass === 'followup' ? { $ne: null } : null,
|
|
205
|
+
$or: [
|
|
206
|
+
{ 'engagement.cooldownUntil': null },
|
|
207
|
+
{ 'engagement.cooldownUntil': { $lte: now } },
|
|
208
|
+
],
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function claimInvitation({ candidateId, invitationClass, invitationCycle, templateVersion, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
213
|
+
if (!INVITATION_CLASSES.includes(invitationClass)) throw new Error(`invalid invitation class: ${invitationClass}`);
|
|
214
|
+
if (!invitationCycle) throw new Error('invitationCycle is required');
|
|
215
|
+
if (!templateVersion) throw new Error('templateVersion is required');
|
|
216
|
+
const claimedAt = new Date(now);
|
|
217
|
+
const idempotencyKey = invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion });
|
|
218
|
+
const eligibility = claimEligibility({ candidateId, invitationClass, now: claimedAt });
|
|
219
|
+
const claimed = await Model.findOneAndUpdate({
|
|
220
|
+
...eligibility,
|
|
221
|
+
'invitationAttempts.idempotencyKey': { $ne: idempotencyKey },
|
|
222
|
+
}, {
|
|
223
|
+
$set: { activeInvitationKey: idempotencyKey },
|
|
224
|
+
$push: {
|
|
225
|
+
invitationAttempts: {
|
|
226
|
+
idempotencyKey,
|
|
227
|
+
invitationClass,
|
|
228
|
+
invitationCycle,
|
|
229
|
+
templateVersion,
|
|
230
|
+
status: 'queued',
|
|
231
|
+
createdAt: claimedAt,
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
$inc: { revision: 1 },
|
|
235
|
+
}, { new: true });
|
|
236
|
+
if (claimed) return claimed;
|
|
237
|
+
return Model.findOneAndUpdate({
|
|
238
|
+
...eligibility,
|
|
239
|
+
invitationAttempts: { $elemMatch: { idempotencyKey, status: 'failed' } },
|
|
240
|
+
}, {
|
|
241
|
+
$set: {
|
|
242
|
+
activeInvitationKey: idempotencyKey,
|
|
243
|
+
'invitationAttempts.$[attempt].status': 'queued',
|
|
244
|
+
'invitationAttempts.$[attempt].providerMessageId': null,
|
|
245
|
+
'invitationAttempts.$[attempt].error': null,
|
|
246
|
+
'invitationAttempts.$[attempt].createdAt': claimedAt,
|
|
247
|
+
'invitationAttempts.$[attempt].settledAt': null,
|
|
248
|
+
},
|
|
249
|
+
$inc: { revision: 1 },
|
|
250
|
+
}, {
|
|
251
|
+
new: true,
|
|
252
|
+
arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': 'failed' }],
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function attemptSettlement({ status, providerMessageId, error, now }) {
|
|
257
|
+
return {
|
|
258
|
+
'invitationAttempts.$[attempt].status': status,
|
|
259
|
+
'invitationAttempts.$[attempt].settledAt': now,
|
|
260
|
+
'invitationAttempts.$[attempt].error': error,
|
|
261
|
+
...(providerMessageId ? { 'invitationAttempts.$[attempt].providerMessageId': providerMessageId } : {}),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function settleActiveAttempt({ candidateId, idempotencyKey, status, providerMessageId, error, now }, engagementStates, engagementPatch, Model) {
|
|
266
|
+
const priorStatuses = ['queued', 'unknown'];
|
|
267
|
+
return Model.findOneAndUpdate({
|
|
268
|
+
candidateId,
|
|
269
|
+
activeInvitationKey: idempotencyKey,
|
|
270
|
+
'engagement.state': { $in: engagementStates },
|
|
271
|
+
invitationAttempts: { $elemMatch: { idempotencyKey, status: { $in: priorStatuses } } },
|
|
272
|
+
}, {
|
|
273
|
+
$set: {
|
|
274
|
+
...attemptSettlement({ idempotencyKey, status, providerMessageId, error, now }),
|
|
275
|
+
...engagementPatch,
|
|
276
|
+
},
|
|
277
|
+
$inc: { revision: 1 },
|
|
278
|
+
}, {
|
|
279
|
+
new: true,
|
|
280
|
+
arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function settleFirstSuccess(args, Model) {
|
|
285
|
+
const cooldownUntil = new Date(args.now.getTime() + COOLDOWN_MS);
|
|
286
|
+
const deliveryPatch = {
|
|
287
|
+
activeInvitationKey: null,
|
|
288
|
+
cooldownInvitationKey: args.idempotencyKey,
|
|
289
|
+
'engagement.lastInvitedAt': args.now,
|
|
290
|
+
'engagement.cooldownUntil': cooldownUntil,
|
|
291
|
+
};
|
|
292
|
+
const invited = await settleActiveAttempt(
|
|
293
|
+
args,
|
|
294
|
+
['notInvited', 'invited'],
|
|
295
|
+
{ ...deliveryPatch, 'engagement.state': 'invited' },
|
|
296
|
+
Model,
|
|
297
|
+
);
|
|
298
|
+
if (invited) return invited;
|
|
299
|
+
return settleActiveAttempt(args, ['registered', 'attended', 'declined'], deliveryPatch, Model);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function advanceSuccessfulAttempt(args, Model) {
|
|
303
|
+
const priorStatuses = args.status === 'delivered' ? ['sent'] : ['sent', 'delivered'];
|
|
304
|
+
if (!['delivered', 'read'].includes(args.status)) return null;
|
|
305
|
+
return Model.findOneAndUpdate({
|
|
306
|
+
candidateId: args.candidateId,
|
|
307
|
+
invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: { $in: priorStatuses } } },
|
|
308
|
+
}, {
|
|
309
|
+
$set: attemptSettlement(args),
|
|
310
|
+
$inc: { revision: 1 },
|
|
311
|
+
}, {
|
|
312
|
+
new: true,
|
|
313
|
+
arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function settleSentFailure(args, Model) {
|
|
318
|
+
const query = {
|
|
319
|
+
candidateId: args.candidateId,
|
|
320
|
+
invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: 'sent' } },
|
|
321
|
+
};
|
|
322
|
+
const options = {
|
|
323
|
+
new: true,
|
|
324
|
+
arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': 'sent' }],
|
|
325
|
+
};
|
|
326
|
+
const ownedCooldown = await Model.findOneAndUpdate({
|
|
327
|
+
...query,
|
|
328
|
+
cooldownInvitationKey: args.idempotencyKey,
|
|
329
|
+
}, {
|
|
330
|
+
$set: {
|
|
331
|
+
...attemptSettlement(args),
|
|
332
|
+
cooldownInvitationKey: null,
|
|
333
|
+
'engagement.cooldownUntil': null,
|
|
334
|
+
},
|
|
335
|
+
$inc: { revision: 1 },
|
|
336
|
+
}, options);
|
|
337
|
+
if (ownedCooldown) return ownedCooldown;
|
|
338
|
+
return Model.findOneAndUpdate({
|
|
339
|
+
...query,
|
|
340
|
+
cooldownInvitationKey: { $ne: args.idempotencyKey },
|
|
341
|
+
}, {
|
|
342
|
+
$set: attemptSettlement(args),
|
|
343
|
+
$inc: { revision: 1 },
|
|
344
|
+
}, options);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function settleInvitation({ candidateId, idempotencyKey, status, providerMessageId = null, error = null, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
348
|
+
if (!DELIVERY_STATUSES.includes(status)) throw new Error(`invalid invitation outcome: ${status}`);
|
|
349
|
+
const args = { candidateId, idempotencyKey, status, providerMessageId, error, now: new Date(now) };
|
|
350
|
+
if (status === 'unknown') {
|
|
351
|
+
return settleActiveAttempt(args, ENGAGEMENT_STATES, {}, Model);
|
|
352
|
+
}
|
|
353
|
+
if (status === 'failed') {
|
|
354
|
+
const activeFailure = await settleActiveAttempt(args, ENGAGEMENT_STATES, {
|
|
355
|
+
activeInvitationKey: null,
|
|
356
|
+
cooldownInvitationKey: null,
|
|
357
|
+
'engagement.cooldownUntil': null,
|
|
358
|
+
}, Model);
|
|
359
|
+
return activeFailure || settleSentFailure(args, Model);
|
|
360
|
+
}
|
|
361
|
+
const firstSuccess = await settleFirstSuccess(args, Model);
|
|
362
|
+
return firstSuccess || advanceSuccessfulAttempt(args, Model);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function engagementPatch(state, evidenceId, occurredAt, preference) {
|
|
366
|
+
const patch = { 'engagement.state': state };
|
|
367
|
+
if (state === 'registered') {
|
|
368
|
+
patch['engagement.registrationEvidenceId'] = evidenceId;
|
|
369
|
+
patch['engagement.registeredAt'] = occurredAt;
|
|
370
|
+
} else if (state === 'attended') {
|
|
371
|
+
patch['engagement.attendanceEvidenceId'] = evidenceId;
|
|
372
|
+
if (occurredAt != null) patch['engagement.attendedAt'] = occurredAt;
|
|
373
|
+
} else if (state === 'declined') {
|
|
374
|
+
patch['engagement.declineEvidenceId'] = evidenceId;
|
|
375
|
+
patch['engagement.declinedAt'] = occurredAt;
|
|
376
|
+
patch['engagement.declinePreference'] = preference;
|
|
377
|
+
}
|
|
378
|
+
return patch;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async function recordEngagement({ patientId, service, state, evidenceId = null, occurredAt = new Date(), preference = null }, { Model = getSupportCandidateModel(), historicalAttendance = false } = {}) {
|
|
382
|
+
if (!ENGAGEMENT_STATES.includes(state)) throw new Error(`invalid engagement state: ${state}`);
|
|
383
|
+
if (state === 'attended' && (typeof evidenceId !== 'string' || !evidenceId.trim())) {
|
|
384
|
+
throw new Error('attendance evidenceId is required');
|
|
385
|
+
}
|
|
386
|
+
const allowedPriorStates = state === 'invited'
|
|
387
|
+
? ['notInvited', 'invited']
|
|
388
|
+
: state === 'registered'
|
|
389
|
+
? ['notInvited', 'invited', 'registered']
|
|
390
|
+
: historicalAttendance ? ENGAGEMENT_STATES.filter((prior) => prior !== 'declined') : ENGAGEMENT_STATES;
|
|
391
|
+
return Model.findOneAndUpdate({
|
|
392
|
+
patientId,
|
|
393
|
+
service,
|
|
394
|
+
'engagement.state': { $in: allowedPriorStates },
|
|
395
|
+
}, {
|
|
396
|
+
$set: engagementPatch(state, evidenceId, occurredAt == null ? null : new Date(occurredAt), preference),
|
|
397
|
+
$inc: { revision: 1 },
|
|
398
|
+
}, { new: true });
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function markInvitedCandidateAccepted({ patientId, service, sessionId = null }, { Model = getSupportCandidateModel() } = {}) {
|
|
402
|
+
return Model.findOneAndUpdate({
|
|
403
|
+
patientId,
|
|
404
|
+
service,
|
|
405
|
+
activeInvitationKey: null,
|
|
406
|
+
cooldownInvitationKey: null,
|
|
407
|
+
$or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
|
|
408
|
+
'engagement.state': { $in: ['notInvited', 'invited', 'registered'] },
|
|
409
|
+
}, {
|
|
410
|
+
$set: engagementPatch('registered', sessionId, new Date(), null),
|
|
411
|
+
$inc: { revision: 1 },
|
|
412
|
+
}, { new: true });
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function markInvitedCandidateDeclined({ patientId, service, preference = 'not_now' }, { Model = getSupportCandidateModel() } = {}) {
|
|
416
|
+
if (!['another_date', 'not_now', 'never'].includes(preference)) throw new Error(`invalid decline preference: ${preference}`);
|
|
417
|
+
return Model.findOneAndUpdate({
|
|
418
|
+
patientId,
|
|
419
|
+
service,
|
|
420
|
+
activeInvitationKey: null,
|
|
421
|
+
cooldownInvitationKey: null,
|
|
422
|
+
$or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
|
|
423
|
+
'engagement.state': { $in: ENGAGEMENT_STATES },
|
|
424
|
+
}, {
|
|
425
|
+
$set: engagementPatch('declined', null, new Date(), preference),
|
|
426
|
+
$inc: { revision: 1 },
|
|
427
|
+
}, { new: true });
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function recordLegacyInvitationResponse({ patientId, service, outcome, sessionId = null, preference = 'not_now' }, options = {}) {
|
|
431
|
+
if (outcome === 'accepted') {
|
|
432
|
+
if (!sessionId) throw new Error('sessionId is required for a legacy acceptance');
|
|
433
|
+
return markInvitedCandidateAccepted({ patientId, service, sessionId }, options);
|
|
434
|
+
}
|
|
435
|
+
if (outcome === 'declined') return markInvitedCandidateDeclined({ patientId, service, preference }, options);
|
|
436
|
+
throw new Error(`invalid legacy invitation outcome: ${outcome}`);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function markCandidateAccepted(args, options = {}) {
|
|
440
|
+
return markInvitedCandidateAccepted(args, options);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function markCandidateDeclined(args, options = {}) {
|
|
444
|
+
return markInvitedCandidateDeclined(args, options);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async function rescheduleDeclinedCandidate(candidateId, { Model = getSupportCandidateModel() } = {}) {
|
|
448
|
+
return Model.findOneAndUpdate(
|
|
449
|
+
{ candidateId, 'engagement.state': 'declined', 'engagement.declinePreference': 'another_date' },
|
|
450
|
+
{
|
|
451
|
+
$set: { 'engagement.state': 'notInvited', 'engagement.declinePreference': null },
|
|
452
|
+
$inc: { revision: 1 },
|
|
453
|
+
},
|
|
454
|
+
{ new: true },
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function clearCandidateEscalation(candidateId, {
|
|
459
|
+
reviewedRevision, approvedForGroup = false, reviewedRisk, Model = getSupportCandidateModel(),
|
|
460
|
+
} = {}) {
|
|
461
|
+
if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
|
|
462
|
+
if (approvedForGroup) requireGroupReview(reviewedRevision, reviewedRisk);
|
|
463
|
+
const reviewedAt = new Date();
|
|
464
|
+
if (approvedForGroup) {
|
|
465
|
+
const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
|
|
466
|
+
for (const service of services) {
|
|
467
|
+
const cleared = await Model.findOneAndUpdate(
|
|
468
|
+
{ candidateId, service, disposition: 'escalated', revision: reviewedRevision },
|
|
469
|
+
{
|
|
470
|
+
$set: {
|
|
471
|
+
...reviewedGroupPatch(service, reviewedRisk, reviewedAt),
|
|
472
|
+
'escalation.clearedAt': reviewedAt,
|
|
473
|
+
},
|
|
474
|
+
$inc: { revision: 1 },
|
|
475
|
+
},
|
|
476
|
+
{ new: true },
|
|
477
|
+
);
|
|
478
|
+
if (cleared) return cleared;
|
|
479
|
+
}
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
return Model.findOneAndUpdate(
|
|
483
|
+
{ candidateId, disposition: 'escalated', revision: reviewedRevision },
|
|
484
|
+
{
|
|
485
|
+
$set: {
|
|
486
|
+
disposition: 'reviewRequired',
|
|
487
|
+
groupEligible: false,
|
|
488
|
+
specialistClearedAt: reviewedAt,
|
|
489
|
+
'escalation.clearedAt': reviewedAt,
|
|
490
|
+
},
|
|
491
|
+
$inc: { revision: 1 },
|
|
492
|
+
},
|
|
493
|
+
{ new: true },
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function readSupportDashboardCandidates() {
|
|
498
|
+
const rows = await getSupportCandidateModel().find({
|
|
499
|
+
service: { $in: ['nutrition', 'psychology'] },
|
|
500
|
+
$or: [
|
|
501
|
+
{ disposition: { $in: ['reviewRequired', 'escalated'] } },
|
|
502
|
+
{ service: 'psychology', disposition: 'individual', psychologyRisk: 'orange' },
|
|
503
|
+
{ 'operationalReviews.0': { $exists: true } },
|
|
504
|
+
{ operationalReviewOverflow: true },
|
|
505
|
+
{ invitationAttempts: { $elemMatch: { status: { $in: ['failed', 'unknown'] } } } },
|
|
506
|
+
],
|
|
507
|
+
})
|
|
508
|
+
.select('-_id candidateId patientId service disposition psychologyRisk escalation operationalReviews operationalReviewOverflow reasonCodes createdAt lastEvaluatedAt invitationAttempts.invitationCycle invitationAttempts.status invitationAttempts.createdAt')
|
|
509
|
+
.limit(1001).maxTimeMS(10000).lean();
|
|
510
|
+
if (rows.length > 1000) throw new Error('Support dashboard candidates incomplete');
|
|
511
|
+
return rows;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
module.exports = {
|
|
515
|
+
updateSupportOperationalReview,
|
|
516
|
+
readSupportDashboardCandidates,
|
|
517
|
+
approveCandidate,
|
|
518
|
+
candidatePatch,
|
|
519
|
+
claimInvitation,
|
|
520
|
+
clearCandidateEscalation,
|
|
521
|
+
evidenceKey,
|
|
522
|
+
initialState,
|
|
523
|
+
markCandidateAccepted,
|
|
524
|
+
markCandidateDeclined,
|
|
525
|
+
nextState,
|
|
526
|
+
normalizeEvidence,
|
|
527
|
+
recordEngagement,
|
|
528
|
+
recordLegacyInvitationResponse,
|
|
529
|
+
recordSupportRoutingRecommendation,
|
|
530
|
+
rescheduleDeclinedCandidate,
|
|
531
|
+
settleInvitation,
|
|
532
|
+
};
|