@peopl-health/nexus 6.4.24 → 6.4.25

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.
@@ -33,9 +33,9 @@ const BRIDGE_WAIT_MS = 2 * 60 * 1000;
33
33
  // A delivered ask, one the provider accepted without confirming delivery, or one an earlier turn already answered.
34
34
  const ASKED_OUTCOMES = ['sent', 'unknown', 'already_answered'];
35
35
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
36
+ const ASK_SPACING_MS = 20 * 60 * 1000;
36
37
  const getMessaging = () => require('../core/NexusMessaging');
37
38
  const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
38
- 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}». ${ASK_RULES}`;
39
39
  const graveAskText = (flags) => `La revisión de esta escalación necesita saber si la paciente tiene: ${flags.join('; ')}. Pregúntale, en un solo mensaje breve y con palabras sencillas, por lo que ella pueda notar o medir, sin nombrar diagnósticos. ${ASK_RULES}`;
40
40
 
41
41
  // A note too long for the template ends on a whole word with «…», so the cut shows.
@@ -45,6 +45,9 @@ const noteOf = (text) => {
45
45
  };
46
46
  const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
47
47
  const timeOf = (value) => new Date(value).getTime();
48
+ const episodeAsks = (review, clock) => (review.blockingAsks ?? []).filter((ask) => timeOf(ask.draftAt) >= clock.since.getTime()
49
+ && (ASKED_OUTCOMES.includes(ask.outcome) || (!ask.skippedReason && ask.outcome == null)));
50
+ const lastAskAt = (review, clock) => Math.max(0, ...episodeAsks(review, clock).map((ask) => timeOf(ask.sentAt)));
48
51
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
49
52
  // When the team's alert for this grave datum first fell due, which a failed send's retry does not move; one not recorded yet has not.
50
53
  const graveDueAt = (review, clock, flag) => {
@@ -336,7 +339,7 @@ async function remindQuietPatient(review, clock, now) {
336
339
  const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
337
340
  if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
338
341
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
339
- if (now.getTime() < dueAt.getTime()) return;
342
+ if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
340
343
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
341
344
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
342
345
 
@@ -375,23 +378,23 @@ async function remindQuietPatient(review, clock, now) {
375
378
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
376
379
  }
377
380
 
378
- // Once per draft the bot asks its blocking question or the pending grave data, unless a question is open; after a patient message, once the bot replied.
381
+ // Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
379
382
  async function askBlockingQuestion(review, clock, now) {
380
383
  // With the doctor, only a case the bot handed over is still asked, and only its grave data.
381
384
  const withDoctor = review.status === 'awaiting_doctor';
382
385
  if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
383
386
  const latest = (review.drafts ?? []).at(-1);
384
387
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
385
- const blocking = withDoctor ? null : latest.blockingQuestion;
386
- // With the doctor, a datum already asked or already sent to the team is not asked again on every redraft.
387
- const settled = withDoctor ? new Set([
388
- ...(review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag),
389
- ...(review.blockingAsks ?? []).filter((entry) => ASKED_OUTCOMES.includes(entry.outcome) && timeOf(entry.draftAt) >= clock.since.getTime()).flatMap((entry) => entry.flags ?? []),
390
- ].map(normalizedKeyOf)) : new Set();
391
- const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
388
+ // A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
389
+ const settled = new Set([
390
+ ...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
391
+ ...episodeAsks(review, clock).flatMap((entry) => entry.flags ?? []),
392
+ ].map(normalizedKeyOf));
393
+ const graveFlags = latest.urgentPresentRedFlags?.length ? []
392
394
  : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
393
- const question = blocking || graveFlags.join('; ') || null;
394
- const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
395
+ const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
396
+ const question = graveFlags.join('; ') || blocking || null;
397
+ const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
395
398
  if (!question) return;
396
399
  const asks = review.blockingAsks ?? [];
397
400
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
@@ -401,6 +404,8 @@ async function askBlockingQuestion(review, clock, now) {
401
404
 
402
405
  let skippedReason = await takenOf(review, clock);
403
406
  if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
407
+ // Patients answered a separate message about a datum that is not grave with «No» or not at all, so it goes only in the doctor's note.
408
+ if (!skippedReason && blocking) skippedReason = 'not_grave';
404
409
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
405
410
  const claimed = await getEscalationReview().updateOne(
406
411
  { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
@@ -415,8 +420,7 @@ async function askBlockingQuestion(review, clock, now) {
415
420
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
416
421
  return takenOf(fresh, clock);
417
422
  };
418
- const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
419
- getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
423
+ getMessaging().processInstruction(review.patientCode, graveAskText(graveFlags), 'developer', { triggeredBy: OPERATOR, beforeRun })
420
424
  .then((result) => result?.outcome ?? null, (error) => {
421
425
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
422
426
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.24",
3
+ "version": "6.4.25",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",