@peopl-health/nexus 6.0.10 → 6.0.12

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.
@@ -106,6 +106,13 @@ function capUrgentFlags(block, held) {
106
106
  return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
107
107
  }
108
108
 
109
+ // The draft names the red flag its blocking question asks about: ruling that flag out while asking for it contradicts itself, so it stays pending.
110
+ function reopenBlockingFlag(block, blockingFlag) {
111
+ if (!blockingFlag || !Array.isArray(block?.redFlags)) return block;
112
+ const key = normalizedKeyOf(blockingFlag);
113
+ return { ...block, redFlags: block.redFlags.map((flag) => (flag?.present === false && normalizedKeyOf(flag.flag) === key ? { ...flag, present: null } : flag)) };
114
+ }
115
+
109
116
  async function generateEscalationDraft({
110
117
  code, callLogs = [], alarms = [], agentCharacterization = null, heldUrgentFlags = [], provider, trace = null, reviewId = null, now = Date.now(),
111
118
  } = {}) {
@@ -149,7 +156,7 @@ async function generateEscalationDraft({
149
156
  const patientMessage = trimmed(parsed?.patientMessage);
150
157
  // The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
151
158
  const held = new Set(heldUrgentFlags.map(normalizedKeyOf));
152
- const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(block, held));
159
+ const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(reopenBlockingFlag(block, parsed?.sufficientForDoctor === false ? trimmed(parsed?.blockingFlag) : null), held));
153
160
  if (!blocks.length) {
154
161
  const shape = parsed.symptoms;
155
162
  logger.warn('[escalationDraft] generation returned a malformed symptom list', {
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,
@@ -90,6 +90,14 @@ const quietReminderSchema = new mongoose.Schema({
90
90
  delivered: { type: Boolean, default: null },
91
91
  }, { _id: false });
92
92
 
93
+ const blockingAskSchema = new mongoose.Schema({
94
+ draftAt: { type: Date, required: true },
95
+ question: { type: String, default: null },
96
+ sentAt: { type: Date, required: true },
97
+ skippedReason: { type: String, default: null },
98
+ outcome: { type: String, default: null },
99
+ }, { _id: false });
100
+
93
101
  const reviewUpdateSchema = new mongoose.Schema({
94
102
  turnId: { type: String, required: true },
95
103
  tools: { type: [String], default: [] },
@@ -246,6 +254,7 @@ const escalationReviewSchema = new mongoose.Schema({
246
254
  autoHandoffFailedAt: { type: Date, default: null },
247
255
  autoHandoffAttempts: { type: Number, default: 0 },
248
256
  quietReminders: { type: [quietReminderSchema], default: [] },
257
+ blockingAsks: { type: [blockingAskSchema], default: [] },
249
258
  feverPromptStartedAt: { type: Date, default: null },
250
259
  approverViewedAt: { type: Date, default: null },
251
260
  previousReviewId: { type: String, default: null },
@@ -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 };
@@ -28,6 +28,7 @@ const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, r
28
28
  const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
29
29
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
30
30
  const getMessaging = () => require('../core/NexusMessaging');
31
+ const blockingAskText = (question) => `La revisión de esta escalación necesita un dato que todavía falta. Pregúntale a la paciente, en un solo mensaje breve y con tus palabras: «${question}». No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.`;
31
32
 
32
33
  const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
33
34
  const timeOf = (value) => new Date(value).getTime();
@@ -236,6 +237,14 @@ async function skipGraveAlerts(review, clock, now) {
236
237
  for (const entry of unsentGraveAlerts(review, clock)) await setOn(review, entry, { sentAt: now, skippedReason: 'patient_hospitalized' }, { sentAt: null });
237
238
  }
238
239
 
240
+ // The last message the patient saw: the quiet reminder itself and a send that never arrived are no question of the bot's.
241
+ async function lastChatMessage(code) {
242
+ const [last] = await getMessages({
243
+ numero: code, origin: { $nin: ['system', 'instruction'] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
244
+ }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
245
+ return last;
246
+ }
247
+
239
248
  // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
240
249
  async function remindQuietPatient(review, clock, now) {
241
250
  if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
@@ -248,11 +257,8 @@ async function remindQuietPatient(review, clock, now) {
248
257
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
249
258
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
250
259
 
251
- // The draft's missing datum never reaches the bot, so the reminder needs a question of the bot's own still open in the chat.
252
- // The reminder itself and a send that never arrived are no question of the bot's.
253
- const [last] = await getMessages({
254
- numero: review.patientCode, origin: { $nin: ['system', 'instruction'] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
255
- }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
260
+ // The reminder points back to a question of the bot's own still open in the chat.
261
+ const last = await lastChatMessage(review.patientCode);
256
262
  let skippedReason = null;
257
263
  if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
258
264
  else if (!last?.from_me || !String(last.body ?? '').includes('?')) skippedReason = 'no_open_question';
@@ -286,6 +292,52 @@ async function remindQuietPatient(review, clock, now) {
286
292
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
287
293
  }
288
294
 
295
+ // The bot asks the draft's blocking question once per draft, unless its own last message left a question open.
296
+ async function askBlockingQuestion(review, clock, now) {
297
+ if (!OUTCOME_LEVELS.includes(clock.level) || review.status !== 'draft_ready' || review.closedAt) return;
298
+ const latest = (review.drafts ?? []).at(-1);
299
+ if (latest?.writtenBy !== DRAFT_OPERATOR || !latest.blockingQuestion || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
300
+ const asks = review.blockingAsks ?? [];
301
+ if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
302
+ const last = await lastChatMessage(review.patientCode);
303
+
304
+ let skippedReason = await takenOf(review, clock);
305
+ if (!skippedReason && !last?.from_me) skippedReason = 'patient_wrote';
306
+ if (!skippedReason && String(last.body ?? '').includes('?')) skippedReason = 'question_open';
307
+ if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
308
+ const claimed = await getEscalationReview().updateOne(
309
+ { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
310
+ { $push: { blockingAsks: { draftAt: latest.createdAt, question: latest.blockingQuestion, sentAt: now, skippedReason, outcome: null } } },
311
+ BOOKKEEPING,
312
+ );
313
+ if (!claimed.modifiedCount || skippedReason) return;
314
+ // The turn runs in the background so the sweep does not wait on it; while it waits for the chat lock the case can be handed over, redrafted or taken.
315
+ const beforeRun = async () => {
316
+ const fresh = await getEscalationReview().findById(review._id).lean();
317
+ if (!fresh || fresh.closedAt || fresh.status !== 'draft_ready') return 'moved';
318
+ if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
319
+ return takenOf(fresh, clock);
320
+ };
321
+ getMessaging().processInstruction(review.patientCode, blockingAskText(latest.blockingQuestion), 'developer', { triggeredBy: OPERATOR, beforeRun })
322
+ .then((result) => result?.outcome ?? null, (error) => {
323
+ logger.error('[CharacterizationOutcome] The blocking question was not asked', {
324
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
325
+ });
326
+ return 'threw';
327
+ })
328
+ .then(async (outcome) => {
329
+ await getEscalationReview().updateOne(
330
+ { _id: review._id, blockingAsks: { $elemMatch: { draftAt: latest.createdAt } } },
331
+ { $set: { 'blockingAsks.$.outcome': outcome } },
332
+ BOOKKEEPING,
333
+ );
334
+ await audit(review, { action: 'blocking_question_asked', urgencyLevel: clock.level, outcome });
335
+ })
336
+ .catch((error) => logger.error('[CharacterizationOutcome] The blocking question outcome was not recorded', {
337
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
338
+ }));
339
+ }
340
+
289
341
  // After the bot escalates: hands the case to the doctor once it is enough or the patient stopped answering, and tells the team.
290
342
  async function settleCharacterization(review, clock, now) {
291
343
  if (!clock) return;
@@ -301,6 +353,7 @@ async function settleCharacterization(review, clock, now) {
301
353
  if (hospitalized) await skipGraveAlerts(review, clock, now);
302
354
  else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
303
355
  await remindQuietPatient(review, clock, now);
356
+ await askBlockingQuestion(review, clock, now);
304
357
  }
305
358
 
306
359
  module.exports = { outcomeOf, settleCharacterization };
@@ -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 };
@@ -171,7 +171,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
171
171
  closedAt: null,
172
172
  status: { $in: PRE_DECISION_STATUSES },
173
173
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
174
- }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, quietReminders: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
174
+ }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, quietReminders: 1, blockingAsks: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
175
175
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
176
176
  'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
177
177
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.10",
3
+ "version": "6.0.12",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",