@peopl-health/nexus 5.57.7 → 5.57.8

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.
@@ -40,8 +40,10 @@ const getOfficeMessagesController = async (req, res) => {
40
40
 
41
41
  const sendOfficeMessageController = async (req, res) => {
42
42
  try {
43
- const { triggeredBy, text, clientMessageId } = req.body || {};
44
- const delivery = await sendOfficeMessage({ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId });
43
+ const { triggeredBy, text, clientMessageId, fileUrl, fileName } = req.body || {};
44
+ const delivery = await sendOfficeMessage({
45
+ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId, fileUrl, fileName,
46
+ });
45
47
  res.status(201).json({ success: true, ...delivery });
46
48
  } catch (error) {
47
49
  respondWithError(res, error, 'sending office message', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
@@ -1,4 +1,5 @@
1
1
  const { Estado_General_ID, Monitoreo_ID } = require('../config/airtableConfig');
2
+ const runtimeConfig = require('../config/runtimeConfig');
2
3
 
3
4
  const { httpError, requiredText } = require('../utils/httpErrorUtils');
4
5
  const { inlineOf } = require('../utils/coercionUtils');
@@ -7,6 +8,7 @@ const { logger } = require('../utils/logger');
7
8
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
9
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
9
10
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
11
+ const { prepareMessageMedia } = require('../helpers/mediaHelper');
10
12
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
11
13
  const { sendMessage } = require('../core/NexusMessaging');
12
14
 
@@ -14,20 +16,23 @@ const { getRecordByFilter } = require('./airtableService');
14
16
  const { getMessages } = require('./messageService');
15
17
  const { getPatientInformation } = require('./patientService');
16
18
 
17
- const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
18
19
  const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
19
20
  const HIDDEN_ORIGINS = ['system', 'instruction'];
20
21
  const DEFAULT_MESSAGE_LIMIT = 30;
21
22
  const MAX_MESSAGE_LIMIT = 50;
22
23
  const MAX_TEXT_LENGTH = 1500;
23
24
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
25
+ const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
26
+ const DOCUMENT_FILE_TYPE = 'document';
24
27
 
25
28
  async function getOfficeAssistant(email) {
26
29
  const normalized = String(email ?? '').trim().toLowerCase();
27
30
  if (!normalized) return null;
28
31
 
29
32
  const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
30
- const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
33
+ // No field list: Airtable rejects a listed column that does not exist yet, which would take the whole office view down
34
+ // until document_template_content_sid is added.
35
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, undefined, true) || [];
31
36
  const doctor = inlineOf(assistant?.doctor_match);
32
37
  const label = inlineOf(assistant?.office_label);
33
38
  if (!doctor || !label) return null;
@@ -37,6 +42,7 @@ async function getOfficeAssistant(email) {
37
42
  doctor,
38
43
  label,
39
44
  templateContentSid: inlineOf(assistant.template_content_sid) || null,
45
+ documentTemplateContentSid: inlineOf(assistant.document_template_content_sid) || null,
40
46
  };
41
47
  }
42
48
 
@@ -100,34 +106,74 @@ async function readOfficeMessages({ requestedBy, code, limit }) {
100
106
  };
101
107
  }
102
108
 
103
- function officeMessage({ assistant, patientCode, text, inWindow }) {
109
+ function officeDocumentUrl(fileUrl) {
110
+ if (!fileUrl) return null;
111
+ const bucketName = runtimeConfig.get('AWS_S3_BUCKET_NAME');
112
+ let url = null;
113
+ try {
114
+ url = new URL(String(fileUrl));
115
+ } catch {
116
+ url = null;
117
+ }
118
+ // The approved document template pins the bucket host and takes the rest of the URL as a variable.
119
+ const bucketHost = new RegExp(`^${escapeRegExp(bucketName ?? '')}\\.s3(\\.[a-z0-9-]+)?\\.amazonaws\\.com$`);
120
+ if (!bucketName || url?.protocol !== 'https:' || !bucketHost.test(url.hostname)) {
121
+ throw httpError(400, 'The document must be uploaded before it is sent');
122
+ }
123
+ return url;
124
+ }
125
+
126
+ // Twilio needs the file type in a template's media URL, and uploads are stored without an
127
+ // extension, so the template gets the copy prepareMessageMedia stores with one.
128
+ async function templateDocumentOf(document, patientCode) {
129
+ const { mediaUrl } = await prepareMessageMedia({
130
+ code: patientCode, fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name,
131
+ });
132
+ // prepareMessageMedia answers with the original URL when the copy fails, and that one has no file type.
133
+ if (!mediaUrl || mediaUrl === document.url.href) throw httpError(502, 'The document could not be prepared for the template');
134
+ return { ...document, url: officeDocumentUrl(mediaUrl) };
135
+ }
136
+
137
+ function officeMessage({ assistant, patientCode, text, inWindow, document }) {
138
+ const attachment = document ? { fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name } : {};
104
139
  if (inWindow) {
105
140
  if (text.length > MAX_TEXT_LENGTH) throw httpError(422, `The message exceeds ${MAX_TEXT_LENGTH} characters`);
106
- return { code: patientCode, body: `${assistant.label}: ${text}` };
141
+ return { code: patientCode, body: text ? `${assistant.label}: ${text}` : assistant.label, ...attachment };
107
142
  }
108
143
 
109
- const templateText = text.replace(/\s+/g, ' ').trim();
144
+ const templateText = text.replace(/\s+/g, ' ').trim() || DOCUMENT_TEMPLATE_DEFAULT_TEXT;
110
145
  if (templateText.length > MAX_TEMPLATE_TEXT_LENGTH) {
111
146
  throw httpError(422, `Outside the 24-hour window the message is sent as a template and cannot exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters`);
112
147
  }
113
- if (!assistant.templateContentSid) throw httpError(503, 'The office template is not configured; the patient is outside the 24-hour window');
148
+ const contentSid = document ? assistant.documentTemplateContentSid : assistant.templateContentSid;
149
+ if (!contentSid) {
150
+ const template = document ? 'office document template' : 'office template';
151
+ throw httpError(503, `The ${template} is not configured; the patient is outside the 24-hour window`);
152
+ }
114
153
  return {
115
154
  code: patientCode,
116
155
  body: `${assistant.label}: ${templateText}`,
117
- contentSid: assistant.templateContentSid,
118
- variables: { 1: templateText },
156
+ contentSid,
157
+ variables: document
158
+ ? { 1: templateText, 2: `${document.url.pathname.slice(1)}${document.url.search}` }
159
+ : { 1: templateText },
160
+ ...attachment,
119
161
  };
120
162
  }
121
163
 
122
- async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
164
+ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId, fileUrl, fileName }) {
123
165
  const assistant = await requireOfficeAssistant(requestedBy);
124
166
  const patientCode = await officePatientCode(assistant, code);
125
- const messageText = requiredText(text, 'text');
167
+ const url = officeDocumentUrl(fileUrl);
168
+ const document = url ? { url, name: fileName } : null;
169
+ const messageText = document ? String(text ?? '').trim() : requiredText(text, 'text');
126
170
  const messageKey = requiredText(clientMessageId, 'clientMessageId');
127
171
 
128
172
  const inWindow = await isWithin24HourWindow(patientCode);
173
+ const isDocumentTemplate = Boolean(document && !inWindow && assistant.documentTemplateContentSid);
174
+ const sentDocument = isDocumentTemplate ? await templateDocumentOf(document, patientCode) : document;
129
175
  const message = {
130
- ...officeMessage({ assistant, patientCode, text: messageText, inWindow }),
176
+ ...officeMessage({ assistant, patientCode, text: messageText, inWindow, document: sentDocument }),
131
177
  triggeredBy: assistant.email,
132
178
  idempotencyKey: `office:${patientCode}:${messageKey}`,
133
179
  };
@@ -143,6 +189,7 @@ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
143
189
  assistant: assistant.email,
144
190
  code: redactDirectIdentifiers(patientCode),
145
191
  transport,
192
+ hasDocument: Boolean(document),
146
193
  duplicate: result?.duplicate === true,
147
194
  });
148
195
  return { transport, messageId: result?.messageId || null, duplicate: result?.duplicate === true };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.7",
3
+ "version": "5.57.8",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",