@peopl-health/nexus 5.60.0-dev.11092 → 5.60.0-dev.11094
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/adapters/messageAdapters/TwilioMessageAdapter.js +0 -1
- package/lib/clinical/models/supportLightModel.js +72 -0
- package/lib/clinical/services/supportInvitability.js +65 -1
- package/lib/clinical/services/supportLightService.js +204 -0
- package/lib/index.d.ts +101 -4
- package/lib/index.js +4 -0
- package/lib/services/messageService.js +1 -4
- package/lib/storage/MongoStorage.js +2 -12
- package/lib/utils/dateUtils.js +7 -0
- package/package.json +1 -1
- package/lib/clinical/models/clinicalSourceEventModel.js +0 -32
- package/lib/clinical/services/clinicalEventService.js +0 -132
- package/lib/clinical/services/clinicalMessageCaptureService.js +0 -69
|
@@ -26,7 +26,6 @@ class TwilioMessageAdapter extends MessageAdapter {
|
|
|
26
26
|
processed: false,
|
|
27
27
|
pushName: rawMessage.ProfileName || null,
|
|
28
28
|
body,
|
|
29
|
-
normalizedContent: contactBody ? { type: 'extracted_contact', text: contactBody } : null,
|
|
30
29
|
media,
|
|
31
30
|
interactive,
|
|
32
31
|
quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const lightEvidenceSchema = new mongoose.Schema({
|
|
6
|
+
source: { type: String, required: true, enum: ['triage', 'chat', 'specialist', 'sweep'] },
|
|
7
|
+
sourceId: { type: String, required: true },
|
|
8
|
+
summary: { type: String, default: null, maxlength: 1000 },
|
|
9
|
+
}, { _id: false });
|
|
10
|
+
|
|
11
|
+
const lightEventSchema = new mongoose.Schema({
|
|
12
|
+
outcome: { type: String, required: true, enum: ['applied', 'pending', 'withdrawn', 'accepted', 'rejected'] },
|
|
13
|
+
from: { type: String, default: null },
|
|
14
|
+
to: { type: String, required: true },
|
|
15
|
+
source: { type: String, required: true, enum: ['ai', 'human'] },
|
|
16
|
+
actor: { type: String, required: true },
|
|
17
|
+
evidence: { type: [lightEvidenceSchema], default: [] },
|
|
18
|
+
reason: { type: String, default: null, maxlength: 1000 },
|
|
19
|
+
revision: { type: Number, required: true },
|
|
20
|
+
at: { type: Date, required: true },
|
|
21
|
+
}, { _id: false });
|
|
22
|
+
|
|
23
|
+
const supportLightSchema = new mongoose.Schema({
|
|
24
|
+
patientId: { type: String, required: true },
|
|
25
|
+
service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
|
|
26
|
+
color: { type: String, required: true },
|
|
27
|
+
source: { type: String, required: true, enum: ['ai', 'human'] },
|
|
28
|
+
setBy: { type: String, required: true },
|
|
29
|
+
setAt: { type: Date, required: true },
|
|
30
|
+
evidence: { type: [lightEvidenceSchema], default: [] },
|
|
31
|
+
reason: { type: String, default: null, maxlength: 1000 },
|
|
32
|
+
pendingImprovement: {
|
|
33
|
+
type: new mongoose.Schema({
|
|
34
|
+
color: { type: String, required: true },
|
|
35
|
+
proposedBy: { type: String, required: true },
|
|
36
|
+
proposedAt: { type: Date, required: true },
|
|
37
|
+
evidence: { type: [lightEvidenceSchema], default: [] },
|
|
38
|
+
reason: { type: String, default: null, maxlength: 1000 },
|
|
39
|
+
}, { _id: false }),
|
|
40
|
+
default: null,
|
|
41
|
+
},
|
|
42
|
+
outbox: { type: [lightEventSchema], default: [] },
|
|
43
|
+
revision: { type: Number, default: 0 },
|
|
44
|
+
}, { timestamps: true });
|
|
45
|
+
|
|
46
|
+
supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
|
|
47
|
+
supportLightSchema.index({ service: 1, color: 1 });
|
|
48
|
+
supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
|
|
49
|
+
|
|
50
|
+
const supportLightEventSchema = new mongoose.Schema({
|
|
51
|
+
patientId: { type: String, required: true },
|
|
52
|
+
service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
|
|
53
|
+
...lightEventSchema.obj,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
57
|
+
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
58
|
+
|
|
59
|
+
function getSupportLightModel() {
|
|
60
|
+
const conn = clinicalConnection();
|
|
61
|
+
return conn.models.SupportLight || conn.model('SupportLight', supportLightSchema, 'supportLights');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function getSupportLightEventModel() {
|
|
65
|
+
const conn = clinicalConnection();
|
|
66
|
+
return conn.models.SupportLightEvent
|
|
67
|
+
|| conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = {
|
|
71
|
+
getSupportLightModel, getSupportLightEventModel, supportLightSchema, supportLightEventSchema,
|
|
72
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { mexicoIsoWeek } = require('../../utils/dateUtils');
|
|
2
|
+
|
|
1
3
|
/* Who may be invited to a collective support session.
|
|
2
4
|
*
|
|
3
5
|
* Lives apart from supportCandidateService and supportActionService because those two are
|
|
@@ -17,4 +19,66 @@ function isSafeGroupCandidate(candidate) {
|
|
|
17
19
|
.every(([field, value]) => candidate[field] === value));
|
|
18
20
|
}
|
|
19
21
|
|
|
20
|
-
|
|
22
|
+
const LIGHT_SCALE = Object.freeze({
|
|
23
|
+
nutrition: Object.freeze(['green', 'yellow', 'red']),
|
|
24
|
+
psychology: Object.freeze(['green', 'orange', 'red']),
|
|
25
|
+
});
|
|
26
|
+
const LIGHT_SOURCES = Object.freeze(['ai', 'human']);
|
|
27
|
+
|
|
28
|
+
function lightRank(service, color) {
|
|
29
|
+
return LIGHT_SCALE[service]?.indexOf(color) ?? -1;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function assertLight(service, color) {
|
|
33
|
+
if (!LIGHT_SCALE[service]) throw new Error(`invalid support service: ${service}`);
|
|
34
|
+
if (color !== 'unknown' && lightRank(service, color) === -1) throw new Error(`invalid ${service} light: ${color}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function nextLight(current, { service, color, source }) {
|
|
38
|
+
assertLight(service, color);
|
|
39
|
+
if (!LIGHT_SOURCES.includes(source)) throw new Error(`invalid light source: ${source}`);
|
|
40
|
+
const currentColor = current?.color ?? 'unknown';
|
|
41
|
+
const pendingColor = current?.pendingImprovement?.color ?? null;
|
|
42
|
+
if (source === 'human') return { outcome: 'applied', color, source, pendingImprovement: null };
|
|
43
|
+
if (color === 'unknown') return { outcome: 'unchanged' };
|
|
44
|
+
if (color === currentColor) return pendingColor ? { outcome: 'withdrawn', pendingImprovement: null } : { outcome: 'unchanged' };
|
|
45
|
+
if (currentColor === 'unknown' || lightRank(service, color) > lightRank(service, currentColor)) {
|
|
46
|
+
return { outcome: 'applied', color, source, pendingImprovement: null };
|
|
47
|
+
}
|
|
48
|
+
if (color === pendingColor) return { outcome: 'unchanged' };
|
|
49
|
+
return { outcome: 'pending', pendingImprovement: { color } };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const WEEKLY_COLLECTIVE_LIMIT = Object.freeze({ psychology: 1 });
|
|
53
|
+
|
|
54
|
+
function collectiveOffer({
|
|
55
|
+
service, color = 'unknown', invitationPaused = false, invitedThisWeek = false,
|
|
56
|
+
collectivesThisWeek = 0, hasCapacity = false,
|
|
57
|
+
}) {
|
|
58
|
+
assertLight(service, color);
|
|
59
|
+
const refuse = (reason) => ({ allowed: false, reason });
|
|
60
|
+
if (color === 'red') return refuse('light_red');
|
|
61
|
+
if (service === 'psychology' && color === 'orange') return refuse('light_orange');
|
|
62
|
+
if (service === 'psychology' && color === 'unknown') return refuse('light_unconfirmed');
|
|
63
|
+
if (invitationPaused) return refuse('invitation_paused');
|
|
64
|
+
if (invitedThisWeek) return refuse('already_invited_this_week');
|
|
65
|
+
const limit = WEEKLY_COLLECTIVE_LIMIT[service];
|
|
66
|
+
if (limit != null && collectivesThisWeek >= limit) return refuse('weekly_limit');
|
|
67
|
+
if (!hasCapacity) return refuse('no_capacity');
|
|
68
|
+
return { allowed: true, reason: null };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function supportWeek(date) {
|
|
72
|
+
return mexicoIsoWeek(date);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = {
|
|
76
|
+
GROUP_INVITABLE,
|
|
77
|
+
isSafeGroupCandidate,
|
|
78
|
+
LIGHT_SCALE,
|
|
79
|
+
LIGHT_SOURCES,
|
|
80
|
+
WEEKLY_COLLECTIVE_LIMIT,
|
|
81
|
+
nextLight,
|
|
82
|
+
collectiveOffer,
|
|
83
|
+
supportWeek,
|
|
84
|
+
};
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
|
|
2
|
+
const { logger } = require('../../utils/logger');
|
|
3
|
+
const { nextLight } = require('./supportInvitability');
|
|
4
|
+
|
|
5
|
+
const AI_ACTOR = 'ai';
|
|
6
|
+
const BOARD_LIMIT = 2000;
|
|
7
|
+
const HISTORY_READ_LIMIT = 200;
|
|
8
|
+
|
|
9
|
+
function requireText(value, name) {
|
|
10
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function requireReviewedRevision(value) {
|
|
14
|
+
if (value !== null && !(Number.isInteger(value) && value >= 0)) {
|
|
15
|
+
throw new Error('reviewedRevision is required: the revision the specialist saw, or null for no light yet');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function actorFor(source, actor) {
|
|
20
|
+
if (source === 'ai') return actor || AI_ACTOR;
|
|
21
|
+
requireText(actor, 'actor');
|
|
22
|
+
return actor;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function lightPatch(change, { actor, evidence, reason, now }) {
|
|
26
|
+
if (change.outcome === 'pending') {
|
|
27
|
+
return { pendingImprovement: { ...change.pendingImprovement, proposedBy: actor, proposedAt: now, evidence, reason } };
|
|
28
|
+
}
|
|
29
|
+
if (change.outcome === 'withdrawn') return { pendingImprovement: null };
|
|
30
|
+
return {
|
|
31
|
+
color: change.color, source: change.source, setBy: actor, setAt: now,
|
|
32
|
+
evidence, reason, pendingImprovement: null,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function flushOutbox(EventModel, light) {
|
|
37
|
+
for (const event of light?.outbox || []) {
|
|
38
|
+
const key = { patientId: light.patientId, service: light.service, revision: event.revision };
|
|
39
|
+
try {
|
|
40
|
+
await EventModel.updateOne(key, { $setOnInsert: { ...event, ...key } }, { upsert: true });
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error?.code !== 11000) throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function settleOutbox(Model, EventModel, light) {
|
|
48
|
+
try {
|
|
49
|
+
await flushOutbox(EventModel, light);
|
|
50
|
+
await Model.updateOne(
|
|
51
|
+
{ patientId: light.patientId, service: light.service, revision: light.revision },
|
|
52
|
+
{ $set: { outbox: [] } },
|
|
53
|
+
);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
logger.warn('[supportLight] history entry left in the outbox', {
|
|
56
|
+
code: light.patientId, service: light.service, revision: light.revision, error: error.message, stack: error.stack,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function writeLight(Model, query, existing, patch, event) {
|
|
62
|
+
const owner = existing ? { ...query, revision: existing.revision } : { ...query, setAt: { $exists: false } };
|
|
63
|
+
const revision = (existing?.revision ?? 0) + 1;
|
|
64
|
+
try {
|
|
65
|
+
return await Model.findOneAndUpdate(owner, {
|
|
66
|
+
$set: { ...patch, outbox: [{ ...event, revision }] },
|
|
67
|
+
...(!existing ? { $setOnInsert: query } : {}),
|
|
68
|
+
$inc: { revision: 1 },
|
|
69
|
+
}, { new: true, upsert: !existing, setDefaultsOnInsert: true, lean: true });
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error?.code === 11000) return null;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function eventFor(change, existing, { color, source, actor, evidence, reason, at }) {
|
|
77
|
+
const pendingColor = existing?.pendingImprovement?.color ?? null;
|
|
78
|
+
if (change.outcome === 'withdrawn') {
|
|
79
|
+
return { outcome: 'withdrawn', from: existing.color, to: pendingColor, source, actor, evidence, reason, at };
|
|
80
|
+
}
|
|
81
|
+
return { outcome: change.outcome, from: existing?.color ?? null, to: color, source, actor, evidence, reason, at };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function applySupportLight({
|
|
85
|
+
patientId, service, color, source, actor = null, evidence = [], reason = null, now = new Date(), reviewedRevision,
|
|
86
|
+
}, { Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
|
|
87
|
+
requireText(patientId, 'patientId');
|
|
88
|
+
const who = actorFor(source, actor);
|
|
89
|
+
const isHuman = source === 'human';
|
|
90
|
+
if (isHuman) requireReviewedRevision(reviewedRevision);
|
|
91
|
+
const at = new Date(now);
|
|
92
|
+
const query = { patientId, service };
|
|
93
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
94
|
+
const existing = await Model.findOne(query).lean();
|
|
95
|
+
if (isHuman && (existing?.revision ?? null) !== reviewedRevision) return { light: existing, outcome: 'stale' };
|
|
96
|
+
const change = nextLight(existing, { service, color, source });
|
|
97
|
+
if (change.outcome === 'unchanged') return { light: existing, outcome: 'unchanged' };
|
|
98
|
+
await flushOutbox(EventModel, existing);
|
|
99
|
+
const event = eventFor(change, existing, { color, source, actor: who, evidence, reason, at });
|
|
100
|
+
const light = await writeLight(Model, query, existing, lightPatch(change, { actor: who, evidence, reason, now: at }), event);
|
|
101
|
+
if (light) {
|
|
102
|
+
await settleOutbox(Model, EventModel, light);
|
|
103
|
+
return { light, outcome: change.outcome };
|
|
104
|
+
}
|
|
105
|
+
if (isHuman) return { light: await Model.findOne(query).lean(), outcome: 'stale' };
|
|
106
|
+
}
|
|
107
|
+
throw new Error('support light changed repeatedly during update');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function resolvePendingImprovement({
|
|
111
|
+
patientId, service, accept, actor, reviewedRevision, now = new Date(),
|
|
112
|
+
}, { Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
|
|
113
|
+
requireText(patientId, 'patientId');
|
|
114
|
+
requireText(actor, 'actor');
|
|
115
|
+
if (typeof accept !== 'boolean') throw new Error('accept must be a boolean');
|
|
116
|
+
if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
|
|
117
|
+
const at = new Date(now);
|
|
118
|
+
const query = { patientId, service, revision: reviewedRevision, pendingImprovement: { $ne: null } };
|
|
119
|
+
const existing = await Model.findOne(query).lean();
|
|
120
|
+
if (!existing?.pendingImprovement) return null;
|
|
121
|
+
await flushOutbox(EventModel, existing);
|
|
122
|
+
const pending = existing.pendingImprovement;
|
|
123
|
+
const patch = accept
|
|
124
|
+
? { color: pending.color, source: 'human', setBy: actor, setAt: at, evidence: pending.evidence || [], reason: pending.reason ?? null, pendingImprovement: null }
|
|
125
|
+
: { pendingImprovement: null };
|
|
126
|
+
const event = {
|
|
127
|
+
outcome: accept ? 'accepted' : 'rejected', from: existing.color, to: pending.color, source: 'human', actor,
|
|
128
|
+
evidence: pending.evidence || [], reason: pending.reason ?? null, at, revision: reviewedRevision + 1,
|
|
129
|
+
};
|
|
130
|
+
const light = await Model.findOneAndUpdate(query, { $set: { ...patch, outbox: [event] }, $inc: { revision: 1 } }, { new: true, lean: true });
|
|
131
|
+
if (light) await settleOutbox(Model, EventModel, light);
|
|
132
|
+
return light;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function readSupportLights(patientId, { Model = getSupportLightModel() } = {}) {
|
|
136
|
+
requireText(patientId, 'patientId');
|
|
137
|
+
return Model.find({ patientId }).select('-outbox').lean();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function readSupportLightHistory(patientId, {
|
|
141
|
+
service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
|
|
142
|
+
} = {}) {
|
|
143
|
+
requireText(patientId, 'patientId');
|
|
144
|
+
const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, HISTORY_READ_LIMIT) : HISTORY_READ_LIMIT;
|
|
145
|
+
const scope = { patientId, ...(service ? { service } : {}) };
|
|
146
|
+
const [stored, lights] = await Promise.all([
|
|
147
|
+
EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
|
|
148
|
+
Model.find(scope).select('patientId service outbox').lean(),
|
|
149
|
+
]);
|
|
150
|
+
const byKey = new Map(stored.map((event) => [`${event.service}:${event.revision}`, event]));
|
|
151
|
+
for (const light of lights) {
|
|
152
|
+
for (const event of light.outbox || []) {
|
|
153
|
+
const key = `${light.service}:${event.revision}`;
|
|
154
|
+
if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return [...byKey.values()]
|
|
158
|
+
.sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
|
|
159
|
+
|| left.service.localeCompare(right.service))
|
|
160
|
+
.slice(0, bounded);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function boardFilter({ service = null, color = null, pendingOnly = false } = {}) {
|
|
164
|
+
return {
|
|
165
|
+
...(service ? { service } : {}),
|
|
166
|
+
...(color ? { color } : {}),
|
|
167
|
+
...(pendingOnly ? { pendingImprovement: { $ne: null } } : {}),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const BOARD_RANK = {
|
|
172
|
+
$switch: {
|
|
173
|
+
branches: [
|
|
174
|
+
{ case: { $eq: ['$color', 'red'] }, then: 0 },
|
|
175
|
+
{ case: { $ne: [{ $ifNull: ['$pendingImprovement', null] }, null] }, then: 1 },
|
|
176
|
+
{ case: { $in: ['$color', ['orange', 'unknown']] }, then: 2 },
|
|
177
|
+
],
|
|
178
|
+
default: 3,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
async function readSupportLightBoard(filters = {}, { limit = BOARD_LIMIT, offset = 0, Model = getSupportLightModel() } = {}) {
|
|
183
|
+
const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, BOARD_LIMIT) : BOARD_LIMIT;
|
|
184
|
+
const skipped = Number.isInteger(offset) && offset > 0 ? offset : 0;
|
|
185
|
+
return Model.aggregate([
|
|
186
|
+
{ $match: boardFilter(filters) },
|
|
187
|
+
{ $project: { _id: 0, outbox: 0, evidence: 0, 'pendingImprovement.evidence': 0 } },
|
|
188
|
+
{ $set: { boardRank: BOARD_RANK } },
|
|
189
|
+
{ $sort: { boardRank: 1, setAt: -1, patientId: 1, service: 1 } },
|
|
190
|
+
{ $skip: skipped },
|
|
191
|
+
{ $limit: bounded },
|
|
192
|
+
{ $unset: 'boardRank' },
|
|
193
|
+
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = {
|
|
197
|
+
BOARD_LIMIT,
|
|
198
|
+
HISTORY_READ_LIMIT,
|
|
199
|
+
applySupportLight,
|
|
200
|
+
readSupportLightBoard,
|
|
201
|
+
resolvePendingImprovement,
|
|
202
|
+
readSupportLights,
|
|
203
|
+
readSupportLightHistory,
|
|
204
|
+
};
|
package/lib/index.d.ts
CHANGED
|
@@ -11,8 +11,6 @@ declare module '@peopl-health/nexus' {
|
|
|
11
11
|
contactName?: string | null;
|
|
12
12
|
contactLabel?: string | null;
|
|
13
13
|
body?: string;
|
|
14
|
-
/** Derived first-capture contact evidence; never canonical patient identity. */
|
|
15
|
-
normalizedContent?: { type: 'extracted_contact'; text: string } | null;
|
|
16
14
|
message?: string;
|
|
17
15
|
timestamp?: string | Date;
|
|
18
16
|
createdAt?: string | Date;
|
|
@@ -88,8 +86,6 @@ declare module '@peopl-health/nexus' {
|
|
|
88
86
|
}
|
|
89
87
|
|
|
90
88
|
export interface StorageConfig {
|
|
91
|
-
/** Explicit prospective journal configuration; omitted or false keeps capture disabled. */
|
|
92
|
-
clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
|
|
93
89
|
mongoUri: string;
|
|
94
90
|
dbName: string;
|
|
95
91
|
collections?: {
|
|
@@ -922,6 +918,107 @@ declare module '@peopl-health/nexus' {
|
|
|
922
918
|
}, options?: { Model?: unknown }): Promise<SupportActionResult | null>;
|
|
923
919
|
};
|
|
924
920
|
|
|
921
|
+
export type SupportLightColor = 'green' | 'yellow' | 'orange' | 'red' | 'unknown';
|
|
922
|
+
export type SupportLightSource = 'ai' | 'human';
|
|
923
|
+
export type SupportLightOutcome = 'applied' | 'pending' | 'withdrawn' | 'unchanged';
|
|
924
|
+
export type CollectiveRefusal = 'light_red' | 'light_orange' | 'light_unconfirmed' | 'invitation_paused'
|
|
925
|
+
| 'already_invited_this_week' | 'weekly_limit' | 'no_capacity';
|
|
926
|
+
|
|
927
|
+
export interface SupportLightEvidence {
|
|
928
|
+
source: 'triage' | 'chat' | 'specialist' | 'sweep';
|
|
929
|
+
sourceId: string;
|
|
930
|
+
summary?: string | null;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
export interface SupportLightRecord {
|
|
934
|
+
patientId: string;
|
|
935
|
+
service: SupportService;
|
|
936
|
+
color: SupportLightColor;
|
|
937
|
+
source: SupportLightSource;
|
|
938
|
+
setBy: string;
|
|
939
|
+
setAt: Date;
|
|
940
|
+
evidence: SupportLightEvidence[];
|
|
941
|
+
reason: string | null;
|
|
942
|
+
pendingImprovement: {
|
|
943
|
+
color: SupportLightColor;
|
|
944
|
+
proposedBy: string;
|
|
945
|
+
proposedAt: Date;
|
|
946
|
+
evidence: SupportLightEvidence[];
|
|
947
|
+
reason: string | null;
|
|
948
|
+
} | null;
|
|
949
|
+
revision: number;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
export type SupportLightBoardRecord = Omit<SupportLightRecord, 'evidence' | 'pendingImprovement'> & {
|
|
953
|
+
pendingImprovement: Omit<NonNullable<SupportLightRecord['pendingImprovement']>, 'evidence'> | null;
|
|
954
|
+
};
|
|
955
|
+
|
|
956
|
+
export interface SupportLightEventRecord {
|
|
957
|
+
patientId: string;
|
|
958
|
+
service: SupportService;
|
|
959
|
+
outcome: 'applied' | 'pending' | 'withdrawn' | 'accepted' | 'rejected';
|
|
960
|
+
from: SupportLightColor | null;
|
|
961
|
+
to: SupportLightColor;
|
|
962
|
+
source: SupportLightSource;
|
|
963
|
+
actor: string;
|
|
964
|
+
evidence: SupportLightEvidence[];
|
|
965
|
+
reason: string | null;
|
|
966
|
+
revision: number;
|
|
967
|
+
at: Date;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
export const supportLightService: {
|
|
971
|
+
applySupportLight(request: {
|
|
972
|
+
patientId: string;
|
|
973
|
+
service: SupportService;
|
|
974
|
+
color: SupportLightColor;
|
|
975
|
+
source: SupportLightSource;
|
|
976
|
+
actor?: string | null;
|
|
977
|
+
evidence?: SupportLightEvidence[];
|
|
978
|
+
reason?: string | null;
|
|
979
|
+
now?: Date;
|
|
980
|
+
reviewedRevision?: number | null;
|
|
981
|
+
}, options?: { Model?: unknown; EventModel?: unknown }): Promise<{ light: SupportLightRecord | null; outcome: SupportLightOutcome | 'stale' }>;
|
|
982
|
+
resolvePendingImprovement(request: {
|
|
983
|
+
patientId: string;
|
|
984
|
+
service: SupportService;
|
|
985
|
+
accept: boolean;
|
|
986
|
+
actor: string;
|
|
987
|
+
reviewedRevision: number;
|
|
988
|
+
now?: Date;
|
|
989
|
+
}, options?: { Model?: unknown; EventModel?: unknown }): Promise<SupportLightRecord | null>;
|
|
990
|
+
readSupportLights(patientId: string, options?: { Model?: unknown }): Promise<SupportLightRecord[]>;
|
|
991
|
+
readSupportLightBoard(filters?: {
|
|
992
|
+
service?: SupportService | null;
|
|
993
|
+
color?: SupportLightColor | null;
|
|
994
|
+
pendingOnly?: boolean;
|
|
995
|
+
}, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
|
|
996
|
+
BOARD_LIMIT: number;
|
|
997
|
+
HISTORY_READ_LIMIT: number;
|
|
998
|
+
readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
export const supportInvitability: {
|
|
1002
|
+
LIGHT_SCALE: Readonly<Record<SupportService, readonly SupportLightColor[]>>;
|
|
1003
|
+
LIGHT_SOURCES: readonly SupportLightSource[];
|
|
1004
|
+
WEEKLY_COLLECTIVE_LIMIT: Readonly<Partial<Record<SupportService, number>>>;
|
|
1005
|
+
GROUP_INVITABLE: readonly Readonly<Record<string, unknown>>[];
|
|
1006
|
+
isSafeGroupCandidate(candidate: Partial<SupportCandidateRecord>): boolean;
|
|
1007
|
+
nextLight(
|
|
1008
|
+
current: { color?: SupportLightColor | null } | null | undefined,
|
|
1009
|
+
proposal: { service: SupportService; color: SupportLightColor; source: SupportLightSource },
|
|
1010
|
+
): { outcome: SupportLightOutcome; color?: SupportLightColor; source?: SupportLightSource; pendingImprovement?: { color: SupportLightColor } | null };
|
|
1011
|
+
collectiveOffer(request: {
|
|
1012
|
+
service: SupportService;
|
|
1013
|
+
color?: SupportLightColor;
|
|
1014
|
+
invitationPaused?: boolean;
|
|
1015
|
+
invitedThisWeek?: boolean;
|
|
1016
|
+
collectivesThisWeek?: number;
|
|
1017
|
+
hasCapacity?: boolean;
|
|
1018
|
+
}): { allowed: boolean; reason: CollectiveRefusal | null };
|
|
1019
|
+
supportWeek(date: Date | string): string | null;
|
|
1020
|
+
};
|
|
1021
|
+
|
|
925
1022
|
// BatchingManager — per-chatId concurrency control
|
|
926
1023
|
export interface BatchingConfig {
|
|
927
1024
|
enabled?: boolean;
|
package/lib/index.js
CHANGED
|
@@ -48,6 +48,8 @@ const { MapCache } = require('./utils/MapCache');
|
|
|
48
48
|
const supportCandidateService = require('./clinical/services/supportCandidateService');
|
|
49
49
|
const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
|
|
50
50
|
const supportActionService = require('./clinical/services/supportActionService');
|
|
51
|
+
const supportLightService = require('./clinical/services/supportLightService');
|
|
52
|
+
const supportInvitability = require('./clinical/services/supportInvitability');
|
|
51
53
|
const {
|
|
52
54
|
NutritionSafetyDecision,
|
|
53
55
|
FINDING_CODES,
|
|
@@ -355,6 +357,8 @@ module.exports = {
|
|
|
355
357
|
supportCandidateService,
|
|
356
358
|
registerDashboardProvider,
|
|
357
359
|
supportActionService,
|
|
360
|
+
supportLightService,
|
|
361
|
+
supportInvitability,
|
|
358
362
|
NutritionSafetyDecision,
|
|
359
363
|
FINDING_CODES,
|
|
360
364
|
FINDING_VALUES,
|
|
@@ -9,8 +9,6 @@ const { getClinicalContext } = require('../helpers/patientInformationHelper');
|
|
|
9
9
|
|
|
10
10
|
const { updateRecordByFilter } = require('../services/airtableService');
|
|
11
11
|
|
|
12
|
-
const { captureClinicalMessage } = require('../clinical/services/clinicalMessageCaptureService');
|
|
13
|
-
|
|
14
12
|
const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
|
|
15
13
|
|
|
16
14
|
async function getMessages(query, options = {}) {
|
|
@@ -30,9 +28,8 @@ async function aggregateMessages(pipeline, options = {}) {
|
|
|
30
28
|
return Message.aggregate(pipeline, options);
|
|
31
29
|
}
|
|
32
30
|
|
|
33
|
-
async function insertMessage(values
|
|
31
|
+
async function insertMessage(values) {
|
|
34
32
|
try {
|
|
35
|
-
await captureClinicalMessage(values, options?.clinicalEventCapture);
|
|
36
33
|
if (!values.clinical_context) {
|
|
37
34
|
const { clinicalContext } = await getClinicalContext(values.numero);
|
|
38
35
|
values.clinical_context = clinicalContext;
|
|
@@ -16,7 +16,6 @@ const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
|
|
|
16
16
|
class MongoStorage {
|
|
17
17
|
constructor(config) {
|
|
18
18
|
this.mongoUri = config.mongoUri;
|
|
19
|
-
this.clinicalEventCapture = config.clinicalEventCapture;
|
|
20
19
|
this.dbName = config.dbName;
|
|
21
20
|
this.collections = config.collections || {
|
|
22
21
|
messages: 'messages',
|
|
@@ -40,7 +39,7 @@ class MongoStorage {
|
|
|
40
39
|
async saveMessage(messageData) {
|
|
41
40
|
try {
|
|
42
41
|
const values = this.buildMessageValues(messageData);
|
|
43
|
-
const { doc } = await insertMessage(values
|
|
42
|
+
const { doc } = await insertMessage(values);
|
|
44
43
|
logger.info('[MongoStorage] Message stored');
|
|
45
44
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId);
|
|
46
45
|
return doc;
|
|
@@ -55,7 +54,7 @@ class MongoStorage {
|
|
|
55
54
|
...messageData,
|
|
56
55
|
statusInfo: { status: 'queued', updatedAt: new Date() }
|
|
57
56
|
});
|
|
58
|
-
const { doc } = await insertMessage(values
|
|
57
|
+
const { doc } = await insertMessage(values);
|
|
59
58
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId, 'queued');
|
|
60
59
|
return doc;
|
|
61
60
|
}
|
|
@@ -113,15 +112,6 @@ class MongoStorage {
|
|
|
113
112
|
plainBody: messageData.plainBody || '',
|
|
114
113
|
processed: messageData.processed || false,
|
|
115
114
|
message_id: messageId,
|
|
116
|
-
sourceText: messageData.plainBody ?? messageData.body,
|
|
117
|
-
normalizedContent: messageData.normalizedContent,
|
|
118
|
-
sourceSystem: messageData.sourceSystem,
|
|
119
|
-
sourceProvider: messageData.provider,
|
|
120
|
-
sourceRecordId: messageData.sourceRecordId,
|
|
121
|
-
sourceRevision: messageData.sourceRevision,
|
|
122
|
-
sourceTimestamp: messageData.sourceTimestamp,
|
|
123
|
-
sourceActorId: messageData.from,
|
|
124
|
-
quotedMessageId: messageData.quotedMessageId,
|
|
125
115
|
interactive_type: messageData.interactive?.type || null,
|
|
126
116
|
interactive_data: messageData.interactive || null,
|
|
127
117
|
from_me: messageData.fromMe !== undefined ? messageData.fromMe : true,
|
package/lib/utils/dateUtils.js
CHANGED
|
@@ -47,6 +47,12 @@ const mexicoDay = (value) => {
|
|
|
47
47
|
return at.isValid() ? at.format('YYYY-MM-DD') : null;
|
|
48
48
|
};
|
|
49
49
|
|
|
50
|
+
const mexicoIsoWeek = (value) => {
|
|
51
|
+
if (value === null || value === undefined || value === '') return null;
|
|
52
|
+
const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
|
|
53
|
+
return at.isValid() ? at.format('GGGG-[W]WW') : null;
|
|
54
|
+
};
|
|
55
|
+
|
|
50
56
|
const daysSince = (from, now = Date.now()) => {
|
|
51
57
|
const at = Date.parse(from);
|
|
52
58
|
return Number.isNaN(at) ? null : Math.max(0, Math.floor((now - at) / 86400000));
|
|
@@ -60,6 +66,7 @@ module.exports = {
|
|
|
60
66
|
ageInYears,
|
|
61
67
|
isoDay,
|
|
62
68
|
mexicoDay,
|
|
69
|
+
mexicoIsoWeek,
|
|
63
70
|
mexicoStamp,
|
|
64
71
|
daysSince
|
|
65
72
|
};
|
package/package.json
CHANGED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
const mongoose = require('mongoose');
|
|
2
|
-
|
|
3
|
-
const { clinicalConnection } = require('../config/connection');
|
|
4
|
-
|
|
5
|
-
const clinicalSourceEventSchema = new mongoose.Schema({
|
|
6
|
-
_id: { type: String, required: true },
|
|
7
|
-
tenantId: { type: String, required: true, immutable: true },
|
|
8
|
-
sourceSystem: { type: String, required: true, immutable: true },
|
|
9
|
-
sourceRecordId: { type: String, required: true, immutable: true },
|
|
10
|
-
sourceRevision: { type: String, required: true, immutable: true },
|
|
11
|
-
sourceMessageId: { type: String, default: null, immutable: true },
|
|
12
|
-
patientId: { type: String, default: null, immutable: true },
|
|
13
|
-
identity: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
14
|
-
actor: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
15
|
-
experiencer: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
16
|
-
validTime: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
17
|
-
recordTime: { type: Date, required: true, immutable: true },
|
|
18
|
-
evidenceRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
|
|
19
|
-
artifactRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
|
|
20
|
-
normalizedContent: { type: mongoose.Schema.Types.Mixed, default: null, immutable: true },
|
|
21
|
-
payload: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
22
|
-
schemaVersion: { type: String, required: true, immutable: true },
|
|
23
|
-
policyVersion: { type: String, default: null, immutable: true },
|
|
24
|
-
}, { versionKey: false, autoCreate: false, autoIndex: false });
|
|
25
|
-
|
|
26
|
-
function getClinicalSourceEventModel() {
|
|
27
|
-
const connection = clinicalConnection();
|
|
28
|
-
return connection.models.ClinicalSourceEvent
|
|
29
|
-
|| connection.model('ClinicalSourceEvent', clinicalSourceEventSchema, 'clinicalSourceEvent');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
module.exports = { getClinicalSourceEventModel, clinicalSourceEventSchema };
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
const { createHash } = require('crypto');
|
|
2
|
-
|
|
3
|
-
class ClinicalSourceError extends Error {
|
|
4
|
-
constructor(code, message) {
|
|
5
|
-
super(message);
|
|
6
|
-
this.name = 'ClinicalSourceError';
|
|
7
|
-
this.code = code;
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
function invalidSource() {
|
|
12
|
-
return new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
function isStableId(value) {
|
|
16
|
-
return typeof value === 'string' && value.length > 0 && value.trim() === value;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
// JSON only: reject values that would silently disappear or change during persistence.
|
|
20
|
-
function canonical(value, ancestors = new Set()) {
|
|
21
|
-
if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
|
|
22
|
-
if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
|
|
23
|
-
if (typeof value !== 'object' || ancestors.has(value)) throw invalidSource();
|
|
24
|
-
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw invalidSource();
|
|
25
|
-
ancestors.add(value);
|
|
26
|
-
const result = Array.isArray(value)
|
|
27
|
-
? '[' + Array.from(value, item => canonical(item, ancestors)).join(',') + ']'
|
|
28
|
-
: '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key], ancestors)).join(',') + '}';
|
|
29
|
-
ancestors.delete(value);
|
|
30
|
-
return result;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function validateClinicalSourceEvent(envelope) {
|
|
34
|
-
if (!envelope || typeof envelope !== 'object') throw invalidSource();
|
|
35
|
-
for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'schemaVersion']) {
|
|
36
|
-
if (!isStableId(envelope[field])) throw invalidSource();
|
|
37
|
-
}
|
|
38
|
-
if (envelope.sourceMessageId != null && !isStableId(envelope.sourceMessageId)) throw invalidSource();
|
|
39
|
-
if (envelope.patientId !== null && !isStableId(envelope.patientId)) throw invalidSource();
|
|
40
|
-
if (!['unknown', 'ambiguous', 'resolved'].includes(envelope.identity?.status) || !Array.isArray(envelope.identity.sourceRefs)) throw invalidSource();
|
|
41
|
-
if ((envelope.patientId !== null) !== (envelope.identity.status === 'resolved')) throw invalidSource();
|
|
42
|
-
for (const field of ['actor', 'experiencer', 'payload']) {
|
|
43
|
-
if (!envelope[field] || typeof envelope[field] !== 'object' || Array.isArray(envelope[field])) throw invalidSource();
|
|
44
|
-
}
|
|
45
|
-
if (!Array.isArray(envelope.evidenceRefs)) throw invalidSource();
|
|
46
|
-
const artifactRefs = envelope.artifactRefs === undefined ? [] : envelope.artifactRefs;
|
|
47
|
-
if (!Array.isArray(artifactRefs)) throw invalidSource();
|
|
48
|
-
const attachmentIndexes = new Set();
|
|
49
|
-
for (const ref of artifactRefs) {
|
|
50
|
-
if (!ref || typeof ref !== 'object' || Array.isArray(ref)
|
|
51
|
-
|| Object.keys(ref).some(key => !['attachmentIndex', 'bucket', 'key'].includes(key))
|
|
52
|
-
|| !Number.isSafeInteger(ref.attachmentIndex) || ref.attachmentIndex < 0
|
|
53
|
-
|| attachmentIndexes.has(ref.attachmentIndex) || !isStableId(ref.bucket) || !isStableId(ref.key)) throw invalidSource();
|
|
54
|
-
attachmentIndexes.add(ref.attachmentIndex);
|
|
55
|
-
}
|
|
56
|
-
const normalizedContent = envelope.normalizedContent ?? null;
|
|
57
|
-
if (normalizedContent !== null && (typeof normalizedContent !== 'object' || Array.isArray(normalizedContent)
|
|
58
|
-
|| Object.keys(normalizedContent).some(key => !['type', 'text'].includes(key))
|
|
59
|
-
|| normalizedContent.type !== 'extracted_contact' || typeof normalizedContent.text !== 'string'
|
|
60
|
-
|| !normalizedContent.text.trim())) throw invalidSource();
|
|
61
|
-
if (!['known', 'unknown'].includes(envelope.validTime?.status)) throw invalidSource();
|
|
62
|
-
if (envelope.validTime.status === 'known' && (typeof envelope.validTime.at !== 'string' || !Number.isFinite(Date.parse(envelope.validTime.at)))) throw invalidSource();
|
|
63
|
-
if (envelope.validTime.status === 'unknown' && envelope.validTime.at != null) throw invalidSource();
|
|
64
|
-
if (envelope.policyVersion !== null && !isStableId(envelope.policyVersion)) throw invalidSource();
|
|
65
|
-
const document = {};
|
|
66
|
-
for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'patientId', 'identity', 'actor', 'experiencer', 'validTime', 'evidenceRefs', 'payload', 'schemaVersion', 'policyVersion']) document[field] = envelope[field];
|
|
67
|
-
document.sourceMessageId = envelope.sourceMessageId ?? null;
|
|
68
|
-
document.artifactRefs = artifactRefs;
|
|
69
|
-
document.normalizedContent = normalizedContent;
|
|
70
|
-
return JSON.parse(canonical(document));
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function sourceFingerprint(document) {
|
|
74
|
-
// Identity adjudication, policy selection, capture artifacts and observation time are not source revisions.
|
|
75
|
-
const omitted = new Set(['artifactRefs', 'normalizedContent', 'patientId', 'identity', 'policyVersion', 'recordTime', '_id']);
|
|
76
|
-
const source = Object.fromEntries(Object.entries(document).filter(([key]) => !omitted.has(key)));
|
|
77
|
-
return canonical({ ...source, identitySourceRefs: document.identity.sourceRefs });
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function persistenceClassification(stage, error) {
|
|
81
|
-
if (stage === 'unacknowledged') return 'unacknowledged';
|
|
82
|
-
if (stage === 'missing_duplicate') return 'not_found';
|
|
83
|
-
if ([50, 64].includes(error?.code) || error?.name === 'MongoNetworkTimeoutError') return 'timeout';
|
|
84
|
-
if ([13, 18].includes(error?.code)) return 'authorization';
|
|
85
|
-
if ([6, 7, 89, 91].includes(error?.code)
|
|
86
|
-
|| ['MongoNetworkError', 'MongoServerSelectionError'].includes(error?.name)) return 'unavailable';
|
|
87
|
-
return 'unknown';
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
async function ingestClinicalSourceEvent(envelope) {
|
|
91
|
-
const document = validateClinicalSourceEvent(envelope);
|
|
92
|
-
const eventId = createHash('sha256').update(JSON.stringify([
|
|
93
|
-
document.tenantId, document.sourceSystem, document.sourceRecordId, document.sourceRevision,
|
|
94
|
-
])).digest('hex');
|
|
95
|
-
const fingerprint = sourceFingerprint(document);
|
|
96
|
-
let stage = 'model';
|
|
97
|
-
try {
|
|
98
|
-
const { getClinicalSourceEventModel } = require('../models/clinicalSourceEventModel');
|
|
99
|
-
const { collection } = getClinicalSourceEventModel();
|
|
100
|
-
try {
|
|
101
|
-
stage = 'write';
|
|
102
|
-
const result = await collection.insertOne({ ...document, _id: eventId, recordTime: new Date() }, { writeConcern: { w: 'majority', j: true, wtimeoutMS: 10000 } });
|
|
103
|
-
if (!result?.acknowledged) {
|
|
104
|
-
stage = 'unacknowledged';
|
|
105
|
-
throw new Error();
|
|
106
|
-
}
|
|
107
|
-
return { eventId, state: document.patientId === null ? 'identity_pending' : 'recorded' };
|
|
108
|
-
} catch (error) {
|
|
109
|
-
if (error.code !== 11000) throw error;
|
|
110
|
-
stage = 'duplicate_read';
|
|
111
|
-
const existing = await collection.findOne({ _id: eventId }, { readPreference: 'primary', readConcern: { level: 'majority' } });
|
|
112
|
-
if (!existing) {
|
|
113
|
-
stage = 'missing_duplicate';
|
|
114
|
-
throw new Error();
|
|
115
|
-
}
|
|
116
|
-
stage = 'duplicate_verify';
|
|
117
|
-
if (sourceFingerprint(existing) !== fingerprint) throw new ClinicalSourceError('CLINICAL_SOURCE_CONFLICT', 'Clinical source revision conflict');
|
|
118
|
-
return { eventId, state: 'duplicate' };
|
|
119
|
-
}
|
|
120
|
-
} catch (error) {
|
|
121
|
-
if (error instanceof ClinicalSourceError && error.code === 'CLINICAL_SOURCE_CONFLICT') throw error;
|
|
122
|
-
try {
|
|
123
|
-
const { logger } = require('../../utils/logger');
|
|
124
|
-
logger.error('[clinicalEventService] Source persistence failed', { stage, classification: persistenceClassification(stage, error) });
|
|
125
|
-
} catch {
|
|
126
|
-
// Diagnostic availability must not change the safe public failure contract.
|
|
127
|
-
}
|
|
128
|
-
throw new ClinicalSourceError('CLINICAL_SOURCE_PERSISTENCE', 'Clinical source persistence failed');
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
module.exports = { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError };
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
const { isBenchMode } = require('../../utils/benchModeHelper');
|
|
2
|
-
const { isShadowRun } = require('../../utils/shadowScope');
|
|
3
|
-
const { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError } = require('./clinicalEventService');
|
|
4
|
-
|
|
5
|
-
function pick(source, fields) {
|
|
6
|
-
if (!source || typeof source !== 'object') return null;
|
|
7
|
-
return Object.fromEntries(fields.filter(field => source[field] !== undefined).map(field => [field, source[field]]));
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
function mediaEvidence(media) {
|
|
11
|
-
const fields = ['key', 'bucket', 'bucketName', 'mimeType', 'mediaType', 'contentType', 'filename', 'fileName', 'fileSize', 'caption', 'url', 'size', 'sha256'];
|
|
12
|
-
const evidence = pick(media, fields);
|
|
13
|
-
if (evidence && Array.isArray(media.metadata?.attachments)) {
|
|
14
|
-
evidence.attachments = media.metadata.attachments.map(item => pick(item, fields));
|
|
15
|
-
}
|
|
16
|
-
return evidence;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function privateArtifactRefs(media) {
|
|
20
|
-
const attachments = Array.isArray(media?.metadata?.attachments) ? media.metadata.attachments : [];
|
|
21
|
-
return [media, ...attachments].flatMap((item, attachmentIndex) => {
|
|
22
|
-
const bucket = item?.bucketName ?? item?.bucket;
|
|
23
|
-
if (bucket == null || item?.key == null) return [];
|
|
24
|
-
return [{ attachmentIndex, bucket, key: item.key }];
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function buildClinicalMessageEnvelope(values, tenantId) {
|
|
29
|
-
const raw = values.raw ?? {};
|
|
30
|
-
if (typeof raw !== 'object' || Array.isArray(raw)) throw new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
|
|
31
|
-
const sourceSystem = values.sourceSystem || values.sourceProvider || (raw.MessageSid ? 'twilio' : raw.key?.id ? 'baileys' : 'whatsapp_platform');
|
|
32
|
-
const sourceId = values.sourceRecordId ?? values.message_id;
|
|
33
|
-
const actorId = values.contact_code || values.sourceActorId || raw.From || raw.key?.remoteJid || values.numero || null;
|
|
34
|
-
const providerEvidence = pick(raw, ['MessageSid', 'SmsSid', 'OriginalRepliedMessageSid', 'Body', 'ButtonPayload', 'ButtonText', 'ListId', 'ListTitle', 'ListDescription', 'FlowData', 'InteractiveData', 'NumMedia', 'MediaUrl0', 'MediaContentType0']);
|
|
35
|
-
const mediaFields = Object.keys(raw).filter(key => /^Media(?:Url|ContentType)\d+$/.test(key));
|
|
36
|
-
Object.assign(providerEvidence, pick(raw, mediaFields));
|
|
37
|
-
const hasProviderMedia = mediaFields.some(key => /^MediaUrl\d+$/.test(key));
|
|
38
|
-
const event = {
|
|
39
|
-
tenantId, sourceSystem, sourceRecordId: sourceId, sourceRevision: values.sourceRevision ?? '1',
|
|
40
|
-
sourceMessageId: values.message_id ?? null, patientId: null,
|
|
41
|
-
identity: { status: 'unknown', sourceRefs: values.numero ? [{ system: 'message_transport', id: values.numero }] : [] },
|
|
42
|
-
actor: { type: 'transport_contact', sourceId: actorId, reportedRole: values.contact_role || null, authenticatedRole: null },
|
|
43
|
-
experiencer: { patientId: null, status: 'unknown' },
|
|
44
|
-
validTime: { status: 'unknown' },
|
|
45
|
-
evidenceRefs: [],
|
|
46
|
-
artifactRefs: privateArtifactRefs(values.media),
|
|
47
|
-
normalizedContent: values.normalizedContent ?? null,
|
|
48
|
-
payload: {
|
|
49
|
-
sourceTimestamp: values.sourceTimestamp ?? null,
|
|
50
|
-
text: typeof raw.Body === 'string' ? raw.Body : values.sourceText ?? values.plainBody ?? values.body ?? '',
|
|
51
|
-
interactive: pick(values.interactive_data, ['type', 'payload', 'title', 'id', 'description', 'replyId', 'flowData', 'interactiveData']) || (values.interactive_type ? { type: values.interactive_type } : null),
|
|
52
|
-
media: hasProviderMedia ? null : mediaEvidence(values.media),
|
|
53
|
-
providerEvidence,
|
|
54
|
-
quotedMessageId: values.quotedMessageId ?? raw.OriginalRepliedMessageSid ?? null,
|
|
55
|
-
},
|
|
56
|
-
schemaVersion: '1', policyVersion: null,
|
|
57
|
-
};
|
|
58
|
-
return validateClinicalSourceEvent(event);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function captureClinicalMessage(values, settings = {}) {
|
|
62
|
-
const enabled = settings?.enabled;
|
|
63
|
-
if (enabled !== true && enabled !== 'true') return { state: 'skipped', reason: 'disabled' };
|
|
64
|
-
if (isShadowRun() || isBenchMode(values?.numero) || isBenchMode(values?.contact_code)) return { state: 'skipped', reason: 'isolated_run' };
|
|
65
|
-
if (values?.from_me !== false || !['patient', 'whatsapp_platform'].includes(values?.origin)) return { state: 'skipped', reason: 'excluded_message' };
|
|
66
|
-
return ingestClinicalSourceEvent(buildClinicalMessageEnvelope(values, settings.tenantId));
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
module.exports = { buildClinicalMessageEnvelope, captureClinicalMessage };
|