@peopl-health/nexus 6.4.17 → 6.4.19

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.
@@ -8,7 +8,11 @@ const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length >
8
8
 
9
9
  const DURATION_TEXTS = Object.freeze({ as_needed: 'solo si lo necesita', continuous: 'de forma continua, hasta nuevo aviso', unspecified: null });
10
10
  const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
11
- const durationTextOf = (item) => (!item.duration || item.duration === 'days' ? `por ${daysText(item.days)}` : DURATION_TEXTS[item.duration]);
11
+ const SAID_DURATION = Object.freeze({ as_needed: /raz[oó]n necesaria|si lo necesita/i, continuous: /forma continua/i });
12
+ const durationTextOf = (item) => {
13
+ if (!item.duration || item.duration === 'days') return `por ${daysText(item.days)}`;
14
+ return SAID_DURATION[item.duration]?.test(`${item.dose ?? ''} ${item.frequency ?? ''}`) ? null : DURATION_TEXTS[item.duration];
15
+ };
12
16
  const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${[item.dose, item.frequency, durationTextOf(item)].filter(Boolean).join(' ')}.`;
13
17
  const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
14
18
  // The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours.
@@ -56,21 +60,13 @@ function prescriptionText(plan) {
56
60
  return lines.join('\n');
57
61
  }
58
62
 
59
- const FREQUENCY_DURATIONS = Object.freeze([[/\s*por raz[oó]n necesaria$/i, 'as_needed'], [/\s*de forma continua$/i, 'continuous']]);
60
-
61
- // A formulary frequency that already names the duration gives it up, so the line does not say it twice.
62
- function frequencyDurationOf(frequency) {
63
- const [pattern, duration] = FREQUENCY_DURATIONS.find(([candidate]) => candidate.test(frequency ?? '')) ?? [];
64
- return duration ? { frequency: frequency.replace(pattern, ''), duration } : { frequency, duration: 'days' };
65
- }
66
-
67
63
  // The formulary's own fields; a drug it no longer lists keeps its old text as the dose, for the doctor to split.
68
64
  function dosingOf(item, formularyKey) {
69
65
  const entry = formularyFor(formularyKey);
70
66
  const dosing = entry && findDrug(entry, item)?.dosing;
71
67
  if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, duration: 'days', days: null, note: null };
72
- const { frequency, duration } = frequencyDurationOf(dosing.frequency ?? null);
73
- return { dose: dosing.dose ?? null, frequency, duration, days: duration === 'days' ? dosing.days ?? null : null, note: dosing.note ?? null };
68
+ const duration = dosing.duration ?? 'days';
69
+ return { dose: dosing.dose ?? null, frequency: dosing.frequency ?? null, duration, days: duration === 'days' ? dosing.days ?? null : null, note: dosing.note ?? null };
74
70
  }
75
71
 
76
72
  // What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
@@ -96,7 +96,7 @@ const TREATMENT_FORMULARY = deepFreeze([
96
96
  {
97
97
  drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
98
98
  instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
99
- dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria' },
99
+ dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria', duration: 'as_needed' },
100
100
  contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
101
101
  },
102
102
  ],
@@ -256,12 +256,12 @@ const TREATMENT_FORMULARY = deepFreeze([
256
256
  {
257
257
  drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
258
258
  instructions: 'capa fina cada 12 horas de forma continua',
259
- dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua' },
259
+ dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua', duration: 'continuous' },
260
260
  },
261
261
  {
262
262
  drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
263
263
  instructions: '2 a 3 veces al día de forma continua',
264
- dosing: { dose: '2 a 3 veces al día de forma continua' }, isPharmacological: false,
264
+ dosing: { dose: '2 a 3 veces al día de forma continua', duration: 'continuous' }, isPharmacological: false,
265
265
  },
266
266
  { drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
267
267
  { drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
@@ -48,9 +48,9 @@ function itemOf(item, index) {
48
48
  const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
49
49
  const reason = textOf(item?.reason, `${name}.reason`);
50
50
  if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
51
- const duration = item?.duration ?? 'days';
52
- if (!PLAN_DURATIONS.includes(duration)) throw httpError(400, `${name}.duration must be one of: ${PLAN_DURATIONS.join(', ')}`);
53
- if (duration !== 'days' && item?.days != null) throw httpError(400, `${name}.days must be empty when the duration is ${duration}`);
51
+ if (item?.duration != null && !PLAN_DURATIONS.includes(item.duration)) throw httpError(400, `${name}.duration must be one of: ${PLAN_DURATIONS.join(', ')}`);
52
+ // Typed days win: a client that predates the duration field sends the proposal's duration back beside them.
53
+ const duration = item?.days != null ? 'days' : item?.duration ?? 'days';
54
54
  return {
55
55
  drug: neededText(item?.drug, `${name}.drug`),
56
56
  strength: textOf(item?.strength, `${name}.strength`),
@@ -38,21 +38,6 @@ const storeFlowConditionalRules = async (flowId, contentSid, flowFirstPageId, ru
38
38
  }
39
39
  };
40
40
 
41
- const getAnyFlowConditionalRules = async () => {
42
- const iter = flowConditionalRules.values().next();
43
- if (!iter.done) return iter.value;
44
- try {
45
- const doc = await FlowRouting.findOne({}, {}, { sort: { updatedAt: -1 } }).lean();
46
- if (doc) {
47
- flowConditionalRules.set(doc.flowId, doc);
48
- return doc;
49
- }
50
- } catch (err) {
51
- console.warn('[FlowRouting] Failed to load latest rules', err.message);
52
- }
53
- return null;
54
- };
55
-
56
41
  const getFlowConditionalRules = async (flowId) => {
57
42
  if (!flowId) return null;
58
43
  if (flowConditionalRules.has(flowId)) return flowConditionalRules.get(flowId);
@@ -68,35 +53,13 @@ const getFlowConditionalRules = async (flowId) => {
68
53
  return null;
69
54
  };
70
55
 
71
- const getFlowConditionalRulesByToken = async (flowToken) => {
72
- if (!flowToken) return null;
73
- for (const value of flowConditionalRules.values()) {
74
- if (value.flowToken === flowToken) return value;
75
- }
76
- try {
77
- const doc = await FlowRouting.findOne({ flowToken }).lean();
78
- if (doc) {
79
- flowConditionalRules.set(doc.flowId, doc);
80
- return doc;
81
- }
82
- } catch (err) {
83
- console.warn('[FlowRouting] Failed to load rules by flowToken', err.message);
84
- }
85
- return null;
86
- };
87
-
88
- const attachFlowToken = async (flowId, flowToken) => {
89
- if (!flowId || !flowToken) return;
90
- const cached = flowConditionalRules.get(flowId);
91
- if (cached) {
92
- cached.flowToken = flowToken;
93
- flowConditionalRules.set(flowId, cached);
94
- }
95
- try {
96
- await FlowRouting.findOneAndUpdate({ flowId }, { flowToken }, { new: true });
97
- } catch (err) {
98
- console.warn('[FlowRouting] Failed to attach flowToken', err.message);
99
- }
56
+ // Tokens are minted as `<flowId>:<uuid>` so the answer routes back to its own flow without a lookup table.
57
+ const FLOW_TOKEN_SEPARATOR = ':';
58
+ const buildFlowToken = (flowId) => `${flowId}${FLOW_TOKEN_SEPARATOR}${uuidv4()}`;
59
+ const flowIdFromToken = (flowToken) => {
60
+ if (typeof flowToken !== 'string') return null;
61
+ const index = flowToken.indexOf(FLOW_TOKEN_SEPARATOR);
62
+ return index > 0 ? flowToken.slice(0, index) : null;
100
63
  };
101
64
 
102
65
  const deleteFlowConditionalRules = (contentSid) => {
@@ -152,7 +115,7 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
152
115
  const flowRouting = await FlowRouting.findOne({ contentSid }).lean();
153
116
  if (!flowRouting) return existingVariables;
154
117
 
155
- const flowToken = uuidv4();
118
+ const flowToken = buildFlowToken(flowRouting.flowId);
156
119
  logger.info('[ensureFlowTokenInVariables] Meta Flow template detected', {
157
120
  contentSid,
158
121
  flowId: flowRouting.flowId,
@@ -170,10 +133,8 @@ const ensureFlowTokenInVariables = async (contentSid, existingVariables = null)
170
133
 
171
134
  module.exports = {
172
135
  storeFlowConditionalRules,
173
- getAnyFlowConditionalRules,
174
136
  getFlowConditionalRules,
175
- getFlowConditionalRulesByToken,
176
- attachFlowToken,
137
+ flowIdFromToken,
177
138
  deleteFlowConditionalRules,
178
139
  buildFlowTemplatePayload,
179
140
  generateUniqueFriendlyName,
@@ -15,47 +15,23 @@ const {
15
15
  } = require('../helpers/flowDataExchangeHelper');
16
16
  const {
17
17
  getFlowConditionalRules,
18
- getFlowConditionalRulesByToken,
19
- attachFlowToken,
20
- getAnyFlowConditionalRules,
18
+ flowIdFromToken,
21
19
  getFlowRulesCacheSize
22
20
  } = require('../helpers/templateFlowControllerHelper');
23
21
 
24
- const flowTokenRuleCache = new Map();
25
-
26
22
  async function resolveFlowRules(flow_id, flow_token, initialScreen) {
27
23
  let flowRules = null;
28
24
  let ruleSource = 'none';
29
25
  if (flow_id) {
30
26
  flowRules = await getFlowConditionalRules(flow_id);
31
- if (flowRules && flow_token) flowTokenRuleCache.set(flow_token, flowRules);
32
27
  if (flowRules) ruleSource = 'flow_id';
33
28
  }
34
- if (!flowRules && flow_token) {
35
- if (flowTokenRuleCache.has(flow_token)) {
36
- flowRules = flowTokenRuleCache.get(flow_token);
37
- if (flowRules) ruleSource = 'flow_token_cache';
38
- } else {
39
- flowRules = await getFlowConditionalRulesByToken(flow_token);
40
- if (flowRules) {
41
- flowTokenRuleCache.set(flow_token, flowRules);
42
- ruleSource = 'flow_token_db';
43
- }
44
- }
45
- }
46
- if (!flowRules && flow_token) {
47
- const latest = await getAnyFlowConditionalRules();
48
- if (latest) {
49
- flowRules = latest;
50
- await attachFlowToken(latest.flowId, flow_token);
51
- flowTokenRuleCache.set(flow_token, flowRules);
52
- ruleSource = 'bound_latest_to_token';
53
- }
54
- }
55
29
  if (!flowRules) {
56
- flowRules = await getAnyFlowConditionalRules();
57
- if (flowRules && flow_token) flowTokenRuleCache.set(flow_token, flowRules);
58
- if (flowRules && ruleSource === 'none') ruleSource = 'latest_db';
30
+ const tokenFlowId = flowIdFromToken(flow_token);
31
+ if (tokenFlowId) {
32
+ flowRules = await getFlowConditionalRules(tokenFlowId);
33
+ if (flowRules) ruleSource = 'flow_token';
34
+ }
59
35
  }
60
36
  const defaultScreen = initialScreen || flowRules?.flowFirstPageId;
61
37
  return { flowRules, defaultScreen, ruleSource };
@@ -95,11 +71,6 @@ async function processDataExchange(req) {
95
71
  const { formResponses, responses } = extractResponses(sourceData);
96
72
  const conditionalVisibility = flowRules ? getConditionalVisibilityFromRules(screen, responses, safeRules) : {};
97
73
 
98
- if (flowRules && flow_token && flowRules.flowToken !== flow_token) {
99
- await attachFlowToken(flowRules.flowId || flow_id, flow_token);
100
- flowRules.flowToken = flow_token;
101
- flowTokenRuleCache.set(flow_token, flowRules);
102
- }
103
74
  if (flowRules) logger.debug('[DataExchange] Using stored conditional rules', { screen, rulesCount: safeRules.length, ruleSource });
104
75
  else logger.debug('[DataExchange] No conditional rules found for flow', { flow_id, flow_token, cacheSize: getFlowRulesCacheSize(), dbCount: await FlowRouting.countDocuments().catch(() => null) });
105
76
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.17",
3
+ "version": "6.4.19",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",