@peopl-health/nexus 5.76.8 → 5.77.0-dev.16338

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.
@@ -26,6 +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
30
 
30
31
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
31
32
  const { getMessages, updateMessage } = require('../services/messageService');
@@ -243,6 +244,7 @@ class NexusMessaging {
243
244
  }
244
245
 
245
246
  if (messageData.code) ensureThreadExists(messageData.code);
247
+ if (result?.success === true) observeSend(messageData);
246
248
 
247
249
  return result;
248
250
  }
package/lib/index.d.ts CHANGED
@@ -942,6 +942,13 @@ declare module '@peopl-health/nexus' {
942
942
  provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
943
943
  ): void;
944
944
 
945
+ export type ContactCategory = 'clinical' | 'triage' | 'sessions' | 'followup' | 'invitations' | 'unclassified';
946
+
947
+ export function registerContactCategories(categories: {
948
+ contentSids?: Record<string, ContactCategory>;
949
+ triggeredBy?: Record<string, ContactCategory>;
950
+ }): void;
951
+
945
952
  export const supportCandidateService: {
946
953
  updateSupportOperationalReview(request: {
947
954
  patientId: string;
package/lib/index.js CHANGED
@@ -54,6 +54,7 @@ const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./serv
54
54
  const { MapCache } = require('./utils/MapCache');
55
55
  const supportCandidateService = require('./clinical/services/supportCandidateService');
56
56
  const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
57
+ const { registerContactCategories } = require('./services/contactGateService');
57
58
  const supportActionService = require('./clinical/services/supportActionService');
58
59
  const supportLightService = require('./clinical/services/supportLightService');
59
60
  const supportInvitability = require('./clinical/services/supportInvitability');
@@ -395,6 +396,7 @@ module.exports = {
395
396
  MapCache,
396
397
  supportCandidateService,
397
398
  registerDashboardProvider,
399
+ registerContactCategories,
398
400
  supportActionService,
399
401
  supportLightService,
400
402
  supportInvitability,
@@ -0,0 +1,26 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const CONTACT_GATE_TTL_SECONDS = 90 * 24 * 60 * 60;
4
+
5
+ const contactGateDecisionSchema = new mongoose.Schema({
6
+ code: { type: String, required: true },
7
+ contactCode: { type: String, default: null },
8
+ kind: { type: String, enum: ['operator', 'reply', 'proactive'], required: true },
9
+ category: { type: String, default: null },
10
+ mode: { type: String, enum: ['shadow'], required: true },
11
+ wouldAllow: { type: Boolean, required: true },
12
+ reason: { type: String, default: null },
13
+ dayCount: { type: Number, default: 0 },
14
+ weekCount: { type: Number, default: 0 },
15
+ sendKind: { type: String, default: null },
16
+ triggeredBy: { type: String, default: null },
17
+ contentSid: { type: String, default: null },
18
+ createdAt: { type: Date, default: Date.now }
19
+ });
20
+
21
+ contactGateDecisionSchema.index({ code: 1, kind: 1, createdAt: -1 }, { name: 'contact_gate_code_kind_idx' });
22
+ contactGateDecisionSchema.index({ createdAt: 1 }, { name: 'contact_gate_ttl_idx', expireAfterSeconds: CONTACT_GATE_TTL_SECONDS });
23
+
24
+ const ContactGateDecision = mongoose.model('ContactGateDecision', contactGateDecisionSchema);
25
+
26
+ module.exports = { ContactGateDecision, CONTACT_GATE_TTL_SECONDS };
@@ -0,0 +1,115 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { logger } = require('../utils/logger');
5
+
6
+ const { ContactGateDecision } = require('../models/contactGateDecisionModel');
7
+ const { isStaffSend } = require('../helpers/staffSendHelper');
8
+ const { getMessages } = require('./messageService');
9
+
10
+ const CATEGORIES = ['clinical', 'triage', 'sessions', 'followup', 'invitations', 'unclassified'];
11
+ const EXEMPT_CATEGORIES = ['clinical'];
12
+ const DAILY_CAP = 2;
13
+ const WEEKLY_CAP = 6;
14
+ const CONTACT_TIMEZONE = 'America/Mexico_City';
15
+ const CONTACT_HOURS = { start: 9, end: 21 };
16
+ const REPLY_WINDOW_MS = 30 * 60 * 1000;
17
+ const NEXUS_TRIGGER_CATEGORIES = {
18
+ paused_safety_net: 'clinical',
19
+ seguimiento: 'followup',
20
+ followup: 'followup',
21
+ send_reminder: 'followup'
22
+ };
23
+
24
+ const registered = { contentSids: {}, triggeredBy: {} };
25
+
26
+ function registerContactCategories({ contentSids = {}, triggeredBy = {} } = {}) {
27
+ const unknown = [...Object.values(contentSids), ...Object.values(triggeredBy)].find(value => !CATEGORIES.includes(value));
28
+ if (unknown !== undefined) throw new Error(`Unknown contact category: ${unknown}`);
29
+ Object.assign(registered.contentSids, contentSids);
30
+ Object.assign(registered.triggeredBy, triggeredBy);
31
+ }
32
+
33
+ function contactGateMode() {
34
+ return runtimeConfig.get('CONTACT_GATE_MODE') === 'shadow' ? 'shadow' : 'off';
35
+ }
36
+
37
+ function triggerSource(triggeredBy) {
38
+ const trigger = String(triggeredBy || '');
39
+ return trigger.startsWith('followup_') ? 'followup' : trigger.split(':')[0];
40
+ }
41
+
42
+ function categoryOf({ contentSid, triggeredBy }) {
43
+ const source = triggerSource(triggeredBy);
44
+ return registered.contentSids[contentSid] || registered.triggeredBy[source] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
45
+ }
46
+
47
+ // A released or recovery send carries no trigger of its own; it inherits the one of the message it delivers.
48
+ async function triggerOf({ triggeredBy, parentMessageId }) {
49
+ if (triggeredBy || !parentMessageId) return triggeredBy || null;
50
+ const [parent] = await getMessages({ _id: parentMessageId }, { select: 'triggeredBy', limit: 1 });
51
+ return parent?.triggeredBy || null;
52
+ }
53
+
54
+ async function classify(messageData, now) {
55
+ if (isStaffSend(messageData.triggeredBy)) return { kind: 'operator', category: null };
56
+ const [inbound] = await getMessages(
57
+ {
58
+ numero: messageData.code,
59
+ contact_code: messageData.contactCode || null,
60
+ from_me: false,
61
+ createdAt: { $gte: new Date(now.getTime() - REPLY_WINDOW_MS) }
62
+ },
63
+ { select: '_id', limit: 1 }
64
+ );
65
+ return { kind: inbound ? 'reply' : 'proactive', category: categoryOf(messageData) };
66
+ }
67
+
68
+ const isCounted = ({ kind, category }) => kind === 'proactive' && !EXEMPT_CATEGORIES.includes(category);
69
+
70
+ async function priorCounts(code, now) {
71
+ const local = moment(now).tz(CONTACT_TIMEZONE);
72
+ const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES } };
73
+ const [dayCount, weekCount] = await Promise.all([
74
+ ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('day').toDate() } }),
75
+ ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('isoWeek').toDate() } })
76
+ ]);
77
+ return { dayCount, weekCount };
78
+ }
79
+
80
+ function verdict(classified, { dayCount, weekCount }, now) {
81
+ if (!isCounted(classified)) return { wouldAllow: true, reason: null };
82
+ const hour = moment(now).tz(CONTACT_TIMEZONE).hour();
83
+ if (hour < CONTACT_HOURS.start || hour >= CONTACT_HOURS.end) return { wouldAllow: false, reason: 'outside_hours' };
84
+ if (dayCount >= DAILY_CAP) return { wouldAllow: false, reason: 'daily_cap' };
85
+ if (weekCount >= WEEKLY_CAP) return { wouldAllow: false, reason: 'weekly_cap' };
86
+ return { wouldAllow: true, reason: null };
87
+ }
88
+
89
+ // Shadow mode only records what the gate would have decided about a send that already went out; it never blocks one.
90
+ async function observeSend(messageData, now = new Date()) {
91
+ const code = messageData?.code;
92
+ try {
93
+ if (contactGateMode() !== 'shadow' || !code) return null;
94
+ const triggeredBy = await triggerOf(messageData);
95
+ const classified = await classify({ ...messageData, triggeredBy }, now);
96
+ 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
+ });
109
+ } catch (error) {
110
+ logger.warn('[contactGate] Shadow decision was not recorded', { code, error: error.message });
111
+ return null;
112
+ }
113
+ }
114
+
115
+ module.exports = { registerContactCategories, observeSend };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.76.8",
3
+ "version": "5.77.0-dev.16338",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",