@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
|
@@ -1,18 +1,69 @@
|
|
|
1
1
|
const { fhirId } = require('../helpers/fhirHelper');
|
|
2
|
-
const { identifier } = require('../helpers/elementHelper');
|
|
2
|
+
const { identifier, extension } = require('../helpers/elementHelper');
|
|
3
|
+
const { PATIENT_SLUG } = require('../constants/projectionSlugs');
|
|
4
|
+
const { PATIENT_EXT } = require('../constants/extensionSlugs');
|
|
5
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
6
|
+
|
|
7
|
+
// `m` is deliberately absent: it means Mujer (female) in the Hombre/Mujer convention this data uses
|
|
8
|
+
// and Masculino (male) in the other, so it is the one token that could assert the wrong sex.
|
|
9
|
+
const GENDER_BY_TERM = {
|
|
10
|
+
mujer: 'female',
|
|
11
|
+
femenino: 'female',
|
|
12
|
+
femenina: 'female',
|
|
13
|
+
f: 'female',
|
|
14
|
+
hombre: 'male',
|
|
15
|
+
varon: 'male',
|
|
16
|
+
masculino: 'male',
|
|
17
|
+
h: 'male',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
function normalizeTerm(value) {
|
|
21
|
+
return foldAccents(String(value ?? '').trim().toLowerCase());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function genderFrom(sexo) {
|
|
25
|
+
return GENDER_BY_TERM[normalizeTerm(sexo)] || null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function ageFrom(edad) {
|
|
29
|
+
const raw = String(edad ?? '').trim();
|
|
30
|
+
if (!/^\d{1,3}$/.test(raw)) return null;
|
|
31
|
+
const age = Number(raw);
|
|
32
|
+
return age > 0 && age < 130 ? age : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// estado_general writes day-first dates; the two halves are indistinguishable above 12.
|
|
36
|
+
function birthDateFrom(fechaNacimiento) {
|
|
37
|
+
const match = String(fechaNacimiento ?? '').trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
|
|
38
|
+
if (!match) return null;
|
|
39
|
+
const [, day, month, year] = match.map(Number);
|
|
40
|
+
if (year < 1900) return null;
|
|
41
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
42
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;
|
|
43
|
+
if (date.getTime() > Date.now()) return null;
|
|
44
|
+
return date.toISOString().slice(0, 10);
|
|
45
|
+
}
|
|
3
46
|
|
|
4
47
|
class Patient {
|
|
5
48
|
constructor(payload) {
|
|
6
49
|
Object.assign(this, payload);
|
|
7
50
|
}
|
|
8
51
|
|
|
9
|
-
static
|
|
10
|
-
|
|
52
|
+
static fromClinicalProfile({ patientId, profile = null }) {
|
|
53
|
+
if (!String(patientId ?? '').trim()) throw new Error('Patient requires a patientId');
|
|
54
|
+
const payload = {
|
|
11
55
|
resourceType: 'Patient',
|
|
12
56
|
id: fhirId(String(patientId)),
|
|
13
|
-
identifier: [identifier(
|
|
14
|
-
}
|
|
57
|
+
identifier: [identifier(PATIENT_SLUG, String(patientId))],
|
|
58
|
+
};
|
|
59
|
+
const gender = genderFrom(profile?.demografia?.sexo);
|
|
60
|
+
if (gender) payload.gender = gender;
|
|
61
|
+
const birthDate = birthDateFrom(profile?.demografia?.fecha_nacimiento);
|
|
62
|
+
if (birthDate) payload.birthDate = birthDate;
|
|
63
|
+
const age = ageFrom(profile?.demografia?.edad);
|
|
64
|
+
if (!birthDate && age) payload.extension = [extension(PATIENT_EXT.AGE, { valueInteger: age })];
|
|
65
|
+
return new Patient(payload);
|
|
15
66
|
}
|
|
16
67
|
}
|
|
17
68
|
|
|
18
|
-
module.exports = { Patient };
|
|
69
|
+
module.exports = { Patient, genderFrom, ageFrom };
|
|
@@ -1,27 +1,63 @@
|
|
|
1
1
|
const { getDeviceId, getOrganizationId } = require('../config/fhirConfig');
|
|
2
2
|
const { fhirId } = require('../helpers/fhirHelper');
|
|
3
|
-
const {
|
|
3
|
+
const { reference, codeableConcept, toIso } = require('../helpers/elementHelper');
|
|
4
4
|
|
|
5
5
|
class Provenance {
|
|
6
6
|
constructor(payload) {
|
|
7
7
|
Object.assign(this, payload);
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
static
|
|
11
|
-
|
|
10
|
+
static fromDispatchedEscalation({ target, recordedAt, activityText }) {
|
|
11
|
+
return new Provenance({
|
|
12
12
|
resourceType: 'Provenance',
|
|
13
|
-
id: fhirId(`${
|
|
13
|
+
id: fhirId(`${target.id}-prov`),
|
|
14
14
|
target: [{ reference: `${target.resourceType}/${target.id}` }],
|
|
15
|
-
recorded:
|
|
15
|
+
recorded: toIso(recordedAt),
|
|
16
16
|
agent: [{ who: reference('Device', getDeviceId()), onBehalfOf: reference('Organization', getOrganizationId()) }],
|
|
17
17
|
activity: codeableConcept(activityText),
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
static fromSymptomCase({ provenanceId, targetRefs, recordedAt, activityText }) {
|
|
22
|
+
return new Provenance({
|
|
23
|
+
resourceType: 'Provenance',
|
|
24
|
+
id: fhirId(provenanceId),
|
|
25
|
+
target: targetRefs,
|
|
26
|
+
recorded: toIso(recordedAt),
|
|
27
|
+
agent: [{ who: reference('Device', getDeviceId()), onBehalfOf: reference('Organization', getOrganizationId()) }],
|
|
28
|
+
activity: codeableConcept(activityText),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static fromPatientRisk({ assessment }) {
|
|
33
|
+
return new Provenance({
|
|
34
|
+
resourceType: 'Provenance',
|
|
35
|
+
id: fhirId(`${assessment.assessmentId}-prov`),
|
|
36
|
+
target: [{ reference: `RiskAssessment/${fhirId(assessment.assessmentId)}` }],
|
|
37
|
+
recorded: toIso(assessment.assessedAt),
|
|
38
|
+
agent: [{ who: reference('Device', getDeviceId()), onBehalfOf: reference('Organization', getOrganizationId()) }],
|
|
39
|
+
activity: codeableConcept('patient-risk-assessment'),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static fromSafetyGate({ gate }) {
|
|
44
|
+
return Provenance.fromSymptomCase({
|
|
45
|
+
provenanceId: `${gate.runId}-safety-prov`,
|
|
46
|
+
targetRefs: [{ reference: `RiskAssessment/${fhirId(`${gate.runId}-safety`)}` }],
|
|
47
|
+
recordedAt: gate.createdAt,
|
|
48
|
+
activityText: 'recommendation-safety-gate',
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static fromResultObservations({ targetIds, provenanceId, activityText, now }) {
|
|
53
|
+
return new Provenance({
|
|
54
|
+
resourceType: 'Provenance',
|
|
55
|
+
id: fhirId(provenanceId),
|
|
56
|
+
target: targetIds.map((id) => ({ reference: `Observation/${fhirId(id)}` })),
|
|
57
|
+
recorded: now,
|
|
58
|
+
agent: [{ who: reference('Device', getDeviceId()), onBehalfOf: reference('Organization', getOrganizationId()) }],
|
|
59
|
+
activity: codeableConcept(activityText),
|
|
60
|
+
});
|
|
25
61
|
}
|
|
26
62
|
}
|
|
27
63
|
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
2
|
+
const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
|
|
3
|
+
const {
|
|
4
|
+
identifier,
|
|
5
|
+
patientReference,
|
|
6
|
+
reference,
|
|
7
|
+
codeableConcept,
|
|
8
|
+
extension,
|
|
9
|
+
toIso,
|
|
10
|
+
} = require('../helpers/elementHelper');
|
|
11
|
+
const { PATIENT_RISK_SLUG, SAFETY_GATE_SLUG } = require('../constants/projectionSlugs');
|
|
12
|
+
const { RISK_EXT, SAFETY_GATE_EXT } = require('../constants/extensionSlugs');
|
|
13
|
+
|
|
14
|
+
const RISK_SEVERITY_CODESYSTEM = 'risk-severity';
|
|
15
|
+
const PREDICTION_KIND_AE = 'ae';
|
|
16
|
+
const PREDICTION_KIND_DISEASE = 'disease';
|
|
17
|
+
const PREDICTION_KIND_COMORBIDITY = 'comorbidity';
|
|
18
|
+
|
|
19
|
+
const PROBABILITY_TO_RISK = { high: 'high', medium: 'moderate', low: 'low' };
|
|
20
|
+
const PREDICTION_BASIS_STATUSES = ['confirmed', 'partially_confirmed'];
|
|
21
|
+
|
|
22
|
+
function safetyGatePrediction(ae) {
|
|
23
|
+
const risk = PROBABILITY_TO_RISK[ae.probabilityGivenPatient] || ae.probabilityGivenPatient;
|
|
24
|
+
const prediction = {
|
|
25
|
+
outcome: codeableConcept(ae.ctcaeTerm),
|
|
26
|
+
qualitativeRisk: codeableConcept(risk, { code: risk, system: codeSystemUrl(RISK_SEVERITY_CODESYSTEM) }),
|
|
27
|
+
};
|
|
28
|
+
const rationaleBits = [];
|
|
29
|
+
if (ae.whyIsRelevant) rationaleBits.push(ae.whyIsRelevant);
|
|
30
|
+
const grounding = ae.groundedIn.filter(Boolean).join('; ');
|
|
31
|
+
if (grounding) rationaleBits.push(`sustento: ${grounding}`);
|
|
32
|
+
if (rationaleBits.length) prediction.rationale = rationaleBits.join(' | ');
|
|
33
|
+
return prediction;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const isPresent = (value) => value !== null && value !== undefined;
|
|
37
|
+
|
|
38
|
+
function safetyGateExtensions(gate) {
|
|
39
|
+
const out = [
|
|
40
|
+
extension(SAFETY_GATE_EXT.URGENT_UNDER_24H, { valueBoolean: Boolean(gate.urgentUnder24h) }),
|
|
41
|
+
];
|
|
42
|
+
if (isPresent(gate.maxActionTimeHours)) {
|
|
43
|
+
out.push(extension(SAFETY_GATE_EXT.MAX_ACTION_TIME_HOURS, { valueInteger: gate.maxActionTimeHours }));
|
|
44
|
+
}
|
|
45
|
+
if (isPresent(gate.escalationRoute)) {
|
|
46
|
+
out.push(extension(SAFETY_GATE_EXT.ESCALATION_ROUTE, { valueString: gate.escalationRoute }));
|
|
47
|
+
}
|
|
48
|
+
if (isPresent(gate.reasonForEscalation)) {
|
|
49
|
+
out.push(extension(SAFETY_GATE_EXT.REASON_FOR_ESCALATION, { valueString: gate.reasonForEscalation }));
|
|
50
|
+
}
|
|
51
|
+
for (const redFlag of gate.redFlags || []) {
|
|
52
|
+
out.push(extension(SAFETY_GATE_EXT.RED_FLAG, { valueString: JSON.stringify(redFlag) }));
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function aePrediction(ae) {
|
|
58
|
+
const prediction = {
|
|
59
|
+
outcome: codeableConcept(ae.aeName),
|
|
60
|
+
qualitativeRisk: codeableConcept(ae.severityIfConfirmed, {
|
|
61
|
+
code: ae.severityIfConfirmed,
|
|
62
|
+
system: codeSystemUrl(RISK_SEVERITY_CODESYSTEM),
|
|
63
|
+
}),
|
|
64
|
+
extension: [extension(RISK_EXT.PREDICTION_KIND, { valueString: PREDICTION_KIND_AE })],
|
|
65
|
+
};
|
|
66
|
+
if (ae.why) prediction.rationale = ae.why;
|
|
67
|
+
for (const term of ae.relatedSymptomTerms) {
|
|
68
|
+
prediction.extension.push(extension(RISK_EXT.RELATED_SYMPTOM_TERM, { valueString: term }));
|
|
69
|
+
}
|
|
70
|
+
for (const symptom of ae.minimumSymptomSet) {
|
|
71
|
+
prediction.extension.push(extension(RISK_EXT.MINIMUM_SYMPTOM_SET, { valueString: symptom }));
|
|
72
|
+
}
|
|
73
|
+
return prediction;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function diseasePrediction(risk) {
|
|
77
|
+
const prediction = {
|
|
78
|
+
outcome: codeableConcept(risk.bodySite),
|
|
79
|
+
extension: [extension(RISK_EXT.PREDICTION_KIND, { valueString: PREDICTION_KIND_DISEASE })],
|
|
80
|
+
};
|
|
81
|
+
for (const complication of risk.complications) {
|
|
82
|
+
prediction.extension.push(extension(RISK_EXT.DISEASE_COMPLICATION, { valueString: complication }));
|
|
83
|
+
}
|
|
84
|
+
for (const symptom of risk.warningSymptoms) {
|
|
85
|
+
prediction.extension.push(extension(RISK_EXT.DISEASE_WARNING_SYMPTOM, { valueString: symptom }));
|
|
86
|
+
}
|
|
87
|
+
for (const term of risk.relatedSymptomTerms) {
|
|
88
|
+
prediction.extension.push(extension(RISK_EXT.RELATED_SYMPTOM_TERM, { valueString: term }));
|
|
89
|
+
}
|
|
90
|
+
for (const comorbidity of risk.amplifierComorbidities) {
|
|
91
|
+
prediction.extension.push(extension(RISK_EXT.DISEASE_AMPLIFIER, { valueString: comorbidity }));
|
|
92
|
+
}
|
|
93
|
+
return prediction;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function comorbidityPrediction(amplifier) {
|
|
97
|
+
const prediction = {
|
|
98
|
+
outcome: codeableConcept(amplifier.comorbidity),
|
|
99
|
+
rationale: amplifier.interaction,
|
|
100
|
+
extension: [extension(RISK_EXT.PREDICTION_KIND, { valueString: PREDICTION_KIND_COMORBIDITY })],
|
|
101
|
+
};
|
|
102
|
+
if (amplifier.clinicalNote) {
|
|
103
|
+
prediction.extension.push(extension(RISK_EXT.COMORBIDITY_CLINICAL_NOTE, { valueString: amplifier.clinicalNote }));
|
|
104
|
+
}
|
|
105
|
+
return prediction;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
class RiskAssessment {
|
|
109
|
+
constructor(payload) {
|
|
110
|
+
Object.assign(this, payload);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
static fromPatientRisk({ assessment }) {
|
|
114
|
+
const payload = {
|
|
115
|
+
resourceType: 'RiskAssessment',
|
|
116
|
+
id: fhirId(assessment.assessmentId),
|
|
117
|
+
identifier: [identifier(PATIENT_RISK_SLUG, assessment.assessmentId)],
|
|
118
|
+
status: assessment.status,
|
|
119
|
+
subject: patientReference(assessment.patientId),
|
|
120
|
+
performer: reference('Device', getDeviceId()),
|
|
121
|
+
occurrenceDateTime: toIso(assessment.assessedAt),
|
|
122
|
+
};
|
|
123
|
+
const prediction = [
|
|
124
|
+
...assessment.predictedAes.map(aePrediction),
|
|
125
|
+
...assessment.diseaseRisks.map(diseasePrediction),
|
|
126
|
+
...assessment.comorbidityAmplifiers.map(comorbidityPrediction),
|
|
127
|
+
];
|
|
128
|
+
if (prediction.length) payload.prediction = prediction;
|
|
129
|
+
const extensions = [];
|
|
130
|
+
if (assessment.sourceRegimen) extensions.push(extension(RISK_EXT.SOURCE_REGIMEN, { valueString: assessment.sourceRegimen }));
|
|
131
|
+
if (assessment.sourceDiagnosis) extensions.push(extension(RISK_EXT.SOURCE_DIAGNOSIS, { valueString: assessment.sourceDiagnosis }));
|
|
132
|
+
if (assessment.sourcePhase) extensions.push(extension(RISK_EXT.SOURCE_PHASE, { valueString: assessment.sourcePhase }));
|
|
133
|
+
if (assessment.assessedByModel) extensions.push(extension(RISK_EXT.ASSESSED_BY_MODEL, { valueString: assessment.assessedByModel }));
|
|
134
|
+
if (assessment.derivedFrom) extensions.push(extension(RISK_EXT.PREVIOUS_ASSESSMENT, { valueString: assessment.derivedFrom }));
|
|
135
|
+
if (assessment.validUntil) extensions.push(extension(RISK_EXT.VALID_UNTIL, { valueString: toIso(assessment.validUntil) }));
|
|
136
|
+
if (assessment.sourceDataCutoff) extensions.push(extension(RISK_EXT.SOURCE_DATA_CUTOFF, { valueString: toIso(assessment.sourceDataCutoff) }));
|
|
137
|
+
if (assessment.assessmentTrigger) extensions.push(extension(RISK_EXT.ASSESSMENT_TRIGGER, { valueString: assessment.assessmentTrigger }));
|
|
138
|
+
if (assessment.methodVersion) extensions.push(extension(RISK_EXT.METHOD_VERSION, { valueString: assessment.methodVersion }));
|
|
139
|
+
for (const item of assessment.missingInformation || []) {
|
|
140
|
+
extensions.push(extension(RISK_EXT.MISSING_INFORMATION, { valueString: item }));
|
|
141
|
+
}
|
|
142
|
+
if (assessment.changeFromPrevious) {
|
|
143
|
+
const change = assessment.changeFromPrevious;
|
|
144
|
+
extensions.push(extension(RISK_EXT.CHANGE_TYPE, { valueString: change.changeType }));
|
|
145
|
+
extensions.push(extension(RISK_EXT.CHANGE_DIRECTION, { valueString: change.direction }));
|
|
146
|
+
extensions.push(extension(RISK_EXT.CHANGE_MATERIAL, { valueString: String(change.materialChange) }));
|
|
147
|
+
for (const reason of change.reasonsForChange) extensions.push(extension(RISK_EXT.CHANGE_REASON, { valueString: reason }));
|
|
148
|
+
for (const item of change.newInformation) extensions.push(extension(RISK_EXT.CHANGE_NEW_INFO, { valueString: item }));
|
|
149
|
+
for (const item of change.resolvedInformation) extensions.push(extension(RISK_EXT.CHANGE_RESOLVED_INFO, { valueString: item }));
|
|
150
|
+
}
|
|
151
|
+
if (extensions.length) payload.extension = extensions;
|
|
152
|
+
return new RiskAssessment(payload);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
static fromSafetyGate({ gate }) {
|
|
156
|
+
const payload = {
|
|
157
|
+
resourceType: 'RiskAssessment',
|
|
158
|
+
id: fhirId(`${gate.runId}-safety`),
|
|
159
|
+
identifier: [identifier(SAFETY_GATE_SLUG, `${gate.runId}-safety`)],
|
|
160
|
+
status: 'final',
|
|
161
|
+
subject: patientReference(gate.patientId),
|
|
162
|
+
performer: reference('Device', getDeviceId()),
|
|
163
|
+
occurrenceDateTime: toIso(gate.createdAt),
|
|
164
|
+
};
|
|
165
|
+
const prediction = gate.redFlags
|
|
166
|
+
.filter((redFlag) => PREDICTION_BASIS_STATUSES.includes(redFlag.verificationStatus))
|
|
167
|
+
.flatMap((redFlag) => redFlag.relatedAes.map(safetyGatePrediction));
|
|
168
|
+
if (prediction.length) payload.prediction = prediction;
|
|
169
|
+
if (gate.summary) payload.note = [{ text: gate.summary }];
|
|
170
|
+
if (gate.urgentUnder24h && gate.escalationRoute) {
|
|
171
|
+
payload.mitigation = `ruta de escalamiento: ${gate.escalationRoute}`
|
|
172
|
+
+ (gate.maxActionTimeHours ? `; actuar en ≤${gate.maxActionTimeHours}h` : '');
|
|
173
|
+
}
|
|
174
|
+
payload.extension = safetyGateExtensions(gate);
|
|
175
|
+
return new RiskAssessment(payload);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
module.exports = {
|
|
180
|
+
RiskAssessment,
|
|
181
|
+
PREDICTION_KIND_AE,
|
|
182
|
+
PREDICTION_KIND_DISEASE,
|
|
183
|
+
PREDICTION_KIND_COMORBIDITY,
|
|
184
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
|
|
2
|
+
const {
|
|
3
|
+
identifier,
|
|
4
|
+
reference,
|
|
5
|
+
patientReference,
|
|
6
|
+
codeableConcept,
|
|
7
|
+
extension,
|
|
8
|
+
toIso,
|
|
9
|
+
} = require('../helpers/elementHelper');
|
|
10
|
+
const {
|
|
11
|
+
ESCALATION_SLUG,
|
|
12
|
+
ESCALATION_KIND_SLUG,
|
|
13
|
+
ESCALATION_CASE_SLUG,
|
|
14
|
+
ESCALATION_CASE_STATUS_SLUG,
|
|
15
|
+
ESCALATION_DECISION_SLUG,
|
|
16
|
+
SYMPTOM_CASE_SLUG,
|
|
17
|
+
} = require('../constants/projectionSlugs');
|
|
18
|
+
const { SEVERITY_TO_PRIORITY } = require('../constants/severityPriority');
|
|
19
|
+
const { caseStatusOf } = require('../constants/escalationCaseStatus');
|
|
20
|
+
|
|
21
|
+
const ESCALATION_CASE_CODE = 'escalation_case';
|
|
22
|
+
|
|
23
|
+
const TICKET_STATUS_TO_TASK_STATUS = {
|
|
24
|
+
queued: 'requested',
|
|
25
|
+
sent: 'requested',
|
|
26
|
+
acknowledged: 'in-progress',
|
|
27
|
+
failed: 'failed',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const CANCEL_REASON_CODES = ['no_requiere', 'paciente_fallecido'];
|
|
31
|
+
|
|
32
|
+
class Task {
|
|
33
|
+
constructor(payload) {
|
|
34
|
+
Object.assign(this, payload);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static fromTicketEscalation({ ticket, deviceId }) {
|
|
38
|
+
const payload = {
|
|
39
|
+
resourceType: 'Task',
|
|
40
|
+
id: fhirId(ticket.eventId),
|
|
41
|
+
identifier: [identifier(ESCALATION_SLUG, ticket.eventId)],
|
|
42
|
+
status: TICKET_STATUS_TO_TASK_STATUS[ticket.status],
|
|
43
|
+
intent: 'order',
|
|
44
|
+
priority: ticket.priority || SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
|
|
45
|
+
code: codeableConcept(ticket.kind, { code: ticket.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
|
|
46
|
+
for: patientReference(ticket.patientId),
|
|
47
|
+
authoredOn: toIso(ticket.createdAt),
|
|
48
|
+
requester: reference('Device', deviceId),
|
|
49
|
+
};
|
|
50
|
+
if (ticket.title) payload.description = ticket.title;
|
|
51
|
+
if (ticket.reason) payload.note = [{ text: ticket.reason }];
|
|
52
|
+
if (typeof ticket.slaMinutes === 'number' && ticket.slaMinutes > 0) {
|
|
53
|
+
const start = new Date(ticket.createdAt);
|
|
54
|
+
const end = new Date(start.getTime() + ticket.slaMinutes * 60000);
|
|
55
|
+
payload.restriction = { period: { start: toIso(start), end: toIso(end) } };
|
|
56
|
+
payload.extension = [extension('sla-budget-minutes', { valueInteger: ticket.slaMinutes })];
|
|
57
|
+
}
|
|
58
|
+
return new Task(payload);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The operational case of an escalation review; its symptoms are the Conditions in `reason`.
|
|
62
|
+
static fromEscalationReview({ review, priority, conditionIds = [], deviceId }) {
|
|
63
|
+
const reviewId = String(review._id);
|
|
64
|
+
const { status, businessStatus, label } = caseStatusOf(review.status);
|
|
65
|
+
const payload = {
|
|
66
|
+
resourceType: 'Task',
|
|
67
|
+
id: fhirId(`escalation-case-${reviewId}`),
|
|
68
|
+
identifier: [identifier(ESCALATION_CASE_SLUG, reviewId)],
|
|
69
|
+
status,
|
|
70
|
+
businessStatus: codeableConcept(label, { code: businessStatus, system: codeSystemUrl(ESCALATION_CASE_STATUS_SLUG), display: label }),
|
|
71
|
+
intent: 'order',
|
|
72
|
+
priority: priority || 'routine',
|
|
73
|
+
code: codeableConcept(ESCALATION_CASE_CODE, { code: ESCALATION_CASE_CODE, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
|
|
74
|
+
for: patientReference(review.patientCode),
|
|
75
|
+
authoredOn: toIso(review.createdAt),
|
|
76
|
+
lastModified: toIso(review.updatedAt),
|
|
77
|
+
requester: reference('Device', deviceId),
|
|
78
|
+
executionPeriod: { start: toIso(review.createdAt), ...(review.closedAt ? { end: toIso(review.closedAt) } : {}) },
|
|
79
|
+
};
|
|
80
|
+
if (conditionIds.length) {
|
|
81
|
+
payload.reason = conditionIds.map((id) => {
|
|
82
|
+
const symptom = { ...reference('Condition', id), type: 'Condition', identifier: identifier(SYMPTOM_CASE_SLUG, id) };
|
|
83
|
+
return { reference: symptom };
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
// Only a code reaches FHIR: the operator's cancellation note is free text.
|
|
87
|
+
if (review.status === 'cancelled') {
|
|
88
|
+
const reasonCode = CANCEL_REASON_CODES.find((code) => String(review.cancellationReason ?? '').startsWith(code)) ?? 'cancelado_por_equipo';
|
|
89
|
+
payload.statusReason = { concept: codeableConcept(reasonCode) };
|
|
90
|
+
}
|
|
91
|
+
const decision = review.decisions?.at(-1)?.decision;
|
|
92
|
+
if (decision) {
|
|
93
|
+
payload.output = [{
|
|
94
|
+
type: codeableConcept('decision'),
|
|
95
|
+
valueCodeableConcept: codeableConcept(decision, { code: decision, system: codeSystemUrl(ESCALATION_DECISION_SLUG) }),
|
|
96
|
+
}];
|
|
97
|
+
}
|
|
98
|
+
return new Task(payload);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { Task };
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
const { fhirId } = require('../helpers/fhirHelper');
|
|
2
|
+
const { compareClaims, isLiveConflict, weightOf } = require('../helpers/contextArbitrationHelper');
|
|
3
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
4
|
+
const { logger } = require('../../utils/logger');
|
|
5
|
+
const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
|
|
6
|
+
const { MAX_ALTERNATES } = require('../constants/variableRegistry');
|
|
7
|
+
const { CONTEXT_FACT_SLUG } = require('../constants/projectionSlugs');
|
|
8
|
+
const { getFhirStore } = require('../stores/fhirStore');
|
|
9
|
+
const {
|
|
10
|
+
CONTEXT_RESOURCE_TYPES,
|
|
11
|
+
toFhir,
|
|
12
|
+
fromFhir,
|
|
13
|
+
conceptKeyOf,
|
|
14
|
+
scopeOf,
|
|
15
|
+
claimOf,
|
|
16
|
+
alternatesOf,
|
|
17
|
+
withArbitration,
|
|
18
|
+
isContextFact,
|
|
19
|
+
variableEntry,
|
|
20
|
+
isSingleton,
|
|
21
|
+
contextKeyOf,
|
|
22
|
+
} = require('../projections/contextFactProjection');
|
|
23
|
+
const { ClinicalAssertion } = require('../../shared/dtos/ClinicalAssertion');
|
|
24
|
+
const { storeResources } = require('./fhirService');
|
|
25
|
+
|
|
26
|
+
const valueKey = (value) => foldAccents(String(value ?? '').trim().toLowerCase()).replace(/\s+/g, ' ');
|
|
27
|
+
|
|
28
|
+
function sameValue(a, b) {
|
|
29
|
+
return valueKey(a) === valueKey(b);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const laterOf = (a, b) => {
|
|
33
|
+
const [ta, tb] = [Date.parse(a), Date.parse(b)];
|
|
34
|
+
return Number.isFinite(ta) && Number.isFinite(tb) && tb > ta ? b : a;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function mergeContextFact(existing, incoming) {
|
|
38
|
+
if (!existing || !isContextFact(incoming)) return incoming;
|
|
39
|
+
const next = claimOf(incoming);
|
|
40
|
+
const prior = claimOf(existing);
|
|
41
|
+
const { variableId } = next;
|
|
42
|
+
const evaluatedAt = laterOf(next.recordTime, prior.recordTime);
|
|
43
|
+
const ordering = compareClaims(next, prior, variableId, evaluatedAt);
|
|
44
|
+
// An unreadable recordTime sorts oldest rather than poisoning the comparison: Date.parse returns
|
|
45
|
+
// NaN, every comparison against it is false, and the incumbent would win the tie forever. The
|
|
46
|
+
// projection stores timestamps through instantOrNull, so a null on the stored side is reachable.
|
|
47
|
+
const at = (claim) => { const t = Date.parse(claim?.recordTime); return Number.isFinite(t) ? t : -Infinity; };
|
|
48
|
+
const nextWins = ordering > 0 || (ordering === 0 && at(next) >= at(prior));
|
|
49
|
+
const winner = nextWins ? next : prior;
|
|
50
|
+
const loser = nextWins ? prior : next;
|
|
51
|
+
|
|
52
|
+
// Keyed by the claim, and the source read the way sourceRole reads it, or "Self" and " self "
|
|
53
|
+
// each consume a slot and one rival silently pushes another out.
|
|
54
|
+
const byClaim = new Map();
|
|
55
|
+
for (const alternate of [...alternatesOf(existing), loser]) {
|
|
56
|
+
if (!alternate.value || sameValue(alternate.value, winner.value)) continue;
|
|
57
|
+
const sourceKey = String(alternate.source ?? '').trim().toLowerCase();
|
|
58
|
+
if (!sourceKey) continue;
|
|
59
|
+
byClaim.set(JSON.stringify([sourceKey, valueKey(alternate.value)]), alternate);
|
|
60
|
+
}
|
|
61
|
+
const ranked = [...byClaim.values()]
|
|
62
|
+
.sort((a, b) => compareClaims(b, a, variableId, evaluatedAt));
|
|
63
|
+
|
|
64
|
+
// Decided over every rival before truncation: dropping a rival for space must not drop the flag.
|
|
65
|
+
const winnerWeight = Math.max(weightOf(winner, variableId, evaluatedAt), Number.MIN_VALUE);
|
|
66
|
+
const openConflict = ranked.some(
|
|
67
|
+
(alternate) => isLiveConflict(alternate, winner, { variableId, evaluatedAt, winnerWeight }),
|
|
68
|
+
);
|
|
69
|
+
if (ranked.length > MAX_ALTERNATES) {
|
|
70
|
+
logger.warn('[clinicalContext] Rivals dropped for space', {
|
|
71
|
+
variableId, kept: MAX_ALTERNATES, dropped: ranked.length - MAX_ALTERNATES,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return withArbitration(nextWins ? incoming : existing, winner, {
|
|
75
|
+
alternates: ranked.slice(0, MAX_ALTERNATES),
|
|
76
|
+
openConflict,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function assertStorable(claim, patientId) {
|
|
81
|
+
if (claim.patientId !== patientId) {
|
|
82
|
+
throw new Error(`storeContextFacts patientId mismatch: expected ${patientId}`);
|
|
83
|
+
}
|
|
84
|
+
if (!variableEntry(claim.variableId)) {
|
|
85
|
+
throw new Error(`storeContextFacts unknown context variable ${claim.variableId}`);
|
|
86
|
+
}
|
|
87
|
+
if (!isSingleton(claim.variableId) && !String(claim.concept ?? '').trim()) {
|
|
88
|
+
throw new Error(`storeContextFacts concept is required for the list-like variable ${claim.variableId}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function storeContextFacts({ patientId, assertions }) {
|
|
93
|
+
if (!String(patientId ?? '').trim()) throw new Error('storeContextFacts patientId is required');
|
|
94
|
+
if (!Array.isArray(assertions)) throw new Error('storeContextFacts assertions must be an array');
|
|
95
|
+
const claims = assertions.map((assertion) => new ClinicalAssertion(assertion));
|
|
96
|
+
const seen = new Set();
|
|
97
|
+
for (const claim of claims) {
|
|
98
|
+
assertStorable(claim, patientId);
|
|
99
|
+
const key = conceptKeyOf(claim);
|
|
100
|
+
if (seen.has(key)) throw new Error(`storeContextFacts duplicate concept in batch: ${key}`);
|
|
101
|
+
seen.add(key);
|
|
102
|
+
}
|
|
103
|
+
const { stored } = await storeResources(claims.flatMap((claim) => toFhir(claim)), { merge: mergeContextFact });
|
|
104
|
+
return { count: stored.length, ids: stored };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The Provenance is left in place, so the store still answers what was written and when it went.
|
|
108
|
+
async function retractContextFacts({ patientId, conceptKeys }) {
|
|
109
|
+
const scope = String(patientId ?? '').trim();
|
|
110
|
+
if (!scope) throw new Error('retractContextFacts patientId is required');
|
|
111
|
+
if (!Array.isArray(conceptKeys)) throw new Error('retractContextFacts conceptKeys must be an array');
|
|
112
|
+
const foreign = conceptKeys.find((key) => scopeOf(key) !== scope);
|
|
113
|
+
if (foreign) throw new Error(`retractContextFacts conceptKey outside the patient scope: ${foreign}`);
|
|
114
|
+
if (!conceptKeys.length) return { count: 0, keys: [] };
|
|
115
|
+
|
|
116
|
+
const store = getFhirStore();
|
|
117
|
+
const wanted = new Set(conceptKeys);
|
|
118
|
+
const patient = `Patient/${fhirId(scope)}`;
|
|
119
|
+
const found = await Promise.all(CONTEXT_RESOURCE_TYPES.map(
|
|
120
|
+
(resourceType) => store.find({ patient, resourceType, identifierSlug: CONTEXT_FACT_SLUG }),
|
|
121
|
+
));
|
|
122
|
+
const keys = [];
|
|
123
|
+
for (const resource of found.flat()) {
|
|
124
|
+
const conceptKey = contextKeyOf(resource);
|
|
125
|
+
if (!wanted.has(conceptKey)) continue;
|
|
126
|
+
await store.delete(store.resourceKeyFor(resource));
|
|
127
|
+
keys.push(conceptKey);
|
|
128
|
+
}
|
|
129
|
+
return { count: keys.length, keys };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function listContextFactPatients() {
|
|
133
|
+
const store = getFhirStore();
|
|
134
|
+
const found = await Promise.all(CONTEXT_RESOURCE_TYPES.map(
|
|
135
|
+
(resourceType) => store.find({ resourceType, identifierSlug: CONTEXT_FACT_SLUG }),
|
|
136
|
+
));
|
|
137
|
+
const scopes = found.flat().map((resource) => scopeOf(contextKeyOf(resource))).filter(Boolean);
|
|
138
|
+
return [...new Set(scopes)];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function readContextFacts({ patientId }) {
|
|
142
|
+
const scope = String(patientId ?? '').trim();
|
|
143
|
+
if (!scope) throw new Error('readContextFacts patientId is required');
|
|
144
|
+
const store = getFhirStore();
|
|
145
|
+
const patient = `Patient/${fhirId(scope)}`;
|
|
146
|
+
const found = await Promise.all(CONTEXT_RESOURCE_TYPES.map(
|
|
147
|
+
(resourceType) => store.find({ patient, resourceType, identifierSlug: CONTEXT_FACT_SLUG }),
|
|
148
|
+
));
|
|
149
|
+
const rows = fromFhir(found.flat());
|
|
150
|
+
const mine = rows.filter((row) => scopeOf(row.conceptKey) === scope);
|
|
151
|
+
if (mine.length !== rows.length) {
|
|
152
|
+
logger.error('[clinicalContext] Facts scoped to another patient were dropped before rendering', {
|
|
153
|
+
patientId: maskSensitiveValue(scope), dropped: rows.length - mine.length, kept: mine.length,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return mine;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = {
|
|
160
|
+
storeContextFacts, readContextFacts, retractContextFacts, listContextFactPatients,
|
|
161
|
+
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const {
|
|
2
|
-
const {
|
|
1
|
+
const { toFhir } = require('../projections/clinicalMentionProjection');
|
|
2
|
+
const { storeResources } = require('./fhirService');
|
|
3
3
|
|
|
4
4
|
async function storeClinicalMentions({ patientId, mentions }) {
|
|
5
5
|
for (const mention of mentions) {
|
|
@@ -7,9 +7,7 @@ async function storeClinicalMentions({ patientId, mentions }) {
|
|
|
7
7
|
throw new Error(`storeClinicalMentions patientId mismatch: expected ${patientId}`);
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
const
|
|
11
|
-
const resources = bundle.entry.map((entry) => entry.resource);
|
|
12
|
-
const { stored } = await storeResources(resources);
|
|
10
|
+
const { stored } = await storeResources(mentions.flatMap(toFhir));
|
|
13
11
|
return { stored: stored.length, ids: stored, patientId };
|
|
14
12
|
}
|
|
15
13
|
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { fhirId } = require('../helpers/fhirHelper');
|
|
2
|
+
const { CLUSTER_IMPRESSION_SLUG } = require('../constants/projectionSlugs');
|
|
3
|
+
const { getFhirStore } = require('../stores/fhirStore');
|
|
4
|
+
const { toFhir, fromFhir } = require('../projections/clusterProjection');
|
|
5
|
+
const { storeResources } = require('./fhirService');
|
|
6
|
+
|
|
7
|
+
async function storeCluster({ patientId, cluster, history = [] }) {
|
|
8
|
+
if (cluster.patientId !== patientId) {
|
|
9
|
+
throw new Error(`storeCluster patientId mismatch: expected ${patientId}`);
|
|
10
|
+
}
|
|
11
|
+
const { stored } = await storeResources(toFhir({ cluster, history }));
|
|
12
|
+
return { count: stored.length, ids: stored };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function readClusters({ patientId, label = null, status = null }) {
|
|
16
|
+
const store = getFhirStore();
|
|
17
|
+
const patient = `Patient/${fhirId(patientId)}`;
|
|
18
|
+
const resources = await store.find({
|
|
19
|
+
patient,
|
|
20
|
+
resourceType: 'ClinicalImpression',
|
|
21
|
+
identifierSlug: CLUSTER_IMPRESSION_SLUG,
|
|
22
|
+
});
|
|
23
|
+
return fromFhir(resources, { patientId })
|
|
24
|
+
.filter((cluster) => (!label || cluster.label === label) && (!status || cluster.status === status));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = {
|
|
28
|
+
storeCluster,
|
|
29
|
+
readClusters,
|
|
30
|
+
};
|