@peopl-health/nexus 6.0.30 → 6.1.0-dev.18137

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.
@@ -1,6 +1,5 @@
1
1
  const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
2
2
  const { inlineOf, oneLineOf } = require('../../utils/coercionUtils');
3
- const { mexicoStamp } = require('../../utils/dateUtils');
4
3
 
5
4
  const URGENCY_LABELS = {
6
5
  stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
@@ -82,13 +81,20 @@ function proposalLine({ proposal, conduct, sections }) {
82
81
  ].filter(Boolean).join(' ');
83
82
  }
84
83
 
84
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
85
+ // The part as a whole phrase of the text, so «no» is not found inside «ibuprofeno».
86
+ const includesText = (text, part) => Boolean(text && part) && new RegExp(`(^|[^\\p{L}\\d/])${escaped(part)}($|[^\\p{L}\\d/])`, 'iu').test(text);
87
+
85
88
  function symptomParagraph(entry, fallbackSymptom) {
86
89
  const sections = entry.sections ?? {};
87
- const grade = [1, 2, 3].includes(sections.grade) ? `G${sections.grade}` : 'grado no establecido';
90
+ const label = inlineOf(sections.symptom) || fallbackSymptom || 'Síntoma no especificado';
91
+ const graded = [1, 2, 3, 4, 5].includes(sections.grade);
92
+ const grade = graded ? `G${sections.grade}` : 'grado no establecido';
88
93
  const { present, absent, unassessed } = flagsByStatus(sections);
89
94
  const summary = inlineOf(sections.characterizationSummary);
90
95
  return [
91
- `${inlineOf(sections.symptom) || fallbackSymptom || 'Síntoma no especificado'} (${grade}):`,
96
+ // An ungraded symptom whose label already names a grade is not called ungraded.
97
+ !graded && /\bG[1-5]\b/.test(label) ? `${label}:` : `${label} (${grade}):`,
92
98
  summary && sentence(summary),
93
99
  present.length && `${present.length > 1 ? 'Banderas rojas presentes' : 'Bandera roja presente'}: ${sentence(present.join(', '))}`,
94
100
  !present.length && !unassessed.length && absent.length && 'Sin banderas rojas.',
@@ -102,12 +108,15 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
102
108
  const lastDose = inlineOf(context?.lastDose);
103
109
  const priorManagement = inlineOf(context?.priorManagement);
104
110
  const response = inlineOf(context?.response);
105
- const urgency = [URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel), alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null].filter(Boolean);
106
111
  const priorities = inlineOf(shared?.doctorPriorities);
112
+ // The last dose is said once, so not again when the treatment text already gives it.
113
+ const dose = includesText(treatment, lastDose) ? null : `última dosis: ${lastDose || 'no disponible'}`;
114
+ // A response that already reads as one («sin respuesta», «respuesta parcial») is not prefixed again; «no aplica» says nothing.
115
+ const answer = response && !/^no aplica\b/i.test(response) && !includesText(priorManagement, response)
116
+ && (/^(respuesta\b|(sin|no)\s)/i.test(response) ? response : `respuesta ${response}`);
107
117
  return [
108
- urgency.length ? `Urgencia: ${urgency.join(' · ')}` : null,
109
- `Tratamiento: ${treatment || 'no disponible'}; última dosis ${lastDose || 'no disponible'}.`,
110
- priorManagement || response ? `Manejo previo: ${sentence([priorManagement, response && `respuesta ${response}`].filter(Boolean).join('; '))}` : null,
118
+ treatment || lastDose ? `Tratamiento: ${[treatment || 'no disponible', dose].filter(Boolean).join('; ')}.` : 'Tratamiento y última dosis: no disponibles.',
119
+ priorManagement || answer ? `Manejo previo: ${sentence([priorManagement, answer].filter(Boolean).join('; '))}` : null,
111
120
  vitalsLine(shared?.vitals),
112
121
  inlineOf(shared?.objectiveData) ? `Datos objetivos: ${sentence(inlineOf(shared.objectiveData))}` : null,
113
122
  '',
@@ -120,7 +129,8 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
120
129
 
121
130
  function identityLines({ identity, review }) {
122
131
  const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
123
- return [`Paciente: ${identity.patientName} · ${phone}`, `Médico tratante: ${withTitle(identity.treatingDoctor)}`];
132
+ const patient = identity.age ? `${identity.patientName}, ${identity.age} años` : identity.patientName;
133
+ return [`Paciente: ${patient} · ${phone}`, `Médico tratante: ${withTitle(identity.treatingDoctor)}`];
124
134
  }
125
135
 
126
136
  function withIdentity({ identity, review, doctorText }) {
@@ -19,7 +19,6 @@ const MIN_AGE_MS = 15 * 60 * 1000;
19
19
  const RETRY_MAX_AGE_MS = 60 * 60 * 1000;
20
20
  const MAX_CANDIDATES = 20;
21
21
  const MAX_RETRIES_PER_PASS = 3;
22
- const TRANSIENT_DISPATCH_FAILURES = new Set(['triage_read_failed', 'patient_read_failed', 'item_read_failed']);
23
22
  const CLAIM_TTL_MS = 60 * 60 * 1000;
24
23
  const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
25
24
  const RETRY_SETTLE_MS = 5 * 60 * 1000;
@@ -223,7 +222,7 @@ async function sweepInterruptedTriages({
223
222
  } = {}) {
224
223
  const result = { found: 0, retried: 0, skipped: 0 };
225
224
  if (!retryLive()) return result;
226
- const active = await leases.listActive({ interrupted: true, source: programSource() });
225
+ const active = await leases.listActive();
227
226
  if (!active) return result;
228
227
 
229
228
  const due = active.filter(({ value }) => value.source === programSource()
@@ -247,7 +246,7 @@ async function sweepInterruptedTriages({
247
246
  await retrigger(run);
248
247
  result.retried += 1;
249
248
  } catch (error) {
250
- if (TRANSIENT_DISPATCH_FAILURES.has(error.message)) await claims.release(`${triageRecordId}:${value.startedAt}`);
249
+ await claims.release(`${triageRecordId}:${value.startedAt}`);
251
250
  logger.error('[recommendationRecovery] retry of an interrupted run could not be dispatched', { ...run, error: error.message });
252
251
  }
253
252
  }
@@ -153,7 +153,7 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
153
153
  inflightRuns.set(payload.triageRecordId, inflight);
154
154
  inflight.leaseWritten = inflightLeases.set(payload.triageRecordId, lease);
155
155
  if (shuttingDown) inflight.interrupted = inflight.leaseWritten;
156
- Promise.resolve()
156
+ inflight.leaseWritten
157
157
  .then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId, supportRouting }))
158
158
  .then((settle) => {
159
159
  logger.info('[triageRecommendation] settled', { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: settle.status, reason: settle.reason });
@@ -181,7 +181,6 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
181
181
  .finally(async () => {
182
182
  if (inflightRuns.get(payload.triageRecordId) !== inflight) return;
183
183
  inflightRuns.delete(payload.triageRecordId);
184
- await inflight.leaseWritten;
185
184
  await inflight.interrupted;
186
185
  await inflightLeases.release(payload.triageRecordId);
187
186
  });
@@ -108,12 +108,11 @@ class WriteClaimStore {
108
108
  }
109
109
  }
110
110
 
111
- async listActive(valueMatch = {}) {
111
+ async listActive() {
112
112
  if (!this._durable()) return null;
113
- const query = { key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } };
114
- for (const [field, expected] of Object.entries(valueMatch)) query[`value.${field}`] = expected;
115
113
  try {
116
- const claims = await WriteClaim.find(query).sort({ createdAt: -1 }).limit(100).lean();
114
+ const claims = await WriteClaim.find({ key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } })
115
+ .limit(100).lean();
117
116
  return claims.map((claim) => ({ key: claim.key.slice(this.namespace.length + 1), value: claim.value }));
118
117
  } catch (error) {
119
118
  logger.warn('[writeClaimStore] Claims could not be listed', { namespace: this.namespace, error: error.message });
@@ -66,4 +66,4 @@ class Patient {
66
66
  }
67
67
  }
68
68
 
69
- module.exports = { Patient, genderFrom, ageFrom };
69
+ module.exports = { Patient, genderFrom, ageFrom, birthDateFrom };
@@ -28,6 +28,10 @@ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contest
28
28
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
29
29
  // A reminder this late (an outage, a deploy) is not sent.
30
30
  const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
31
+ // A turn that sent a bridge has answered by then, or inbound recovery takes it over.
32
+ const BRIDGE_WAIT_MS = 2 * 60 * 1000;
33
+ // A delivered ask, one the provider accepted without confirming delivery, or one an earlier turn already answered.
34
+ const ASKED_OUTCOMES = ['sent', 'unknown', 'already_answered'];
31
35
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
32
36
  const getMessaging = () => require('../core/NexusMessaging');
33
37
  const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
@@ -77,9 +81,18 @@ function outcomeOf(review, clock, now) {
77
81
  // A grave question still inside its wait holds the case even when the rest is enough.
78
82
  if (pendingFlagsOf(review, clock.since).flags.length) return null;
79
83
  if (latest.sufficientForDoctor === true) return { grave: [], update, notify, note: withUpdate(null) };
80
- // The latest draft follows the patient's latest answer, so its age is how long the question has gone unanswered.
81
- if (latest.sufficientForDoctor !== false || minutesSince(latest.createdAt, now) < wait) return null;
82
- return { grave: [], update, notify, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
84
+ if (latest.sufficientForDoctor !== false) return null;
85
+ // The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
86
+ const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
87
+ const sent = ask && !ask.skippedReason;
88
+ // A first handoff with a question waits for its ask (recorded once the bot's reply is in), or in flight, up to twice the wait.
89
+ if (!update && latest.blockingQuestion && (!ask || (sent && ask.outcome == null)) && minutesSince(sent ? ask.sentAt : latest.createdAt, now) < 2 * wait) return null;
90
+ if (minutesSince(sent ? ask.sentAt : latest.createdAt, now) < wait) return null;
91
+ const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
92
+ // An update's draft is never asked about, so it says only what is missing.
93
+ if (update) return { grave: [], update, notify, note: withUpdate(noteOf(missing)) };
94
+ const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open';
95
+ return { grave: [], update, notify, note: noteOf(`${missing} (${asked ? 'no contestó' : 'no se le preguntó'})`) };
83
96
  }
84
97
 
85
98
  const audit = (review, changes) => logPatientChange({
@@ -99,7 +112,7 @@ async function claimGraveAlerts(review, clock, grave, now) {
99
112
  .filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
100
113
  const fresh = grave.filter((entry) => !recorded.has(entry.flag));
101
114
  // «No contestó» only for a datum the bot asked about while that question is still open; otherwise «no lo ha dicho».
102
- const askedFlags = new Set((review.blockingAsks ?? []).filter((ask) => ask.outcome === 'sent' && timeOf(ask.draftAt) >= clock.since.getTime())
115
+ const askedFlags = new Set((review.blockingAsks ?? []).filter((ask) => ASKED_OUTCOMES.includes(ask.outcome) && timeOf(ask.draftAt) >= clock.since.getTime())
103
116
  .flatMap((ask) => (ask.flags ?? []).map(normalizedKeyOf)));
104
117
  const open = fresh.some(({ flag, reason }) => reason === 'unanswered' && askedFlags.has(flag))
105
118
  && hasOpenQuestion(await lastChatMessage(review.patientCode).catch(() => null));
@@ -131,9 +144,18 @@ async function handOff(review, clock, outcome, now) {
131
144
  try {
132
145
  if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
133
146
  const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
134
- await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
147
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
135
148
  } catch (error) {
136
- if (digest) await getEscalationReview().updateOne({ _id: review._id, status: { $ne: 'awaiting_doctor' } }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
149
+ // Someone handed the case off since the sweep read it: nothing failed, and the next sweep reads the new handoff.
150
+ const next = `doctorHandoffs.${(review.doctorHandoffs ?? []).length}`;
151
+ const overtaken = error?.statusCode === 409
152
+ && Boolean(await getEscalationReview().exists({ _id: review._id, [next]: { $exists: true } }).catch(() => null));
153
+ // The digest stays queued for a handoff still being sent or one that did not ring the doctor, as another sweep's may rely on it.
154
+ const unqueue = overtaken
155
+ ? { [`${next}.transport`]: { $exists: true, $ne: null } }
156
+ : { status: { $nin: ['awaiting_doctor', 'handing_off'] } };
157
+ if (digest) await getEscalationReview().updateOne({ _id: review._id, ...unqueue }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
158
+ if (overtaken) return false;
137
159
  const attempt = attemptsOf(review, clock) + 1;
138
160
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
139
161
  // A 409 is mostly another sweep or a person who moved the case first.
@@ -216,8 +238,8 @@ async function graveMessage(review, clock, entries) {
216
238
  }
217
239
 
218
240
  const sameEntry = (entry) => ({ flag: entry.flag, since: entry.since });
219
- const setOn = (review, entry, fields, filter = {}) => getEscalationReview().updateOne(
220
- { _id: review._id, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
241
+ const setOn = (review, entry, fields, filter = {}, guard = {}) => getEscalationReview().updateOne(
242
+ { _id: review._id, ...guard, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
221
243
  { $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`graveAlerts.$.${key}`, value])) },
222
244
  BOOKKEEPING,
223
245
  );
@@ -238,7 +260,9 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
238
260
  const message = await graveMessage(review, clock, pending);
239
261
  const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
240
262
  const sending = [];
241
- for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null })).modifiedCount) sending.push(entry);
263
+ // A decision or a closing since the sweep read the case means the alert is no longer due.
264
+ const undecided = { closedAt: null, status: { $in: PRE_DECISION_STATUSES }, decisions: { $size: (review.decisions ?? []).length } };
265
+ for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null }, undecided)).modifiedCount) sending.push(entry);
242
266
  if (!sending.length) return 0;
243
267
  let delivered = 0;
244
268
  try {
@@ -272,7 +296,7 @@ async function skipGraveAlerts(review, clock, now) {
272
296
  async function lastChatMessage(code) {
273
297
  const [last] = await getMessages({
274
298
  numero: code, origin: { $nin: [...INTERNAL_ORIGINS] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
275
- }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
299
+ }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body createdAt raw.bridge' });
276
300
  return last;
277
301
  }
278
302
 
@@ -338,7 +362,8 @@ async function askBlockingQuestion(review, clock, now) {
338
362
  const asks = review.blockingAsks ?? [];
339
363
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
340
364
  const last = await lastChatMessage(review.patientCode);
341
- if (!last?.from_me) return;
365
+ // A recent bridge means the bot's turn is still running; its reply decides whether a question is open.
366
+ if (!last?.from_me || (last.raw?.bridge && now.getTime() - timeOf(last.createdAt) < BRIDGE_WAIT_MS)) return;
342
367
 
343
368
  let skippedReason = await takenOf(review, clock);
344
369
  if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
@@ -5,7 +5,8 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
5
  const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
6
  const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
- const { isoDay, mexicoDay } = require('../utils/dateUtils');
8
+ const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
9
+ const { safeParse } = require('../utils/jsonUtils');
9
10
  const {
10
11
  CALL_OUTCOMES,
11
12
  CANCELLABLE_AFTER_HANDOFF_STATUSES,
@@ -45,6 +46,7 @@ const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/hel
45
46
  const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
46
47
  const { composePrompt } = require('../clinical/services/promptComposerService');
47
48
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
49
+ const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
48
50
 
49
51
  const { getPatientInformation, logPatientChange } = require('./patientService');
50
52
  const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
@@ -72,6 +74,7 @@ const MAX_ALERT_ATTEMPTS = 3;
72
74
  const BOOKKEEPING = { timestamps: false };
73
75
  const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
74
76
  const DUPLICATE_KEY_ERROR = 11000;
77
+ const HANDING_OFF_WAIT_MS = 3000;
75
78
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
76
79
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
77
80
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
@@ -348,7 +351,10 @@ function doctorIdentity(patient) {
348
351
  const missing = [];
349
352
  if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
350
353
  if (!treatingDoctor) missing.push('médico tratante');
351
- return { patientName, treatingDoctor, missing };
354
+ const demografia = safeParse(patient?.['clinical-context-json'], null)?.demografia;
355
+ const born = ageInYears(birthDateFrom(demografia?.fecha_nacimiento));
356
+ const age = born > 0 && born < 130 ? born : ageFrom(demografia?.edad);
357
+ return { patientName, treatingDoctor, age, missing };
352
358
  }
353
359
 
354
360
  async function readDoctorIdentity(review) {
@@ -792,6 +798,21 @@ async function appendKeepingDraft(id, entry) {
792
798
  throw httpError(409, STATUS_CONFLICT);
793
799
  }
794
800
 
801
+ // With the doctor the case keeps its status; a bot handoff redrafts it as an update, so the call reaches the draft the doctor reads.
802
+ async function appendWithDoctor(id, entry) {
803
+ for (let attempt = 0; attempt < 2; attempt += 1) {
804
+ const review = await loadReview(id);
805
+ // The bot's own update passes through handing_off while it sends; the call waits for it once.
806
+ if (review.status === 'handing_off' && attempt === 0) {
807
+ await new Promise((resolve) => { setTimeout(resolve, HANDING_OFF_WAIT_MS); });
808
+ continue;
809
+ }
810
+ if (review.status !== 'awaiting_doctor') break;
811
+ return updateReview(id, ['awaiting_doctor'], { $push: { callLogs: entry }, ...(updatesDoctor(review) && { $set: redraftAfterCall() }) });
812
+ }
813
+ throw httpError(409, STATUS_CONFLICT);
814
+ }
815
+
795
816
  async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
796
817
  const reviewId = reviewIdOf(id);
797
818
  const operator = requiredText(updatedBy, 'updatedBy');
@@ -844,11 +865,13 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
844
865
  if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
845
866
 
846
867
  const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
847
- const review = outcome === 'contacted'
848
- ? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
849
- : await appendKeepingDraft(reviewId, entry);
868
+ const review = await (outcome === 'contacted'
869
+ ? updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
870
+ : appendKeepingDraft(reviewId, entry))
871
+ .catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)));
850
872
  await audit(review, operator, requestId, { action: 'call_logged', outcome });
851
- if (outcome !== 'contacted') return review;
873
+ // Note facts are confirmed only while the case is documented, so none are proposed while it is with the doctor.
874
+ if (outcome !== 'contacted' || review.status === 'awaiting_doctor') return review;
852
875
  return proposeNoteFacts(review, operator, requestId);
853
876
  }
854
877
 
@@ -1681,7 +1704,7 @@ async function soleApprover() {
1681
1704
  }
1682
1705
 
1683
1706
  // With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
1684
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
1707
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
1685
1708
  const reviewId = reviewIdOf(id);
1686
1709
  const operator = requiredText(sentBy, 'sentBy');
1687
1710
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -1724,7 +1747,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note =
1724
1747
  reviewId,
1725
1748
  [review.status],
1726
1749
  { $set: { status: 'handing_off', operationClaim: claim } },
1727
- { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
1750
+ // A caller that read the case earlier passes how many handoffs it saw, so one made since is not repeated.
1751
+ { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt, ...(handoffs != null && { doctorHandoffs: { $size: handoffs } }) },
1728
1752
  );
1729
1753
  let delivery = {};
1730
1754
  let updated;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.30",
3
+ "version": "6.1.0-dev.18137",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",