@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
package/lib/fhir/index.js
CHANGED
|
@@ -1,15 +1,49 @@
|
|
|
1
1
|
const { registerProjector, project, storeResources } = require('./services/fhirService');
|
|
2
2
|
const { storeClinicalMentions } = require('./services/clinicalMentionService');
|
|
3
|
+
const { storeResultObservations } = require('./services/resultObservationService');
|
|
4
|
+
const { storeSymptomCase, readSymptomCases } = require('./services/symptomCaseService');
|
|
5
|
+
const {
|
|
6
|
+
storePatientRisk, readPatientRiskAssessments, deletePatientRisk,
|
|
7
|
+
storeSafetyGate, safetyGateExists, readSafetyGate, readSafetyGates,
|
|
8
|
+
} = require('./services/riskService');
|
|
9
|
+
const {
|
|
10
|
+
storeRecommendationPlan,
|
|
11
|
+
recommendationPlanExists,
|
|
12
|
+
readActiveRecommendations,
|
|
13
|
+
readRecommendationPlans,
|
|
14
|
+
recordRecommendationOutcome,
|
|
15
|
+
recordRecommendationReview,
|
|
16
|
+
} = require('./services/recommendationService');
|
|
17
|
+
const { storeContingency, readContingencies } = require('./services/contingencyService');
|
|
18
|
+
const { readDispatchedEscalations, readEscalationCases, storeEscalationCase } = require('./services/escalationService');
|
|
19
|
+
const { storeIntervention, readInterventions } = require('./services/interventionService');
|
|
20
|
+
const { storeCluster, readClusters } = require('./services/clusterService');
|
|
21
|
+
const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
|
|
22
|
+
const {
|
|
23
|
+
storePalliativeAssessment,
|
|
24
|
+
readPalliativeAssessments,
|
|
25
|
+
storePalliativeCarePlan,
|
|
26
|
+
readPalliativeCarePlans,
|
|
27
|
+
} = require('./services/palliativeService');
|
|
3
28
|
const { storeTriage } = require('./services/triageService');
|
|
29
|
+
const { storePatient, storePatientDeceased, readPatient } = require('./services/patientService');
|
|
30
|
+
const { storeHospitalization, readHospitalization } = require('./services/encounterService');
|
|
31
|
+
const {
|
|
32
|
+
storeContextFacts, readContextFacts, retractContextFacts, listContextFactPatients,
|
|
33
|
+
} = require('./services/clinicalContextService');
|
|
4
34
|
const { patientSnapshot } = require('./services/snapshotService');
|
|
5
35
|
const { registerAllProjectors } = require('./projections/registerProjectors');
|
|
6
36
|
const { getFhirStore, ensureFhirIndexes } = require('./stores/fhirStore');
|
|
7
37
|
const fhirConfig = require('./config/fhirConfig');
|
|
38
|
+
const catalogConfig = require('./config/catalogConfig');
|
|
39
|
+
const terminologyService = require('./services/terminologyService');
|
|
8
40
|
|
|
9
41
|
async function initialize() {
|
|
10
42
|
registerAllProjectors();
|
|
11
43
|
await fhirConfig.initialize();
|
|
44
|
+
await catalogConfig.initialize();
|
|
12
45
|
await ensureFhirIndexes();
|
|
46
|
+
await terminologyService.initialize();
|
|
13
47
|
}
|
|
14
48
|
|
|
15
49
|
module.exports = {
|
|
@@ -18,7 +52,48 @@ module.exports = {
|
|
|
18
52
|
project,
|
|
19
53
|
storeResources,
|
|
20
54
|
storeClinicalMentions,
|
|
55
|
+
storeResultObservations,
|
|
56
|
+
storeSymptomCase,
|
|
57
|
+
readSymptomCases,
|
|
58
|
+
storePatientRisk,
|
|
59
|
+
readPatientRiskAssessments,
|
|
60
|
+
deletePatientRisk,
|
|
61
|
+
storeSafetyGate,
|
|
62
|
+
safetyGateExists,
|
|
63
|
+
readSafetyGate,
|
|
64
|
+
readSafetyGates,
|
|
65
|
+
storeRecommendationPlan,
|
|
66
|
+
recommendationPlanExists,
|
|
67
|
+
readActiveRecommendations,
|
|
68
|
+
readRecommendationPlans,
|
|
69
|
+
recordRecommendationOutcome,
|
|
70
|
+
recordRecommendationReview,
|
|
71
|
+
storeContingency,
|
|
72
|
+
readContingencies,
|
|
73
|
+
readDispatchedEscalations,
|
|
74
|
+
storeEscalationCase,
|
|
75
|
+
readEscalationCases,
|
|
76
|
+
storeIntervention,
|
|
77
|
+
readInterventions,
|
|
78
|
+
storeCluster,
|
|
79
|
+
readClusters,
|
|
80
|
+
closeRoutingDispositions,
|
|
81
|
+
storeRoutingDecision,
|
|
82
|
+
readRoutingDecisions,
|
|
83
|
+
storePalliativeAssessment,
|
|
84
|
+
readPalliativeAssessments,
|
|
85
|
+
storePalliativeCarePlan,
|
|
86
|
+
readPalliativeCarePlans,
|
|
21
87
|
storeTriage,
|
|
88
|
+
storePatient,
|
|
89
|
+
storePatientDeceased,
|
|
90
|
+
storeHospitalization,
|
|
91
|
+
readHospitalization,
|
|
92
|
+
readPatient,
|
|
93
|
+
storeContextFacts,
|
|
94
|
+
readContextFacts,
|
|
95
|
+
retractContextFacts,
|
|
96
|
+
listContextFactPatients,
|
|
22
97
|
patientSnapshot,
|
|
23
98
|
getFhirStore,
|
|
24
99
|
ensureFhirIndexes,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const mongoose = require('mongoose');
|
|
2
2
|
|
|
3
3
|
const SYMPTOM_SYSTEM_SUFFIX = '/pro-ctcae';
|
|
4
|
+
const TURN_ID_EXT_SUFFIX = '-turn-id';
|
|
4
5
|
|
|
5
6
|
const envelopeSchema = new mongoose.Schema(
|
|
6
7
|
{
|
|
@@ -11,6 +12,7 @@ const envelopeSchema = new mongoose.Schema(
|
|
|
11
12
|
date: { type: Date, default: null },
|
|
12
13
|
reference: { type: String, default: null },
|
|
13
14
|
symptomTerm: { type: String, default: null },
|
|
15
|
+
turnId: { type: String, default: null },
|
|
14
16
|
},
|
|
15
17
|
resource: { type: mongoose.Schema.Types.Mixed, required: true },
|
|
16
18
|
meta: {
|
|
@@ -23,6 +25,14 @@ const envelopeSchema = new mongoose.Schema(
|
|
|
23
25
|
|
|
24
26
|
envelopeSchema.index({ 'index.patient': 1, 'index.date': -1 });
|
|
25
27
|
envelopeSchema.index({ 'index.patient': 1, 'index.symptomTerm': 1, 'index.date': -1 });
|
|
28
|
+
envelopeSchema.index(
|
|
29
|
+
{ 'index.patient': 1, 'resource.identifier.system': 1, 'index.date': -1 },
|
|
30
|
+
{ partialFilterExpression: { 'meta.deleted': false } },
|
|
31
|
+
);
|
|
32
|
+
envelopeSchema.index(
|
|
33
|
+
{ 'index.patient': 1, 'index.turnId': 1, 'index.date': -1 },
|
|
34
|
+
{ partialFilterExpression: { 'meta.deleted': false, 'index.turnId': { $type: 'string' } } },
|
|
35
|
+
);
|
|
26
36
|
envelopeSchema.index({ 'index.reference': 1 }, { partialFilterExpression: { 'index.reference': { $type: 'string' } } });
|
|
27
37
|
envelopeSchema.index({ 'resource.status': 1 }, { sparse: true });
|
|
28
38
|
|
|
@@ -50,11 +60,13 @@ envelopeSchema.statics.deriveIndex = function deriveIndex(resource) {
|
|
|
50
60
|
resource.recordedDate ||
|
|
51
61
|
resource.onsetDateTime ||
|
|
52
62
|
resource.occurrenceDateTime ||
|
|
63
|
+
resource.sent ||
|
|
53
64
|
resource.start ||
|
|
54
65
|
(resource.effectivePeriod || {}).start ||
|
|
55
66
|
(resource.period || {}).start ||
|
|
56
67
|
(resource.actualPeriod || {}).start ||
|
|
57
68
|
((resource.requestedPeriod || [])[0] || {}).start ||
|
|
69
|
+
resource.created ||
|
|
58
70
|
null;
|
|
59
71
|
return {
|
|
60
72
|
resourceType: resource.resourceType || null,
|
|
@@ -62,6 +74,7 @@ envelopeSchema.statics.deriveIndex = function deriveIndex(resource) {
|
|
|
62
74
|
date: instantOf(date),
|
|
63
75
|
reference: resource.resourceType && resource.id ? `${resource.resourceType}/${resource.id}` : null,
|
|
64
76
|
symptomTerm: symptomTermOf(resource),
|
|
77
|
+
turnId: turnIdOf(resource),
|
|
65
78
|
};
|
|
66
79
|
};
|
|
67
80
|
|
|
@@ -88,6 +101,14 @@ function symptomTermOf(resource) {
|
|
|
88
101
|
return null;
|
|
89
102
|
}
|
|
90
103
|
|
|
104
|
+
function turnIdOf(resource) {
|
|
105
|
+
for (const ext of resource.extension || []) {
|
|
106
|
+
const url = (ext || {}).url;
|
|
107
|
+
if (typeof url === 'string' && url.endsWith(TURN_ID_EXT_SUFFIX)) return ext.valueString || null;
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
91
112
|
function businessIdentifier(resource) {
|
|
92
113
|
for (const identifier of resource.identifier || []) {
|
|
93
114
|
const system = (identifier || {}).system;
|
|
@@ -122,6 +143,7 @@ function patientReferenceOf(resource) {
|
|
|
122
143
|
return (
|
|
123
144
|
patientRef(resource.subject) ||
|
|
124
145
|
patientRef(resource.patient) ||
|
|
146
|
+
patientRef(resource.for) ||
|
|
125
147
|
patientRef(resource.performer) ||
|
|
126
148
|
participantRef()
|
|
127
149
|
);
|
|
@@ -1,65 +1,227 @@
|
|
|
1
|
-
const { getSystems } = require('../config/fhirConfig');
|
|
2
|
-
const {
|
|
1
|
+
const { getDeviceId, getOrganizationId, getSystems } = require('../config/fhirConfig');
|
|
2
|
+
const { stringifyValue } = require('../utils/normalizeUtils');
|
|
3
|
+
const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
|
|
4
|
+
const { ctcaeSlug } = require('../helpers/terminologyHelper');
|
|
5
|
+
const { reference, patientReference, codeableConcept, extension, toInstant } = require('../helpers/elementHelper');
|
|
6
|
+
const { baseResource, problemListCategory, observationCategory } = require('../helpers/resourceHelper');
|
|
3
7
|
const { MENTION_SLUG } = require('../constants/projectionSlugs');
|
|
4
|
-
const {
|
|
5
|
-
const {
|
|
6
|
-
|
|
7
|
-
const { Procedure } = require('../resources/Procedure');
|
|
8
|
-
const { Appointment } = require('../resources/Appointment');
|
|
9
|
-
const { Provenance } = require('../resources/Provenance');
|
|
10
|
-
|
|
11
|
-
const PROJECTOR_NAME = 'clinicalMention';
|
|
8
|
+
const { MENTION_EXT } = require('../constants/extensionSlugs');
|
|
9
|
+
const { PROCEDURE_STATUS, statusFrom } = require('./contextFactProjection');
|
|
10
|
+
|
|
12
11
|
const ACTIVITY_TEXT = 'clinical-mention-extraction';
|
|
12
|
+
const OBSERVED_FIELD_SYSTEM_KEY = 'observedField';
|
|
13
13
|
|
|
14
14
|
const DEDICATED_AGGREGATE = new Set(['comorbidity', 'allergy', 'performance_status']);
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
const CATEGORY_TO_OBSERVATION_CATEGORY = {
|
|
17
|
+
symptom: 'survey',
|
|
18
|
+
lab_value: 'laboratory',
|
|
19
|
+
emotion: 'survey',
|
|
20
|
+
indication: 'exam',
|
|
21
|
+
diagnosis: 'exam',
|
|
22
|
+
};
|
|
18
23
|
|
|
24
|
+
const DIAGNOSIS_CATEGORIES = new Set(['diagnosis', 'indication']);
|
|
25
|
+
|
|
26
|
+
function toFhir(mention) {
|
|
27
|
+
const { fact, provenance } = mention;
|
|
19
28
|
if (DEDICATED_AGGREGATE.has(fact.category)) return [];
|
|
29
|
+
const primary = primaryResource(mention);
|
|
30
|
+
return [primary, mentionProvenance(primary, provenance)];
|
|
31
|
+
}
|
|
20
32
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
extension('mention-assertion-confidence', { valueDecimal: assertion.confidence }),
|
|
28
|
-
];
|
|
29
|
-
if (fact.temporality) {
|
|
30
|
-
extensions.push(extension('mention-temporality', { valueString: fact.temporality }));
|
|
31
|
-
}
|
|
33
|
+
const BUILDER_BY_CATEGORY = {
|
|
34
|
+
medication: medicationStatementResource,
|
|
35
|
+
adherence: medicationStatementResource,
|
|
36
|
+
treatment: procedureResource,
|
|
37
|
+
appointment: appointmentResource,
|
|
38
|
+
};
|
|
32
39
|
|
|
33
|
-
|
|
34
|
-
|
|
40
|
+
function primaryResource(mention) {
|
|
41
|
+
const { fact } = mention;
|
|
42
|
+
const build = BUILDER_BY_CATEGORY[fact.category];
|
|
43
|
+
if (build) return build(mention);
|
|
44
|
+
const currentAffirmedDiagnosis = DIAGNOSIS_CATEGORIES.has(fact.category)
|
|
45
|
+
&& fact.assertion.temporal === 'current'
|
|
46
|
+
&& !fact.assertion.negated;
|
|
47
|
+
return currentAffirmedDiagnosis ? conditionResource(mention) : observationResource(mention);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function mentionCode(fact) {
|
|
51
|
+
return fact.ctcaeV5Term
|
|
52
|
+
? codeableConcept(fact.canonicalTerm, { code: ctcaeSlug(fact.ctcaeV5Term), system: codeSystemUrl('ctcae-v5-term'), display: fact.ctcaeV5Term })
|
|
35
53
|
: codeableConcept(fact.canonicalTerm);
|
|
36
|
-
const primary = primaryResource({ fact, provenance, code, extensions });
|
|
37
|
-
return [primary, Provenance.fromMentionProjection({ target: primary, provenance, activityText: ACTIVITY_TEXT })];
|
|
38
54
|
}
|
|
39
55
|
|
|
40
|
-
function
|
|
41
|
-
const assertion = fact
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
56
|
+
function mentionExtensions(fact, provenance = null) {
|
|
57
|
+
const { assertion } = fact;
|
|
58
|
+
const out = [
|
|
59
|
+
extension(MENTION_EXT.ASSERTION_NEGATED, { valueBoolean: assertion.negated }),
|
|
60
|
+
extension(MENTION_EXT.ASSERTION_HEDGED, { valueBoolean: assertion.hedged }),
|
|
61
|
+
extension(MENTION_EXT.ASSERTION_EXPERIENCER, { valueString: assertion.experiencer }),
|
|
62
|
+
extension(MENTION_EXT.ASSERTION_TEMPORAL, { valueString: assertion.temporal }),
|
|
63
|
+
extension(MENTION_EXT.ASSERTION_CONFIDENCE, { valueDecimal: assertion.confidence }),
|
|
64
|
+
];
|
|
65
|
+
if (fact.temporality) out.push(extension(MENTION_EXT.TEMPORALITY, { valueString: fact.temporality }));
|
|
66
|
+
if (provenance?.needsConfirmation) out.push(extension(MENTION_EXT.NEEDS_CONFIRMATION, { valueBoolean: true }));
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const quoteNotes = (provenance) => {
|
|
71
|
+
const quotes = provenance.verbatimQuotes || [];
|
|
72
|
+
return quotes.length ? quotes.map((text) => ({ text })) : null;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
function observationResource({ fact, provenance }) {
|
|
76
|
+
const categoryCode = CATEGORY_TO_OBSERVATION_CATEGORY[fact.category] || 'exam';
|
|
77
|
+
const payload = {
|
|
78
|
+
...baseResource('Observation', fact.mentionId, MENTION_SLUG, fact.patientId),
|
|
79
|
+
status: 'preliminary',
|
|
80
|
+
category: [observationCategory(categoryCode)],
|
|
81
|
+
code: mentionCode(fact),
|
|
82
|
+
performer: [patientReference(fact.patientId)],
|
|
83
|
+
effectiveDateTime: toInstant(fact.reportedAt),
|
|
84
|
+
issued: toInstant(provenance.recordedAt),
|
|
85
|
+
extension: mentionExtensions(fact, provenance),
|
|
86
|
+
};
|
|
87
|
+
if (fact.assertion.negated) {
|
|
88
|
+
payload.interpretation = [codeableConcept('Negative', { code: 'NEG', system: getSystems().observationInterpretation, display: 'Negative' })];
|
|
89
|
+
payload.valueCodeableConcept = codeableConcept('Ausente (negado por el paciente)');
|
|
48
90
|
}
|
|
49
|
-
|
|
50
|
-
|
|
91
|
+
const quotes = quoteNotes(provenance);
|
|
92
|
+
const components = observedFieldComponents(fact.observedFields);
|
|
93
|
+
if (quotes) payload.note = quotes;
|
|
94
|
+
if (components.length) payload.component = components;
|
|
95
|
+
return payload;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function conditionResource({ fact, provenance }) {
|
|
99
|
+
const systems = getSystems();
|
|
100
|
+
const verification = fact.assertion.hedged ? 'unconfirmed' : 'provisional';
|
|
101
|
+
const payload = {
|
|
102
|
+
...baseResource('Condition', fact.mentionId, MENTION_SLUG, fact.patientId),
|
|
103
|
+
clinicalStatus: codeableConcept('active', { code: 'active', system: systems.conditionClinical }),
|
|
104
|
+
verificationStatus: codeableConcept(verification, { code: verification, system: systems.conditionVerStatus }),
|
|
105
|
+
category: [problemListCategory()],
|
|
106
|
+
code: mentionCode(fact),
|
|
107
|
+
recordedDate: toInstant(provenance.recordedAt),
|
|
108
|
+
extension: mentionExtensions(fact, provenance),
|
|
109
|
+
};
|
|
110
|
+
const quotes = quoteNotes(provenance);
|
|
111
|
+
if (quotes) payload.note = quotes;
|
|
112
|
+
return payload;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function medicationStatementResource({ fact, provenance }) {
|
|
116
|
+
const payload = {
|
|
117
|
+
...baseResource('MedicationStatement', fact.mentionId, MENTION_SLUG, fact.patientId),
|
|
118
|
+
status: provenance.needsConfirmation ? 'draft' : 'recorded',
|
|
119
|
+
medication: { concept: mentionCode(fact) },
|
|
120
|
+
effectiveDateTime: toInstant(fact.reportedAt),
|
|
121
|
+
extension: mentionExtensions(fact, provenance),
|
|
122
|
+
};
|
|
123
|
+
const adherence = adherenceFor(fact.assertion);
|
|
124
|
+
if (adherence) {
|
|
125
|
+
payload.adherence = {
|
|
126
|
+
code: codeableConcept(adherence, { code: adherence, system: getSystems().medicationStatementAdherence }),
|
|
127
|
+
};
|
|
51
128
|
}
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
129
|
+
const quotes = quoteNotes(provenance);
|
|
130
|
+
if (quotes) payload.note = quotes;
|
|
131
|
+
return payload;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function adherenceFor(assertion) {
|
|
135
|
+
if (assertion.negated) return 'not-taking';
|
|
136
|
+
if (assertion.temporal === 'historical') return 'stopped';
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function procedureStatus(fact, provenance) {
|
|
141
|
+
if (fact.assertion.negated) return 'not-done';
|
|
142
|
+
if (provenance.needsConfirmation) return 'unknown';
|
|
143
|
+
return statusFrom(PROCEDURE_STATUS, fact.observedFields?.status, { absent: 'completed', unrecognised: 'completed' });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function procedureResource({ fact, provenance }) {
|
|
147
|
+
const payload = {
|
|
148
|
+
...baseResource('Procedure', fact.mentionId, MENTION_SLUG, fact.patientId),
|
|
149
|
+
status: procedureStatus(fact, provenance),
|
|
150
|
+
code: mentionCode(fact),
|
|
151
|
+
occurrenceDateTime: toInstant(fact.reportedAt),
|
|
152
|
+
recorder: patientReference(fact.patientId),
|
|
153
|
+
extension: mentionExtensions(fact, provenance),
|
|
154
|
+
};
|
|
155
|
+
const quotes = quoteNotes(provenance);
|
|
156
|
+
if (quotes) payload.note = quotes;
|
|
157
|
+
return payload;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const EXACT_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
161
|
+
|
|
162
|
+
function isExactCalendarDateTime(value) {
|
|
163
|
+
if (typeof value !== 'string') return false;
|
|
164
|
+
const trimmed = value.trim();
|
|
165
|
+
const match = EXACT_DATE_TIME.exec(trimmed);
|
|
166
|
+
if (!match || Number.isNaN(Date.parse(trimmed))) return false;
|
|
167
|
+
const year = Number(match[1]);
|
|
168
|
+
const month = Number(match[2]);
|
|
169
|
+
const day = Number(match[3]);
|
|
170
|
+
const hour = Number(match[4]);
|
|
171
|
+
const minute = Number(match[5]);
|
|
172
|
+
const second = match[6] === undefined ? 0 : Number(match[6]);
|
|
173
|
+
if (year < 1 || month < 1 || month > 12 || day < 1) return false;
|
|
174
|
+
if (hour > 23 || minute > 59 || second > 59) return false;
|
|
175
|
+
const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
176
|
+
const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
177
|
+
return day <= daysInMonth[month - 1];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function appointmentResource({ fact, provenance }) {
|
|
181
|
+
const scheduledFor = fact.observedFields?.scheduled_for ?? null;
|
|
182
|
+
const isExactDateTime = isExactCalendarDateTime(scheduledFor);
|
|
183
|
+
const payload = {
|
|
184
|
+
...baseResource('Appointment', fact.mentionId, MENTION_SLUG),
|
|
185
|
+
status: fact.assertion.negated ? 'cancelled' : 'proposed',
|
|
186
|
+
description: fact.canonicalTerm,
|
|
187
|
+
participant: [{ actor: patientReference(fact.patientId), status: 'accepted' }],
|
|
188
|
+
extension: mentionExtensions(fact, provenance),
|
|
189
|
+
};
|
|
190
|
+
if (isExactDateTime) payload.start = toInstant(scheduledFor);
|
|
191
|
+
const quotes = quoteNotes(provenance);
|
|
192
|
+
if (quotes) payload.note = quotes;
|
|
193
|
+
return payload;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function mentionProvenance(target, provenance) {
|
|
197
|
+
return {
|
|
198
|
+
resourceType: 'Provenance',
|
|
199
|
+
id: fhirId(`${provenance.mentionId}-prov`),
|
|
200
|
+
target: [reference(target.resourceType, target.id)],
|
|
201
|
+
recorded: toInstant(provenance.recordedAt),
|
|
202
|
+
agent: [{ who: reference('Device', getDeviceId()), onBehalfOf: reference('Organization', getOrganizationId()) }],
|
|
203
|
+
activity: codeableConcept(ACTIVITY_TEXT),
|
|
204
|
+
extension: [
|
|
205
|
+
extension(MENTION_EXT.TURN_ID, { valueString: provenance.turnId }),
|
|
206
|
+
extension(MENTION_EXT.SOURCE, { valueString: provenance.source }),
|
|
207
|
+
extension(MENTION_EXT.EXTRACTOR_CONFIDENCE, { valueDecimal: provenance.extractorConfidence }),
|
|
208
|
+
],
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function observedFieldComponents(observedFields) {
|
|
213
|
+
const components = [];
|
|
214
|
+
for (const [key, raw] of Object.entries(observedFields || {})) {
|
|
215
|
+
const text = stringifyValue(raw);
|
|
216
|
+
if (!text) continue;
|
|
217
|
+
components.push({
|
|
218
|
+
code: codeableConcept(key, { code: key, system: getSystems()[OBSERVED_FIELD_SYSTEM_KEY] }),
|
|
219
|
+
valueString: text,
|
|
220
|
+
});
|
|
58
221
|
}
|
|
59
|
-
return
|
|
222
|
+
return components;
|
|
60
223
|
}
|
|
61
224
|
|
|
62
225
|
module.exports = {
|
|
63
|
-
|
|
64
|
-
PROJECTOR_NAME,
|
|
226
|
+
toFhir,
|
|
65
227
|
};
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { codeSystemUrl } = require('../helpers/fhirHelper');
|
|
4
|
+
const { identifier, reference, codeableConcept, extension, toIso } = require('../helpers/elementHelper');
|
|
5
|
+
const { baseResource, provenance } = require('../helpers/resourceHelper');
|
|
6
|
+
const { extMap, identifierValue, referencedIds } = require('../helpers/fhirReadHelper');
|
|
7
|
+
const { CLUSTER_IMPRESSION_SLUG, CLUSTER_LABEL_SLUG } = require('../constants/projectionSlugs');
|
|
8
|
+
const { CLUSTER_EXT } = require('../constants/extensionSlugs');
|
|
9
|
+
const { ClusterImpression } = require('../../shared/dtos/ClusterImpression');
|
|
10
|
+
const { logger } = require('../../utils/logger');
|
|
11
|
+
|
|
12
|
+
const LIST_SEPARATOR = '; ';
|
|
13
|
+
const STATUS_TO_FHIR = { active: 'in-progress', dissolved: 'completed' };
|
|
14
|
+
const ACTIVITY_CODESYSTEM = 'clinical-activity';
|
|
15
|
+
const ACTIVITY_CODES = {
|
|
16
|
+
opened: 'cluster-hypothesis-opened',
|
|
17
|
+
updated: 'cluster-hypothesis-updated',
|
|
18
|
+
dissolved: 'cluster-hypothesis-dissolved',
|
|
19
|
+
};
|
|
20
|
+
const DEFAULT_ACTIVITY_CODE = 'cluster-hypothesis';
|
|
21
|
+
|
|
22
|
+
function toFhir({ cluster, history = [] }) {
|
|
23
|
+
const records = history.length
|
|
24
|
+
? [...history].sort((a, b) => Date.parse(a.recordedAt) - Date.parse(b.recordedAt))
|
|
25
|
+
: [{ turnId: 'opened', action: 'opened', recordedAt: cluster.openedAt, transitionReason: null }];
|
|
26
|
+
return [clusterResource(cluster), ...records.map((record) => historyProvenance(cluster.clusterId, record))];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function clusterResource(cluster) {
|
|
30
|
+
const payload = {
|
|
31
|
+
...baseResource('ClinicalImpression', cluster.clusterId, CLUSTER_IMPRESSION_SLUG, cluster.patientId),
|
|
32
|
+
status: STATUS_TO_FHIR[cluster.status],
|
|
33
|
+
problem: cluster.memberCaseIds.map((caseId) => reference('Condition', caseId)),
|
|
34
|
+
extension: clusterExtensions(cluster),
|
|
35
|
+
};
|
|
36
|
+
if (cluster.label) payload.identifier.push(identifier(CLUSTER_LABEL_SLUG, cluster.label));
|
|
37
|
+
if (cluster.relationshipModel) payload.summary = cluster.relationshipModel;
|
|
38
|
+
if (cluster.openingReasoning) payload.description = cluster.openingReasoning;
|
|
39
|
+
if (cluster.dissolvedAt) payload.effectivePeriod = { start: toIso(cluster.openedAt), end: toIso(cluster.dissolvedAt) };
|
|
40
|
+
else payload.effectiveDateTime = toIso(cluster.openedAt);
|
|
41
|
+
if (cluster.dissolveCategory) payload.statusReason = codeableConcept(cluster.dissolveCategory);
|
|
42
|
+
return payload;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function clusterExtensions(cluster) {
|
|
46
|
+
const out = [
|
|
47
|
+
extension(CLUSTER_EXT.HYPOTHESIS_TYPE, { valueString: cluster.hypothesisType }),
|
|
48
|
+
extension(CLUSTER_EXT.CONFIDENCE, { valueString: cluster.confidence }),
|
|
49
|
+
extension(CLUSTER_EXT.CLINICAL_SIGNIFICANCE, { valueString: cluster.clinicalSignificance }),
|
|
50
|
+
];
|
|
51
|
+
if (cluster.strengthensIf.length) {
|
|
52
|
+
out.push(extension(CLUSTER_EXT.STRENGTHENS_IF, { valueString: cluster.strengthensIf.join(LIST_SEPARATOR) }));
|
|
53
|
+
}
|
|
54
|
+
if (cluster.weakensIf.length) {
|
|
55
|
+
out.push(extension(CLUSTER_EXT.WEAKENS_IF, { valueString: cluster.weakensIf.join(LIST_SEPARATOR) }));
|
|
56
|
+
}
|
|
57
|
+
for (const caseId of cluster.memberCaseIds) out.push(extension(CLUSTER_EXT.MEMBER_CASE_ID, { valueString: caseId }));
|
|
58
|
+
out.push(extension(CLUSTER_EXT.STATUS, { valueString: cluster.status }));
|
|
59
|
+
if (cluster.consultationId) out.push(extension(CLUSTER_EXT.CONSULTATION_ID, { valueString: cluster.consultationId }));
|
|
60
|
+
if (cluster.dissolveReason) out.push(extension(CLUSTER_EXT.DISSOLVE_REASON, { valueString: cluster.dissolveReason }));
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function historyProvenance(clusterId, record) {
|
|
65
|
+
const code = ACTIVITY_CODES[record.action] || DEFAULT_ACTIVITY_CODE;
|
|
66
|
+
const payload = provenance({
|
|
67
|
+
provenanceId: `${clusterId}-prov-${record.turnId}-${record.action}`,
|
|
68
|
+
targetRefs: [reference('ClinicalImpression', clusterId)],
|
|
69
|
+
recordedAt: record.recordedAt,
|
|
70
|
+
activity: codeableConcept(code, { code, system: codeSystemUrl(ACTIVITY_CODESYSTEM) }),
|
|
71
|
+
});
|
|
72
|
+
if (record.transitionReason) {
|
|
73
|
+
payload.extension = [extension('transition-reason', { valueString: record.transitionReason })];
|
|
74
|
+
}
|
|
75
|
+
return payload;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function fromFhir(resources, { patientId }) {
|
|
79
|
+
const out = [];
|
|
80
|
+
for (const resource of resources) {
|
|
81
|
+
if (resource.resourceType !== 'ClinicalImpression') continue;
|
|
82
|
+
if (!identifierValue(resource, CLUSTER_IMPRESSION_SLUG)) continue;
|
|
83
|
+
try {
|
|
84
|
+
out.push(new ClusterImpression(reconstruct(resource, patientId)));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error instanceof ZodError) {
|
|
87
|
+
logger.warn({ clusterId: resource.id }, 'skipping malformed cluster ClinicalImpression');
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function reconstruct(resource, patientId) {
|
|
97
|
+
const ext = extMap(resource);
|
|
98
|
+
const splitList = (value) => (value ? value.split(LIST_SEPARATOR) : []);
|
|
99
|
+
return {
|
|
100
|
+
schemaVersion: '1',
|
|
101
|
+
clusterId: identifierValue(resource, CLUSTER_IMPRESSION_SLUG),
|
|
102
|
+
patientId,
|
|
103
|
+
label: identifierValue(resource, CLUSTER_LABEL_SLUG) || '',
|
|
104
|
+
hypothesisType: ext[CLUSTER_EXT.HYPOTHESIS_TYPE],
|
|
105
|
+
status: ext[CLUSTER_EXT.STATUS],
|
|
106
|
+
confidence: ext[CLUSTER_EXT.CONFIDENCE],
|
|
107
|
+
clinicalSignificance: ext[CLUSTER_EXT.CLINICAL_SIGNIFICANCE],
|
|
108
|
+
memberCaseIds: referencedIds(resource, CLUSTER_EXT.MEMBER_CASE_ID, (resource.problem || []).map((p) => p.reference)),
|
|
109
|
+
consultationId: ext[CLUSTER_EXT.CONSULTATION_ID] || null,
|
|
110
|
+
relationshipModel: resource.summary || '',
|
|
111
|
+
strengthensIf: splitList(ext[CLUSTER_EXT.STRENGTHENS_IF]),
|
|
112
|
+
weakensIf: splitList(ext[CLUSTER_EXT.WEAKENS_IF]),
|
|
113
|
+
openingReasoning: resource.description || '',
|
|
114
|
+
openedAt: resource.effectiveDateTime || resource.effectivePeriod?.start,
|
|
115
|
+
dissolvedAt: resource.effectivePeriod?.end || null,
|
|
116
|
+
dissolveReason: ext[CLUSTER_EXT.DISSOLVE_REASON] || null,
|
|
117
|
+
dissolveCategory: resource.statusReason?.text || null,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = {
|
|
122
|
+
toFhir,
|
|
123
|
+
fromFhir,
|
|
124
|
+
};
|