@peopl-health/nexus 6.0.0-dev.718 → 6.0.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.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const { programSource } = require('../config/programConfig');
|
|
2
|
+
const { escapeFormulaValue } = require('./airtableFormulaHelper');
|
|
3
|
+
|
|
4
|
+
const CLOSED_REQUEST_STATUSES = [
|
|
5
|
+
'resuelto',
|
|
6
|
+
'no resuelto',
|
|
7
|
+
'solicitud repetida',
|
|
8
|
+
'no es requerimiento',
|
|
9
|
+
'no es ofrecimiento',
|
|
10
|
+
'alucinación',
|
|
11
|
+
'revisado',
|
|
12
|
+
];
|
|
13
|
+
const ATTENTION_REQUEST_STATUS = 'sin atender';
|
|
14
|
+
const ATTENTION_CASE_WINDOW_DAYS = 60;
|
|
15
|
+
const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
|
|
16
|
+
const URGENT_REQUEST_URGENCY = 'urgent';
|
|
17
|
+
const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
|
|
18
|
+
const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
|
|
19
|
+
// The operations statuses that close a case in Airtable, including the legacy lowercase one.
|
|
20
|
+
const CLOSING_CASE_OPERATIONS_STATUSES = new Set(['Cerrado', 'No requiere', 'cerrado']);
|
|
21
|
+
const programSourceFilter = (field) => `FIND('${escapeFormulaValue(programSource())}', ARRAYJOIN({${field}}))`;
|
|
22
|
+
|
|
23
|
+
const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
|
|
24
|
+
|
|
25
|
+
const isWithinAttentionWindow = (createdAt) => {
|
|
26
|
+
const created = Date.parse(createdAt || '');
|
|
27
|
+
return Number.isFinite(created) && Date.now() - created <= ATTENTION_CASE_WINDOW_MS;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const needsRequestAttention = (status) => status === ATTENTION_REQUEST_STATUS;
|
|
31
|
+
|
|
32
|
+
// A case stays open until it is closed: a closed_time, or a closing operations status not yet stamped.
|
|
33
|
+
const isCaseOpen = (closedTime, createdAt, operationsStatus) => !closedTime
|
|
34
|
+
&& !CLOSING_CASE_OPERATIONS_STATUSES.has(operationsStatus)
|
|
35
|
+
&& isWithinAttentionWindow(createdAt);
|
|
36
|
+
|
|
37
|
+
// A case needs attention until it is attended, which stamps its resolved_time.
|
|
38
|
+
const needsCaseAttention = (resolvedTime, createdAt) => !resolvedTime && isWithinAttentionWindow(createdAt);
|
|
39
|
+
|
|
40
|
+
const isRequestUrgent = (urgency) => urgency === URGENT_REQUEST_URGENCY;
|
|
41
|
+
|
|
42
|
+
const isCaseUrgent = (type) => URGENT_CASE_TYPES.includes(type);
|
|
43
|
+
|
|
44
|
+
module.exports = {
|
|
45
|
+
ATTENTION_CASE_WINDOW_DAYS,
|
|
46
|
+
CLOSED_REQUEST_STATUSES,
|
|
47
|
+
CLOSING_CASE_OPERATIONS_STATUSES,
|
|
48
|
+
ATTENTION_REQUEST_STATUS,
|
|
49
|
+
REQUEST_URGENCIES,
|
|
50
|
+
isCaseOpen,
|
|
51
|
+
isCaseUrgent,
|
|
52
|
+
isRequestOpen,
|
|
53
|
+
isRequestUrgent,
|
|
54
|
+
needsCaseAttention,
|
|
55
|
+
needsRequestAttention,
|
|
56
|
+
programSourceFilter,
|
|
57
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { Thread } = require('../models/threadModel');
|
|
3
|
+
|
|
4
|
+
async function botIsPaused(code, { label = '[pausedThread]' } = {}) {
|
|
5
|
+
if (!code) return false;
|
|
6
|
+
try {
|
|
7
|
+
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
8
|
+
return Boolean(paused);
|
|
9
|
+
} catch (error) {
|
|
10
|
+
logger.warn(`${label} thread state unreadable; treating the bot as paused`, { code, error: error.message });
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function alertsMutedFor(code, inboundAt, { label = '[pausedThread]' } = {}) {
|
|
16
|
+
if (!code || !inboundAt) return false;
|
|
17
|
+
try {
|
|
18
|
+
const thread = await Thread.findOne({ code }, { doNotAlertThrough: 1 }).lean();
|
|
19
|
+
if (!thread?.doNotAlertThrough) return false;
|
|
20
|
+
return new Date(inboundAt).getTime() <= new Date(thread.doNotAlertThrough).getTime();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
logger.warn(`${label} could not read whether this silence was waved off; alerting anyway`, { code, error: error.message });
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function pausedSince(code, since) {
|
|
28
|
+
const paused = await Thread.findOne({ code, stopped: true, pausedAt: { $gt: since } }, { _id: 1 }).lean();
|
|
29
|
+
return Boolean(paused);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function patientIsDeceased(code) {
|
|
33
|
+
const deceased = await Thread.findOne({ code, deceasedAt: { $ne: null } }, { _id: 1 }).lean();
|
|
34
|
+
return Boolean(deceased);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { alertsMutedFor, botIsPaused, patientIsDeceased, pausedSince };
|
|
@@ -11,6 +11,7 @@ const { analyzeImage } = require('../clinical/helpers/llmsHelper');
|
|
|
11
11
|
const { cleanupFiles, downloadMediaAndCreateFile } = require('./filesHelper.js');
|
|
12
12
|
|
|
13
13
|
const DEBUG_ENABLED = runtimeConfig.get('DEBUG_MESSAGE_CONTENT') === 'true';
|
|
14
|
+
const ANALYSIS_FAILED_TEXT = 'No se pudo analizar la imagen que envió el paciente.';
|
|
14
15
|
const logger = {
|
|
15
16
|
info: (context, metadata = {}) => {
|
|
16
17
|
const safeMetadata = sanitizeLogMetadata(metadata);
|
|
@@ -40,11 +41,22 @@ const processTextMessage = (reply) => {
|
|
|
40
41
|
return [{ type: 'text', text: reply.body }];
|
|
41
42
|
};
|
|
42
43
|
|
|
44
|
+
const renderMeasurements = (measurements) => {
|
|
45
|
+
const values = measurements
|
|
46
|
+
.map(({ label, value, unit }) => [label, value, unit].filter(Boolean).join(' '))
|
|
47
|
+
.join(' - ');
|
|
48
|
+
const unsure = measurements.filter(({ confidence }) => confidence !== 'high').map(({ label }) => label);
|
|
49
|
+
const line = `Valores leídos en pantalla: ${values}.`;
|
|
50
|
+
if (!unsure.length) return line;
|
|
51
|
+
return `${line}\nLectura dudosa en ${unsure.join(', ')}: pídele al paciente que confirme ese número antes de darlo por bueno.`;
|
|
52
|
+
};
|
|
53
|
+
|
|
43
54
|
const processImageFileCore = async (fileName, reply) => {
|
|
44
55
|
const messagesChat = [];
|
|
45
56
|
const timings = { analysis_ms: 0, url_generation_ms: 0 };
|
|
46
57
|
let imageAnalysis = null;
|
|
47
58
|
let url = null;
|
|
59
|
+
let failed = false;
|
|
48
60
|
|
|
49
61
|
const isSticker = reply.media?.mediaType === 'sticker' ||
|
|
50
62
|
fileName.toLowerCase().includes('sticker/') ||
|
|
@@ -59,8 +71,15 @@ const processImageFileCore = async (fileName, reply) => {
|
|
|
59
71
|
)(fileName, isSticker, reply.media?.contentType);
|
|
60
72
|
imageAnalysis = analysis;
|
|
61
73
|
timings.analysis_ms = analysisDuration;
|
|
62
|
-
|
|
74
|
+
|
|
75
|
+
if (imageAnalysis?.analysisFailed) {
|
|
76
|
+
failed = true;
|
|
77
|
+
messagesChat.push({ type: 'text', text: ANALYSIS_FAILED_TEXT });
|
|
78
|
+
return { messagesChat, url, timings, failed };
|
|
79
|
+
}
|
|
80
|
+
|
|
63
81
|
const invalidAnalysis = ['NOT_MEDICAL', 'QUALITY_INSUFFICIENT'];
|
|
82
|
+
const unusableAnalysis = invalidAnalysis.some(tag => imageAnalysis?.medical_analysis?.includes(tag));
|
|
64
83
|
|
|
65
84
|
if (imageAnalysis?.medical_relevance && !isSticker) {
|
|
66
85
|
const { result: presignedUrl, duration: urlDuration } = await withTracing(
|
|
@@ -72,21 +91,27 @@ const processImageFileCore = async (fileName, reply) => {
|
|
|
72
91
|
timings.url_generation_ms = urlDuration;
|
|
73
92
|
}
|
|
74
93
|
|
|
75
|
-
|
|
94
|
+
const parts = [];
|
|
95
|
+
if (!isSticker && !unusableAnalysis && imageAnalysis?.measurements?.length) {
|
|
96
|
+
parts.push(renderMeasurements(imageAnalysis.measurements));
|
|
97
|
+
}
|
|
76
98
|
if (!isSticker && imageAnalysis?.has_table && imageAnalysis.table_data) {
|
|
77
|
-
|
|
78
|
-
} else if (!isSticker && imageAnalysis?.medical_analysis &&
|
|
79
|
-
!invalidAnalysis.some(tag => imageAnalysis.medical_analysis.includes(tag))) {
|
|
80
|
-
text = imageAnalysis.medical_analysis;
|
|
99
|
+
parts.push(imageAnalysis.table_data);
|
|
81
100
|
}
|
|
101
|
+
if (!isSticker && imageAnalysis?.medical_analysis && !unusableAnalysis) {
|
|
102
|
+
parts.push(imageAnalysis.medical_analysis);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const text = parts.length ? parts.join('\n\n') : (imageAnalysis?.description || 'Image processed');
|
|
82
106
|
messagesChat.push({ type: 'text', text });
|
|
83
107
|
|
|
84
108
|
} catch (error) {
|
|
85
109
|
logger.error('processImageFile', error, { message_id: reply.message_id });
|
|
86
|
-
|
|
110
|
+
failed = true;
|
|
111
|
+
messagesChat.push({ type: 'text', text: ANALYSIS_FAILED_TEXT });
|
|
87
112
|
}
|
|
88
113
|
|
|
89
|
-
return { messagesChat, url, timings };
|
|
114
|
+
return { messagesChat, url, timings, failed };
|
|
90
115
|
};
|
|
91
116
|
|
|
92
117
|
const processImageFile = withTracing(
|
|
@@ -101,6 +126,7 @@ const processImageFile = withTracing(
|
|
|
101
126
|
const processAudioFileCore = async (fileName, provider) => {
|
|
102
127
|
const messagesChat = [];
|
|
103
128
|
const timings = { transcribe_ms: 0 };
|
|
129
|
+
let failed = false;
|
|
104
130
|
|
|
105
131
|
try {
|
|
106
132
|
const { result: audioTranscript, duration } = await withTracing(
|
|
@@ -119,10 +145,11 @@ const processAudioFileCore = async (fileName, provider) => {
|
|
|
119
145
|
messagesChat.push({ type: 'text', text });
|
|
120
146
|
} catch (error) {
|
|
121
147
|
logger.error('processAudioFile', error);
|
|
122
|
-
|
|
148
|
+
failed = true;
|
|
149
|
+
messagesChat.push({ type: 'text', text: 'No se pudo transcribir el audio que envió el paciente.' });
|
|
123
150
|
}
|
|
124
151
|
|
|
125
|
-
return { messagesChat, timings };
|
|
152
|
+
return { messagesChat, timings, failed };
|
|
126
153
|
};
|
|
127
154
|
|
|
128
155
|
const processAudioFile = withTracing(
|
|
@@ -136,14 +163,15 @@ const processAudioFile = withTracing(
|
|
|
136
163
|
const processMediaFilesCore = async (code, reply, provider) => {
|
|
137
164
|
const timings = { download_ms: 0, image_analysis_ms: 0, audio_transcription_ms: 0, url_generation_ms: 0 };
|
|
138
165
|
|
|
139
|
-
if (!reply.media) return { messagesChat: [], url: null, tempFiles: [], timings };
|
|
166
|
+
if (!reply.media) return { messagesChat: [], url: null, tempFiles: [], timings, failed: false };
|
|
140
167
|
|
|
141
168
|
if (reply.media?.metadata?.processedContent) {
|
|
142
169
|
return {
|
|
143
170
|
messagesChat: [{ type: 'text', text: reply.media.metadata.processedContent }],
|
|
144
171
|
url: null,
|
|
145
172
|
tempFiles: [],
|
|
146
|
-
timings
|
|
173
|
+
timings,
|
|
174
|
+
failed: false
|
|
147
175
|
};
|
|
148
176
|
}
|
|
149
177
|
|
|
@@ -156,6 +184,7 @@ const processMediaFilesCore = async (code, reply, provider) => {
|
|
|
156
184
|
|
|
157
185
|
const messagesChat = [];
|
|
158
186
|
let url = null;
|
|
187
|
+
let failed = false;
|
|
159
188
|
|
|
160
189
|
for (const fileName of fileNames) {
|
|
161
190
|
if (fileName.toLowerCase().includes('.wbmp')) continue;
|
|
@@ -167,17 +196,19 @@ const processMediaFilesCore = async (code, reply, provider) => {
|
|
|
167
196
|
if (isImageLike) {
|
|
168
197
|
const result = await processImageFile(fileName, reply);
|
|
169
198
|
messagesChat.push(...result.messagesChat);
|
|
199
|
+
if (result.failed) failed = true;
|
|
170
200
|
if (result.url) url = result.url;
|
|
171
201
|
timings.image_analysis_ms += result.timings?.analysis_ms || 0;
|
|
172
202
|
timings.url_generation_ms += result.timings?.url_generation_ms || 0;
|
|
173
203
|
} else if (fileName.includes('audio')) {
|
|
174
204
|
const result = await processAudioFile(fileName, provider);
|
|
175
205
|
messagesChat.push(...result.messagesChat);
|
|
206
|
+
if (result.failed) failed = true;
|
|
176
207
|
timings.audio_transcription_ms += result.timings?.transcribe_ms || 0;
|
|
177
208
|
}
|
|
178
209
|
}
|
|
179
210
|
|
|
180
|
-
return { messagesChat, url, tempFiles: fileNames, timings };
|
|
211
|
+
return { messagesChat, url, tempFiles: fileNames, timings, failed };
|
|
181
212
|
};
|
|
182
213
|
|
|
183
214
|
const processMediaFiles = withTracing(
|
|
@@ -197,7 +228,7 @@ const processThreadMessageCore = async (code, replies, provider) => {
|
|
|
197
228
|
replyArray.map(async (reply) => {
|
|
198
229
|
try {
|
|
199
230
|
const textMessages = processTextMessage(reply);
|
|
200
|
-
const { messagesChat: mediaMessages, url, tempFiles, timings: mt } = await processMediaFiles(code, reply, provider);
|
|
231
|
+
const { messagesChat: mediaMessages, url, tempFiles, timings: mt, failed } = await processMediaFiles(code, reply, provider);
|
|
201
232
|
|
|
202
233
|
if (mt) {
|
|
203
234
|
timings.download_ms += mt.download_ms || 0;
|
|
@@ -210,10 +241,10 @@ const processThreadMessageCore = async (code, replies, provider) => {
|
|
|
210
241
|
const messages = [...textMessages, ...mediaMessages].map(content => ({ role, content }));
|
|
211
242
|
|
|
212
243
|
await cleanupFiles(tempFiles);
|
|
213
|
-
return { isPatient: reply.origin === 'patient', url, messages, reply, tempFiles };
|
|
244
|
+
return { isPatient: reply.origin === 'patient', url, messages, reply, tempFiles, failed };
|
|
214
245
|
} catch (error) {
|
|
215
246
|
logger.error('processThreadMessage', error, { message_id: reply.message_id });
|
|
216
|
-
return { isPatient: false, url: null, messages: [], reply, tempFiles: [] };
|
|
247
|
+
return { isPatient: false, url: null, messages: [], reply, tempFiles: [], failed: Boolean(reply.media) };
|
|
217
248
|
}
|
|
218
249
|
})
|
|
219
250
|
);
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
|
|
5
|
+
const { SendClaim } = require('../models/sendClaimModel');
|
|
6
|
+
const { ensureWhatsAppFormat } = require('./twilioHelper');
|
|
7
|
+
|
|
8
|
+
const DUPLICATE_KEY_ERROR = 11000;
|
|
9
|
+
const EPHEMERAL_VALUE = /^\d+\/\d+\/\d{13}\//;
|
|
10
|
+
const CLAIM_TIMEOUT_MS = 1000;
|
|
11
|
+
|
|
12
|
+
function withTimeout(promise) {
|
|
13
|
+
let timer;
|
|
14
|
+
const timeout = new Promise(resolve => {
|
|
15
|
+
timer = setTimeout(() => resolve(null), CLAIM_TIMEOUT_MS);
|
|
16
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
17
|
+
});
|
|
18
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let indexesReady = null;
|
|
22
|
+
|
|
23
|
+
function ensureIndexes() {
|
|
24
|
+
if (!indexesReady) {
|
|
25
|
+
indexesReady = SendClaim.init().catch(error => {
|
|
26
|
+
indexesReady = null;
|
|
27
|
+
logger.error('[SendClaim] Index build failed, duplicate suppression is disabled', { error: error.message });
|
|
28
|
+
throw error;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return indexesReady;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function contentSignature(variables) {
|
|
35
|
+
if (!variables || typeof variables !== 'object') return '';
|
|
36
|
+
const keys = Object.keys(variables).sort();
|
|
37
|
+
if (!keys.length) return '';
|
|
38
|
+
|
|
39
|
+
const describe = subset => subset.map(key => `${key}=${variables[key]}`).join('|');
|
|
40
|
+
const stable = keys.filter(key => !(typeof variables[key] === 'string' && EPHEMERAL_VALUE.test(variables[key])));
|
|
41
|
+
|
|
42
|
+
// With no stable value to sign, the expiring URL is the only identity available. It is
|
|
43
|
+
// deterministic inside its window, so retries still collide; only a send that straddles a
|
|
44
|
+
// window boundary escapes suppression, which costs a duplicate rather than a dropped message.
|
|
45
|
+
const source = stable.length ? describe(stable) : describe(keys);
|
|
46
|
+
return crypto.createHash('sha1').update(source).digest('hex').slice(0, 12);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildSendClaimKey({ code, contactCode, contentSid, variables, idempotencyKey } = {}) {
|
|
50
|
+
if (idempotencyKey) return `idem:${idempotencyKey}`;
|
|
51
|
+
if (!code || !contentSid) return null;
|
|
52
|
+
const signature = contentSignature(variables);
|
|
53
|
+
const recipient = contactCode ? `${ensureWhatsAppFormat(code)}>${ensureWhatsAppFormat(contactCode)}` : ensureWhatsAppFormat(code);
|
|
54
|
+
return `tpl:${recipient}:${contentSid}${signature ? `:${signature}` : ''}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function isCompletedClaim(key) {
|
|
58
|
+
try {
|
|
59
|
+
const existing = await withTimeout(SendClaim.findOne({ key }).lean());
|
|
60
|
+
return existing?.status === 'completed';
|
|
61
|
+
} catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function acquireSendClaim(messageData = {}) {
|
|
67
|
+
const key = buildSendClaimKey(messageData);
|
|
68
|
+
if (!key) return { acquired: true, key: null, claimId: null };
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
const ready = await withTimeout(ensureIndexes().then(() => true));
|
|
72
|
+
if (!ready) {
|
|
73
|
+
logger.error('[SendClaim] Index check timed out, letting the send through', { key });
|
|
74
|
+
return { acquired: true, key, claimId: null };
|
|
75
|
+
}
|
|
76
|
+
} catch {
|
|
77
|
+
return { acquired: true, key, claimId: null };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
const claim = await withTimeout(SendClaim.create({
|
|
82
|
+
key,
|
|
83
|
+
...(messageData.code && { code: messageData.code }),
|
|
84
|
+
...(messageData.contentSid && { contentSid: messageData.contentSid })
|
|
85
|
+
}));
|
|
86
|
+
if (!claim) {
|
|
87
|
+
logger.error('[SendClaim] Claim timed out, letting the send through', { key });
|
|
88
|
+
return { acquired: true, key, claimId: null };
|
|
89
|
+
}
|
|
90
|
+
return { acquired: true, key, claimId: claim._id };
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error?.code === DUPLICATE_KEY_ERROR) {
|
|
93
|
+
logger.warn('[SendClaim] Concurrent send suppressed', { key });
|
|
94
|
+
return { acquired: false, completed: await isCompletedClaim(key), key, claimId: null };
|
|
95
|
+
}
|
|
96
|
+
logger.error('[SendClaim] Claim check failed, letting the send through', { key, error: error.message });
|
|
97
|
+
return { acquired: true, key, claimId: null };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function completeSendClaim(claimId) {
|
|
102
|
+
if (!claimId) return true;
|
|
103
|
+
try {
|
|
104
|
+
const result = await withTimeout(SendClaim.updateOne(
|
|
105
|
+
{ _id: claimId },
|
|
106
|
+
{ $set: { status: 'completed', completedAt: new Date() } },
|
|
107
|
+
));
|
|
108
|
+
if (!result) {
|
|
109
|
+
logger.warn('[SendClaim] Claim completion timed out', { claimId: String(claimId) });
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
return result?.matchedCount === 1;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
logger.warn('[SendClaim] Could not complete the claim', { claimId: String(claimId), error: error.message });
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function releaseSendClaim(claimId) {
|
|
120
|
+
if (!claimId) return;
|
|
121
|
+
await SendClaim.deleteOne({ _id: claimId }).catch(error =>
|
|
122
|
+
logger.warn('[SendClaim] Could not release the claim', { claimId: String(claimId), error: error.message })
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = { acquireSendClaim, completeSendClaim, releaseSendClaim, buildSendClaimKey };
|
|
@@ -1,12 +1,36 @@
|
|
|
1
|
+
const { generatePresignedUrl } = require('../config/awsConfig');
|
|
1
2
|
const { logger } = require('../utils/logger');
|
|
2
3
|
const { Message } = require('../models/messageModel');
|
|
3
|
-
const TemplateModel = require('../models/templateModel');
|
|
4
|
+
const { Template: TemplateModel } = require('../models/templateModel');
|
|
4
5
|
const { Template } = require('../templates/templateStructure');
|
|
5
6
|
const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
|
|
6
7
|
|
|
7
8
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
8
9
|
|
|
9
10
|
const TEMPLATE_BODY_LIMIT = 1024;
|
|
11
|
+
const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
12
|
+
|
|
13
|
+
async function resolveRecoveryMediaUrl(media) {
|
|
14
|
+
if (!media?.bucketName || !media?.key) return null;
|
|
15
|
+
try {
|
|
16
|
+
return await generatePresignedUrl(media.bucketName, media.key, RECOVERY_MEDIA_URL_TTL_SECONDS);
|
|
17
|
+
} catch (error) {
|
|
18
|
+
logger.warn('[TemplateRecovery] Could not presign media; sending text-only', { error: error.message });
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const PHI_TOKEN = /<<[A-Z_]+_\d+>>|(?<![\w@.])persona_\d+(?![\w@.])/i;
|
|
24
|
+
|
|
25
|
+
function hasUnresolvedPhi(body) {
|
|
26
|
+
return PHI_TOKEN.test(body || '');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function resolveRecoveryBody(messageDoc) {
|
|
30
|
+
if (messageDoc.plainBody) return messageDoc.plainBody;
|
|
31
|
+
const decoded = await getMessaging().getPhiProcessor()?.decodeBody(messageDoc.body, messageDoc.numero);
|
|
32
|
+
return decoded || messageDoc.body;
|
|
33
|
+
}
|
|
10
34
|
|
|
11
35
|
async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null } = {}) {
|
|
12
36
|
try {
|
|
@@ -23,7 +47,16 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
23
47
|
try {
|
|
24
48
|
const claim = await Message.updateOne(
|
|
25
49
|
{ _id: messageDocId, 'statusInfo.recoveryStartedAt': null },
|
|
26
|
-
{
|
|
50
|
+
{
|
|
51
|
+
$set: { 'statusInfo.recoveryStartedAt': new Date() },
|
|
52
|
+
$unset: {
|
|
53
|
+
'statusInfo.recoveryFailedAt': '',
|
|
54
|
+
'statusInfo.recoveryRejectedAt': '',
|
|
55
|
+
'statusInfo.recoveryAttempt': '',
|
|
56
|
+
'statusInfo.recoveryWarnedAt': '',
|
|
57
|
+
'statusInfo.recoveryCheckedAt': ''
|
|
58
|
+
}
|
|
59
|
+
}
|
|
27
60
|
);
|
|
28
61
|
if (!claim.modifiedCount && !claim.nModified) {
|
|
29
62
|
logger.info('[TemplateRecovery] Already in progress', logCtx);
|
|
@@ -41,14 +74,20 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
41
74
|
return;
|
|
42
75
|
}
|
|
43
76
|
|
|
77
|
+
const recoveryBody = await resolveRecoveryBody(messageDoc);
|
|
44
78
|
const templateName = `auto_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
45
79
|
const template = new Template(templateName, 'UTILITY', 'es');
|
|
46
|
-
template.setBody(
|
|
80
|
+
template.setBody(recoveryBody, []);
|
|
81
|
+
|
|
82
|
+
const mediaUrl = await resolveRecoveryMediaUrl(messageDoc.media);
|
|
83
|
+
if (mediaUrl) template.setMedia(mediaUrl);
|
|
47
84
|
|
|
48
85
|
let twilioContent;
|
|
49
86
|
let setupErr = null;
|
|
50
|
-
if (
|
|
51
|
-
setupErr = new Error(
|
|
87
|
+
if (hasUnresolvedPhi(recoveryBody)) {
|
|
88
|
+
setupErr = new Error('Body still carries a PHI placeholder after decoding');
|
|
89
|
+
} else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
|
|
90
|
+
setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
|
|
52
91
|
} else {
|
|
53
92
|
try {
|
|
54
93
|
twilioContent = await template.save();
|
|
@@ -62,7 +101,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
62
101
|
await recordDeliveryAttempt({
|
|
63
102
|
messageId: messageDocId,
|
|
64
103
|
kind: 'recovery_template_setup',
|
|
65
|
-
body:
|
|
104
|
+
body: recoveryBody,
|
|
66
105
|
twilioResult: twilioContent?.sid ? { sid: twilioContent.sid } : null,
|
|
67
106
|
...(setupErr && { errorSource: 'server', errorMessage: setupErr.message })
|
|
68
107
|
});
|
|
@@ -96,7 +135,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
96
135
|
{ $set: { 'statusInfo.recoveryTemplateSid': twilioContent.sid } }
|
|
97
136
|
);
|
|
98
137
|
|
|
99
|
-
logger.info('[TemplateRecovery] Template created', { ...logCtx, templateSid: twilioContent.sid });
|
|
138
|
+
logger.info('[TemplateRecovery] Template created', { ...logCtx, templateSid: twilioContent.sid, hasMedia: !!mediaUrl });
|
|
100
139
|
|
|
101
140
|
await scheduleTemplateApproval({
|
|
102
141
|
templateSid: twilioContent.sid,
|
|
@@ -114,4 +153,23 @@ async function handle24HourWindowError(message, messageSid) {
|
|
|
114
153
|
return triggerTemplateRecovery(message, { source: 'reactive', messageSid });
|
|
115
154
|
}
|
|
116
155
|
|
|
117
|
-
|
|
156
|
+
async function cleanupRecoveryTemplate(messageDoc) {
|
|
157
|
+
const templateSid = messageDoc?.statusInfo?.recoveryTemplateSid;
|
|
158
|
+
if (!templateSid || !messageDoc?._id) return;
|
|
159
|
+
|
|
160
|
+
const claim = await Message.updateOne(
|
|
161
|
+
{ _id: messageDoc._id, 'statusInfo.recoveryTemplateSid': templateSid },
|
|
162
|
+
{ $unset: { 'statusInfo.recoveryTemplateSid': '' } }
|
|
163
|
+
);
|
|
164
|
+
if (!claim.modifiedCount && !claim.nModified) return;
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
const provider = getMessaging().requireProvider();
|
|
168
|
+
await provider.deleteTemplate(templateSid);
|
|
169
|
+
logger.info('[TemplateRecovery] Template deleted after delivery', { messageDocId: String(messageDoc._id), templateSid });
|
|
170
|
+
} catch (error) {
|
|
171
|
+
logger.warn('[TemplateRecovery] Failed to delete template after delivery', { templateSid, error: error.message });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
module.exports = { handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi };
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const { firstOf } = require('../utils/coercionUtils');
|
|
2
|
+
|
|
3
|
+
// Explicit fields because the tables are 245 and 101 columns wide; `symptoms` here is the link field, not the table.
|
|
4
|
+
const TRIAGE_FIELDS = [
|
|
5
|
+
'recordID', 'Created', 'Date', 'triaje_symptoms_id', 'whatsapp_id', 'symptoms',
|
|
6
|
+
'type_quest (from questionnaire_id)', 'is_completed',
|
|
7
|
+
'max_grade_in_triaje', 'min_grade_in_triaje',
|
|
8
|
+
'symp_count_positive', 'symp_count_g2', 'symp_count_g3', 'total_symptoms',
|
|
9
|
+
'recommendations', 'other_symptoms', 'other_pain_text', 'symptoms_change',
|
|
10
|
+
'nutri_risk_level', 'satisfaction_level',
|
|
11
|
+
'has_pain', 'pain_frequency', 'pain_intensity', 'pain_interference', 'most_important_pain',
|
|
12
|
+
// DEPRECATED: ~10 KB of prompt context per triage, superseded by `symptoms`. Remove with the response field once unread.
|
|
13
|
+
'full_symptoms_metadata',
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const SYMPTOM_FIELDS = [
|
|
17
|
+
'symptom_name', 'presencia', 'frecuencia', 'intensidad', 'interferencia', 'cantidad',
|
|
18
|
+
'grade_num', 'composite_calculation', 'grade_symptom',
|
|
19
|
+
'grade_1_symp', 'grade_2_symp', 'grade_3_symp',
|
|
20
|
+
'definition_symp', 'AE category', 'reported-time-frame', 'freetext_derived',
|
|
21
|
+
'combination_code', 'short_recommendation', 'observacion_paciente',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const textOrNull = (value) => {
|
|
25
|
+
const first = firstOf(value);
|
|
26
|
+
if (first === undefined || first === null) return null;
|
|
27
|
+
const text = String(first).trim();
|
|
28
|
+
return text === '' ? null : text;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const numberOrNull = (value) => {
|
|
32
|
+
const first = firstOf(value);
|
|
33
|
+
if (first === undefined || first === null || first === '') return null;
|
|
34
|
+
const parsed = Number(first);
|
|
35
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const listOrNull = (value) => {
|
|
39
|
+
const text = textOrNull(value);
|
|
40
|
+
if (!text) return null;
|
|
41
|
+
const items = text.split(',').map((part) => part.trim()).filter(Boolean);
|
|
42
|
+
return items.length ? items : null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// A yes/no question answers with the string "no", which plain truthiness would read as true.
|
|
46
|
+
const booleanOrNull = (value) => {
|
|
47
|
+
const first = firstOf(value);
|
|
48
|
+
if (first === undefined || first === null || first === '') return null;
|
|
49
|
+
if (typeof first === 'boolean') return first;
|
|
50
|
+
if (typeof first === 'number') return first !== 0;
|
|
51
|
+
const text = String(first).trim().toLowerCase();
|
|
52
|
+
if (['yes', 'si', 'sí', 'true', '1'].includes(text)) return true;
|
|
53
|
+
if (['no', 'false', '0'].includes(text)) return false;
|
|
54
|
+
return null;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Both are exposed because they diverge: `max_grade_in_triaje` rolls up `grade_num`, the prose reports `composite_calculation`.
|
|
58
|
+
const buildSymptom = (row) => ({
|
|
59
|
+
id: row._recordId,
|
|
60
|
+
name: textOrNull(row.symptom_name),
|
|
61
|
+
gradeNum: numberOrNull(row.grade_num),
|
|
62
|
+
compositeGrade: numberOrNull(row.composite_calculation),
|
|
63
|
+
gradeClause: textOrNull(row.grade_symptom),
|
|
64
|
+
gradeScale: {
|
|
65
|
+
g1: textOrNull(row.grade_1_symp),
|
|
66
|
+
g2: textOrNull(row.grade_2_symp),
|
|
67
|
+
g3: textOrNull(row.grade_3_symp),
|
|
68
|
+
},
|
|
69
|
+
definition: textOrNull(row.definition_symp),
|
|
70
|
+
category: textOrNull(row['AE category']),
|
|
71
|
+
reportedTimeFrame: textOrNull(row['reported-time-frame']),
|
|
72
|
+
isFreetextDerived: booleanOrNull(row.freetext_derived) === true,
|
|
73
|
+
combinationCode: textOrNull(row.combination_code),
|
|
74
|
+
// The values stay verbatim: they are the patient's answer.
|
|
75
|
+
attributes: {
|
|
76
|
+
presence: textOrNull(row.presencia),
|
|
77
|
+
frequency: textOrNull(row.frecuencia),
|
|
78
|
+
severity: textOrNull(row.intensidad),
|
|
79
|
+
interference: textOrNull(row.interferencia),
|
|
80
|
+
amount: textOrNull(row.cantidad),
|
|
81
|
+
},
|
|
82
|
+
shortRecommendation: textOrNull(row.short_recommendation),
|
|
83
|
+
patientNote: textOrNull(row.observacion_paciente),
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// The deployed interface reads `id`, `created`, `full_symptoms_metadata`, `whatsapp_id` and `code`: do not reshape them.
|
|
87
|
+
const buildTriageRecord = (row, symptomRows = []) => ({
|
|
88
|
+
id: row.recordID,
|
|
89
|
+
created: row?.Created || null,
|
|
90
|
+
answeredAt: row?.Date || null,
|
|
91
|
+
triageId: numberOrNull(row.triaje_symptoms_id),
|
|
92
|
+
questionnaireType: textOrNull(row['type_quest (from questionnaire_id)']),
|
|
93
|
+
isCompleted: booleanOrNull(row.is_completed),
|
|
94
|
+
maxGrade: numberOrNull(row.max_grade_in_triaje),
|
|
95
|
+
minGrade: numberOrNull(row.min_grade_in_triaje),
|
|
96
|
+
positiveCount: numberOrNull(row.symp_count_positive),
|
|
97
|
+
gradeTwoCount: numberOrNull(row.symp_count_g2),
|
|
98
|
+
gradeThreeCount: numberOrNull(row.symp_count_g3),
|
|
99
|
+
totalSymptoms: numberOrNull(row.total_symptoms),
|
|
100
|
+
recommendations: textOrNull(row.recommendations),
|
|
101
|
+
otherSymptoms: textOrNull(row.other_symptoms),
|
|
102
|
+
otherPainText: textOrNull(row.other_pain_text),
|
|
103
|
+
symptomsChange: listOrNull(row.symptoms_change),
|
|
104
|
+
nutriRiskLevel: textOrNull(row.nutri_risk_level),
|
|
105
|
+
satisfactionLevel: textOrNull(row.satisfaction_level),
|
|
106
|
+
pain: {
|
|
107
|
+
hasPain: booleanOrNull(row.has_pain),
|
|
108
|
+
frequency: textOrNull(row.pain_frequency),
|
|
109
|
+
intensity: textOrNull(row.pain_intensity),
|
|
110
|
+
interference: textOrNull(row.pain_interference),
|
|
111
|
+
mostImportant: textOrNull(row.most_important_pain),
|
|
112
|
+
},
|
|
113
|
+
symptoms: symptomRows.map(buildSymptom),
|
|
114
|
+
full_symptoms_metadata: row?.full_symptoms_metadata || null,
|
|
115
|
+
whatsapp_id: row?.whatsapp_id || null,
|
|
116
|
+
code: row?.whatsapp_id || null,
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
module.exports = {
|
|
120
|
+
TRIAGE_FIELDS,
|
|
121
|
+
SYMPTOM_FIELDS,
|
|
122
|
+
buildSymptom,
|
|
123
|
+
buildTriageRecord,
|
|
124
|
+
};
|