@peopl-health/nexus 5.58.0-dev.10249 → 5.58.0-dev.10496

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.
@@ -195,7 +195,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
195
195
  return { response: finalResponse, toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
196
196
  }
197
197
 
198
- async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
198
+ async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
199
199
  let modelConfig = null;
200
200
  let resolvedInstructions = instructions;
201
201
  if (promptId || presetId) {
@@ -205,7 +205,7 @@ class OpenAIResponsesProvider extends BaseLLMProvider {
205
205
  }
206
206
 
207
207
  const apiConfig = {
208
- ...this._mapModelConfig(modelConfig || {}),
208
+ ...this._mapModelConfig({ ...(modelConfig || {}), ...(maxOutputTokens ? { max_output_tokens: maxOutputTokens } : {}) }),
209
209
  instructions: resolvedInstructions || '',
210
210
  };
211
211
  if (model) apiConfig.model = model;
@@ -1,9 +1,10 @@
1
1
  const { getEscalationDraft } = require('../config/subAgentsConfig');
2
2
 
3
- const { PROTOCOL_VERSION, SYMPTOM_RELIEF_PROTOCOL } = require('../protocols/symptomReliefProtocol');
3
+ const { FORMULARY_VERSION, TREATMENT_FORMULARY, validateProposal } = require('../protocols/treatmentFormulary');
4
4
 
5
5
  const { createLLMProvider } = require('../providers/createLLMProvider');
6
6
 
7
+ const { composeDoctorBody, withholdReason } = require('../helpers/doctorReviewMessageHelper');
7
8
  const { readStructuredText } = require('../helpers/structuredTextHelper');
8
9
 
9
10
  const { getEscalationContext } = require('../../services/escalationContextService');
@@ -18,7 +19,21 @@ const CALL_LOG_LIMIT = 10;
18
19
 
19
20
  const trimmed = (value) => String(value ?? '').trim();
20
21
 
21
- function buildDraftInput({ context, callLogs, protocol }) {
22
+ function settleProposal(parsed) {
23
+ const withheld = withholdReason(parsed);
24
+ const raw = parsed?.treatmentProposal;
25
+ const items = Array.isArray(raw?.items) ? raw.items : [];
26
+ if (withheld) return { proposal: null, withheldReason: withheld, strippedItems: items.length };
27
+ if (!items.length) return { proposal: null, withheldReason: trimmed(parsed?.proposalWithheldReason) || null, strippedItems: 0 };
28
+
29
+ const conditions = Array.isArray(raw.conditions) ? raw.conditions : [];
30
+ const ruledOut = Array.isArray(raw.ruledOut) ? raw.ruledOut : [];
31
+ const proposal = { symptom: raw.symptom, items, conditions, ruledOut };
32
+ const { valid, issues } = validateProposal(proposal, { conditions, ruledOut });
33
+ return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
34
+ }
35
+
36
+ function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
22
37
  const conversation = Array.isArray(context?.conversation)
23
38
  ? context.conversation.slice(-CONVERSATION_TURNS)
24
39
  : context?.conversation ?? null;
@@ -28,8 +43,9 @@ function buildDraftInput({ context, callLogs, protocol }) {
28
43
  : context?.triages ?? null;
29
44
 
30
45
  return {
31
- protocolVersion: PROTOCOL_VERSION,
46
+ protocolVersion: FORMULARY_VERSION,
32
47
  protocol,
48
+ alarms,
33
49
  patient: {
34
50
  clinicalContext: context?.agentContext ?? null,
35
51
  conversation,
@@ -55,7 +71,7 @@ function draftProvider() {
55
71
  }
56
72
  }
57
73
 
58
- async function generateEscalationDraft({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
74
+ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
59
75
  const { presetId } = await getEscalationDraft();
60
76
  const llm = provider ?? draftProvider();
61
77
 
@@ -64,7 +80,7 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
64
80
  }
65
81
 
66
82
  const context = await getEscalationContext({ code, now });
67
- const input = buildDraftInput({ context, callLogs, protocol: SYMPTOM_RELIEF_PROTOCOL });
83
+ const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
68
84
 
69
85
  // Past this point a generation run was issued. Whether the request actually left the process is
70
86
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -91,8 +107,19 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
91
107
  }
92
108
 
93
109
  const parsed = safeParse(readStructuredText(result), null);
94
- const doctorText = trimmed(parsed?.doctorText);
95
110
  const patientMessage = trimmed(parsed?.patientMessage);
111
+ if (!trimmed(parsed?.characterizationSummary)) {
112
+ logger.warn('[escalationDraft] generation did not return the sectioned doctor draft', { reviewId });
113
+ return { completed: false, attempted: true, reason: 'the model did not return the sectioned doctor draft (characterizationSummary missing)' };
114
+ }
115
+ const settled = settleProposal(parsed);
116
+
117
+ if (settled.invalid) {
118
+ logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues: settled.invalid });
119
+ return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${settled.invalid.join('; ')}` };
120
+ }
121
+
122
+ const doctorText = composeDoctorBody({ alarm: alarms[alarms.length - 1] ?? null, sections: parsed, proposal: settled.proposal, withheldReason: settled.withheldReason });
96
123
 
97
124
  if (!doctorText || !patientMessage) {
98
125
  logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
@@ -104,7 +131,10 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
104
131
  attempted: true,
105
132
  doctorText,
106
133
  patientMessage,
107
- protocolVersion: PROTOCOL_VERSION,
134
+ proposal: settled.proposal,
135
+ proposalWithheldReason: settled.withheldReason,
136
+ ...(settled.strippedItems ? { proposalStripped: settled.strippedItems } : {}),
137
+ protocolVersion: FORMULARY_VERSION,
108
138
  sectionsUnavailable: context.degradedSections ?? [],
109
139
  };
110
140
  }
@@ -70,6 +70,7 @@ const { prepareSupportAction } = require('./supportActionService');
70
70
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
71
71
  const GATE_MAX_ATTEMPTS = 2;
72
72
  const PLAN_MAX_ATTEMPTS = 2;
73
+ const PLAN_TRUNCATION_MAX_TOKENS = 16000;
73
74
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
75
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
75
76
  const DEFAULT_CLASSIFIER_WAIT_MS = [15000, 30000, 45000, 60000, 90000];
@@ -593,6 +594,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
593
594
  });
594
595
  settle.planLatencyMs = Date.now() - planStart;
595
596
  settle.attempts = planOutcome.attempts;
597
+ settle.planMaxOutputTokens = planOutcome.planMaxOutputTokens;
596
598
  if (planOutcome.safetyUncertain) settle.supportSafetyCleared = false;
597
599
  if (planOutcome.failure) return finish({ ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] });
598
600
  const { plan, planRepairs, qualityWarnings } = planOutcome;
@@ -850,7 +852,8 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
850
852
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
851
853
  let lastIssues = [];
852
854
  let safetyUncertain = false;
853
- const outcome = (result) => ({ ...result, safetyUncertain });
855
+ let maxOutputTokens = null;
856
+ const outcome = (result) => ({ ...result, safetyUncertain, planMaxOutputTokens: maxOutputTokens });
854
857
  const buildPlan = (takeaways, elements) => new RecommendationPlan({
855
858
  runId: rid,
856
859
  patientId: code,
@@ -883,6 +886,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
883
886
  presetId,
884
887
  input: [{ role: 'user', content }],
885
888
  metadata: { subAgent: 'triage-plan', runId: rid },
889
+ ...(maxOutputTokens ? { maxOutputTokens } : {}),
886
890
  }), { code, rid, stage: 'plan', attempt, budget });
887
891
  } catch {
888
892
  lastIssues = [];
@@ -893,6 +897,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
893
897
  lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
894
898
  firstEvidence = firstEvidence ?? rawEvidence(result);
895
899
  if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
900
+ if (hitTokenLimit(result)) maxOutputTokens = truncationBudget(result, maxOutputTokens);
896
901
  continue;
897
902
  }
898
903
  const parsed = safeParse(readStructuredText(result), null);
@@ -955,6 +960,17 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
955
960
  return outcome({ attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
956
961
  }
957
962
 
963
+ // Anthropic reports stop_reason; OpenAI Responses reports incomplete_details.reason.
964
+ function hitTokenLimit(result) {
965
+ return result?.stop_reason === 'max_tokens' || result?.incomplete_details?.reason === 'max_output_tokens';
966
+ }
967
+
968
+ function truncationBudget(result, current) {
969
+ const used = Number(result?.usage?.output_tokens);
970
+ const next = Number.isFinite(used) && used > 0 ? used * 2 : PLAN_TRUNCATION_MAX_TOKENS;
971
+ return Math.min(Math.max(next, current || 0), PLAN_TRUNCATION_MAX_TOKENS);
972
+ }
973
+
958
974
  function rawEvidence(result) {
959
975
  const text = str(readStructuredText(result)).trim();
960
976
  if (text) return text.slice(0, RAW_EXCERPT_MAX);
@@ -40,8 +40,10 @@ const getOfficeMessagesController = async (req, res) => {
40
40
 
41
41
  const sendOfficeMessageController = async (req, res) => {
42
42
  try {
43
- const { triggeredBy, text, clientMessageId } = req.body || {};
44
- const delivery = await sendOfficeMessage({ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId });
43
+ const { triggeredBy, text, clientMessageId, fileUrl, fileName } = req.body || {};
44
+ const delivery = await sendOfficeMessage({
45
+ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId, fileUrl, fileName,
46
+ });
45
47
  res.status(201).json({ success: true, ...delivery });
46
48
  } catch (error) {
47
49
  respondWithError(res, error, 'sending office message', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
@@ -46,11 +46,12 @@ function contentSignature(variables) {
46
46
  return crypto.createHash('sha1').update(source).digest('hex').slice(0, 12);
47
47
  }
48
48
 
49
- function buildSendClaimKey({ code, contentSid, variables, idempotencyKey } = {}) {
49
+ function buildSendClaimKey({ code, contactCode, contentSid, variables, idempotencyKey } = {}) {
50
50
  if (idempotencyKey) return `idem:${idempotencyKey}`;
51
51
  if (!code || !contentSid) return null;
52
52
  const signature = contentSignature(variables);
53
- return `tpl:${ensureWhatsAppFormat(code)}:${contentSid}${signature ? `:${signature}` : ''}`;
53
+ const recipient = contactCode ? `${ensureWhatsAppFormat(code)}>${ensureWhatsAppFormat(contactCode)}` : ensureWhatsAppFormat(code);
54
+ return `tpl:${recipient}:${contentSid}${signature ? `:${signature}` : ''}`;
54
55
  }
55
56
 
56
57
  async function isCompletedClaim(key) {
package/lib/index.d.ts CHANGED
@@ -188,6 +188,8 @@ declare module '@peopl-health/nexus' {
188
188
  media: any | null;
189
189
  type: 'message' | 'interactive' | 'media';
190
190
  raw?: { role?: string; replyRequested?: boolean };
191
+ contactCode?: string;
192
+ contactRole?: 'caregiver' | null;
191
193
  }
192
194
 
193
195
  export interface MessageStatusEventData {
@@ -312,7 +314,7 @@ declare module '@peopl-health/nexus' {
312
314
  getVariant(): string;
313
315
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
314
316
  runConversation(config?: any): Promise<any>;
315
- runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
317
+ runStructured(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
316
318
  }
317
319
 
318
320
  export interface LLMProvider {
@@ -320,7 +322,7 @@ declare module '@peopl-health/nexus' {
320
322
  getClient?(): any;
321
323
  executeRun(options: { thread: any; assistant: any; message?: string; tools?: any[]; config?: any }): Promise<any>;
322
324
  runConversation(config?: any): Promise<any>;
323
- runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any }): Promise<any>;
325
+ runStructured?(params?: { promptId?: string; presetId?: string; variables?: any; input?: any[]; text?: any; metadata?: any; maxOutputTokens?: number }): Promise<any>;
324
326
  transcribeAudio?(options?: any): Promise<any>;
325
327
  }
326
328
 
@@ -56,6 +56,7 @@ const doctorHandoffSchema = new mongoose.Schema({
56
56
  physicianEmail: { type: String, default: null },
57
57
  transport: { type: String, enum: [null, 'text', 'template'], default: null },
58
58
  messageId: { type: String, default: null },
59
+ message: { type: String, default: null },
59
60
  sentBy: { type: String, required: true },
60
61
  }, { timestamps: { createdAt: true, updatedAt: false } });
61
62
 
@@ -91,6 +92,12 @@ const interruptionResolutionSchema = new mongoose.Schema({
91
92
  notes: { type: String, required: true },
92
93
  }, { timestamps: { createdAt: true, updatedAt: false } });
93
94
 
95
+ const identityBlockSchema = new mongoose.Schema({
96
+ missing: { type: [String], default: [] },
97
+ blockedAt: { type: Date, required: true },
98
+ blockedBy: { type: String, required: true },
99
+ }, { _id: false });
100
+
94
101
  const escalationReviewSchema = new mongoose.Schema({
95
102
  patientCode: { type: String, required: true },
96
103
  patientCaseRecordId: { type: String, default: null },
@@ -126,6 +133,7 @@ const escalationReviewSchema = new mongoose.Schema({
126
133
  patientDelivery: { type: patientDeliverySchema, default: null },
127
134
  pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
128
135
  interruptionResolution: { type: interruptionResolutionSchema, default: null },
136
+ identityBlock: { type: identityBlockSchema, default: null },
129
137
  closedBy: { type: String, default: null },
130
138
  closedAt: { type: Date, default: null },
131
139
  cancellationReason: { type: String, default: null },
@@ -5,7 +5,6 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
5
  const { inlineOf } = require('../utils/coercionUtils');
6
6
  const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
- const { mexicoStamp } = require('../utils/dateUtils');
9
8
  const { isoDay } = require('../utils/dateUtils');
10
9
  const {
11
10
  CALL_OUTCOMES,
@@ -21,6 +20,8 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
21
20
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
22
21
  const { sendMessage } = require('../core/NexusMessaging');
23
22
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
23
+ const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
24
+ const { doctorIdentity, renderDoctorMessage, templateSummary } = require('../clinical/helpers/doctorReviewMessageHelper');
24
25
  const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
25
26
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
26
27
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
@@ -296,42 +297,53 @@ async function syncCase(review, operator, requestId) {
296
297
  }
297
298
  }
298
299
 
299
- const URGENCY_LABELS = {
300
- stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
301
- };
302
-
303
- function doctorHeader(review, patient) {
304
- const name = inlineOf(patient?.name);
305
- const phone = review.patientCode.replace(/^whatsapp:/, '');
306
- const treating = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
300
+ function doctorLink(review) {
301
+ return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
302
+ }
307
303
 
308
- const lines = [name ? `${name} · ${phone}` : phone];
309
- lines.push(`Médico tratante: ${treating || 'no registrado'}`);
304
+ async function readDoctorIdentity(review) {
305
+ let patient;
306
+ try {
307
+ patient = await getPatientInformation(review.patientCode);
308
+ } catch (error) {
309
+ logger.error('[EscalationReview] The patient record could not be read for the doctor message', {
310
+ escalationReviewId: String(review._id), error: redactedError(error),
311
+ });
312
+ throw httpError(503, 'The patient record could not be read; the doctor message needs the patient name and the treating doctor');
313
+ }
314
+ return doctorIdentity(patient);
315
+ }
310
316
 
311
- const alarm = review.alarms?.[review.alarms.length - 1];
312
- if (alarm) {
313
- const said = [
314
- alarm.symptom,
315
- alarm.suspectedCondition,
316
- URGENCY_LABELS[alarm.urgencyLevel] ?? alarm.urgencyLevel,
317
- mexicoStamp(alarm.raisedAt),
318
- ].map(inlineOf).filter(Boolean);
319
- if (said.length) lines.push(`Alarma: ${said.join(' · ')}`);
317
+ async function blockForMissingIdentity({ review, missing, operator }) {
318
+ const blocked = `El mensaje al médico no se envió: falta ${missing.join(' y ')} en el expediente`;
319
+ await getEscalationReview().updateOne(
320
+ { _id: review._id },
321
+ { $set: { identityBlock: { missing, blockedAt: new Date(), blockedBy: operator } } },
322
+ );
323
+ const { written, duplicate } = await writeUnresolvedRequest({
324
+ code: review.patientCode,
325
+ trace: null,
326
+ question: blocked,
327
+ details: `Revisión de escalación ${review._id}: completa ${missing.join(' y ')} en estado_general y vuelve a enviar al médico.`,
328
+ category: 'contact_team_member',
329
+ urgency: 'soon',
330
+ });
331
+ if (!written && !duplicate) {
332
+ logger.error('[EscalationReview] A doctor message was blocked for missing identity and the team ticket was not written', {
333
+ escalationReviewId: String(review._id), missing,
334
+ });
320
335
  }
321
- return lines.join('\n');
336
+ throw httpError(422, blocked);
322
337
  }
323
338
 
324
- async function sendDoctorAlert({ review, draft, approver, operator }) {
339
+ async function sendDoctorAlert({ message, approver, operator }) {
325
340
  const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
326
341
  if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
327
- const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
328
342
  const inWindow = await isWithin24HourWindow(doctorCode);
329
- const patient = await getPatientInformation(review.patientCode).catch(() => null);
330
- const body = `${doctorHeader(review, patient)}\n\n${draft.doctorText}\n\n${link}`;
331
- const message = inWindow
332
- ? { code: doctorCode, body, triggeredBy: operator }
333
- : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
334
- const result = await sendMessage(message);
343
+ const outgoing = inWindow
344
+ ? { code: doctorCode, body: message.body, triggeredBy: operator }
345
+ : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
346
+ const result = await sendMessage(outgoing);
335
347
  if (!result?.success && !result?.completed) {
336
348
  throw httpError(502, 'The WhatsApp message to the physician could not be sent');
337
349
  }
@@ -636,6 +648,7 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
636
648
  const draft = await generateEscalationDraft({
637
649
  code: review.patientCode,
638
650
  callLogs: review.callLogs ?? [],
651
+ alarms: review.alarms ?? [],
639
652
  reviewId: String(review._id),
640
653
  });
641
654
  // A generation run sends the patient's context to a model. That is what the audit exists to
@@ -866,13 +879,34 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
866
879
  if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
867
880
  }
868
881
 
882
+ const draftedAt = draft.createdAt ? new Date(draft.createdAt).getTime() : null;
883
+ if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
884
+ throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
885
+ }
886
+ const identity = await readDoctorIdentity(review);
887
+ if (identity.missing.length) await blockForMissingIdentity({ review, missing: identity.missing, operator });
888
+ const link = doctorLink(review);
889
+ const message = {
890
+ body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
891
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
892
+ };
893
+
869
894
  const claim = newOperationClaim();
870
- await updateReview(reviewId, [review.status], { $set: { status: 'handing_off', operationClaim: claim } }, { drafts: { $size: draftNumber } });
895
+ await updateReview(
896
+ reviewId,
897
+ [review.status],
898
+ { $set: { status: 'handing_off', operationClaim: claim } },
899
+ { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
900
+ );
871
901
  let delivery = {};
872
902
  let updated;
873
903
  try {
874
- if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ review, draft, approver, operator })) };
875
- const handoff = { $push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } } };
904
+ if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
905
+ const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
906
+ const handoff = {
907
+ $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, sentBy: operator } },
908
+ $unset: { identityBlock: '' },
909
+ };
876
910
  const recordUpdate = withCaseMirror(review, handoff, { status: 'en revision_medica' });
877
911
  updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
878
912
  } catch (error) {
@@ -1,4 +1,5 @@
1
1
  const { Estado_General_ID, Monitoreo_ID } = require('../config/airtableConfig');
2
+ const runtimeConfig = require('../config/runtimeConfig');
2
3
 
3
4
  const { httpError, requiredText } = require('../utils/httpErrorUtils');
4
5
  const { inlineOf } = require('../utils/coercionUtils');
@@ -7,6 +8,7 @@ const { logger } = require('../utils/logger');
7
8
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
9
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
9
10
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
11
+ const { prepareMessageMedia } = require('../helpers/mediaHelper');
10
12
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
11
13
  const { sendMessage } = require('../core/NexusMessaging');
12
14
 
@@ -14,20 +16,23 @@ const { getRecordByFilter } = require('./airtableService');
14
16
  const { getMessages } = require('./messageService');
15
17
  const { getPatientInformation } = require('./patientService');
16
18
 
17
- const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
18
19
  const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
19
20
  const HIDDEN_ORIGINS = ['system', 'instruction'];
20
21
  const DEFAULT_MESSAGE_LIMIT = 30;
21
22
  const MAX_MESSAGE_LIMIT = 50;
22
23
  const MAX_TEXT_LENGTH = 1500;
23
24
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
25
+ const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
26
+ const DOCUMENT_FILE_TYPE = 'document';
24
27
 
25
28
  async function getOfficeAssistant(email) {
26
29
  const normalized = String(email ?? '').trim().toLowerCase();
27
30
  if (!normalized) return null;
28
31
 
29
32
  const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
30
- const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
33
+ // No field list: Airtable rejects a listed column that does not exist yet, which would take the whole office view down
34
+ // until document_template_content_sid is added.
35
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, undefined, true) || [];
31
36
  const doctor = inlineOf(assistant?.doctor_match);
32
37
  const label = inlineOf(assistant?.office_label);
33
38
  if (!doctor || !label) return null;
@@ -37,6 +42,7 @@ async function getOfficeAssistant(email) {
37
42
  doctor,
38
43
  label,
39
44
  templateContentSid: inlineOf(assistant.template_content_sid) || null,
45
+ documentTemplateContentSid: inlineOf(assistant.document_template_content_sid) || null,
40
46
  };
41
47
  }
42
48
 
@@ -100,34 +106,78 @@ async function readOfficeMessages({ requestedBy, code, limit }) {
100
106
  };
101
107
  }
102
108
 
103
- function officeMessage({ assistant, patientCode, text, inWindow }) {
109
+ function officeDocumentUrl(fileUrl) {
110
+ if (!fileUrl) return null;
111
+ const bucketName = runtimeConfig.get('AWS_S3_BUCKET_NAME');
112
+ let url = null;
113
+ try {
114
+ url = new URL(String(fileUrl));
115
+ } catch {
116
+ url = null;
117
+ }
118
+ // The approved document template pins the S3 host and takes the rest of the URL as a variable. A bucket name
119
+ // with dots (whatsapp.prod) is presigned path-style, so the bucket is then the first path segment.
120
+ const bucket = escapeRegExp(bucketName ?? '');
121
+ const isVirtualHosted = new RegExp(`^${bucket}\\.s3(\\.[a-z0-9-]+)?\\.amazonaws\\.com$`).test(url?.hostname ?? '');
122
+ const isPathStyle = /^s3(\.[a-z0-9-]+)?\.amazonaws\.com$/.test(url?.hostname ?? '')
123
+ && url.pathname.startsWith(`/${bucketName}/`);
124
+ if (!bucketName || url?.protocol !== 'https:' || !(isVirtualHosted || isPathStyle)) {
125
+ throw httpError(400, 'The document must be uploaded before it is sent');
126
+ }
127
+ return url;
128
+ }
129
+
130
+ // Twilio needs the file type in a template's media URL, and uploads are stored without an
131
+ // extension, so the template gets the copy prepareMessageMedia stores with one.
132
+ async function templateDocumentOf(document, patientCode) {
133
+ const { mediaUrl } = await prepareMessageMedia({
134
+ code: patientCode, fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name,
135
+ });
136
+ // prepareMessageMedia answers with the original URL when the copy fails, and that one has no file type.
137
+ if (!mediaUrl || mediaUrl === document.url.href) throw httpError(502, 'The document could not be prepared for the template');
138
+ return { ...document, url: officeDocumentUrl(mediaUrl) };
139
+ }
140
+
141
+ function officeMessage({ assistant, patientCode, text, inWindow, document }) {
142
+ const attachment = document ? { fileUrl: document.url.href, fileType: DOCUMENT_FILE_TYPE, fileName: document.name } : {};
104
143
  if (inWindow) {
105
144
  if (text.length > MAX_TEXT_LENGTH) throw httpError(422, `The message exceeds ${MAX_TEXT_LENGTH} characters`);
106
- return { code: patientCode, body: `${assistant.label}: ${text}` };
145
+ return { code: patientCode, body: text ? `${assistant.label}: ${text}` : assistant.label, ...attachment };
107
146
  }
108
147
 
109
- const templateText = text.replace(/\s+/g, ' ').trim();
148
+ const templateText = text.replace(/\s+/g, ' ').trim() || DOCUMENT_TEMPLATE_DEFAULT_TEXT;
110
149
  if (templateText.length > MAX_TEMPLATE_TEXT_LENGTH) {
111
150
  throw httpError(422, `Outside the 24-hour window the message is sent as a template and cannot exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters`);
112
151
  }
113
- if (!assistant.templateContentSid) throw httpError(503, 'The office template is not configured; the patient is outside the 24-hour window');
152
+ const contentSid = document ? assistant.documentTemplateContentSid : assistant.templateContentSid;
153
+ if (!contentSid) {
154
+ const template = document ? 'office document template' : 'office template';
155
+ throw httpError(503, `The ${template} is not configured; the patient is outside the 24-hour window`);
156
+ }
114
157
  return {
115
158
  code: patientCode,
116
159
  body: `${assistant.label}: ${templateText}`,
117
- contentSid: assistant.templateContentSid,
118
- variables: { 1: templateText },
160
+ contentSid,
161
+ variables: document
162
+ ? { 1: templateText, 2: `${document.url.pathname.slice(1)}${document.url.search}` }
163
+ : { 1: templateText },
164
+ ...attachment,
119
165
  };
120
166
  }
121
167
 
122
- async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
168
+ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId, fileUrl, fileName }) {
123
169
  const assistant = await requireOfficeAssistant(requestedBy);
124
170
  const patientCode = await officePatientCode(assistant, code);
125
- const messageText = requiredText(text, 'text');
171
+ const url = officeDocumentUrl(fileUrl);
172
+ const document = url ? { url, name: fileName } : null;
173
+ const messageText = document ? String(text ?? '').trim() : requiredText(text, 'text');
126
174
  const messageKey = requiredText(clientMessageId, 'clientMessageId');
127
175
 
128
176
  const inWindow = await isWithin24HourWindow(patientCode);
177
+ const isDocumentTemplate = Boolean(document && !inWindow && assistant.documentTemplateContentSid);
178
+ const sentDocument = isDocumentTemplate ? await templateDocumentOf(document, patientCode) : document;
129
179
  const message = {
130
- ...officeMessage({ assistant, patientCode, text: messageText, inWindow }),
180
+ ...officeMessage({ assistant, patientCode, text: messageText, inWindow, document: sentDocument }),
131
181
  triggeredBy: assistant.email,
132
182
  idempotencyKey: `office:${patientCode}:${messageKey}`,
133
183
  };
@@ -143,6 +193,7 @@ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
143
193
  assistant: assistant.email,
144
194
  code: redactDirectIdentifiers(patientCode),
145
195
  transport,
196
+ hasDocument: Boolean(document),
146
197
  duplicate: result?.duplicate === true,
147
198
  });
148
199
  return { transport, messageId: result?.messageId || null, duplicate: result?.duplicate === true };
@@ -95,6 +95,7 @@ class MongoStorage {
95
95
  fromMe: doc.from_me,
96
96
  triggeredBy: doc.triggeredBy,
97
97
  ...(doc.origin === 'system' && doc.raw ? { raw: doc.raw } : {}),
98
+ ...(doc.contact_code && { contactCode: doc.contact_code, contactRole: doc.contact_role }),
98
99
  status,
99
100
  ...(frontendId && { frontendId })
100
101
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.58.0-dev.10249",
3
+ "version": "5.58.0-dev.10496",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",