@peopl-health/nexus 6.0.0-dev.718 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
4
|
+
const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
|
|
5
|
+
const { patientReference, reference, recipientReference, codeableConcept, extension, notes, toIso } = require('../helpers/elementHelper');
|
|
6
|
+
const { baseResource, provenance } = require('../helpers/resourceHelper');
|
|
7
|
+
const { identifierValue, refToId, extValues, referencedId } = require('../helpers/fhirReadHelper');
|
|
8
|
+
const { INTERVENTION_SLUG, INTERVENTION_KIND_SLUG, INTERVENTION_OUTCOME_SLUG } = require('../constants/projectionSlugs');
|
|
9
|
+
const { Intervention } = require('../../shared/dtos/Intervention');
|
|
10
|
+
const { logger } = require('../../utils/logger');
|
|
11
|
+
|
|
12
|
+
const ACTIVITY_TEXT = 'intervention-record';
|
|
13
|
+
const PROCEDURE_KINDS = new Set(['otc', 'self_care', 'other']);
|
|
14
|
+
|
|
15
|
+
const EXT = {
|
|
16
|
+
CASE_ID: 'intervention-case-id',
|
|
17
|
+
RATIONALE: 'intervention-rationale',
|
|
18
|
+
OUTCOME_NOTES: 'intervention-outcome-notes',
|
|
19
|
+
OUTCOME: 'intervention-outcome',
|
|
20
|
+
RECIPIENT_KIND: 'intervention-recipient-kind',
|
|
21
|
+
RECIPIENT_REF: 'intervention-recipient-ref',
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const INTERVENTION_RESOURCE_TYPES = Object.freeze(['Procedure', 'Communication', 'Task', 'CommunicationRequest']);
|
|
25
|
+
|
|
26
|
+
const interventionReason = (caseId) => [{ reference: reference('Condition', caseId) }];
|
|
27
|
+
const withNote = (payload, intervention) => {
|
|
28
|
+
const note = notes(intervention.rationale, intervention.outcomeNotes);
|
|
29
|
+
return note ? { ...payload, note } : payload;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function toFhir(intervention) {
|
|
33
|
+
const primary = primaryResource(intervention);
|
|
34
|
+
return [primary, provenance({
|
|
35
|
+
provenanceId: `${intervention.interventionId}-prov`,
|
|
36
|
+
targetRefs: [{ reference: `${primary.resourceType}/${fhirId(intervention.interventionId)}` }],
|
|
37
|
+
recordedAt: intervention.deliveredAt,
|
|
38
|
+
activity: codeableConcept(ACTIVITY_TEXT),
|
|
39
|
+
})];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function primaryResource(intervention) {
|
|
43
|
+
if (PROCEDURE_KINDS.has(intervention.kind)) return procedureResource(intervention);
|
|
44
|
+
if (intervention.kind === 'education') return communicationResource(intervention);
|
|
45
|
+
if (intervention.kind === 'team_escalation') return taskResource(intervention);
|
|
46
|
+
if (intervention.kind === 'follow_up_check') return communicationRequestResource(intervention);
|
|
47
|
+
throw new Error(`unknown intervention variant: ${intervention.kind}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function procedureResource(intervention) {
|
|
51
|
+
return withNote({
|
|
52
|
+
...baseResource('Procedure', intervention.interventionId, INTERVENTION_SLUG, intervention.patientId),
|
|
53
|
+
status: intervention.outcome === 'pending' ? 'in-progress' : 'completed',
|
|
54
|
+
code: codeableConcept(intervention.interventionLabel),
|
|
55
|
+
reason: interventionReason(intervention.caseId),
|
|
56
|
+
occurrenceDateTime: toIso(intervention.deliveredAt),
|
|
57
|
+
outcome: codeableConcept(intervention.outcome, { code: intervention.outcome, system: codeSystemUrl(INTERVENTION_OUTCOME_SLUG) }),
|
|
58
|
+
category: [codeableConcept(intervention.kind, { code: intervention.kind, system: codeSystemUrl(INTERVENTION_KIND_SLUG) })],
|
|
59
|
+
extension: interventionExtensions(intervention, { withRecipient: true }),
|
|
60
|
+
}, intervention);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function communicationResource(intervention) {
|
|
64
|
+
return withNote({
|
|
65
|
+
...baseResource('Communication', intervention.interventionId, INTERVENTION_SLUG, intervention.patientId),
|
|
66
|
+
status: 'completed',
|
|
67
|
+
category: [codeableConcept(intervention.kind, { code: intervention.kind, system: codeSystemUrl(INTERVENTION_KIND_SLUG) })],
|
|
68
|
+
reason: interventionReason(intervention.caseId),
|
|
69
|
+
sent: toIso(intervention.deliveredAt),
|
|
70
|
+
payload: [{ contentCodeableConcept: codeableConcept(intervention.interventionLabel) }],
|
|
71
|
+
recipient: [recipientReference({
|
|
72
|
+
patientId: intervention.patientId,
|
|
73
|
+
recipientKind: intervention.recipientKind,
|
|
74
|
+
recipientRefId: intervention.recipientRefId,
|
|
75
|
+
})],
|
|
76
|
+
extension: interventionExtensions(intervention),
|
|
77
|
+
}, intervention);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function taskResource(intervention) {
|
|
81
|
+
const payload = withNote({
|
|
82
|
+
...baseResource('Task', intervention.interventionId, INTERVENTION_SLUG),
|
|
83
|
+
status: intervention.outcome === 'pending' ? 'requested' : 'completed',
|
|
84
|
+
intent: 'order',
|
|
85
|
+
code: codeableConcept(intervention.interventionLabel, {
|
|
86
|
+
code: intervention.kind,
|
|
87
|
+
system: codeSystemUrl(INTERVENTION_KIND_SLUG),
|
|
88
|
+
display: intervention.interventionLabel,
|
|
89
|
+
}),
|
|
90
|
+
authoredOn: toIso(intervention.deliveredAt),
|
|
91
|
+
for: patientReference(intervention.patientId),
|
|
92
|
+
requester: reference('Device', getDeviceId()),
|
|
93
|
+
reason: interventionReason(intervention.caseId),
|
|
94
|
+
extension: interventionExtensions(intervention, { withRecipient: true }),
|
|
95
|
+
}, intervention);
|
|
96
|
+
if (intervention.outcome !== 'pending') {
|
|
97
|
+
const outcomeCc = codeableConcept(intervention.outcome, { code: intervention.outcome, system: codeSystemUrl(INTERVENTION_OUTCOME_SLUG) });
|
|
98
|
+
payload.output = [{ type: codeableConcept(INTERVENTION_OUTCOME_SLUG), valueCodeableConcept: outcomeCc }];
|
|
99
|
+
}
|
|
100
|
+
return payload;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function communicationRequestResource(intervention) {
|
|
104
|
+
return withNote({
|
|
105
|
+
...baseResource('CommunicationRequest', intervention.interventionId, INTERVENTION_SLUG, intervention.patientId),
|
|
106
|
+
status: intervention.outcome === 'pending' ? 'active' : 'completed',
|
|
107
|
+
intent: 'plan',
|
|
108
|
+
category: [codeableConcept(intervention.kind, { code: intervention.kind, system: codeSystemUrl(INTERVENTION_KIND_SLUG) })],
|
|
109
|
+
reason: interventionReason(intervention.caseId),
|
|
110
|
+
payload: [{ contentCodeableConcept: codeableConcept(intervention.interventionLabel) }],
|
|
111
|
+
recipient: [recipientReference({
|
|
112
|
+
patientId: intervention.patientId,
|
|
113
|
+
recipientKind: intervention.recipientKind,
|
|
114
|
+
recipientRefId: intervention.recipientRefId,
|
|
115
|
+
})],
|
|
116
|
+
occurrenceDateTime: toIso(intervention.deliveredAt),
|
|
117
|
+
authoredOn: toIso(intervention.deliveredAt),
|
|
118
|
+
extension: interventionExtensions(intervention),
|
|
119
|
+
}, intervention);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function interventionExtensions(intervention, { withRecipient = false } = {}) {
|
|
123
|
+
const out = [];
|
|
124
|
+
if (intervention.caseId) out.push(extension(EXT.CASE_ID, { valueString: intervention.caseId }));
|
|
125
|
+
if (intervention.rationale) out.push(extension(EXT.RATIONALE, { valueString: intervention.rationale }));
|
|
126
|
+
if (intervention.outcomeNotes) out.push(extension(EXT.OUTCOME_NOTES, { valueString: intervention.outcomeNotes }));
|
|
127
|
+
if (intervention.outcome) out.push(extension(EXT.OUTCOME, { valueString: intervention.outcome }));
|
|
128
|
+
if (withRecipient && intervention.recipientKind === 'related_person' && intervention.recipientRefId) {
|
|
129
|
+
out.push(extension(EXT.RECIPIENT_KIND, { valueString: 'related_person' }));
|
|
130
|
+
out.push(extension(EXT.RECIPIENT_REF, { valueString: intervention.recipientRefId }));
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function fromFhir(resources, { patientId }) {
|
|
136
|
+
return resources
|
|
137
|
+
.filter((r) => INTERVENTION_RESOURCE_TYPES.includes(r.resourceType) && identifierValue(r, INTERVENTION_SLUG))
|
|
138
|
+
.map((resource) => reconstruct(resource, patientId))
|
|
139
|
+
.filter(Boolean);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function reconstruct(resource, patientId) {
|
|
143
|
+
const reasonRef = resource.reason && resource.reason[0] && resource.reason[0].reference;
|
|
144
|
+
const base = {
|
|
145
|
+
interventionId: identifierValue(resource, INTERVENTION_SLUG),
|
|
146
|
+
patientId,
|
|
147
|
+
caseId: referencedId(resource, EXT.CASE_ID, reasonRef?.reference),
|
|
148
|
+
rationale: extValues(resource, EXT.RATIONALE)[0] ?? null,
|
|
149
|
+
outcomeNotes: extValues(resource, EXT.OUTCOME_NOTES)[0] ?? null,
|
|
150
|
+
outcomeExt: extValues(resource, EXT.OUTCOME)[0] ?? null,
|
|
151
|
+
recipientKind: 'patient',
|
|
152
|
+
recipientRefId: null,
|
|
153
|
+
};
|
|
154
|
+
let reconstructed;
|
|
155
|
+
if (resource.resourceType === 'Procedure') reconstructed = reconstructProcedure(resource, base);
|
|
156
|
+
else if (resource.resourceType === 'Communication') reconstructed = reconstructCommunication(resource, base);
|
|
157
|
+
else if (resource.resourceType === 'Task') reconstructed = reconstructTask(resource, base);
|
|
158
|
+
else reconstructed = reconstructCommunicationRequest(resource, base);
|
|
159
|
+
try {
|
|
160
|
+
return new Intervention(reconstructed);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error instanceof ZodError) {
|
|
163
|
+
logger.warn({ interventionId: reconstructed.interventionId }, 'skipping malformed intervention resource');
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function reconstructProcedure(resource, base) {
|
|
171
|
+
const { outcomeExt, ...dto } = base;
|
|
172
|
+
return {
|
|
173
|
+
...dto,
|
|
174
|
+
kind: categoryCode(resource),
|
|
175
|
+
interventionLabel: (resource.code && resource.code.text) || null,
|
|
176
|
+
deliveredAt: resource.occurrenceDateTime,
|
|
177
|
+
outcome: outcomeExt ?? codeableConceptCode(resource.outcome),
|
|
178
|
+
...recipientFromExtension(resource),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function reconstructCommunication(resource, base) {
|
|
183
|
+
const { outcomeExt, ...dto } = base;
|
|
184
|
+
const content = resource.payload && resource.payload[0] && resource.payload[0].contentCodeableConcept;
|
|
185
|
+
const outcome = outcomeExt ?? undefined;
|
|
186
|
+
return {
|
|
187
|
+
...dto,
|
|
188
|
+
kind: categoryCode(resource),
|
|
189
|
+
interventionLabel: (content && content.text) || null,
|
|
190
|
+
deliveredAt: resource.sent,
|
|
191
|
+
...(outcome ? { outcome } : {}),
|
|
192
|
+
...recipientFromReference(resource),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function reconstructTask(resource, base) {
|
|
197
|
+
const { outcomeExt, ...dto } = base;
|
|
198
|
+
const output = resource.output && resource.output[0];
|
|
199
|
+
return {
|
|
200
|
+
...dto,
|
|
201
|
+
kind: codingCode(resource.code),
|
|
202
|
+
interventionLabel: (resource.code && resource.code.text) || null,
|
|
203
|
+
deliveredAt: resource.authoredOn,
|
|
204
|
+
outcome: outcomeExt ?? (output ? codeableConceptCode(output.valueCodeableConcept) : 'pending'),
|
|
205
|
+
...recipientFromExtension(resource),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function reconstructCommunicationRequest(resource, base) {
|
|
210
|
+
const { outcomeExt, ...dto } = base;
|
|
211
|
+
const content = resource.payload && resource.payload[0] && resource.payload[0].contentCodeableConcept;
|
|
212
|
+
return {
|
|
213
|
+
...dto,
|
|
214
|
+
kind: categoryCode(resource),
|
|
215
|
+
interventionLabel: (content && content.text) || null,
|
|
216
|
+
deliveredAt: resource.occurrenceDateTime,
|
|
217
|
+
outcome: outcomeExt ?? (resource.status === 'active' ? 'pending' : 'unknown'),
|
|
218
|
+
...recipientFromReference(resource),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function recipientFromExtension(resource) {
|
|
223
|
+
const kind = extValues(resource, EXT.RECIPIENT_KIND)[0];
|
|
224
|
+
const refId = extValues(resource, EXT.RECIPIENT_REF)[0];
|
|
225
|
+
if (kind === 'related_person' && refId) return { recipientKind: 'related_person', recipientRefId: refId };
|
|
226
|
+
return { recipientKind: 'patient', recipientRefId: null };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function recipientFromReference(resource) {
|
|
230
|
+
const recipientRef = resource.recipient && resource.recipient[0] && resource.recipient[0].reference;
|
|
231
|
+
if (recipientRef && recipientRef.startsWith('RelatedPerson/')) {
|
|
232
|
+
return { recipientKind: 'related_person', recipientRefId: refToId(recipientRef) };
|
|
233
|
+
}
|
|
234
|
+
return { recipientKind: 'patient', recipientRefId: null };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const codingCode = (concept) => (concept && concept.coding && concept.coding[0] && concept.coding[0].code) || null;
|
|
238
|
+
const categoryCode = (resource) => codingCode(resource.category && resource.category[0]);
|
|
239
|
+
const codeableConceptCode = (concept) => codingCode(concept) || (concept && concept.text) || 'pending';
|
|
240
|
+
|
|
241
|
+
module.exports = {
|
|
242
|
+
INTERVENTION_RESOURCE_TYPES,
|
|
243
|
+
toFhir,
|
|
244
|
+
fromFhir,
|
|
245
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
4
|
+
const { codeSystemUrl } = require('../helpers/fhirHelper');
|
|
5
|
+
const { reference, codeableConcept, extension, notes, toIso } = require('../helpers/elementHelper');
|
|
6
|
+
const { baseResource, provenance } = require('../helpers/resourceHelper');
|
|
7
|
+
const { extMap, identifierValue, objectExtension } = require('../helpers/fhirReadHelper');
|
|
8
|
+
const { PALLIATIVE_CAREPLAN_SLUG, PALLIATIVE_CAREPLAN_REC_SLUG } = require('../constants/projectionSlugs');
|
|
9
|
+
const { PALLIATIVE_EXT } = require('../constants/extensionSlugs');
|
|
10
|
+
const { PalliativeCarePlan } = require('../../shared/dtos/PalliativeCarePlan');
|
|
11
|
+
const { logger } = require('../../utils/logger');
|
|
12
|
+
const { reviewHistoryOf } = require('./recommendationPlanProjection');
|
|
13
|
+
|
|
14
|
+
const ACTIVITY_TEXT = 'palliative-careplan';
|
|
15
|
+
const NOTE_SEPARATOR = ': ';
|
|
16
|
+
const FOLLOWUP_SEPARATOR = ' / ';
|
|
17
|
+
|
|
18
|
+
function toFhir(carePlan) {
|
|
19
|
+
const tasks = carePlan.recommendations.map((recommendation) => recommendationResource(recommendation, carePlan));
|
|
20
|
+
const plan = carePlanResource(carePlan, tasks);
|
|
21
|
+
return [
|
|
22
|
+
plan,
|
|
23
|
+
...tasks,
|
|
24
|
+
provenance({
|
|
25
|
+
provenanceId: `${carePlan.careplanId}-prov`,
|
|
26
|
+
targetRefs: [
|
|
27
|
+
{ reference: `CarePlan/${plan.id}` },
|
|
28
|
+
...tasks.map((task) => ({ reference: `Task/${task.id}` })),
|
|
29
|
+
],
|
|
30
|
+
recordedAt: carePlan.committedAt,
|
|
31
|
+
activity: codeableConcept(ACTIVITY_TEXT),
|
|
32
|
+
}),
|
|
33
|
+
];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function carePlanResource(carePlan, tasks) {
|
|
37
|
+
const payload = {
|
|
38
|
+
...baseResource('CarePlan', carePlan.careplanId, PALLIATIVE_CAREPLAN_SLUG, carePlan.patientId),
|
|
39
|
+
status: 'active',
|
|
40
|
+
intent: 'plan',
|
|
41
|
+
category: [codeableConcept(PALLIATIVE_CAREPLAN_SLUG)],
|
|
42
|
+
created: toIso(carePlan.committedAt),
|
|
43
|
+
extension: [extension(PALLIATIVE_EXT.TURN_ID, { valueString: carePlan.turnId })],
|
|
44
|
+
};
|
|
45
|
+
if (carePlan.summary) payload.description = carePlan.summary;
|
|
46
|
+
if (carePlan.assessmentId) {
|
|
47
|
+
payload.extension.push(extension(PALLIATIVE_EXT.ASSESSMENT_ID, { valueString: carePlan.assessmentId }));
|
|
48
|
+
payload.supportingInfo = [reference('ClinicalImpression', carePlan.assessmentId)];
|
|
49
|
+
}
|
|
50
|
+
if (tasks.length) {
|
|
51
|
+
payload.activity = tasks.map((task) => ({ plannedActivityReference: { reference: `Task/${task.id}` } }));
|
|
52
|
+
}
|
|
53
|
+
return payload;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function recommendationResource(recommendation, carePlan) {
|
|
57
|
+
const recommendationId = `${carePlan.careplanId}-rank${recommendation.rank}`;
|
|
58
|
+
const { subject, ...identity } = baseResource('Task', recommendationId, PALLIATIVE_CAREPLAN_REC_SLUG, carePlan.patientId);
|
|
59
|
+
const payload = {
|
|
60
|
+
...identity,
|
|
61
|
+
status: 'requested',
|
|
62
|
+
intent: 'plan',
|
|
63
|
+
code: recommendationCode(recommendation),
|
|
64
|
+
for: subject,
|
|
65
|
+
authoredOn: toIso(carePlan.committedAt),
|
|
66
|
+
requester: reference('Device', getDeviceId()),
|
|
67
|
+
extension: [extension(PALLIATIVE_EXT.CAREPLAN_REC_RANK, { valueInteger: recommendation.rank })],
|
|
68
|
+
};
|
|
69
|
+
if (recommendation.otcOffer?.label) {
|
|
70
|
+
payload.extension.push(extension(PALLIATIVE_EXT.CAREPLAN_OTC_OFFER, { valueString: JSON.stringify(recommendation.otcOffer) }));
|
|
71
|
+
}
|
|
72
|
+
if (recommendation.mainRecommendation) payload.description = recommendation.mainRecommendation;
|
|
73
|
+
const note = notes(...recommendationNoteTexts(recommendation));
|
|
74
|
+
if (note) payload.note = note;
|
|
75
|
+
return payload;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function recommendationCode(recommendation) {
|
|
79
|
+
const code = codeableConcept(recommendation.elementNameShort);
|
|
80
|
+
const ctcaeTerms = (recommendation.ctcaeTerms || []).filter(Boolean);
|
|
81
|
+
if (ctcaeTerms.length) {
|
|
82
|
+
code.coding = ctcaeTerms.map((term) => ({ system: codeSystemUrl('pro-ctcae'), code: term, display: term }));
|
|
83
|
+
}
|
|
84
|
+
return code;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function recommendationNoteTexts(recommendation) {
|
|
88
|
+
const out = [];
|
|
89
|
+
if (recommendation.whenToEscalate) out.push(`when_to_escalate${NOTE_SEPARATOR}${recommendation.whenToEscalate}`);
|
|
90
|
+
if (recommendation.expectedEffectiveness) out.push(`expected_effectiveness${NOTE_SEPARATOR}${recommendation.expectedEffectiveness}`);
|
|
91
|
+
if (recommendation.followup?.type) {
|
|
92
|
+
out.push(`followup${NOTE_SEPARATOR}${recommendation.followup.type}${FOLLOWUP_SEPARATOR}${recommendation.followup.urgency || ''}`);
|
|
93
|
+
}
|
|
94
|
+
if (recommendation.isPharmacologicalMedNeeded !== null) {
|
|
95
|
+
out.push(`is_pharmacological_med_needed${NOTE_SEPARATOR}${recommendation.isPharmacologicalMedNeeded}`);
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function fromFhir(resources, { patientId }) {
|
|
101
|
+
const tasksByReference = new Map();
|
|
102
|
+
for (const resource of resources) {
|
|
103
|
+
if (resource.resourceType === 'Task' && identifierValue(resource, PALLIATIVE_CAREPLAN_REC_SLUG)) {
|
|
104
|
+
tasksByReference.set(`Task/${resource.id}`, resource);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const out = [];
|
|
109
|
+
for (const resource of resources) {
|
|
110
|
+
if (resource.resourceType !== 'CarePlan') continue;
|
|
111
|
+
if (!identifierValue(resource, PALLIATIVE_CAREPLAN_SLUG)) continue;
|
|
112
|
+
try {
|
|
113
|
+
const tasks = recommendationTasks(resource, tasksByReference);
|
|
114
|
+
const carePlan = new PalliativeCarePlan(reconstruct(resource, tasksByReference, patientId));
|
|
115
|
+
// The DTO is strict, so reviews are attached after validation rather than inside it.
|
|
116
|
+
const reviewsByRank = new Map(tasks.map((task) => [
|
|
117
|
+
extMap(task)[PALLIATIVE_EXT.CAREPLAN_REC_RANK],
|
|
118
|
+
reviewHistoryOf(task),
|
|
119
|
+
]));
|
|
120
|
+
for (const recommendation of carePlan.recommendations) {
|
|
121
|
+
recommendation.reviewHistory = reviewsByRank.get(recommendation.rank) || [];
|
|
122
|
+
}
|
|
123
|
+
out.push(carePlan);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof ZodError) {
|
|
126
|
+
logger.warn({ careplanId: resource.id }, 'skipping malformed palliative CarePlan');
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const recommendationTasks = (plan, tasksByReference) => (plan.activity || [])
|
|
136
|
+
.map((activity) => tasksByReference.get(activity.plannedActivityReference?.reference))
|
|
137
|
+
.filter(Boolean);
|
|
138
|
+
|
|
139
|
+
function reconstruct(plan, tasksByReference, patientId) {
|
|
140
|
+
const ext = extMap(plan);
|
|
141
|
+
const recommendations = recommendationTasks(plan, tasksByReference).map(reconstructRecommendation);
|
|
142
|
+
return {
|
|
143
|
+
careplanId: identifierValue(plan, PALLIATIVE_CAREPLAN_SLUG),
|
|
144
|
+
patientId,
|
|
145
|
+
turnId: ext[PALLIATIVE_EXT.TURN_ID],
|
|
146
|
+
assessmentId: ext[PALLIATIVE_EXT.ASSESSMENT_ID] || '',
|
|
147
|
+
committedAt: plan.created,
|
|
148
|
+
summary: plan.description || null,
|
|
149
|
+
recommendations,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function reconstructRecommendation(task) {
|
|
154
|
+
const ext = extMap(task);
|
|
155
|
+
const noteMap = {};
|
|
156
|
+
for (const note of task.note || []) {
|
|
157
|
+
const [key, ...rest] = String(note.text || '').split(NOTE_SEPARATOR);
|
|
158
|
+
noteMap[key] = rest.join(NOTE_SEPARATOR);
|
|
159
|
+
}
|
|
160
|
+
const medsText = noteMap.is_pharmacological_med_needed;
|
|
161
|
+
return {
|
|
162
|
+
rank: ext[PALLIATIVE_EXT.CAREPLAN_REC_RANK],
|
|
163
|
+
elementNameShort: task.code?.text || 'recommendation',
|
|
164
|
+
isPharmacologicalMedNeeded: medsText === undefined ? null : medsText === 'true',
|
|
165
|
+
ctcaeTerms: (task.code?.coding || []).map((coding) => coding.code).filter(Boolean),
|
|
166
|
+
mainRecommendation: task.description || null,
|
|
167
|
+
otcOffer: objectExtension(ext[PALLIATIVE_EXT.CAREPLAN_OTC_OFFER]),
|
|
168
|
+
followup: parseFollowup(noteMap.followup),
|
|
169
|
+
whenToEscalate: noteMap.when_to_escalate || null,
|
|
170
|
+
expectedEffectiveness: noteMap.expected_effectiveness || null,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function parseFollowup(text) {
|
|
175
|
+
if (!text) return null;
|
|
176
|
+
const [type, urgency] = text.split(FOLLOWUP_SEPARATOR);
|
|
177
|
+
return { type: (type || '').trim() || null, urgency: (urgency || '').trim() || null };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = {
|
|
181
|
+
toFhir,
|
|
182
|
+
fromFhir,
|
|
183
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const { ZodError } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
4
|
+
const { reference, codeableConcept, extension, toIso } = require('../helpers/elementHelper');
|
|
5
|
+
const { baseResource, provenance } = require('../helpers/resourceHelper');
|
|
6
|
+
const { extMap, extValues, identifierValue } = require('../helpers/fhirReadHelper');
|
|
7
|
+
const { PALLIATIVE_ASSESSMENT_SLUG, PALLIATIVE_ESCALATION_SLUG } = require('../constants/projectionSlugs');
|
|
8
|
+
const { PALLIATIVE_EXT } = require('../constants/extensionSlugs');
|
|
9
|
+
const { PalliativeAssessment } = require('../../shared/dtos/PalliativeAssessment');
|
|
10
|
+
const { logger } = require('../../utils/logger');
|
|
11
|
+
|
|
12
|
+
const ACTIVITY_TEXT = 'palliative-assessment';
|
|
13
|
+
const DEFAULT_ESCALATION_HOURS = 24;
|
|
14
|
+
|
|
15
|
+
function toFhir(assessment) {
|
|
16
|
+
const escalating = assessment.findings.filter((finding) => finding.escalation !== null);
|
|
17
|
+
const tasks = escalating.map((finding) => escalationResource(finding, assessment));
|
|
18
|
+
return [
|
|
19
|
+
assessmentResource(assessment),
|
|
20
|
+
...tasks,
|
|
21
|
+
provenance({
|
|
22
|
+
provenanceId: `${assessment.assessmentId}-prov`,
|
|
23
|
+
targetRefs: [
|
|
24
|
+
reference('ClinicalImpression', assessment.assessmentId),
|
|
25
|
+
...tasks.map((task) => ({ reference: `Task/${task.id}` })),
|
|
26
|
+
],
|
|
27
|
+
recordedAt: assessment.committedAt,
|
|
28
|
+
activity: codeableConcept(ACTIVITY_TEXT),
|
|
29
|
+
}),
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function assessmentResource(assessment) {
|
|
34
|
+
const payload = {
|
|
35
|
+
...baseResource('ClinicalImpression', assessment.assessmentId, PALLIATIVE_ASSESSMENT_SLUG, assessment.patientId),
|
|
36
|
+
status: 'completed',
|
|
37
|
+
effectiveDateTime: toIso(assessment.committedAt),
|
|
38
|
+
finding: assessment.findings.map((finding) => ({
|
|
39
|
+
item: { concept: codeableConcept(finding.nameShort) },
|
|
40
|
+
extension: findingExtensions(finding),
|
|
41
|
+
})),
|
|
42
|
+
extension: [extension(PALLIATIVE_EXT.TURN_ID, { valueString: assessment.turnId })],
|
|
43
|
+
};
|
|
44
|
+
if (assessment.evaluationSummary) payload.summary = assessment.evaluationSummary;
|
|
45
|
+
if (assessment.rankingRationale) payload.description = assessment.rankingRationale;
|
|
46
|
+
if (assessment.escalationReason) payload.note = [{ text: assessment.escalationReason }];
|
|
47
|
+
return payload;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function findingExtensions(finding) {
|
|
51
|
+
const out = [
|
|
52
|
+
extension(PALLIATIVE_EXT.FINDING_RANK, { valueInteger: finding.rank }),
|
|
53
|
+
extension(PALLIATIVE_EXT.FINDING_ELEMENT_TYPE, { valueString: finding.elementType }),
|
|
54
|
+
extension(PALLIATIVE_EXT.FINDING_TIME_WINDOW, { valueString: finding.timeWindow }),
|
|
55
|
+
extension(PALLIATIVE_EXT.FINDING_CLINICAL_DESCRIPTION, { valueString: finding.clinicalDescription }),
|
|
56
|
+
extension(PALLIATIVE_EXT.FINDING_WHY_RELEVANT, { valueString: finding.whyRelevant }),
|
|
57
|
+
extension(PALLIATIVE_EXT.FINDING_QOL_CRITERIA, { valueString: finding.qolCriteria }),
|
|
58
|
+
extension(PALLIATIVE_EXT.FINDING_IMPROVEMENT_CRITERIA, { valueString: finding.improvementCriteria }),
|
|
59
|
+
extension(PALLIATIVE_EXT.FINDING_CHARACTERIZATION_CRITERIA, { valueString: finding.characterizationCriteria }),
|
|
60
|
+
extension(PALLIATIVE_EXT.FINDING_AUDIT_NOTES, { valueString: finding.auditNotes }),
|
|
61
|
+
];
|
|
62
|
+
for (const term of finding.symptomTerms) out.push(extension(PALLIATIVE_EXT.FINDING_SYMPTOM_TERM, { valueString: term }));
|
|
63
|
+
for (const question of finding.probeQuestions) out.push(extension(PALLIATIVE_EXT.FINDING_PROBE_QUESTION, { valueString: question }));
|
|
64
|
+
if (finding.qolImpact !== null) out.push(extension(PALLIATIVE_EXT.FINDING_QOL_IMPACT, { valueString: finding.qolImpact }));
|
|
65
|
+
if (finding.improvementCapacity !== null) out.push(extension(PALLIATIVE_EXT.FINDING_IMPROVEMENT_CAPACITY, { valueString: finding.improvementCapacity }));
|
|
66
|
+
if (finding.areMedsNeeded !== null) out.push(extension(PALLIATIVE_EXT.FINDING_ARE_MEDS_NEEDED, { valueBoolean: finding.areMedsNeeded }));
|
|
67
|
+
if (finding.needsCharacterization !== null) out.push(extension(PALLIATIVE_EXT.FINDING_NEEDS_CHARACTERIZATION, { valueBoolean: finding.needsCharacterization }));
|
|
68
|
+
if (finding.clusterNote !== null) out.push(extension(PALLIATIVE_EXT.FINDING_CLUSTER_NOTE, { valueString: finding.clusterNote }));
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function escalationResource(finding, assessment) {
|
|
73
|
+
const { escalation } = finding;
|
|
74
|
+
const escalationId = `${assessment.assessmentId}-${finding.rank}`;
|
|
75
|
+
const end = new Date(new Date(assessment.committedAt).getTime() + escalation.maxActionTimeHours * 3600000);
|
|
76
|
+
const { subject, ...identity } = baseResource('Task', escalationId, PALLIATIVE_ESCALATION_SLUG, escalation.patientId);
|
|
77
|
+
const payload = {
|
|
78
|
+
...identity,
|
|
79
|
+
status: 'requested',
|
|
80
|
+
intent: 'order',
|
|
81
|
+
priority: 'urgent',
|
|
82
|
+
code: codeableConcept(finding.nameShort),
|
|
83
|
+
description: escalation.escalationReason,
|
|
84
|
+
for: subject,
|
|
85
|
+
authoredOn: toIso(assessment.committedAt),
|
|
86
|
+
requester: reference('Device', getDeviceId()),
|
|
87
|
+
restriction: { period: { end: toIso(end) } },
|
|
88
|
+
extension: [extension(PALLIATIVE_EXT.ESCALATION_RANK, { valueInteger: finding.rank })],
|
|
89
|
+
};
|
|
90
|
+
if (escalation.escalationRoutes.length) {
|
|
91
|
+
payload.requestedPerformer = escalation.escalationRoutes.map((route) => ({ concept: codeableConcept(route) }));
|
|
92
|
+
}
|
|
93
|
+
return payload;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function fromFhir(resources, { patientId }) {
|
|
97
|
+
const escalationsById = new Map();
|
|
98
|
+
for (const resource of resources) {
|
|
99
|
+
const escalationId = resource.resourceType === 'Task' && identifierValue(resource, PALLIATIVE_ESCALATION_SLUG);
|
|
100
|
+
if (escalationId) escalationsById.set(escalationId, reconstructEscalation(resource, patientId));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const out = [];
|
|
104
|
+
for (const resource of resources) {
|
|
105
|
+
if (resource.resourceType !== 'ClinicalImpression') continue;
|
|
106
|
+
if (!identifierValue(resource, PALLIATIVE_ASSESSMENT_SLUG)) continue;
|
|
107
|
+
try {
|
|
108
|
+
out.push(new PalliativeAssessment(reconstruct(resource, escalationsById, patientId)));
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof ZodError) {
|
|
111
|
+
logger.warn({ assessmentId: resource.id }, 'skipping malformed palliative ClinicalImpression');
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function reconstruct(resource, escalationsById, patientId) {
|
|
121
|
+
const assessmentId = identifierValue(resource, PALLIATIVE_ASSESSMENT_SLUG);
|
|
122
|
+
return {
|
|
123
|
+
assessmentId,
|
|
124
|
+
patientId,
|
|
125
|
+
turnId: extMap(resource)[PALLIATIVE_EXT.TURN_ID],
|
|
126
|
+
committedAt: resource.effectiveDateTime,
|
|
127
|
+
evaluationSummary: resource.summary || '',
|
|
128
|
+
rankingRationale: resource.description || '',
|
|
129
|
+
escalationReason: resource.note?.[0]?.text || null,
|
|
130
|
+
findings: (resource.finding || []).map((finding) => reconstructFinding(finding, escalationsById, assessmentId)),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function reconstructFinding(finding, escalationsById, assessmentId) {
|
|
135
|
+
const ext = extMap(finding);
|
|
136
|
+
const rank = ext[PALLIATIVE_EXT.FINDING_RANK];
|
|
137
|
+
return {
|
|
138
|
+
rank,
|
|
139
|
+
elementType: ext[PALLIATIVE_EXT.FINDING_ELEMENT_TYPE],
|
|
140
|
+
nameShort: finding.item?.concept?.text || null,
|
|
141
|
+
timeWindow: ext[PALLIATIVE_EXT.FINDING_TIME_WINDOW] || '',
|
|
142
|
+
symptomTerms: extValues(finding, PALLIATIVE_EXT.FINDING_SYMPTOM_TERM),
|
|
143
|
+
clinicalDescription: ext[PALLIATIVE_EXT.FINDING_CLINICAL_DESCRIPTION] || '',
|
|
144
|
+
whyRelevant: ext[PALLIATIVE_EXT.FINDING_WHY_RELEVANT] || '',
|
|
145
|
+
qolImpact: ext[PALLIATIVE_EXT.FINDING_QOL_IMPACT] || null,
|
|
146
|
+
qolCriteria: ext[PALLIATIVE_EXT.FINDING_QOL_CRITERIA] || '',
|
|
147
|
+
improvementCapacity: ext[PALLIATIVE_EXT.FINDING_IMPROVEMENT_CAPACITY] || null,
|
|
148
|
+
improvementCriteria: ext[PALLIATIVE_EXT.FINDING_IMPROVEMENT_CRITERIA] || '',
|
|
149
|
+
areMedsNeeded: ext[PALLIATIVE_EXT.FINDING_ARE_MEDS_NEEDED] ?? null,
|
|
150
|
+
needsCharacterization: ext[PALLIATIVE_EXT.FINDING_NEEDS_CHARACTERIZATION] ?? null,
|
|
151
|
+
characterizationCriteria: ext[PALLIATIVE_EXT.FINDING_CHARACTERIZATION_CRITERIA] || '',
|
|
152
|
+
probeQuestions: extValues(finding, PALLIATIVE_EXT.FINDING_PROBE_QUESTION),
|
|
153
|
+
auditNotes: ext[PALLIATIVE_EXT.FINDING_AUDIT_NOTES] || '',
|
|
154
|
+
clusterNote: ext[PALLIATIVE_EXT.FINDING_CLUSTER_NOTE] ?? null,
|
|
155
|
+
escalation: escalationsById.get(`${assessmentId}-${rank}`) || null,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function reconstructEscalation(task, patientId) {
|
|
160
|
+
const end = task.restriction?.period?.end;
|
|
161
|
+
const hours = end
|
|
162
|
+
? Math.round((new Date(end).getTime() - new Date(task.authoredOn).getTime()) / 3600000)
|
|
163
|
+
: DEFAULT_ESCALATION_HOURS;
|
|
164
|
+
return {
|
|
165
|
+
patientId,
|
|
166
|
+
maxActionTimeHours: hours,
|
|
167
|
+
escalationRoutes: (task.requestedPerformer || []).map((performer) => performer.concept?.text || null),
|
|
168
|
+
escalationReason: task.description || '',
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = {
|
|
173
|
+
toFhir,
|
|
174
|
+
fromFhir,
|
|
175
|
+
};
|