@peopl-health/nexus 6.0.4 → 6.0.6
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.
|
@@ -3,6 +3,7 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
|
3
3
|
|
|
4
4
|
const {
|
|
5
5
|
listOfficePatients,
|
|
6
|
+
markOfficeSeen,
|
|
6
7
|
readOfficeMessages,
|
|
7
8
|
sendOfficeMessage,
|
|
8
9
|
} = require('../services/officeAssistantService');
|
|
@@ -50,8 +51,19 @@ const sendOfficeMessageController = async (req, res) => {
|
|
|
50
51
|
}
|
|
51
52
|
};
|
|
52
53
|
|
|
54
|
+
const markOfficeSeenController = async (req, res) => {
|
|
55
|
+
try {
|
|
56
|
+
const { triggeredBy, seenAt } = req.body || {};
|
|
57
|
+
const marker = await markOfficeSeen({ requestedBy: triggeredBy, code: req.params.code, seenAt });
|
|
58
|
+
res.status(200).json({ success: true, ...marker });
|
|
59
|
+
} catch (error) {
|
|
60
|
+
respondWithError(res, error, 'marking office messages seen', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
53
64
|
module.exports = {
|
|
54
65
|
listOfficePatientsController,
|
|
55
66
|
getOfficeMessagesController,
|
|
56
67
|
sendOfficeMessageController,
|
|
68
|
+
markOfficeSeenController,
|
|
57
69
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const officeReadMarkerSchema = new mongoose.Schema({
|
|
4
|
+
email: { type: String, required: true },
|
|
5
|
+
code: { type: String, required: true },
|
|
6
|
+
seenAt: { type: Date, required: true }
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
officeReadMarkerSchema.index({ email: 1, code: 1 }, { name: 'office_read_marker_idx', unique: true });
|
|
10
|
+
|
|
11
|
+
const OfficeReadMarker = mongoose.model('OfficeReadMarker', officeReadMarkerSchema);
|
|
12
|
+
|
|
13
|
+
module.exports = { OfficeReadMarker };
|
package/lib/routes/index.js
CHANGED
|
@@ -149,7 +149,8 @@ const escalationReviewRouteDefinitions = {
|
|
|
149
149
|
const officeAssistantRouteDefinitions = {
|
|
150
150
|
'GET /patients': 'listOfficePatientsController',
|
|
151
151
|
'GET /patients/:code/messages': 'getOfficeMessagesController',
|
|
152
|
-
'POST /patients/:code/messages': 'sendOfficeMessageController'
|
|
152
|
+
'POST /patients/:code/messages': 'sendOfficeMessageController',
|
|
153
|
+
'POST /patients/:code/seen': 'markOfficeSeenController'
|
|
153
154
|
};
|
|
154
155
|
|
|
155
156
|
const createRouter = (routeDefinitions, controllers) => {
|
|
@@ -331,7 +332,8 @@ const builtInControllers = {
|
|
|
331
332
|
// Office assistant controllers
|
|
332
333
|
listOfficePatientsController: officeAssistantController.listOfficePatientsController,
|
|
333
334
|
getOfficeMessagesController: officeAssistantController.getOfficeMessagesController,
|
|
334
|
-
sendOfficeMessageController: officeAssistantController.sendOfficeMessageController
|
|
335
|
+
sendOfficeMessageController: officeAssistantController.sendOfficeMessageController,
|
|
336
|
+
markOfficeSeenController: officeAssistantController.markOfficeSeenController
|
|
335
337
|
};
|
|
336
338
|
|
|
337
339
|
const setupDefaultRoutes = (app) => {
|
|
@@ -152,15 +152,16 @@ async function postHandoffNotice(review, clock, { note }) {
|
|
|
152
152
|
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
153
153
|
const taken = await takenOf(review, clock);
|
|
154
154
|
const header = taken ? '📋 Pasó al médico' : '📋 Pasó al médico · todavía sin tomar';
|
|
155
|
+
const action = !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho';
|
|
155
156
|
const body = [
|
|
156
157
|
header,
|
|
157
158
|
[`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
|
|
158
159
|
note,
|
|
159
|
-
|
|
160
|
+
action,
|
|
160
161
|
link,
|
|
161
162
|
].filter(Boolean).join('\n');
|
|
162
163
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
163
|
-
const sent = await sendGroupNotice(body, quoted, [header, note].filter(Boolean).join('\n'));
|
|
164
|
+
const sent = await sendGroupNotice(body, quoted, [header, note, action].filter(Boolean).join('\n'));
|
|
164
165
|
await audit(review, { action: 'handoff_notice_sent', urgencyLevel: clock.level, delivered: sent.delivered });
|
|
165
166
|
}
|
|
166
167
|
|
|
@@ -6,6 +6,7 @@ const { inlineOf } = require('../utils/coercionUtils');
|
|
|
6
6
|
const { escapeRegExp } = require('../utils/textMatchUtils');
|
|
7
7
|
const { logger } = require('../utils/logger');
|
|
8
8
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
9
|
+
const { OfficeReadMarker } = require('../models/officeReadMarkerModel');
|
|
9
10
|
const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
|
|
10
11
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
11
12
|
const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
@@ -13,7 +14,7 @@ const { ensureWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twil
|
|
|
13
14
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
14
15
|
|
|
15
16
|
const { getRecordByFilter } = require('./airtableService');
|
|
16
|
-
const { getMessages } = require('./messageService');
|
|
17
|
+
const { aggregateMessages, getMessages } = require('./messageService');
|
|
17
18
|
const { getPatientInformation } = require('./patientService');
|
|
18
19
|
|
|
19
20
|
const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
|
|
@@ -24,6 +25,9 @@ const MAX_TEXT_LENGTH = 1500;
|
|
|
24
25
|
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
25
26
|
const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
|
|
26
27
|
const DOCUMENT_FILE_TYPE = 'document';
|
|
28
|
+
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|
|
29
|
+
const REPLY_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
30
|
+
const REPLY_PREVIEW_LENGTH = 120;
|
|
27
31
|
|
|
28
32
|
async function getOfficeAssistant(email) {
|
|
29
33
|
const normalized = String(email ?? '').trim().toLowerCase();
|
|
@@ -65,27 +69,98 @@ async function listOfficePatients({ requestedBy }) {
|
|
|
65
69
|
const assistant = await requireOfficeAssistant(requestedBy);
|
|
66
70
|
const patients = await getRecordByFilter(Estado_General_ID, 'estado_general', fieldEquals('doctor', assistant.doctor), undefined, PATIENT_FIELDS) || [];
|
|
67
71
|
|
|
68
|
-
|
|
72
|
+
const listed = patients
|
|
69
73
|
.filter((patient) => inlineOf(patient.doctor) === assistant.doctor && inlineOf(patient.whatsapp_id) && !isArchivedPatientCode(inlineOf(patient.whatsapp_id)))
|
|
70
74
|
.map((patient) => ({ code: inlineOf(patient.whatsapp_id), name: inlineOf(patient.name) || null }))
|
|
71
75
|
.sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'es'));
|
|
76
|
+
|
|
77
|
+
let replies = new Map();
|
|
78
|
+
try {
|
|
79
|
+
if (listed.length) replies = await repliesFor(listed.map((patient) => patient.code), assistant);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
logger.error('[Office] Could not find who replied; listing without replies', { assistant: assistant.email, error: error.message });
|
|
82
|
+
}
|
|
83
|
+
return listed.map((patient) => ({ ...patient, reply: replies.get(patient.code) ?? null }));
|
|
72
84
|
}
|
|
73
85
|
|
|
86
|
+
const officeLabelPattern = (assistant) => `^${escapeRegExp(assistant.label)}:`;
|
|
87
|
+
const PATIENT_MESSAGE = { from_me: false };
|
|
88
|
+
const officeSends = (assistant) => [
|
|
89
|
+
{ from_me: true, triggeredBy: assistant.email },
|
|
90
|
+
{ from_me: true, origin: 'whatsapp_platform', plainBody: { $regex: officeLabelPattern(assistant) } },
|
|
91
|
+
];
|
|
92
|
+
const AGENT_SEND = { from_me: true, origin: 'assistant' };
|
|
93
|
+
const STAFF_SEND = { from_me: true, origin: 'whatsapp_platform', triggeredBy: { $regex: '@' } };
|
|
94
|
+
|
|
74
95
|
const officeVisibleQuery = (patientCode, assistant) => ({
|
|
75
96
|
numero: patientCode,
|
|
76
97
|
group_id: null,
|
|
77
98
|
origin: { $nin: HIDDEN_ORIGINS },
|
|
78
99
|
$or: [
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
{ from_me: true, origin: 'whatsapp_platform', plainBody: { $regex: `^${escapeRegExp(assistant.label)}:` } },
|
|
100
|
+
PATIENT_MESSAGE,
|
|
101
|
+
...officeSends(assistant),
|
|
82
102
|
// Context for the office: what the agent and PEOPL staff told the patient. Staff sends carry the sender's email;
|
|
83
103
|
// automated sends (reminders, retries) carry a job name and stay hidden.
|
|
84
|
-
|
|
85
|
-
|
|
104
|
+
AGENT_SEND,
|
|
105
|
+
STAFF_SEND,
|
|
86
106
|
],
|
|
87
107
|
});
|
|
88
108
|
|
|
109
|
+
async function lastExchanges(codes, assistant) {
|
|
110
|
+
const sentByOffice = {
|
|
111
|
+
$or: [
|
|
112
|
+
{ $eq: ['$triggeredBy', assistant.email] },
|
|
113
|
+
{ $and: [{ $eq: ['$origin', 'whatsapp_platform'] }, { $regexMatch: { input: { $ifNull: ['$plainBody', ''] }, regex: officeLabelPattern(assistant) } }] },
|
|
114
|
+
],
|
|
115
|
+
};
|
|
116
|
+
const fromPatient = { $not: ['$from_me'] };
|
|
117
|
+
return aggregateMessages([
|
|
118
|
+
{
|
|
119
|
+
$match: {
|
|
120
|
+
numero: { $in: codes },
|
|
121
|
+
group_id: null,
|
|
122
|
+
origin: { $nin: HIDDEN_ORIGINS },
|
|
123
|
+
'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
|
|
124
|
+
createdAt: { $gt: new Date(Date.now() - REPLY_LOOKBACK_MS) },
|
|
125
|
+
$or: [PATIENT_MESSAGE, ...officeSends(assistant), STAFF_SEND],
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
$group: {
|
|
130
|
+
_id: '$numero',
|
|
131
|
+
officeAt: { $max: { $cond: [sentByOffice, '$createdAt', null] } },
|
|
132
|
+
answeredAt: { $max: { $cond: ['$from_me', '$createdAt', null] } },
|
|
133
|
+
lastPatient: { $max: { $cond: [fromPatient, { at: '$createdAt', body: '$plainBody', media: '$media.mediaType' }, null] } },
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
]);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const previewOf = ({ body, media }) => String(body ?? '').trim().slice(0, REPLY_PREVIEW_LENGTH) || (media ? `[${media}]` : '');
|
|
140
|
+
|
|
141
|
+
async function repliesFor(codes, assistant) {
|
|
142
|
+
const replied = (await lastExchanges(codes, assistant))
|
|
143
|
+
.filter(({ officeAt, answeredAt, lastPatient }) => officeAt && lastPatient?.at > answeredAt);
|
|
144
|
+
if (!replied.length) return new Map();
|
|
145
|
+
|
|
146
|
+
const markers = await OfficeReadMarker.find({ email: assistant.email, code: { $in: replied.map(({ _id }) => _id) } }).lean();
|
|
147
|
+
const seenAt = new Map(markers.map((marker) => [marker.code, marker.seenAt]));
|
|
148
|
+
return new Map(replied
|
|
149
|
+
.filter(({ _id, lastPatient }) => !(seenAt.get(_id) >= lastPatient.at))
|
|
150
|
+
.map(({ _id, lastPatient }) => [_id, { at: lastPatient.at, preview: previewOf(lastPatient) }]));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function markOfficeSeen({ requestedBy, code, seenAt }) {
|
|
154
|
+
const assistant = await requireOfficeAssistant(requestedBy);
|
|
155
|
+
const patientCode = await officePatientCode(assistant, code);
|
|
156
|
+
const seen = new Date(seenAt);
|
|
157
|
+
if (!seenAt || Number.isNaN(seen.getTime())) throw httpError(400, 'seenAt must be a date');
|
|
158
|
+
|
|
159
|
+
const clamped = new Date(Math.min(seen.getTime(), Date.now()));
|
|
160
|
+
await OfficeReadMarker.updateOne({ email: assistant.email, code: patientCode }, { $max: { seenAt: clamped } }, { upsert: true });
|
|
161
|
+
return { seenAt: clamped };
|
|
162
|
+
}
|
|
163
|
+
|
|
89
164
|
function officeSenderOf(message, assistant) {
|
|
90
165
|
if (!message.from_me) return 'patient';
|
|
91
166
|
if (message.triggeredBy === assistant.email || String(message.plainBody ?? '').startsWith(`${assistant.label}:`)) return 'office';
|
|
@@ -212,6 +287,7 @@ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId, fil
|
|
|
212
287
|
module.exports = {
|
|
213
288
|
getOfficeAssistant,
|
|
214
289
|
listOfficePatients,
|
|
290
|
+
markOfficeSeen,
|
|
215
291
|
readOfficeMessages,
|
|
216
292
|
sendOfficeMessage,
|
|
217
293
|
};
|