@peopl-health/nexus 5.58.0-dev.10175 → 5.58.0-dev.10233

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.
@@ -7,8 +7,9 @@ const { ScheduledMessage } = require('../models/agendaMessageModel.js');
7
7
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
8
8
  const { FlowRouting } = require('../models/flowRoutingModel.js');
9
9
 
10
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
10
+ const { ensureWhatsAppFormat, stripWhatsAppFormat } = require('../helpers/twilioHelper');
11
11
  const { ensureFlowTokenInVariables } = require('../helpers/templateFlowControllerHelper');
12
+ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper');
12
13
 
13
14
  const { getRecordByFilter } = require('../services/airtableService');
14
15
  const { getMessages } = require('../services/messageService');
@@ -67,7 +68,8 @@ const sendMessageController = async (req, res) => {
67
68
  variables = null,
68
69
  frontendId = null,
69
70
  triggeredBy = null,
70
- idempotencyKey = null
71
+ idempotencyKey = null,
72
+ contactCode = null
71
73
  } = req.body || {};
72
74
 
73
75
  const formattedCode = ensureWhatsAppFormat(code);
@@ -77,13 +79,26 @@ const sendMessageController = async (req, res) => {
77
79
  }
78
80
 
79
81
  try {
82
+ let contact = {};
83
+ if (contactCode) {
84
+ if (sendTime) {
85
+ return res.status(400).json({ success: false, error: 'contactCode cannot be combined with sendTime' });
86
+ }
87
+ const formattedContact = ensureWhatsAppFormat(contactCode);
88
+ const caregiver = await resolveCaregiver(formattedContact, { strict: true });
89
+ if (!caregiver || stripWhatsAppFormat(caregiver.patientCode) !== stripWhatsAppFormat(formattedCode)) {
90
+ return res.status(400).json({ success: false, error: 'contactCode is not a registered caregiver of this patient' });
91
+ }
92
+ contact = { contactCode: formattedContact, contactRole: CAREGIVER_ROLE };
93
+ }
94
+
80
95
  const finalVariables = contentSid ? await ensureFlowTokenInVariables(contentSid, variables) : variables;
81
96
 
82
97
  if (!sendTime) {
83
98
  const result = await sendMessage({
84
99
  fileUrl, body: message, fileType, contentSid, hidePreview,
85
100
  variables: finalVariables, code: formattedCode,
86
- frontendId, triggeredBy, idempotencyKey
101
+ frontendId, triggeredBy, idempotencyKey, ...contact
87
102
  });
88
103
  return res.status(200).json({
89
104
  success: result?.success ?? true,
@@ -58,8 +58,14 @@ async function lookupCaregiver(code) {
58
58
  return { patientCode: ensureWhatsAppFormat(row.whatsapp_id), caregiverName: caregiver.name };
59
59
  }
60
60
 
61
- async function resolveCaregiver(code) {
61
+ async function resolveCaregiver(code, { strict = false } = {}) {
62
62
  if (!code) return null;
63
+ if (strict) {
64
+ const found = await lookupCaregiver(code);
65
+ caregiverCache.set(code, found);
66
+ return found;
67
+ }
68
+
63
69
  const cached = caregiverCache.get(code);
64
70
  if (cached !== undefined) return cached;
65
71
 
@@ -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
  };
@@ -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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.58.0-dev.10175",
3
+ "version": "5.58.0-dev.10233",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",