@peopl-health/nexus 5.65.0-dev.11560 → 5.66.0

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.
@@ -103,32 +103,43 @@ async function evaluatePatientSupport({
103
103
  return { outcome: isPartial ? 'partial' : 'evaluated', changes };
104
104
  }
105
105
 
106
- async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
106
+ async function patientsToEvaluate({
107
+ now, cadenceHours, activeWithinHours, limit, scope, SweepModel,
108
+ }) {
107
109
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
110
+ const activeSince = new Date(now.getTime() - activeWithinHours * HOUR_MS);
108
111
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
109
112
  const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
110
113
  const selected = [];
111
114
  for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
112
115
  const active = await aggregateMessages([
113
- { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
116
+ { $match: { from_me: false, createdAt: { $gte: activeSince }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
114
117
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
115
118
  { $sort: { lastInboundAt: -1, _id: 1 } },
116
119
  { $skip: page * CANDIDATE_PAGE },
117
120
  { $limit: CANDIDATE_PAGE },
118
121
  ]);
119
- const ids = (active || []).map((row) => row._id);
120
- if (!ids.length) break;
121
- const recent = await SweepModel.find({
122
- patientId: { $in: ids },
123
- $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }, { claimedUntil: { $gt: now } }],
124
- }).select('patientId').lean();
125
- const done = new Set(recent.map((row) => row.patientId));
126
- selected.push(...ids.filter((id) => !done.has(id)));
127
- if (ids.length < CANDIDATE_PAGE) break;
122
+ if (!active?.length) break;
123
+ const states = await SweepModel.find({ patientId: { $in: active.map((row) => row._id) } })
124
+ .select('patientId lastEvaluatedAt lastAttemptAt claimedUntil').lean();
125
+ const stateOf = new Map(states.map((state) => [state.patientId, state]));
126
+ selected.push(...active
127
+ .filter((row) => !isSettled(stateOf.get(row._id), { lastInboundAt: row.lastInboundAt, since, retrySince, now }))
128
+ .map((row) => ({ patientId: row._id, lastInboundAt: row.lastInboundAt })));
129
+ if (active.length < CANDIDATE_PAGE) break;
128
130
  }
129
131
  return selected.slice(0, limit);
130
132
  }
131
133
 
134
+ // Settled: evaluated within the cadence, or nothing new since the last evaluation, or tried recently, or claimed.
135
+ function isSettled(state, { lastInboundAt, since, retrySince, now }) {
136
+ if (!state) return false;
137
+ const evaluatedAt = state.lastEvaluatedAt ? new Date(state.lastEvaluatedAt) : null;
138
+ return Boolean((evaluatedAt && (evaluatedAt >= since || evaluatedAt >= new Date(lastInboundAt)))
139
+ || (state.lastAttemptAt && new Date(state.lastAttemptAt) >= retrySince)
140
+ || (state.claimedUntil && new Date(state.claimedUntil) > now));
141
+ }
142
+
132
143
  function validPatientIds(ids) {
133
144
  return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
134
145
  }
@@ -140,11 +151,12 @@ function sweepState(outcome, now) {
140
151
  };
141
152
  }
142
153
 
143
- function stillDue({ now, cadenceHours }) {
154
+ function stillDue({ now, cadenceHours, lastInboundAt }) {
144
155
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
145
156
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
157
+ const notEvaluatedSince = new Date(Math.min(since.getTime(), new Date(lastInboundAt).getTime()));
146
158
  return [
147
- { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: since } }] },
159
+ { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: notEvaluatedSince } }] },
148
160
  { $or: [{ lastAttemptAt: null }, { lastAttemptAt: { $lt: retrySince } }] },
149
161
  ];
150
162
  }
@@ -175,7 +187,8 @@ async function settleClaim(SweepModel, patientId, claimToken, update) {
175
187
  }
176
188
 
177
189
  async function runSupportLightSweep({
178
- now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
190
+ now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, activeWithinHours = cadenceHours,
191
+ windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
179
192
  } = {}, {
180
193
  SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, getConfig = getSupportLightEvaluator,
181
194
  clock = () => new Date(), ...deps
@@ -184,12 +197,14 @@ async function runSupportLightSweep({
184
197
  if (!config?.presetId) return { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [], outcome: 'not_configured' };
185
198
  const isBackfill = Array.isArray(patientIds);
186
199
  const candidates = isBackfill
187
- ? validPatientIds(patientIds).slice(0, limit)
188
- : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
200
+ ? validPatientIds(patientIds).slice(0, limit).map((patientId) => ({ patientId, lastInboundAt: null }))
201
+ : await patientsToEvaluate({
202
+ now, cadenceHours, activeWithinHours: Math.max(activeWithinHours, cadenceHours), limit, scope: scope && validPatientIds(scope), SweepModel,
203
+ });
189
204
  const evaluationDeps = { ...deps, getConfig: async () => config };
190
205
  const summary = { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [] };
191
- for (const patientId of candidates) {
192
- const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours }));
206
+ for (const { patientId, lastInboundAt } of candidates) {
207
+ const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours, lastInboundAt }));
193
208
  if (!claimToken) {
194
209
  summary.busy += 1;
195
210
  continue;
package/lib/index.d.ts CHANGED
@@ -1061,6 +1061,7 @@ declare module '@peopl-health/nexus' {
1061
1061
  patientIds?: string[] | null;
1062
1062
  scope?: string[] | null;
1063
1063
  cadenceHours?: number;
1064
+ activeWithinHours?: number;
1064
1065
  windowDays?: number;
1065
1066
  limit?: number;
1066
1067
  }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.65.0-dev.11560",
3
+ "version": "5.66.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",