@peopl-health/nexus 5.77.0-dev.16340 → 5.77.0-dev.16342

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.
@@ -125,6 +125,7 @@ const sendMessageController = async (req, res) => {
125
125
  success: result?.success ?? true,
126
126
  messageId: _pickMessageId(result, null),
127
127
  status: result?.status || null,
128
+ ...(result?.reason && { reason: result.reason }),
128
129
  ...(result?.preemptive && {
129
130
  preemptive: true,
130
131
  note: 'Recipient outside 24h window; template approval in progress, delivery not guaranteed within the next 15 min'
@@ -26,7 +26,7 @@ const { isStaffSend } = require('../helpers/staffSendHelper');
26
26
 
27
27
  const { createMessagingProvider } = require('../adapters/registry');
28
28
  const { ensureThreadExists } = require('../services/threadService');
29
- const { observeSend } = require('../services/contactGateService');
29
+ const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
30
30
 
31
31
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
32
32
  const { getMessages, updateMessage } = require('../services/messageService');
@@ -390,8 +390,16 @@ class NexusMessaging {
390
390
  return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
391
391
  }
392
392
 
393
+ let gate = null;
393
394
  try {
394
- const result = await this._sendMessage(messageData);
395
+ gate = await reserveSend(messageData);
396
+ if (gate?.blocked) {
397
+ await releaseSendClaim(claim.claimId);
398
+ return { success: false, messageId: null, status: 'contact_capped', reason: gate.reason, category: gate.category, delivered: false, deferred: false };
399
+ }
400
+ const result = await this._sendMessage(gate ? { ...messageData, contactGateDecisionId: gate.decisionId } : messageData);
401
+ // A deferred send is recorded when it actually leaves, so its reservation must not also count.
402
+ if (result?.success !== true || result?.deferred === true) await releaseSend(gate?.decisionId);
395
403
  if (result?.success === true && result?.deferred !== true && !await completeSendClaim(claim.claimId)) {
396
404
  logger.error('[NexusMessaging] send claim completion failed; a retry after the claim expires may send again', {
397
405
  code: messageData.code,
@@ -400,6 +408,7 @@ class NexusMessaging {
400
408
  }
401
409
  return result;
402
410
  } catch (error) {
411
+ await releaseSend(gate?.decisionId);
403
412
  await releaseSendClaim(claim.claimId);
404
413
  throw error;
405
414
  }
package/lib/index.d.ts CHANGED
@@ -944,6 +944,17 @@ declare module '@peopl-health/nexus' {
944
944
 
945
945
  export type ContactCategory = 'clinical' | 'triage' | 'sessions' | 'followup' | 'invitations' | 'unclassified';
946
946
 
947
+ /** What sendMessage returns when the contact gate holds a send back; it never reached the provider. */
948
+ export interface ContactCappedSendResult {
949
+ success: false;
950
+ messageId: null;
951
+ status: 'contact_capped';
952
+ reason: 'outside_hours' | 'daily_cap' | 'weekly_cap';
953
+ category: ContactCategory;
954
+ delivered: false;
955
+ deferred: false;
956
+ }
957
+
947
958
  export function registerContactCategories(categories: {
948
959
  contentSids?: Record<string, ContactCategory>;
949
960
  triggeredBy?: Record<string, ContactCategory>;
@@ -144,6 +144,15 @@ class ScheduledMessageJob extends BaseJob {
144
144
  return { success: false, reason: result.status };
145
145
  }
146
146
 
147
+ if (result?.status === 'contact_capped') {
148
+ await ScheduledMessage.updateOne(
149
+ { _id: scheduledMessageId },
150
+ { $set: { status: 'cancelled', errorCode: result.status, errorMessage: `Contact limit reached: ${result.reason}` } }
151
+ );
152
+ logger.info('[ScheduledMessageJob] Not sent, the patient reached her contact limit', { scheduledMessageId, reason: result.reason });
153
+ return { success: false, reason: result.status };
154
+ }
155
+
147
156
  const messageId = result?.messageId || result?.sid || null;
148
157
 
149
158
  await ScheduledMessage.updateOne(
@@ -7,7 +7,8 @@ const contactGateDecisionSchema = new mongoose.Schema({
7
7
  contactCode: { type: String, default: null },
8
8
  kind: { type: String, enum: ['operator', 'reply', 'proactive'], required: true },
9
9
  category: { type: String, default: null },
10
- mode: { type: String, enum: ['shadow'], required: true },
10
+ mode: { type: String, enum: ['shadow', 'enforce'], required: true },
11
+ status: { type: String, enum: ['reserved', 'sent', 'blocked', 'failed', null], default: null },
11
12
  wouldAllow: { type: Boolean, required: true },
12
13
  reason: { type: String, default: null },
13
14
  dayCount: { type: Number, default: 0 },
@@ -8,12 +8,15 @@ const { isStaffSend } = require('../helpers/staffSendHelper');
8
8
  const { getMessages } = require('./messageService');
9
9
 
10
10
  const CATEGORIES = ['clinical', 'triage', 'sessions', 'followup', 'invitations', 'unclassified'];
11
- const EXEMPT_CATEGORIES = ['clinical'];
11
+ const EXEMPT_CATEGORIES = ['clinical', 'triage', 'sessions'];
12
12
  const DAILY_CAP = 2;
13
13
  const WEEKLY_CAP = 6;
14
14
  const CONTACT_TIMEZONE = 'America/Mexico_City';
15
15
  const CONTACT_HOURS = { start: 8, end: 21 };
16
16
  const REPLY_WINDOW_MS = 30 * 60 * 1000;
17
+ const MODES = ['shadow', 'enforce'];
18
+ const NOT_COUNTED_STATUSES = ['blocked', 'failed'];
19
+ const CHECK_TIMEOUT_MS = 2000;
17
20
  const NEXUS_TRIGGER_CATEGORIES = {
18
21
  paused_safety_net: 'clinical',
19
22
  seguimiento: 'followup',
@@ -31,7 +34,14 @@ function registerContactCategories({ contentSids = {}, triggeredBy = {} } = {})
31
34
  }
32
35
 
33
36
  function contactGateMode() {
34
- return runtimeConfig.get('CONTACT_GATE_MODE') === 'shadow' ? 'shadow' : 'off';
37
+ const mode = runtimeConfig.get('CONTACT_GATE_MODE');
38
+ return MODES.includes(mode) ? mode : 'off';
39
+ }
40
+
41
+ // Only an explicit list blocks; an exempt category in it is still never counted, so never blocked.
42
+ function enforcedCategories() {
43
+ if (contactGateMode() !== 'enforce') return [];
44
+ return String(runtimeConfig.get('CONTACT_GATE_ENFORCE') || '').split(',').map(value => value.trim()).filter(Boolean);
35
45
  }
36
46
 
37
47
  function triggerSource(triggeredBy) {
@@ -41,7 +51,7 @@ function triggerSource(triggeredBy) {
41
51
 
42
52
  function categoryOf({ contentSid, triggeredBy }) {
43
53
  const source = triggerSource(triggeredBy);
44
- return registered.contentSids[contentSid] || registered.triggeredBy[source] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
54
+ return registered.triggeredBy[source] || registered.contentSids[contentSid] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
45
55
  }
46
56
 
47
57
  // A released or recovery send carries no trigger of its own; it inherits the one of the message it delivers.
@@ -67,9 +77,10 @@ async function classify(messageData, now) {
67
77
 
68
78
  const isCounted = ({ kind, category }) => kind === 'proactive' && !EXEMPT_CATEGORIES.includes(category);
69
79
 
70
- async function priorCounts(code, now) {
80
+ async function priorCounts(code, now, ownId = null) {
71
81
  const local = moment(now).tz(CONTACT_TIMEZONE);
72
- const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES } };
82
+ const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES }, status: { $nin: NOT_COUNTED_STATUSES } };
83
+ if (ownId) counted._id = { $ne: ownId };
73
84
  const [dayCount, weekCount] = await Promise.all([
74
85
  ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('day').toDate() } }),
75
86
  ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('isoWeek').toDate() } })
@@ -86,30 +97,92 @@ function verdict(classified, { dayCount, weekCount }, now) {
86
97
  return { wouldAllow: true, reason: null };
87
98
  }
88
99
 
89
- // Shadow mode only records what the gate would have decided about a send that already went out; it never blocks one.
100
+ function decisionRow(messageData, classified, triggeredBy, now) {
101
+ return {
102
+ code: messageData.code,
103
+ ...classified,
104
+ mode: contactGateMode(),
105
+ contactCode: messageData.contactCode || null,
106
+ sendKind: messageData.kind || null,
107
+ triggeredBy,
108
+ contentSid: messageData.contentSid || null,
109
+ createdAt: now
110
+ };
111
+ }
112
+
113
+ function withTimeout(promise) {
114
+ let timer;
115
+ const timeout = new Promise((resolve, reject) => {
116
+ timer = setTimeout(() => reject(new Error('contact gate check timed out')), CHECK_TIMEOUT_MS);
117
+ if (typeof timer.unref === 'function') timer.unref();
118
+ });
119
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
120
+ }
121
+
122
+ // The reservation is written before counting, so of two concurrent sends at the last slot at most one goes out.
123
+ async function reserve(messageData, enforced, now) {
124
+ const triggeredBy = await triggerOf(messageData);
125
+ const classified = await classify({ ...messageData, triggeredBy }, now);
126
+ if (!isCounted(classified) || !enforced.includes(classified.category)) return null;
127
+ const row = await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), wouldAllow: true, status: 'reserved' });
128
+ let decided;
129
+ try {
130
+ const counts = await priorCounts(messageData.code, now, row._id);
131
+ decided = verdict(classified, counts, now);
132
+ await ContactGateDecision.updateOne({ _id: row._id }, { $set: { ...decided, ...counts, status: decided.wouldAllow ? 'reserved' : 'blocked' } });
133
+ } catch (error) {
134
+ await releaseSend(row._id);
135
+ throw error;
136
+ }
137
+ return decided.wouldAllow
138
+ ? { decisionId: row._id }
139
+ : { blocked: true, decisionId: row._id, reason: decided.reason, category: classified.category };
140
+ }
141
+
142
+ // Decides before the send whether an enforced category may go out; any failure lets the send through.
143
+ async function reserveSend(messageData, now = new Date()) {
144
+ const code = messageData?.code;
145
+ try {
146
+ const enforced = enforcedCategories();
147
+ if (!enforced.length || !code) return null;
148
+ const pending = reserve(messageData, enforced, now);
149
+ // A check that finishes after the send went out frees its slot; that send is recorded when it leaves.
150
+ return await withTimeout(pending).catch(error => {
151
+ pending.then(late => releaseSend(late?.decisionId), () => {});
152
+ throw error;
153
+ });
154
+ } catch (error) {
155
+ logger.warn('[contactGate] Send was not checked and goes out', { code, error: error.message });
156
+ return null;
157
+ }
158
+ }
159
+
160
+ // A reservation whose send never left frees its slot.
161
+ async function releaseSend(decisionId) {
162
+ if (!decisionId) return;
163
+ try {
164
+ await ContactGateDecision.updateOne({ _id: decisionId, status: 'reserved' }, { $set: { status: 'failed' } });
165
+ } catch (error) {
166
+ logger.warn('[contactGate] Reservation was not released', { decisionId: String(decisionId), error: error.message });
167
+ }
168
+ }
169
+
170
+ // Records every send that left; a send the gate reserved only confirms its row.
90
171
  async function observeSend(messageData, now = new Date()) {
91
172
  const code = messageData?.code;
92
173
  try {
93
- if (contactGateMode() !== 'shadow' || !code) return null;
174
+ if (contactGateMode() === 'off' || !code) return null;
175
+ if (messageData.contactGateDecisionId) {
176
+ return await ContactGateDecision.findOneAndUpdate({ _id: messageData.contactGateDecisionId }, { $set: { status: 'sent' } }, { new: true });
177
+ }
94
178
  const triggeredBy = await triggerOf(messageData);
95
179
  const classified = await classify({ ...messageData, triggeredBy }, now);
96
180
  const counts = isCounted(classified) ? await priorCounts(code, now) : { dayCount: 0, weekCount: 0 };
97
- return await ContactGateDecision.create({
98
- code,
99
- ...classified,
100
- mode: 'shadow',
101
- ...verdict(classified, counts, now),
102
- ...counts,
103
- contactCode: messageData.contactCode || null,
104
- sendKind: messageData.kind || null,
105
- triggeredBy,
106
- contentSid: messageData.contentSid || null,
107
- createdAt: now
108
- });
181
+ return await ContactGateDecision.create({ ...decisionRow(messageData, classified, triggeredBy, now), ...verdict(classified, counts, now), ...counts });
109
182
  } catch (error) {
110
- logger.warn('[contactGate] Shadow decision was not recorded', { code, error: error.message });
183
+ logger.warn('[contactGate] Send was not recorded', { code, error: error.message });
111
184
  return null;
112
185
  }
113
186
  }
114
187
 
115
- module.exports = { registerContactCategories, observeSend };
188
+ module.exports = { registerContactCategories, reserveSend, releaseSend, observeSend };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.77.0-dev.16340",
3
+ "version": "5.77.0-dev.16342",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",