@peopl-health/nexus 5.57.0 → 5.57.2

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.
@@ -174,7 +174,10 @@ class DefaultMemoryManager extends MemoryManager {
174
174
 
175
175
  _speakerPrefix(msg, role) {
176
176
  if (this._isInlineOperatorTurn(msg, role)) return `${OPERATOR_TURN_PREFIX} `;
177
- if (msg.origin === 'patient' && msg.contact_role === 'caregiver') return `${CAREGIVER_TURN_PREFIX} `;
177
+ if (msg.origin === 'patient' && msg.contact_role === 'caregiver') {
178
+ const label = String(msg.contact_label || '').replace(/[[\]\n]/g, '').trim();
179
+ return label ? `${CAREGIVER_TURN_PREFIX.slice(0, -1)}: ${label}] ` : `${CAREGIVER_TURN_PREFIX} `;
180
+ }
178
181
  if (msg.origin !== 'whatsapp_platform') return '';
179
182
  // The send API records the authenticated sender; without one the send was automated.
180
183
  return msg.triggeredBy ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
@@ -16,7 +16,7 @@ const { Thread } = require('../models/threadModel');
16
16
 
17
17
  const { storeRunMetrics } = require('../helpers/metricsHelper');
18
18
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
19
- const { remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
19
+ const { maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
20
20
  const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
21
21
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
22
22
  const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
@@ -568,6 +568,12 @@ class NexusMessaging {
568
568
 
569
569
  async processIncomingMessage(messageData, { onSaved = null } = {}) {
570
570
  await remapCaregiverSender(messageData);
571
+ if (messageData.contactName) {
572
+ messageData.contactLabel = await maskCaregiverLabel(messageData.contactName, messageData.code, this.phiProcessor).catch((error) => {
573
+ logger.error('[processIncomingMessage] Caregiver name could not be masked; the model sees the role only', { error: error.message });
574
+ return null;
575
+ });
576
+ }
571
577
  const chatId = messageData.code;
572
578
 
573
579
  if (chatId) {
@@ -181,6 +181,12 @@ class PhiProcessor {
181
181
  return encoded;
182
182
  }
183
183
 
184
+ async encodeKnownName(name, numero) {
185
+ if (!this._phiEnabled) return name;
186
+ if (!name || !numero) return null;
187
+ return (await tokenMapService.encode(numero, name, 'PERSONA')) || null;
188
+ }
189
+
184
190
  async inData(messageData, saveFn, handler, { onSaved } = {}) {
185
191
  const decodedBody = messageData.body;
186
192
  const encodedBody = await this.encodeBody(decodedBody, messageData.code);
@@ -1,4 +1,4 @@
1
- const { Monitoreo_ID } = require('../config/airtableConfig');
1
+ const { Historial_Clinico_ID } = require('../config/airtableConfig');
2
2
 
3
3
  const { logger } = require('../utils/logger');
4
4
  const { MapCache } = require('../utils/MapCache');
@@ -14,10 +14,23 @@ const CAREGIVER_ROLE = 'caregiver';
14
14
 
15
15
  const caregiverCache = new MapCache({ maxSize: 1000, ttl: 5 * 60 * 1000 });
16
16
 
17
- const listedNumbers = (value) => String(value || '')
18
- .split(/[,;\n]/)
19
- .map((entry) => stripWhatsAppFormat(entry.replace(/[^\d+]/g, '')))
20
- .filter(Boolean);
17
+ const PHONE_RX = /\+?\d[\d\s-]{6,}\d/;
18
+
19
+ function listedCaregivers(value) {
20
+ return String(value || '')
21
+ .split(/[,;\n]/)
22
+ .map((entry) => {
23
+ const phone = entry.match(PHONE_RX);
24
+ if (!phone) return null;
25
+ const name = entry
26
+ .replace(phone[0], '')
27
+ .replace(/whatsapp:/gi, '')
28
+ .replace(/\s+/g, ' ')
29
+ .replace(/^[\s:–-]+|[\s:–-]+$/g, '');
30
+ return { digits: phone[0].replace(/\D/g, ''), name: name || null };
31
+ })
32
+ .filter(Boolean);
33
+ }
21
34
 
22
35
  async function lookupCaregiver(code) {
23
36
  const digits = stripWhatsAppFormat(code);
@@ -25,20 +38,24 @@ async function lookupCaregiver(code) {
25
38
 
26
39
  const safeCode = escapeFormulaValue(code);
27
40
  const records = await getRecordByFilter(
28
- Monitoreo_ID,
41
+ Historial_Clinico_ID,
29
42
  'estado_general',
30
- `OR({whatsapp_id}='${safeCode}', FIND('${digits}', {${CAREGIVERS_FIELD}}))`,
43
+ `OR({whatsapp_id}='${safeCode}', FIND('${digits}', SUBSTITUTE(SUBSTITUTE({${CAREGIVERS_FIELD}}, ' ', ''), '-', '')))`,
31
44
  );
32
45
  if (!records?.length) return null;
33
46
  if (records.some((row) => row.whatsapp_id === code)) return null;
34
47
 
35
- const patients = records.filter((row) => row.whatsapp_id && listedNumbers(row[CAREGIVERS_FIELD]).includes(digits));
36
- if (patients.length > 1) {
37
- logger.warn('[caregiverHelper] number listed as caregiver of several patients; not remapping', { count: patients.length });
48
+ const matches = records
49
+ .filter((row) => row.whatsapp_id)
50
+ .map((row) => ({ row, caregiver: listedCaregivers(row[CAREGIVERS_FIELD]).find((entry) => entry.digits === digits) }))
51
+ .filter(({ caregiver }) => caregiver);
52
+ if (matches.length > 1) {
53
+ logger.warn('[caregiverHelper] number listed as caregiver of several patients; not remapping', { count: matches.length });
38
54
  return null;
39
55
  }
40
- if (!patients.length) return null;
41
- return { patientCode: ensureWhatsAppFormat(patients[0].whatsapp_id) };
56
+ if (!matches.length) return null;
57
+ const [{ row, caregiver }] = matches;
58
+ return { patientCode: ensureWhatsAppFormat(row.whatsapp_id), caregiverName: caregiver.name };
42
59
  }
43
60
 
44
61
  async function resolveCaregiver(code) {
@@ -62,6 +79,8 @@ async function remapCaregiverSender(messageData) {
62
79
  if (!caregiver) return messageData;
63
80
  messageData.contactCode = messageData.code;
64
81
  messageData.contactRole = CAREGIVER_ROLE;
82
+ messageData.contactName = caregiver.caregiverName || null;
83
+ if (caregiver.caregiverName) messageData.pushName = caregiver.caregiverName;
65
84
  messageData.code = caregiver.patientCode;
66
85
  messageData.from = caregiver.patientCode;
67
86
  return messageData;
@@ -82,6 +101,14 @@ async function replyContactFor(code) {
82
101
  }
83
102
  }
84
103
 
104
+ async function maskCaregiverLabel(name, code, phiProcessor) {
105
+ if (!name) return null;
106
+ const relation = (name.match(/\([^)]*\)/g) || []).join(' ');
107
+ const person = name.replace(/\([^)]*\)/g, '').replace(/\s+/g, ' ').trim();
108
+ const token = person ? await phiProcessor.encodeKnownName(person, code) : null;
109
+ return [token, relation].filter(Boolean).join(' ') || null;
110
+ }
111
+
85
112
  function contactOf(message) {
86
113
  return message?.contact_code ? { contactCode: message.contact_code, contactRole: message.contact_role } : {};
87
114
  }
@@ -94,6 +121,8 @@ module.exports = {
94
121
  CAREGIVERS_FIELD,
95
122
  CAREGIVER_ROLE,
96
123
  contactOf,
124
+ listedCaregivers,
125
+ maskCaregiverLabel,
97
126
  remapCaregiverSender,
98
127
  replyContactFor,
99
128
  resolveCaregiver,
@@ -1,3 +1,5 @@
1
+ const { escapeFormulaValue } = require('./airtableFormulaHelper');
2
+
1
3
  const CLOSED_REQUEST_STATUSES = [
2
4
  'resuelto',
3
5
  'no resuelto',
@@ -7,20 +9,17 @@ const CLOSED_REQUEST_STATUSES = [
7
9
  'alucinación',
8
10
  'revisado',
9
11
  ];
10
- const CLOSED_CASE_STATUSES = ['Resuelto', 'Fallecido'];
11
- const CLOSED_OPERATIONS_STATUS = 'cerrado';
12
12
  const ATTENTION_REQUEST_STATUS = 'sin atender';
13
- const ATTENTION_OPERATIONS_STATUS = 'pendiente';
14
- const ATTENTION_CASE_WINDOW_DAYS = 14;
13
+ const ATTENTION_CASE_WINDOW_DAYS = 60;
15
14
  const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
16
15
  const URGENT_REQUEST_URGENCY = 'urgent';
17
16
  const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
18
17
  const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
18
+ const TASK_PROGRAM_SOURCE = 'auna';
19
19
 
20
- const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
20
+ const programSourceFilter = (field) => `FIND('${escapeFormulaValue(TASK_PROGRAM_SOURCE)}', ARRAYJOIN({${field}}))`;
21
21
 
22
- const isCaseOpen = (status, operationsStatus) => operationsStatus !== CLOSED_OPERATIONS_STATUS
23
- && !CLOSED_CASE_STATUSES.includes(status);
22
+ const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
24
23
 
25
24
  const isWithinAttentionWindow = (createdAt) => {
26
25
  const created = Date.parse(createdAt || '');
@@ -29,9 +28,9 @@ const isWithinAttentionWindow = (createdAt) => {
29
28
 
30
29
  const needsRequestAttention = (status) => status === ATTENTION_REQUEST_STATUS;
31
30
 
32
- const needsCaseAttention = (status, operationsStatus, createdAt) => operationsStatus === ATTENTION_OPERATIONS_STATUS
33
- && !CLOSED_CASE_STATUSES.includes(status)
34
- && isWithinAttentionWindow(createdAt);
31
+ const isCaseOpen = (resolvedTime, createdAt) => !resolvedTime && isWithinAttentionWindow(createdAt);
32
+
33
+ const needsCaseAttention = isCaseOpen;
35
34
 
36
35
  const isRequestUrgent = (urgency) => urgency === URGENT_REQUEST_URGENCY;
37
36
 
@@ -40,7 +39,6 @@ const isCaseUrgent = (type) => URGENT_CASE_TYPES.includes(type);
40
39
  module.exports = {
41
40
  ATTENTION_CASE_WINDOW_DAYS,
42
41
  CLOSED_REQUEST_STATUSES,
43
- ATTENTION_OPERATIONS_STATUS,
44
42
  ATTENTION_REQUEST_STATUS,
45
43
  REQUEST_URGENCIES,
46
44
  isCaseOpen,
@@ -49,4 +47,5 @@ module.exports = {
49
47
  isRequestUrgent,
50
48
  needsCaseAttention,
51
49
  needsRequestAttention,
50
+ programSourceFilter,
52
51
  };
package/lib/index.d.ts CHANGED
@@ -8,6 +8,8 @@ declare module '@peopl-health/nexus' {
8
8
  code?: string;
9
9
  contactCode?: string | null;
10
10
  contactRole?: 'caregiver' | null;
11
+ contactName?: string | null;
12
+ contactLabel?: string | null;
11
13
  body?: string;
12
14
  message?: string;
13
15
  timestamp?: string | Date;
@@ -28,6 +28,7 @@ const messageSchema = new mongoose.Schema({
28
28
  },
29
29
  contact_code: { type: String, default: null },
30
30
  contact_role: { type: String, enum: [null, 'caregiver'], default: null },
31
+ contact_label: { type: String, default: null },
31
32
  tools_executed: {
32
33
  type: [{
33
34
  tool_name: { type: String, required: true },
@@ -1,4 +1,4 @@
1
- const { Historial_Clinico_ID, Symptoms_ID } = require('../config/airtableConfig');
1
+ const { Historial_Clinico_ID } = require('../config/airtableConfig');
2
2
 
3
3
  const { logger } = require('../utils/logger');
4
4
 
@@ -17,7 +17,7 @@ const toMap = (arr, keyFn, valFn) => arr.reduce((m, item) => {
17
17
 
18
18
  const PENDING_TASK_FILTERS = ['pending-tasks', 'pending-cases', 'pending-requests'];
19
19
 
20
- const buildThreadFilter = (filter, { triageIds, taskCodes }) => {
20
+ const buildThreadFilter = (filter, { taskCodes }) => {
21
21
  const base = { lastMessageAt: { $ne: null } };
22
22
  switch (filter) {
23
23
  case 'unread':
@@ -28,8 +28,6 @@ const buildThreadFilter = (filter, { triageIds, taskCodes }) => {
28
28
  return { ...base, lastMessageAt: { $gt: new Date(Date.now() - 86400000) } };
29
29
  case 'no-response':
30
30
  return { ...base, lastMessageFromMe: false };
31
- case 'triage-last-month':
32
- return { ...base, code: { $in: triageIds } };
33
31
  case 'pending-tasks':
34
32
  return { ...base, code: { $in: taskCodes.all } };
35
33
  case 'pending-cases':
@@ -43,12 +41,6 @@ const buildThreadFilter = (filter, { triageIds, taskCodes }) => {
43
41
  };
44
42
 
45
43
  const fetchConversationData = async (filter, skip, limit) => {
46
- let triageIds = [];
47
- if (filter === 'triage-last-month') {
48
- const triageRecords = await getRecordByFilter(Symptoms_ID, 'estado_general', 'TRUE()', 'complete_triage_last_month', ['whatsapp_id']);
49
- triageIds = (triageRecords || []).map(r => r.whatsapp_id).filter(Boolean);
50
- }
51
-
52
44
  const openTaskMap = PENDING_TASK_FILTERS.includes(filter)
53
45
  ? await getOpenTaskSummary()
54
46
  : await getOpenTaskSummary().catch((error) => {
@@ -62,7 +54,7 @@ const fetchConversationData = async (filter, skip, limit) => {
62
54
  requests: taskEntries.filter(([, entry]) => entry.requests > 0).map(([code]) => code),
63
55
  };
64
56
 
65
- const threadFilter = buildThreadFilter(filter, { triageIds, taskCodes });
57
+ const threadFilter = buildThreadFilter(filter, { taskCodes });
66
58
 
67
59
  logger.info('[fetchConversationData] Applying filter', { filter });
68
60
  const startTime = Date.now();
@@ -12,6 +12,7 @@ const {
12
12
  isRequestUrgent,
13
13
  needsCaseAttention,
14
14
  needsRequestAttention,
15
+ programSourceFilter,
15
16
  } = require('../helpers/patientTaskRulesHelper');
16
17
 
17
18
  const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
@@ -97,8 +98,9 @@ const toCase = (row) => ({
97
98
  followUp: row.seguimiento ?? null,
98
99
  note: row.observations ?? null,
99
100
  recommendation: row.recomendation_final ?? null,
100
- isOpen: isCaseOpen(row.status, row.status_operaciones),
101
- needsAttention: needsCaseAttention(row.status, row.status_operaciones, row.created || row._createdTime),
101
+ resolvedAt: row.resolved_time ?? null,
102
+ isOpen: isCaseOpen(row.resolved_time, row.created || row._createdTime),
103
+ needsAttention: needsCaseAttention(row.resolved_time, row.created || row._createdTime),
102
104
  isUrgent: isCaseUrgent(row.type),
103
105
  });
104
106
 
@@ -106,7 +108,7 @@ const TASK_KINDS = {
106
108
  requests: {
107
109
  table: 'unresolved_questions',
108
110
  fields: ['question_id', 'created_time', 'question', 'details', 'category', 'urgency', 'status', 'Observaciones', 'doctor_office'],
109
- scope: fieldEquals('message_tag', 'request'),
111
+ scope: `AND(${fieldEquals('message_tag', 'request')}, ${programSourceFilter('source (from customer_id)')})`,
110
112
  toTask: toRequest,
111
113
  writable: {
112
114
  status: { field: 'status', options: REQUEST_STATUSES },
@@ -116,8 +118,8 @@ const TASK_KINDS = {
116
118
  },
117
119
  cases: {
118
120
  table: 'patient_cases',
119
- fields: ['case_id', 'created', 'description', 'grade', 'type', 'status', 'status_operaciones', 'seguimiento', 'observations', 'recomendation_final'],
120
- scope: null,
121
+ fields: ['case_id', 'created', 'resolved_time', 'description', 'grade', 'type', 'status', 'status_operaciones', 'seguimiento', 'observations', 'recomendation_final'],
122
+ scope: programSourceFilter('source'),
121
123
  toTask: toCase,
122
124
  writable: {
123
125
  status: { field: 'status', options: CASE_STATUSES },
@@ -136,8 +138,7 @@ const validWhatsappId = (code) => {
136
138
 
137
139
  const taskFilter = (kind, whatsappId) => {
138
140
  const guard = `FIND('${escapeFormulaValue(whatsappId)},', ARRAYJOIN({whatsapp_id}, ',') & ',')`;
139
- const { scope } = TASK_KINDS[kind];
140
- return scope ? `AND(${guard}, ${scope})` : guard;
141
+ return `AND(${guard}, ${TASK_KINDS[kind].scope})`;
141
142
  };
142
143
 
143
144
  const byOpenThenNewest = (a, b) => (b.isOpen - a.isOpen) || (b.createdAt || '').localeCompare(a.createdAt || '');
@@ -5,12 +5,12 @@ const { MapCache } = require('../utils/MapCache');
5
5
  const { fieldEquals } = require('../helpers/airtableFormulaHelper');
6
6
  const {
7
7
  ATTENTION_CASE_WINDOW_DAYS,
8
- ATTENTION_OPERATIONS_STATUS,
9
8
  ATTENTION_REQUEST_STATUS,
10
9
  isCaseUrgent,
11
10
  isRequestUrgent,
12
11
  needsCaseAttention,
13
12
  needsRequestAttention,
13
+ programSourceFilter,
14
14
  } = require('../helpers/patientTaskRulesHelper');
15
15
 
16
16
  const { getRecordByFilter } = require('../services/airtableService');
@@ -18,9 +18,9 @@ const { getRecordByFilter } = require('../services/airtableService');
18
18
  const CACHE_KEY = 'open-tasks';
19
19
  const CACHE_TTL_MS = 60000;
20
20
  const REQUEST_FIELDS = ['whatsapp_id', 'status', 'urgency'];
21
- const CASE_FIELDS = ['whatsapp_id', 'status', 'status_operaciones', 'type', 'created'];
22
- const REQUEST_FILTER = `AND(${fieldEquals('message_tag', 'request')}, ${fieldEquals('status', ATTENTION_REQUEST_STATUS)})`;
23
- const CASE_FILTER = `AND(${fieldEquals('status_operaciones', ATTENTION_OPERATIONS_STATUS)}, OR(IS_AFTER({created}, DATEADD(NOW(), -${ATTENTION_CASE_WINDOW_DAYS}, 'days')), {created} = BLANK()))`;
21
+ const CASE_FIELDS = ['whatsapp_id', 'resolved_time', 'type', 'created'];
22
+ const REQUEST_FILTER = `AND(${fieldEquals('message_tag', 'request')}, ${fieldEquals('status', ATTENTION_REQUEST_STATUS)}, ${programSourceFilter('source (from customer_id)')})`;
23
+ const CASE_FILTER = `AND({resolved_time} = BLANK(), OR(IS_AFTER({created}, DATEADD(NOW(), -${ATTENTION_CASE_WINDOW_DAYS}, 'days')), {created} = BLANK()), ${programSourceFilter('source')})`;
24
24
 
25
25
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL_MS });
26
26
  let inFlight = null;
@@ -51,7 +51,7 @@ async function loadSummary() {
51
51
 
52
52
  for (const row of caseRows || []) {
53
53
  const createdAt = row.created || row._createdTime || null;
54
- if (!needsCaseAttention(row.status, row.status_operaciones, createdAt)) continue;
54
+ if (!needsCaseAttention(row.resolved_time, createdAt)) continue;
55
55
  for (const code of codesOf(row)) addTask(summary, code, 'cases', isCaseUrgent(row.type));
56
56
  }
57
57
 
@@ -131,7 +131,8 @@ class MongoStorage {
131
131
  triggeredBy: messageData.triggeredBy || null,
132
132
  ...(messageData.contactCode && {
133
133
  contact_code: ensureWhatsAppFormat(messageData.contactCode),
134
- contact_role: messageData.contactRole || null
134
+ contact_role: messageData.contactRole || null,
135
+ ...(messageData.contactLabel && { contact_label: messageData.contactLabel })
135
136
  })
136
137
  };
137
138
  return values;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0",
3
+ "version": "5.57.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",