@peopl-health/nexus 5.60.0 → 5.61.0-dev.11181
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 +1 -0
- package/lib/clinical/models/clinicalSourceEventModel.js +32 -0
- package/lib/clinical/services/clinicalCaptureConfigService.js +22 -0
- package/lib/clinical/services/clinicalEventService.js +132 -0
- package/lib/clinical/services/clinicalMessageCaptureService.js +72 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +1 -0
- package/lib/services/messageService.js +4 -1
- package/lib/storage/MongoStorage.js +14 -2
- package/package.json +1 -1
|
@@ -26,6 +26,7 @@ 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,
|
|
29
30
|
media,
|
|
30
31
|
interactive,
|
|
31
32
|
quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
|
|
@@ -0,0 +1,32 @@
|
|
|
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 };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const { getModelDatabase } = require('../../config/mongoConfig');
|
|
2
|
+
|
|
3
|
+
class ClinicalCaptureConfigError extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super('Clinical source capture configuration invalid');
|
|
6
|
+
this.name = 'ClinicalCaptureConfigError';
|
|
7
|
+
this.code = 'CLINICAL_SOURCE_CONFIG';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function assertClinicalCaptureConfigured(settings) {
|
|
12
|
+
if (settings?.enabled !== true && settings?.enabled !== 'true') return;
|
|
13
|
+
|
|
14
|
+
const tenantId = settings.tenantId;
|
|
15
|
+
const clinicalDb = getModelDatabase('Clinical');
|
|
16
|
+
if (typeof tenantId !== 'string' || !tenantId || tenantId.trim() !== tenantId
|
|
17
|
+
|| typeof clinicalDb !== 'string' || !clinicalDb.trim()) {
|
|
18
|
+
throw new ClinicalCaptureConfigError();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = { assertClinicalCaptureConfigured, ClinicalCaptureConfigError };
|
|
@@ -0,0 +1,132 @@
|
|
|
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 };
|
|
@@ -0,0 +1,72 @@
|
|
|
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 = raw.From || raw.key?.remoteJid || values.contact_code || values.sourceActorId || 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: {
|
|
42
|
+
status: 'unknown', sourceRefs: actorId ? [{ system: 'message_transport', id: actorId }] : [],
|
|
43
|
+
routingEnrichment: { contactRole: values.contact_role || null, patientReference: values.numero || null },
|
|
44
|
+
},
|
|
45
|
+
actor: { type: 'transport_contact', sourceId: actorId, reportedRole: null, authenticatedRole: null },
|
|
46
|
+
experiencer: { patientId: null, status: 'unknown' },
|
|
47
|
+
validTime: { status: 'unknown' },
|
|
48
|
+
evidenceRefs: [],
|
|
49
|
+
artifactRefs: privateArtifactRefs(values.media),
|
|
50
|
+
normalizedContent: values.normalizedContent ?? null,
|
|
51
|
+
payload: {
|
|
52
|
+
sourceTimestamp: values.sourceTimestamp ?? null,
|
|
53
|
+
text: typeof raw.Body === 'string' ? raw.Body : values.sourceText ?? values.plainBody ?? values.body ?? '',
|
|
54
|
+
interactive: pick(values.interactive_data, ['type', 'payload', 'title', 'id', 'description', 'replyId', 'flowData', 'interactiveData']) || (values.interactive_type ? { type: values.interactive_type } : null),
|
|
55
|
+
media: hasProviderMedia ? null : mediaEvidence(values.media),
|
|
56
|
+
providerEvidence,
|
|
57
|
+
quotedMessageId: values.quotedMessageId ?? raw.OriginalRepliedMessageSid ?? null,
|
|
58
|
+
},
|
|
59
|
+
schemaVersion: '1', policyVersion: null,
|
|
60
|
+
};
|
|
61
|
+
return validateClinicalSourceEvent(event);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function captureClinicalMessage(values, settings = {}) {
|
|
65
|
+
const enabled = settings?.enabled;
|
|
66
|
+
if (enabled !== true && enabled !== 'true') return { state: 'skipped', reason: 'disabled' };
|
|
67
|
+
if (isShadowRun() || isBenchMode(values?.numero) || isBenchMode(values?.contact_code)) return { state: 'skipped', reason: 'isolated_run' };
|
|
68
|
+
if (values?.from_me !== false || !['patient', 'whatsapp_platform'].includes(values?.origin)) return { state: 'skipped', reason: 'excluded_message' };
|
|
69
|
+
return ingestClinicalSourceEvent(buildClinicalMessageEnvelope(values, settings.tenantId));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
module.exports = { buildClinicalMessageEnvelope, captureClinicalMessage };
|
package/lib/index.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ 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;
|
|
14
16
|
message?: string;
|
|
15
17
|
timestamp?: string | Date;
|
|
16
18
|
createdAt?: string | Date;
|
|
@@ -86,6 +88,8 @@ declare module '@peopl-health/nexus' {
|
|
|
86
88
|
}
|
|
87
89
|
|
|
88
90
|
export interface StorageConfig {
|
|
91
|
+
/** Explicit prospective journal configuration. Enabled capture requires tenantId and a Clinical mapping set before Nexus.initialize(). */
|
|
92
|
+
clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
|
|
89
93
|
mongoUri: string;
|
|
90
94
|
dbName: string;
|
|
91
95
|
collections?: {
|
|
@@ -407,6 +411,7 @@ declare module '@peopl-health/nexus' {
|
|
|
407
411
|
export function requestIdMiddleware(req: any, res: any, next: () => void): void;
|
|
408
412
|
export function getRequestId(): string | null;
|
|
409
413
|
|
|
414
|
+
/** Set the Clinical mapping before initializing MongoStorage with enabled clinicalEventCapture. */
|
|
410
415
|
export function setModelDatabases(mapping: Record<string, string>): void;
|
|
411
416
|
export function setModelDatabase(modelName: string, dbName: string): void;
|
|
412
417
|
export function getModelDatabase(modelName: string): string | null;
|
package/lib/index.js
CHANGED
|
@@ -9,6 +9,8 @@ const { getClinicalContext } = require('../helpers/patientInformationHelper');
|
|
|
9
9
|
|
|
10
10
|
const { updateRecordByFilter } = require('../services/airtableService');
|
|
11
11
|
|
|
12
|
+
const { captureClinicalMessage } = require('../clinical/services/clinicalMessageCaptureService');
|
|
13
|
+
|
|
12
14
|
const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
|
|
13
15
|
|
|
14
16
|
async function getMessages(query, options = {}) {
|
|
@@ -28,8 +30,9 @@ async function aggregateMessages(pipeline, options = {}) {
|
|
|
28
30
|
return Message.aggregate(pipeline, options);
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
async function insertMessage(values) {
|
|
33
|
+
async function insertMessage(values, options = {}) {
|
|
32
34
|
try {
|
|
35
|
+
await captureClinicalMessage(values, options?.clinicalEventCapture);
|
|
33
36
|
if (!values.clinical_context) {
|
|
34
37
|
const { clinicalContext } = await getClinicalContext(values.numero);
|
|
35
38
|
values.clinical_context = clinicalContext;
|
|
@@ -12,10 +12,12 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
12
12
|
const { getMessages, insertMessage } = require('../services/messageService');
|
|
13
13
|
|
|
14
14
|
const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
|
|
15
|
+
const { assertClinicalCaptureConfigured } = require('../clinical/services/clinicalCaptureConfigService');
|
|
15
16
|
|
|
16
17
|
class MongoStorage {
|
|
17
18
|
constructor(config) {
|
|
18
19
|
this.mongoUri = config.mongoUri;
|
|
20
|
+
this.clinicalEventCapture = config.clinicalEventCapture;
|
|
19
21
|
this.dbName = config.dbName;
|
|
20
22
|
this.collections = config.collections || {
|
|
21
23
|
messages: 'messages',
|
|
@@ -32,6 +34,7 @@ class MongoStorage {
|
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
async connect() {
|
|
37
|
+
assertClinicalCaptureConfigured(this.clinicalEventCapture);
|
|
35
38
|
await mongoConnect(this.mongoUri);
|
|
36
39
|
if (this.dbName) this.db = getDb(this.dbName);
|
|
37
40
|
}
|
|
@@ -39,7 +42,7 @@ class MongoStorage {
|
|
|
39
42
|
async saveMessage(messageData) {
|
|
40
43
|
try {
|
|
41
44
|
const values = this.buildMessageValues(messageData);
|
|
42
|
-
const { doc } = await insertMessage(values);
|
|
45
|
+
const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
|
|
43
46
|
logger.info('[MongoStorage] Message stored');
|
|
44
47
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId);
|
|
45
48
|
return doc;
|
|
@@ -54,7 +57,7 @@ class MongoStorage {
|
|
|
54
57
|
...messageData,
|
|
55
58
|
statusInfo: { status: 'queued', updatedAt: new Date() }
|
|
56
59
|
});
|
|
57
|
-
const { doc } = await insertMessage(values);
|
|
60
|
+
const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
|
|
58
61
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId, 'queued');
|
|
59
62
|
return doc;
|
|
60
63
|
}
|
|
@@ -112,6 +115,15 @@ class MongoStorage {
|
|
|
112
115
|
plainBody: messageData.plainBody || '',
|
|
113
116
|
processed: messageData.processed || false,
|
|
114
117
|
message_id: messageId,
|
|
118
|
+
sourceText: messageData.plainBody ?? messageData.body,
|
|
119
|
+
normalizedContent: messageData.normalizedContent,
|
|
120
|
+
sourceSystem: messageData.sourceSystem,
|
|
121
|
+
sourceProvider: messageData.provider,
|
|
122
|
+
sourceRecordId: messageData.sourceRecordId,
|
|
123
|
+
sourceRevision: messageData.sourceRevision,
|
|
124
|
+
sourceTimestamp: messageData.sourceTimestamp,
|
|
125
|
+
sourceActorId: messageData.from,
|
|
126
|
+
quotedMessageId: messageData.quotedMessageId,
|
|
115
127
|
interactive_type: messageData.interactive?.type || null,
|
|
116
128
|
interactive_data: messageData.interactive || null,
|
|
117
129
|
from_me: messageData.fromMe !== undefined ? messageData.fromMe : true,
|