@peopl-health/nexus 6.0.29 → 6.0.31

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.
@@ -425,6 +425,17 @@ async function recordReminder({ code, trace, actionType, reminderId, reminderDat
425
425
  });
426
426
  }
427
427
 
428
+ async function isReminderPending({ code, reminderId }) {
429
+ const rows = await airtableService.getRecordByFilter(
430
+ Monitoreo_ID,
431
+ 'reminder',
432
+ `AND(${fieldEquals('whatsapp_id', code)}, ${fieldEquals('schedule_id', reminderId)}, ${PENDING_ROW_FILTER})`,
433
+ null,
434
+ ['schedule_id'],
435
+ );
436
+ return rows.length > 0;
437
+ }
438
+
428
439
  async function hasPendingContingencyRow({ planId }) {
429
440
  const rows = await airtableService.getRecordByFilter(
430
441
  Monitoreo_ID,
@@ -759,6 +770,7 @@ module.exports = {
759
770
  recordClinicalIntake,
760
771
  recordReminder,
761
772
  hasPendingContingencyRow,
773
+ isReminderPending,
762
774
  hasPendingReminderForPatient,
763
775
  readPendingFollowUpsForPatient,
764
776
  readPendingReminderForPatient,
@@ -19,6 +19,7 @@ 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']);
22
23
  const CLAIM_TTL_MS = 60 * 60 * 1000;
23
24
  const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
24
25
  const RETRY_SETTLE_MS = 5 * 60 * 1000;
@@ -222,7 +223,7 @@ async function sweepInterruptedTriages({
222
223
  } = {}) {
223
224
  const result = { found: 0, retried: 0, skipped: 0 };
224
225
  if (!retryLive()) return result;
225
- const active = await leases.listActive();
226
+ const active = await leases.listActive({ interrupted: true, source: programSource() });
226
227
  if (!active) return result;
227
228
 
228
229
  const due = active.filter(({ value }) => value.source === programSource()
@@ -246,7 +247,7 @@ async function sweepInterruptedTriages({
246
247
  await retrigger(run);
247
248
  result.retried += 1;
248
249
  } catch (error) {
249
- await claims.release(`${triageRecordId}:${value.startedAt}`);
250
+ if (TRANSIENT_DISPATCH_FAILURES.has(error.message)) await claims.release(`${triageRecordId}:${value.startedAt}`);
250
251
  logger.error('[recommendationRecovery] retry of an interrupted run could not be dispatched', { ...run, error: error.message });
251
252
  }
252
253
  }
@@ -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
- inflight.leaseWritten
156
+ Promise.resolve()
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,6 +181,7 @@ 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;
184
185
  await inflight.interrupted;
185
186
  await inflightLeases.release(payload.triageRecordId);
186
187
  });
@@ -108,11 +108,12 @@ class WriteClaimStore {
108
108
  }
109
109
  }
110
110
 
111
- async listActive() {
111
+ async listActive(valueMatch = {}) {
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;
113
115
  try {
114
- const claims = await WriteClaim.find({ key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } })
115
- .limit(100).lean();
116
+ const claims = await WriteClaim.find(query).sort({ createdAt: -1 }).limit(100).lean();
116
117
  return claims.map((claim) => ({ key: claim.key.slice(this.namespace.length + 1), value: claim.value }));
117
118
  } catch (error) {
118
119
  logger.warn('[writeClaimStore] Claims could not be listed', { namespace: this.namespace, error: error.message });
@@ -2,7 +2,7 @@ const moment = require('moment-timezone');
2
2
 
3
3
  const { isShadowRun } = require('../helpers/shadowHelper');
4
4
  const { dispatchReminder } = require('../services/reminderDispatchService');
5
- const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp, cancelPendingFollowUps } = require('../services/clinicalAirtableService');
5
+ const { recordReminder, readPendingFollowUpsForPatient, cancelFollowUp, cancelPendingFollowUps, isReminderPending } = require('../services/clinicalAirtableService');
6
6
  const { isWithinTriageProtectionWindow } = require('../services/outreachSweepService');
7
7
  const { UTILITY_BASES, sanitizeVariable } = require('../services/outreachCarrierService');
8
8
  const { logger } = require('../../utils/logger');
@@ -149,6 +149,9 @@ async function handler(args = {}, context = {}) {
149
149
  return JSON.stringify({ success: false, error: 'checkins_paused — the patient asked for fewer messages; do not schedule a seguimiento before the pause ends.', data: { paused_until: moment(pausedUntil).tz(timeZone).format('YYYY-MM-DDTHH:mm') } });
150
150
  }
151
151
  }
152
+ if (actionType === 'update' && targetId && runtime.patientCode && !await isReminderPending({ code: runtime.patientCode, reminderId: targetId })) {
153
+ return JSON.stringify({ success: false, error: 'reminder_not_active — that reminder already went out or was stood down, so it cannot be updated. If a check is still needed, create a new one.', data: { reminder_id: targetId } });
154
+ }
152
155
  if (isRoutineOutreach && actionType === 'create' && runtime.patientCode) {
153
156
  if (await botIsPaused(runtime.patientCode, { label: '[schedulePatientReminder]' })) {
154
157
  return JSON.stringify({ success: false, error: PAUSED_ERROR, data: {} });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.29",
3
+ "version": "6.0.31",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",