@peopl-health/nexus 6.0.11 → 6.0.13

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.
package/lib/index.d.ts CHANGED
@@ -625,6 +625,33 @@ declare module '@peopl-health/nexus' {
625
625
  /** Writes those closures as `stopped` facts (source `unit`, validTime = end date); a dry run unless `dryRun: false` with a `patientScope`. */
626
626
  export function closeStoppedRegimens(options?: { dryRun?: boolean; patientScope?: (patientId: string) => boolean; today?: string }): Promise<RegimenCloserResult>;
627
627
 
628
+ export interface PatientCodeMigrationReport {
629
+ from: string;
630
+ to: string;
631
+ asCaregiver: boolean;
632
+ apply: boolean;
633
+ messages: number;
634
+ summaries: number;
635
+ memories: number;
636
+ thread: 'none' | 'rename' | 'archive_source';
637
+ tokenMap: 'none' | 'rename' | 'merge';
638
+ retokenized: number;
639
+ pendingScheduled: number;
640
+ scheduled: 'none' | 'retarget' | 'left_for_review';
641
+ openPledges: number;
642
+ oldInboundLast24h: number;
643
+ refusals: string[];
644
+ migrationId?: string;
645
+ }
646
+
647
+ export function migratePatientCode(options: {
648
+ from: string;
649
+ to: string;
650
+ asCaregiver?: boolean;
651
+ apply?: boolean;
652
+ operator?: string | null;
653
+ }): Promise<PatientCodeMigrationReport>;
654
+
628
655
  export const routes: any;
629
656
  export function setupDefaultRoutes(app: any): void;
630
657
  export function createRouter(routeDefinitions: Record<string, string>, controllers: Record<string, Function>): any;
package/lib/index.js CHANGED
@@ -60,6 +60,7 @@ const supportActionService = require('./clinical/services/supportActionService')
60
60
  const supportLightService = require('./clinical/services/supportLightService');
61
61
  const supportInvitability = require('./clinical/services/supportInvitability');
62
62
  const supportLightEvaluationService = require('./clinical/services/supportLightEvaluationService');
63
+ const { migratePatientCode } = require('./services/patientCodeMigrationService');
63
64
  const {
64
65
  NutritionSafetyDecision,
65
66
  FINDING_CODES,
@@ -409,6 +410,7 @@ module.exports = {
409
410
  supportLightService,
410
411
  supportInvitability,
411
412
  supportLightEvaluationService,
413
+ migratePatientCode,
412
414
  NutritionSafetyDecision,
413
415
  FINDING_CODES,
414
416
  FINDING_VALUES,
@@ -0,0 +1,21 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Holds decoded names, so it expires once a bad migration would have surfaced.
4
+ const BACKUP_TTL_SECONDS = 180 * 24 * 60 * 60;
5
+
6
+ const patientCodeMigrationSchema = new mongoose.Schema({
7
+ from: { type: String, required: true },
8
+ to: { type: String, required: true },
9
+ asCaregiver: { type: Boolean, default: false },
10
+ operator: { type: String, default: null },
11
+ report: { type: Object, default: null },
12
+ before: { type: Object, required: true },
13
+ }, { timestamps: true });
14
+
15
+ patientCodeMigrationSchema.index({ from: 1, createdAt: -1 });
16
+ patientCodeMigrationSchema.index({ to: 1, createdAt: -1 });
17
+ patientCodeMigrationSchema.index({ createdAt: 1 }, { expireAfterSeconds: BACKUP_TTL_SECONDS });
18
+
19
+ const PatientCodeMigration = mongoose.model('PatientCodeMigration', patientCodeMigrationSchema);
20
+
21
+ module.exports = { PatientCodeMigration };
@@ -0,0 +1,248 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { normalize } = require('../utils/tokenMapUtils');
3
+ const { mapStringsDeep } = require('../utils/sanitizerUtils');
4
+
5
+ const { Message } = require('../models/messageModel');
6
+ const { Thread } = require('../models/threadModel');
7
+ const { getTokenMap } = require('../models/tokenMapModel');
8
+ const { ScheduledMessage } = require('../models/agendaMessageModel');
9
+ const { SafetyNetPledge, OPEN_PLEDGE_STATES } = require('../models/safetyNetPledgeModel');
10
+ const { PatientCodeMigration } = require('../models/patientCodeMigrationModel');
11
+ const { ensureWhatsAppFormat, stripWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twilioHelper');
12
+ const { CAREGIVER_ROLE } = require('../helpers/caregiverHelper');
13
+ const { getConversationSummary } = require('../clinical/models/conversationSummaryModel');
14
+ const { getPatientMemory } = require('../clinical/models/patientMemoryModel');
15
+
16
+ const TOKEN_REGEX = /<<[A-Z_]+_\d+>>/g;
17
+ const HAS_TOKEN = /<<[A-Z_]+_\d+>>/;
18
+ const TOKEN_PARTS = /^<<([A-Z_]+)_(\d+)>>$/;
19
+
20
+ // Fields that identify the document or record what the provider sent; tokens elsewhere are rewritten.
21
+ const UNTOUCHED_FIELDS = new Set(['_id', '__v', 'raw', 'numero', 'code', 'createdAt', 'updatedAt']);
22
+
23
+ // A single migration row holds every moved document; stay well under Mongo's 16 MB document cap.
24
+ const MAX_BACKUP_BYTES = 12 * 1024 * 1024;
25
+ const DAY_MS = 24 * 60 * 60 * 1000;
26
+
27
+ const tokenIndex = (token) => Number(TOKEN_PARTS.exec(token)?.[2] || 0);
28
+ const own = (object, key) => Object.hasOwn(object, key) ? object[key] : undefined;
29
+
30
+ // Each code numbers its tokens on its own, so <<PERSONA_1>> can name a different person on each side.
31
+ function planTokenMerge(source, target) {
32
+ const mapping = new Map();
33
+ const encode = {};
34
+ const decode = {};
35
+ const targetEncode = target?.encode || {};
36
+ const targetDecode = target?.decode || {};
37
+ const sourceDecode = source?.decode || {};
38
+ const normalizedOf = new Map(Object.entries(source?.encode || {}).map(([normalized, token]) => [token, normalized]));
39
+
40
+ let seq = Math.max(
41
+ target?.seq || 0,
42
+ source?.seq || 0,
43
+ ...Object.keys(targetDecode).map(tokenIndex),
44
+ ...Object.keys(sourceDecode).map(tokenIndex),
45
+ );
46
+
47
+ for (const [token, plaintext] of Object.entries(sourceDecode)) {
48
+ const normalized = normalizedOf.get(token) ?? normalize(plaintext);
49
+ const known = own(targetEncode, normalized) ?? own(encode, normalized);
50
+ if (known) {
51
+ if (known !== token) mapping.set(token, known);
52
+ continue;
53
+ }
54
+ let next = token;
55
+ if (own(targetDecode, token) !== undefined || own(decode, token) !== undefined) {
56
+ next = `<<${TOKEN_PARTS.exec(token)?.[1] || 'PERSONA'}_${++seq}>>`;
57
+ mapping.set(token, next);
58
+ }
59
+ encode[normalized] = next;
60
+ decode[next] = plaintext;
61
+ }
62
+
63
+ return { mapping, encode, decode, seq };
64
+ }
65
+
66
+ function retokenize(text, mapping) {
67
+ if (typeof text !== 'string' || !mapping.size) return text;
68
+ return text.replace(TOKEN_REGEX, (token) => mapping.get(token) || token);
69
+ }
70
+
71
+ function retokenizedFields(doc, mapping) {
72
+ const changed = {};
73
+ if (!mapping.size) return changed;
74
+ for (const [key, value] of Object.entries(doc)) {
75
+ if (UNTOUCHED_FIELDS.has(key)) continue;
76
+ const next = mapStringsDeep(value, (text) => retokenize(text, mapping));
77
+ if (next !== value) changed[key] = next;
78
+ }
79
+ return changed;
80
+ }
81
+
82
+ const carriesTokens = (doc) => Object.entries(doc).some(([key, value]) => (
83
+ !UNTOUCHED_FIELDS.has(key) && HAS_TOKEN.test(JSON.stringify(value ?? ''))
84
+ ));
85
+
86
+ const sameFormat = (stored, target) => {
87
+ const digits = stripWhatsAppFormat(target);
88
+ if (String(stored).startsWith('whatsapp:')) return target;
89
+ return String(stored).startsWith('+') ? `+${digits}` : digits;
90
+ };
91
+
92
+ const scheduledCodes = (code) => {
93
+ const digits = stripWhatsAppFormat(code);
94
+ return [code, digits, `+${digits}`];
95
+ };
96
+
97
+ function toCode(number) {
98
+ const code = ensureWhatsAppFormat(number);
99
+ if (typeof code !== 'string' || isArchivedPatientCode(code)) {
100
+ throw new Error('[migratePatientCode] archived codes cannot be migrated');
101
+ }
102
+ if (code.includes('@') || !/^\d{8,15}$/.test(stripWhatsAppFormat(code))) {
103
+ throw new Error('[migratePatientCode] from and to must be WhatsApp phone numbers');
104
+ }
105
+ return code;
106
+ }
107
+
108
+ async function readState(source, target) {
109
+ const TokenMap = getTokenMap();
110
+ const [sourceMap, targetMap, messages, summaries, memories, sourceThreads, targetThread, scheduled, openPledges] = await Promise.all([
111
+ TokenMap.findOne({ code: source }).lean(),
112
+ TokenMap.findOne({ code: target }).lean(),
113
+ Message.find({ numero: source }).lean(),
114
+ getConversationSummary().find({ numero: source }).lean(),
115
+ getPatientMemory().find({ numero: source }).lean(),
116
+ Thread.find({ code: source }).lean(),
117
+ Thread.findOne({ code: target }).lean(),
118
+ ScheduledMessage.find({ code: { $in: scheduledCodes(source) }, status: 'pending' }).lean(),
119
+ SafetyNetPledge.find({ code: source, state: { $in: OPEN_PLEDGE_STATES } }).lean(),
120
+ ]);
121
+ return { sourceMap, targetMap, messages, summaries, memories, sourceThreads, targetThread, scheduled, openPledges };
122
+ }
123
+
124
+ function buildReport({ source, target, asCaregiver, apply }, state, tokenPlan) {
125
+ const recent = Date.now() - DAY_MS;
126
+ return {
127
+ from: source,
128
+ to: target,
129
+ asCaregiver,
130
+ apply,
131
+ messages: state.messages.length,
132
+ summaries: state.summaries.length,
133
+ memories: state.memories.length,
134
+ thread: !state.sourceThreads.length ? 'none' : state.targetThread ? 'archive_source' : 'rename',
135
+ tokenMap: !state.sourceMap ? 'none' : state.targetMap ? 'merge' : 'rename',
136
+ retokenized: tokenPlan.mapping.size,
137
+ pendingScheduled: state.scheduled.length,
138
+ scheduled: !state.scheduled.length ? 'none' : asCaregiver ? 'left_for_review' : 'retarget',
139
+ openPledges: state.openPledges.length,
140
+ oldInboundLast24h: state.messages.filter((doc) => doc.from_me === false && new Date(doc.createdAt).getTime() >= recent).length,
141
+ };
142
+ }
143
+
144
+ function refusals(state) {
145
+ const reasons = [];
146
+ if (state.openPledges.length) reasons.push('the old number has open safety-net pledges; let them resolve first');
147
+ const orphanTokens = !state.sourceMap && state.targetMap
148
+ && [...state.messages, ...state.summaries, ...state.memories].some(carriesTokens);
149
+ if (orphanTokens) reasons.push('the old number has tokenized text but no token map; restore its archived map first');
150
+ return reasons;
151
+ }
152
+
153
+ // Live encoding on the new number can claim a token between the read and this write.
154
+ async function mergeTokenMap(target, tokenPlan) {
155
+ const filter = { code: target };
156
+ const additions = {};
157
+ for (const [normalized, token] of Object.entries(tokenPlan.encode)) {
158
+ filter[`encode.${normalized}`] = { $exists: false };
159
+ additions[`encode.${normalized}`] = token;
160
+ }
161
+ for (const [token, plaintext] of Object.entries(tokenPlan.decode)) {
162
+ filter[`decode.${token}`] = { $exists: false };
163
+ additions[`decode.${token}`] = plaintext;
164
+ }
165
+ const update = { $max: { seq: tokenPlan.seq }, ...(Object.keys(additions).length && { $set: additions }) };
166
+ const res = await getTokenMap().updateOne(filter, update);
167
+ if (!res?.matchedCount) {
168
+ throw new Error('[migratePatientCode] the new number encoded names while migrating; nothing moved, run it again');
169
+ }
170
+ }
171
+
172
+ const rewriteOps = (docs, setFor) => docs.map((doc) => ({
173
+ updateOne: { filter: { _id: doc._id }, update: { $set: setFor(doc) } },
174
+ }));
175
+
176
+ async function moveThreads(source, target, state, migrationId) {
177
+ const archived = `archived:${source}`;
178
+ const [newest, ...rest] = [...state.sourceThreads].sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0));
179
+ const toArchive = state.targetThread ? state.sourceThreads : rest;
180
+ if (!state.targetThread && newest) await Thread.updateOne({ _id: newest._id }, { $set: { code: target } });
181
+ if (toArchive.length) {
182
+ await Thread.updateMany({ _id: { $in: toArchive.map((doc) => doc._id) } }, { $set: { code: archived, stopped: true } });
183
+ }
184
+ logger.debug('[migratePatientCode] Threads moved', { migrationId, renamed: !state.targetThread && !!newest, archived: toArchive.length });
185
+ }
186
+
187
+ async function migratePatientCode({ from, to, asCaregiver = false, apply = false, operator = null } = {}) {
188
+ const source = toCode(from);
189
+ const target = toCode(to);
190
+ if (source === target) throw new Error('[migratePatientCode] from and to must be two different numbers');
191
+
192
+ const state = await readState(source, target);
193
+ const merging = !!(state.sourceMap && state.targetMap);
194
+ const tokenPlan = planTokenMerge(merging ? state.sourceMap : null, merging ? state.targetMap : null);
195
+ const report = buildReport({ source, target, asCaregiver, apply }, state, tokenPlan);
196
+ const reasons = refusals(state);
197
+ if (!apply) return { ...report, refusals: reasons };
198
+ if (reasons.length) throw new Error(`[migratePatientCode] not applied: ${reasons.join('; ')}`);
199
+
200
+ const before = {
201
+ messages: state.messages,
202
+ summaries: state.summaries,
203
+ memories: state.memories,
204
+ threads: [...state.sourceThreads, state.targetThread].filter(Boolean),
205
+ tokenMaps: [state.sourceMap, state.targetMap].filter(Boolean),
206
+ scheduled: state.scheduled,
207
+ };
208
+ if (Buffer.byteLength(JSON.stringify(before)) > MAX_BACKUP_BYTES) {
209
+ throw new Error('[migratePatientCode] history too large for an in-database backup; export it first');
210
+ }
211
+
212
+ if (merging) await mergeTokenMap(target, tokenPlan);
213
+ const migration = await PatientCodeMigration.create({ from: source, to: target, asCaregiver, operator, report, before });
214
+ const migrationId = String(migration._id);
215
+ const TokenMap = getTokenMap();
216
+ if (state.sourceMap) {
217
+ const code = merging ? `archived:${source}:${migrationId}` : target;
218
+ await TokenMap.updateOne({ _id: state.sourceMap._id }, { $set: { code } });
219
+ }
220
+
221
+ const { mapping } = tokenPlan;
222
+ if (state.messages.length) {
223
+ await Message.bulkWrite(rewriteOps(state.messages, (doc) => ({
224
+ ...retokenizedFields(doc, mapping),
225
+ numero: target,
226
+ ...(asCaregiver && !doc.contact_code && { contact_code: source, contact_role: CAREGIVER_ROLE }),
227
+ })));
228
+ }
229
+ if (state.summaries.length) {
230
+ await getConversationSummary().bulkWrite(rewriteOps(state.summaries, (doc) => ({ ...retokenizedFields(doc, mapping), numero: target })));
231
+ }
232
+ if (state.memories.length) {
233
+ await getPatientMemory().bulkWrite(rewriteOps(state.memories, (doc) => ({ ...retokenizedFields(doc, mapping), numero: target })));
234
+ }
235
+
236
+ await moveThreads(source, target, state, migrationId);
237
+
238
+ if (state.scheduled.length && !asCaregiver) {
239
+ await ScheduledMessage.bulkWrite(rewriteOps(state.scheduled, (doc) => ({ code: sameFormat(doc.code, target) })));
240
+ }
241
+
242
+ await PatientCodeMigration.updateOne({ _id: migration._id }, { $set: { 'report.completedAt': new Date() } });
243
+ const { from: _from, to: _to, ...counts } = report;
244
+ logger.info('[migratePatientCode] Patient history moved', { migrationId, ...counts });
245
+ return { ...report, refusals: [], migrationId };
246
+ }
247
+
248
+ module.exports = { migratePatientCode };
@@ -1,4 +1,5 @@
1
1
  const { Monitoreo_ID } = require('../config/airtableConfig');
2
+ const { programSourceFormula } = require('../config/programConfig');
2
3
 
3
4
  const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper');
4
5
 
@@ -16,15 +17,16 @@ async function getEscalationApprover(email) {
16
17
  const normalized = String(email ?? '').trim().toLowerCase();
17
18
  if (!normalized) return null;
18
19
 
19
- const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {aprueba_vaiven})`;
20
+ const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {aprueba_vaiven}, ${programSourceFormula()})`;
20
21
  const [physician] = await getRecordByFilter(Monitoreo_ID, 'physicians', formula, null, APPROVER_FIELDS, true) || [];
21
22
  if (!physician) return null;
22
23
 
23
24
  return approverOf(physician, normalized);
24
25
  }
25
26
 
27
+ // A physician approves escalations only for the programs ticked on their row.
26
28
  async function listEscalationApprovers() {
27
- const physicians = await getRecordByFilter(Monitoreo_ID, 'physicians', '{aprueba_vaiven}', null, APPROVER_FIELDS, true) || [];
29
+ const physicians = await getRecordByFilter(Monitoreo_ID, 'physicians', `AND({aprueba_vaiven}, ${programSourceFormula()})`, null, APPROVER_FIELDS, true) || [];
28
30
  return physicians.filter((physician) => physician.email).map((physician) => approverOf(physician));
29
31
  }
30
32
 
@@ -2,6 +2,7 @@ const axios = require('axios');
2
2
 
3
3
  const runtimeConfig = require('../config/runtimeConfig');
4
4
  const { Monitoreo_ID } = require('../config/airtableConfig');
5
+ const { programSourceFormula } = require('../config/programConfig');
5
6
  const { logger } = require('../utils/logger');
6
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
8
  const { withTimeout } = require('../utils/timeoutUtils');
@@ -38,8 +39,9 @@ function configuredPhones() {
38
39
  .filter((code) => PATIENT_CODE.test(code));
39
40
  }
40
41
 
42
+ // Only the members on call for this program; a member with no program gets no alert.
41
43
  async function readRoster() {
42
- const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, '{activo}', null, ROSTER_FIELDS);
44
+ const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, `AND({activo}, ${programSourceFormula()})`, null, ROSTER_FIELDS);
43
45
  if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
44
46
  return rows
45
47
  .map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [] }))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.11",
3
+ "version": "6.0.13",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",