@peopl-health/nexus 6.0.0-dev.718 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
const { logger } = require('../../utils/logger');
|
|
2
1
|
const { getSystems } = require('../config/fhirConfig');
|
|
3
2
|
const { codeSystemUrl } = require('../helpers/fhirHelper');
|
|
4
3
|
const { codeableConcept } = require('../helpers/elementHelper');
|
|
5
4
|
const terminology = require('../helpers/terminologyHelper');
|
|
6
5
|
const { PAIN_TERM } = require('../helpers/compositeHelper');
|
|
6
|
+
const { OTHER_SYMPTOMS_INTENSITY_SCALE } = require('../helpers/triagePayloadHelper');
|
|
7
|
+
const { GRADE_METHOD } = require('../constants/gradeMethods');
|
|
8
|
+
const { logger } = require('../../utils/logger');
|
|
7
9
|
const { Condition } = require('../resources/Condition');
|
|
8
10
|
const { Device } = require('../resources/Device');
|
|
9
11
|
const { Observation } = require('../resources/Observation');
|
|
@@ -11,19 +13,27 @@ const { Patient } = require('../resources/Patient');
|
|
|
11
13
|
const { Questionnaire } = require('../resources/Questionnaire');
|
|
12
14
|
const { QuestionnaireResponse } = require('../resources/QuestionnaireResponse');
|
|
13
15
|
|
|
14
|
-
const GRADE_METHOD = 'PRO-CTCAE composite → CTCAE (unofficial approximation)';
|
|
15
16
|
const INGEST_DEVICE_ID = 'lookup-table-grade-estimator';
|
|
16
17
|
|
|
17
18
|
const PAIN_PRESENCE_LINK = 'pain.presence';
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
19
|
+
const PAIN_SYMPTOMS_LINK = 'pain.symptoms';
|
|
20
|
+
const PAIN_MOST_IMPORTANT_LINK = 'pain.most_important';
|
|
21
|
+
const PAIN_OTHER_LINK = 'pain.other';
|
|
22
|
+
const ADDITIONAL_SYMPTOMS_LINK = 'triage.additional_symptoms';
|
|
23
|
+
const OTHER_SYMPTOMS_LINK = 'triage.other_symptoms';
|
|
24
|
+
const OTHER_SYMPTOMS_INTENSITY_LINK = 'triage.other_symptoms_intensity';
|
|
25
|
+
const NON_IDENTIFIED_SYMPTOMS_LINK = 'triage.non_identified_symptoms';
|
|
26
|
+
const SYMPTOMS_CHANGE_LINK = 'triage.symptoms_change';
|
|
24
27
|
|
|
25
28
|
const linkId = (term, dimension) => `${term}.${dimension}`;
|
|
26
29
|
|
|
30
|
+
function symptomPickAnswers(catalog, picks) {
|
|
31
|
+
return (picks || []).map((pick) => String(pick).trim()).filter(Boolean).map((pick) => {
|
|
32
|
+
const term = terminology.termForItem(catalog, pick);
|
|
33
|
+
return term ? { valueCoding: terminology.codingsFor(catalog, term)[0] } : { valueString: pick };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
27
37
|
const answerOption = (catalog, dimension, options) =>
|
|
28
38
|
options.map((label, i) => {
|
|
29
39
|
const weight = terminology.standardOrdinal(catalog, dimension, label);
|
|
@@ -47,12 +57,29 @@ function painCanonicalItems(catalog) {
|
|
|
47
57
|
type: 'coding',
|
|
48
58
|
answerOption: answerOption(catalog, 'presence', terminology.standardScale(catalog, 'presence')),
|
|
49
59
|
},
|
|
50
|
-
{ linkId:
|
|
60
|
+
{ linkId: PAIN_SYMPTOMS_LINK, text: 'Dolor — síntomas confirmados', type: 'coding', repeats: true },
|
|
61
|
+
{ linkId: PAIN_MOST_IMPORTANT_LINK, text: 'Dolor más importante — descripción libre', type: 'string' },
|
|
62
|
+
{ linkId: PAIN_OTHER_LINK, text: 'Dolor — descripción libre', type: 'string' },
|
|
63
|
+
];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function freeTextCanonicalItems() {
|
|
67
|
+
return [
|
|
68
|
+
{ linkId: ADDITIONAL_SYMPTOMS_LINK, text: 'Síntomas adicionales reportados', type: 'coding', repeats: true },
|
|
69
|
+
{ linkId: OTHER_SYMPTOMS_LINK, text: 'Otros síntomas — descripción libre', type: 'string' },
|
|
70
|
+
{
|
|
71
|
+
linkId: OTHER_SYMPTOMS_INTENSITY_LINK,
|
|
72
|
+
text: 'Otros síntomas — intensidad',
|
|
73
|
+
type: 'string',
|
|
74
|
+
answerOption: OTHER_SYMPTOMS_INTENSITY_SCALE.map((label) => ({ valueString: label })),
|
|
75
|
+
},
|
|
76
|
+
{ linkId: NON_IDENTIFIED_SYMPTOMS_LINK, text: 'Síntomas no evaluados en el triaje — respuesta', type: 'string' },
|
|
77
|
+
{ linkId: SYMPTOMS_CHANGE_LINK, text: 'Cambio reportado de síntomas', type: 'string', repeats: true },
|
|
51
78
|
];
|
|
52
79
|
}
|
|
53
80
|
|
|
54
81
|
function projectProctcaeCanonical(catalog) {
|
|
55
|
-
const items = painCanonicalItems(catalog);
|
|
82
|
+
const items = [...painCanonicalItems(catalog), ...freeTextCanonicalItems()];
|
|
56
83
|
for (const term of terminology.allTerms(catalog)) {
|
|
57
84
|
const textEs = terminology.codeText(catalog, term);
|
|
58
85
|
for (const dim of terminology.dimensionsFor(catalog, term)) {
|
|
@@ -73,7 +100,7 @@ function projectProctcaeCanonical(catalog) {
|
|
|
73
100
|
}
|
|
74
101
|
|
|
75
102
|
function projectTriagePatient(patientId) {
|
|
76
|
-
return Patient.
|
|
103
|
+
return Patient.fromClinicalProfile({ patientId });
|
|
77
104
|
}
|
|
78
105
|
|
|
79
106
|
function projectTriageIngestDevice(catalog) {
|
|
@@ -109,7 +136,7 @@ function projectProctcaeSymptomObservation(catalog, sym) {
|
|
|
109
136
|
: null,
|
|
110
137
|
components,
|
|
111
138
|
gradeConcept: terminology.gradeConcept(sym.grade),
|
|
112
|
-
method: codeableConcept(GRADE_METHOD),
|
|
139
|
+
method: codeableConcept(sym.gradeBasis && sym.gradeBasis !== 'composite' ? `${GRADE_METHOD.proctcae_composite} · ${sym.gradeBasis}` : GRADE_METHOD.proctcae_composite),
|
|
113
140
|
deviceId: INGEST_DEVICE_ID,
|
|
114
141
|
});
|
|
115
142
|
}
|
|
@@ -153,12 +180,32 @@ function projectTriageQuestionnaireResponse(catalog, qr) {
|
|
|
153
180
|
: { valueString: String(label) };
|
|
154
181
|
byLink.set(link, { linkId: link, answer: [answer] });
|
|
155
182
|
}
|
|
156
|
-
const
|
|
157
|
-
if (
|
|
158
|
-
byLink.set(
|
|
183
|
+
const painPicks = symptomPickAnswers(catalog, pain.locations);
|
|
184
|
+
if (painPicks.length) {
|
|
185
|
+
byLink.set(PAIN_SYMPTOMS_LINK, { linkId: PAIN_SYMPTOMS_LINK, answer: painPicks });
|
|
159
186
|
}
|
|
160
187
|
}
|
|
161
188
|
}
|
|
189
|
+
const setFreeText = (link, value) => {
|
|
190
|
+
const text = String(value ?? '').trim();
|
|
191
|
+
if (text) byLink.set(link, { linkId: link, answer: [{ valueString: text }] });
|
|
192
|
+
};
|
|
193
|
+
setFreeText(PAIN_MOST_IMPORTANT_LINK, pain.mostImportant);
|
|
194
|
+
setFreeText(PAIN_OTHER_LINK, pain.otherText);
|
|
195
|
+
const additional = symptomPickAnswers(catalog, qr.additionalSymptoms);
|
|
196
|
+
if (additional.length) {
|
|
197
|
+
byLink.set(ADDITIONAL_SYMPTOMS_LINK, { linkId: ADDITIONAL_SYMPTOMS_LINK, answer: additional });
|
|
198
|
+
}
|
|
199
|
+
setFreeText(OTHER_SYMPTOMS_LINK, qr.otherSymptomsText);
|
|
200
|
+
setFreeText(OTHER_SYMPTOMS_INTENSITY_LINK, qr.otherSymptomsInterference);
|
|
201
|
+
setFreeText(NON_IDENTIFIED_SYMPTOMS_LINK, qr.nonIdentifiedSymptoms);
|
|
202
|
+
const changes = (qr.symptomsChange || []).map((entry) => String(entry).trim()).filter(Boolean);
|
|
203
|
+
if (changes.length) {
|
|
204
|
+
byLink.set(SYMPTOMS_CHANGE_LINK, {
|
|
205
|
+
linkId: SYMPTOMS_CHANGE_LINK,
|
|
206
|
+
answer: changes.map((entry) => ({ valueString: entry })),
|
|
207
|
+
});
|
|
208
|
+
}
|
|
162
209
|
return QuestionnaireResponse.fromTriageProjection({ qr, items: [...byLink.values()] });
|
|
163
210
|
}
|
|
164
211
|
|
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
const { getDeviceId } = require('../config/fhirConfig');
|
|
2
|
+
const { codeSystemUrl } = require('../helpers/fhirHelper');
|
|
3
|
+
const { reference, patientReference, codeableConcept, extension, toIso } = require('../helpers/elementHelper');
|
|
4
|
+
const { baseResource, provenance } = require('../helpers/resourceHelper');
|
|
5
|
+
const { extMap, extValues, identifierValue, objectExtension } = require('../helpers/fhirReadHelper');
|
|
6
|
+
const { recommendationId, sourceOfRun } = require('../helpers/recommendationIds');
|
|
7
|
+
const { isQuoteAnchored } = require('../../utils/textMatchUtils');
|
|
8
|
+
const { RECOMMENDATION_EXT } = require('../constants/extensionSlugs');
|
|
9
|
+
const {
|
|
10
|
+
RECOMMENDATION_PLAN_SLUG,
|
|
11
|
+
RECOMMENDATION_ELEMENTS_SLUG,
|
|
12
|
+
RECOMMENDATION_REC_SLUG,
|
|
13
|
+
} = require('../constants/projectionSlugs');
|
|
14
|
+
|
|
15
|
+
const PROJECTOR_NAME = 'recommendationPlan';
|
|
16
|
+
const ACTIVITY_TEXT = 'recommendations-process';
|
|
17
|
+
const OUTCOME_KEY = 'recommendation-outcome';
|
|
18
|
+
const REVIEW_KEY = 'recommendation-review';
|
|
19
|
+
const REVIEW_VERDICTS = ['confirmed', 'corrected', 'rejected'];
|
|
20
|
+
const NOTE_SEPARATOR = ': ';
|
|
21
|
+
const CARE_PLAN_CATEGORY = 'symptom_management';
|
|
22
|
+
const NOTE_LABELS = {
|
|
23
|
+
whenToEscalate: 'cuándo escalar',
|
|
24
|
+
expectedEffectiveness: 'efectividad esperada',
|
|
25
|
+
contraindications: 'contraindicaciones',
|
|
26
|
+
isPharmacologicalMedNeeded: 'requiere coordinación farmacológica',
|
|
27
|
+
characterizationNeeded: 'requiere caracterización',
|
|
28
|
+
minCharacterizationVariables: 'variables de caracterización',
|
|
29
|
+
};
|
|
30
|
+
const NOTE_KEYS = Object.fromEntries(Object.entries(NOTE_LABELS).map(([key, label]) => [label, key]));
|
|
31
|
+
|
|
32
|
+
const BASIS_LABELS = { rank: 'rank', type: 'tipo', qolImpact: 'QoL', whyRelevant: 'relevancia', groundedIn: 'sustento' };
|
|
33
|
+
const BASIS_SEPARATOR = '; ';
|
|
34
|
+
const EMPTY_BASIS = { rank: null, type: null, qolImpact: null, whyRelevant: null, groundedIn: [] };
|
|
35
|
+
|
|
36
|
+
function toFhir({ plan, hasSafetyGate, anchorAgainst = null, qualityWarnings = [], producedBy = null }) {
|
|
37
|
+
const ranked = [...plan.elements].sort((a, b) => a.rank - b.rank);
|
|
38
|
+
const taskIds = ranked.map((element) => recommendationId(plan.runId, element.rank));
|
|
39
|
+
const elements = elementsResource(plan, ranked, anchorAgainst);
|
|
40
|
+
const carePlan = carePlanResource(plan, taskIds, hasSafetyGate, { qualityWarnings, producedBy });
|
|
41
|
+
const tasks = ranked.map((element, index) => recommendationResource(plan, element, taskIds[index]));
|
|
42
|
+
return [
|
|
43
|
+
elements,
|
|
44
|
+
carePlan,
|
|
45
|
+
...tasks,
|
|
46
|
+
provenance({
|
|
47
|
+
provenanceId: `${plan.runId}-careplan-prov`,
|
|
48
|
+
targetRefs: [elements, carePlan, ...tasks].map((resource) => ({ reference: `${resource.resourceType}/${resource.id}` })),
|
|
49
|
+
recordedAt: plan.createdAt,
|
|
50
|
+
activity: codeableConcept(ACTIVITY_TEXT),
|
|
51
|
+
}),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function elementsResource(plan, ranked, anchorAgainst) {
|
|
56
|
+
const payload = {
|
|
57
|
+
...baseResource('ClinicalImpression', `${plan.runId}-palliative`, RECOMMENDATION_ELEMENTS_SLUG),
|
|
58
|
+
subject: patientReference(plan.patientId),
|
|
59
|
+
status: 'completed',
|
|
60
|
+
effectiveDateTime: toIso(plan.createdAt),
|
|
61
|
+
finding: ranked.map((element) => ({
|
|
62
|
+
item: { concept: codeableConcept(element.nameShort) },
|
|
63
|
+
basis: elementBasis(element),
|
|
64
|
+
extension: elementExtensions(element, anchorAgainst),
|
|
65
|
+
})),
|
|
66
|
+
};
|
|
67
|
+
if (plan.takeaways.summaryInternal) payload.summary = plan.takeaways.summaryInternal;
|
|
68
|
+
return payload;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function elementBasis(element) {
|
|
72
|
+
const basis = [`rank: ${element.rank}`, `tipo: ${element.type}`];
|
|
73
|
+
if (element.qolImpact) basis.push(`QoL: ${element.qolImpact}`);
|
|
74
|
+
if (element.whyRelevant) basis.push(`relevancia: ${element.whyRelevant}`);
|
|
75
|
+
const grounding = element.groundedIn.filter(Boolean).join('; ');
|
|
76
|
+
if (grounding) basis.push(`sustento: ${grounding}`);
|
|
77
|
+
return basis.join('; ');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const evidenceExtension = (text, anchorAgainst) => extension(RECOMMENDATION_EXT.ELEMENT_EVIDENCE, {
|
|
81
|
+
// Strict, or 60% token overlap would stamp "anchored" on a sentence with an invented word.
|
|
82
|
+
valueString: JSON.stringify({ text, anchored: isQuoteAnchored(text, anchorAgainst, { strict: true }) }),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
function elementExtensions(element, anchorAgainst = null) {
|
|
86
|
+
const out = [
|
|
87
|
+
extension(RECOMMENDATION_EXT.ELEMENT_RANK, { valueInteger: element.rank }),
|
|
88
|
+
extension(RECOMMENDATION_EXT.ELEMENT_TYPE, { valueString: element.type }),
|
|
89
|
+
extension(RECOMMENDATION_EXT.ELEMENT_WHY_RELEVANT, { valueString: element.whyRelevant }),
|
|
90
|
+
extension(RECOMMENDATION_EXT.ELEMENT_ESCALATION_URGENT, { valueBoolean: element.escalation.urgentUnder24h }),
|
|
91
|
+
];
|
|
92
|
+
for (const grounding of element.groundedIn) {
|
|
93
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_GROUNDED_IN, { valueString: grounding }));
|
|
94
|
+
if (anchorAgainst) out.push(evidenceExtension(grounding, anchorAgainst));
|
|
95
|
+
}
|
|
96
|
+
for (const symptom of element.recommendation.symptomsPatientFacing) {
|
|
97
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_SYMPTOM_PATIENT_FACING, { valueString: symptom }));
|
|
98
|
+
}
|
|
99
|
+
for (const symptom of element.symptoms) {
|
|
100
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_SYMPTOM, { valueString: JSON.stringify(symptom) }));
|
|
101
|
+
}
|
|
102
|
+
for (const route of element.escalation.routes) {
|
|
103
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_ESCALATION_ROUTE, { valueString: route }));
|
|
104
|
+
}
|
|
105
|
+
if (element.timeWindow !== null) out.push(extension(RECOMMENDATION_EXT.ELEMENT_TIME_WINDOW, { valueString: element.timeWindow }));
|
|
106
|
+
if (element.qolImpact !== null) out.push(extension(RECOMMENDATION_EXT.ELEMENT_QOL_IMPACT, { valueString: element.qolImpact }));
|
|
107
|
+
if (element.improvementCapacity !== null) {
|
|
108
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_IMPROVEMENT_CAPACITY, { valueString: element.improvementCapacity }));
|
|
109
|
+
}
|
|
110
|
+
if (element.escalation.maxActionTimeHours !== null) {
|
|
111
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_ESCALATION_MAX_HOURS, { valueInteger: element.escalation.maxActionTimeHours }));
|
|
112
|
+
}
|
|
113
|
+
if (element.escalation.clinicalCriteria !== null) {
|
|
114
|
+
out.push(extension(RECOMMENDATION_EXT.ELEMENT_ESCALATION_CRITERIA, { valueString: element.escalation.clinicalCriteria }));
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function carePlanResource(plan, taskIds, hasSafetyGate, audit) {
|
|
120
|
+
const payload = {
|
|
121
|
+
...baseResource('CarePlan', `${plan.runId}-careplan`, RECOMMENDATION_PLAN_SLUG),
|
|
122
|
+
subject: patientReference(plan.patientId),
|
|
123
|
+
status: 'active',
|
|
124
|
+
intent: 'plan',
|
|
125
|
+
category: [codeableConcept(CARE_PLAN_CATEGORY)],
|
|
126
|
+
created: toIso(plan.createdAt),
|
|
127
|
+
activity: taskIds.map((taskId) => ({ plannedActivityReference: reference('Task', taskId) })),
|
|
128
|
+
extension: planExtensions(plan, audit),
|
|
129
|
+
};
|
|
130
|
+
if (hasSafetyGate) payload.supportingInfo = [reference('RiskAssessment', `${plan.runId}-safety`)];
|
|
131
|
+
if (plan.takeaways.summaryInternal) payload.description = plan.takeaways.summaryInternal;
|
|
132
|
+
if (plan.takeaways.summaryPatientFacing) payload.note = [{ text: plan.takeaways.summaryPatientFacing }];
|
|
133
|
+
return payload;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// On the plan, not the settle event: the chat lane writes none.
|
|
137
|
+
const warningRecord = (warning) => {
|
|
138
|
+
if (typeof warning === 'string') {
|
|
139
|
+
const text = warning.trim();
|
|
140
|
+
return text ? { code: null, path: null, problem: text } : null;
|
|
141
|
+
}
|
|
142
|
+
const problem = typeof warning?.problem === 'string' ? warning.problem.trim() : '';
|
|
143
|
+
if (!problem) return null;
|
|
144
|
+
return {
|
|
145
|
+
code: typeof warning?.code === 'string' ? warning.code : null,
|
|
146
|
+
path: typeof warning?.path === 'string' ? warning.path.trim() || null : null,
|
|
147
|
+
problem,
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
function planExtensions(plan, { qualityWarnings = [], producedBy = null } = {}) {
|
|
152
|
+
const out = [
|
|
153
|
+
extension(RECOMMENDATION_EXT.ORIGIN, { valueString: plan.origin }),
|
|
154
|
+
extension(RECOMMENDATION_EXT.TURN_ID, { valueString: plan.turnId }),
|
|
155
|
+
extension(RECOMMENDATION_EXT.SAFETY_CONFIRMATION_NEEDED, { valueBoolean: plan.takeaways.safetyConfirmationNeeded }),
|
|
156
|
+
extension(RECOMMENDATION_EXT.VITAL_RISK_POSSIBLE_NOW, { valueBoolean: plan.takeaways.vitalRiskPossibleNow }),
|
|
157
|
+
];
|
|
158
|
+
if (plan.takeaways.safetyConfirmationQuestion !== null) {
|
|
159
|
+
out.push(extension(RECOMMENDATION_EXT.SAFETY_CONFIRMATION_QUESTION, { valueString: plan.takeaways.safetyConfirmationQuestion }));
|
|
160
|
+
}
|
|
161
|
+
for (const warning of (qualityWarnings || []).map(warningRecord).filter(Boolean)) {
|
|
162
|
+
out.push(extension(RECOMMENDATION_EXT.QUALITY_WARNING, { valueString: JSON.stringify(warning) }));
|
|
163
|
+
}
|
|
164
|
+
if (producedBy?.model) out.push(extension(RECOMMENDATION_EXT.PRODUCED_BY_MODEL, { valueString: producedBy.model }));
|
|
165
|
+
if (producedBy?.methodVersion) {
|
|
166
|
+
out.push(extension(RECOMMENDATION_EXT.METHOD_VERSION, { valueString: producedBy.methodVersion }));
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function recommendationResource(plan, element, taskId) {
|
|
172
|
+
const { recommendation } = element;
|
|
173
|
+
return {
|
|
174
|
+
...baseResource('Task', taskId, RECOMMENDATION_REC_SLUG),
|
|
175
|
+
for: patientReference(plan.patientId),
|
|
176
|
+
status: 'requested',
|
|
177
|
+
intent: 'plan',
|
|
178
|
+
code: {
|
|
179
|
+
text: element.nameShort,
|
|
180
|
+
coding: element.targetedCtcaeTerms.map((term) => ({
|
|
181
|
+
system: codeSystemUrl('pro-ctcae'), code: term, display: term,
|
|
182
|
+
})),
|
|
183
|
+
},
|
|
184
|
+
description: recommendation.patient.mainRecommendation,
|
|
185
|
+
authoredOn: toIso(plan.createdAt),
|
|
186
|
+
requester: reference('Device', getDeviceId()),
|
|
187
|
+
note: recommendationNotes(element).map((text) => ({ text })),
|
|
188
|
+
extension: recommendationExtensions(recommendation, plan),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function recommendationExtensions(recommendation, plan) {
|
|
193
|
+
const out = [extension(RECOMMENDATION_EXT.REC_RUN_ID, { valueString: plan.runId })];
|
|
194
|
+
if (recommendation.otcOffer) {
|
|
195
|
+
out.push(extension(RECOMMENDATION_EXT.REC_OTC_OFFER, { valueString: JSON.stringify(recommendation.otcOffer) }));
|
|
196
|
+
}
|
|
197
|
+
if (recommendation.followup !== null && recommendation.followup !== undefined) {
|
|
198
|
+
out.push(extension(RECOMMENDATION_EXT.REC_FOLLOWUP, { valueString: recommendation.followup }));
|
|
199
|
+
}
|
|
200
|
+
if (recommendation.followupUrgency !== null && recommendation.followupUrgency !== undefined) {
|
|
201
|
+
out.push(extension(RECOMMENDATION_EXT.REC_FOLLOWUP_URGENCY, { valueString: recommendation.followupUrgency }));
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function recommendationNotes(element) {
|
|
207
|
+
const { recommendation } = element;
|
|
208
|
+
const { patient } = recommendation;
|
|
209
|
+
const out = [];
|
|
210
|
+
if (patient.whenToEscalate) out.push(`${NOTE_LABELS.whenToEscalate}: ${patient.whenToEscalate}`);
|
|
211
|
+
if (patient.expectedEffectiveness) out.push(`${NOTE_LABELS.expectedEffectiveness}: ${patient.expectedEffectiveness}`);
|
|
212
|
+
if (patient.contraindications) out.push(`${NOTE_LABELS.contraindications}: ${patient.contraindications}`);
|
|
213
|
+
out.push(`${NOTE_LABELS.isPharmacologicalMedNeeded}: ${recommendation.isPharmacologicalMedNeeded}`);
|
|
214
|
+
if (element.characterizationNeeded !== null && element.characterizationNeeded !== undefined) {
|
|
215
|
+
out.push(`${NOTE_LABELS.characterizationNeeded}: ${element.characterizationNeeded}`);
|
|
216
|
+
}
|
|
217
|
+
if (element.minCharacterizationVariables?.length) {
|
|
218
|
+
out.push(`${NOTE_LABELS.minCharacterizationVariables}: ${JSON.stringify(element.minCharacterizationVariables)}`);
|
|
219
|
+
}
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function recommendationNotesOf(task) {
|
|
224
|
+
const out = {};
|
|
225
|
+
for (const entry of task.note || []) {
|
|
226
|
+
const text = String(entry.text || '');
|
|
227
|
+
const separator = text.indexOf(NOTE_SEPARATOR);
|
|
228
|
+
if (separator < 0) continue;
|
|
229
|
+
const key = NOTE_KEYS[text.slice(0, separator)];
|
|
230
|
+
if (key) out[key] = text.slice(separator + NOTE_SEPARATOR.length);
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function characterizationVariablesOf(noteValue) {
|
|
236
|
+
if (!noteValue) return [];
|
|
237
|
+
try {
|
|
238
|
+
const parsed = JSON.parse(noteValue);
|
|
239
|
+
return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === 'string') : [];
|
|
240
|
+
} catch {
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function outcomeEntry({ outcome, adherence, notes, source, recordedAt, eventKey = null }) {
|
|
246
|
+
const entry = {
|
|
247
|
+
type: codeableConcept(OUTCOME_KEY),
|
|
248
|
+
valueCodeableConcept: codeableConcept(outcome, { code: outcome, system: codeSystemUrl(OUTCOME_KEY) }),
|
|
249
|
+
extension: [extension(RECOMMENDATION_EXT.OUTCOME_SOURCE, { valueString: source })],
|
|
250
|
+
};
|
|
251
|
+
if (adherence) entry.extension.push(extension(RECOMMENDATION_EXT.OUTCOME_ADHERENCE, { valueString: adherence }));
|
|
252
|
+
if (notes) entry.extension.push(extension(RECOMMENDATION_EXT.OUTCOME_NOTES, { valueString: notes }));
|
|
253
|
+
entry.extension.push(extension(RECOMMENDATION_EXT.OUTCOME_RECORDED_AT, { valueDateTime: recordedAt }));
|
|
254
|
+
if (eventKey) entry.extension.push(extension(RECOMMENDATION_EXT.OUTCOME_EVENT, { valueString: eventKey }));
|
|
255
|
+
return entry;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function reviewEntry({ verdict, note, correctedText, reviewedBy, recordedAt, eventKey }) {
|
|
259
|
+
const entry = {
|
|
260
|
+
type: codeableConcept(REVIEW_KEY),
|
|
261
|
+
valueCodeableConcept: codeableConcept(verdict, { code: verdict, system: codeSystemUrl(REVIEW_KEY) }),
|
|
262
|
+
extension: [
|
|
263
|
+
extension(RECOMMENDATION_EXT.REVIEW_VERDICT, { valueString: verdict }),
|
|
264
|
+
extension(RECOMMENDATION_EXT.REVIEW_BY, { valueString: reviewedBy }),
|
|
265
|
+
extension(RECOMMENDATION_EXT.REVIEW_RECORDED_AT, { valueDateTime: recordedAt }),
|
|
266
|
+
],
|
|
267
|
+
};
|
|
268
|
+
if (note) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_NOTE, { valueString: note }));
|
|
269
|
+
if (correctedText) {
|
|
270
|
+
entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT, { valueString: correctedText }));
|
|
271
|
+
}
|
|
272
|
+
if (eventKey) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_EVENT, { valueString: eventKey }));
|
|
273
|
+
return entry;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const hasReviewEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.REVIEW_EVENT);
|
|
277
|
+
|
|
278
|
+
const reviewOf = (entry) => {
|
|
279
|
+
const ext = extMap(entry);
|
|
280
|
+
return {
|
|
281
|
+
verdict: ext[RECOMMENDATION_EXT.REVIEW_VERDICT] || null,
|
|
282
|
+
note: ext[RECOMMENDATION_EXT.REVIEW_NOTE] || null,
|
|
283
|
+
correctedText: ext[RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT] || null,
|
|
284
|
+
reviewedBy: ext[RECOMMENDATION_EXT.REVIEW_BY] || null,
|
|
285
|
+
recordedAt: ext[RECOMMENDATION_EXT.REVIEW_RECORDED_AT] || null,
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
function reviewByEvent(task, eventKey) {
|
|
290
|
+
const entry = (task?.output || []).find((row) => (
|
|
291
|
+
row.type?.text === REVIEW_KEY && extMap(row)[RECOMMENDATION_EXT.REVIEW_EVENT] === eventKey
|
|
292
|
+
));
|
|
293
|
+
return entry ? reviewOf(entry) : null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// By `recordedAt`, not insertion order: concurrent writes timestamp before they upsert.
|
|
297
|
+
function reviewHistoryOf(task) {
|
|
298
|
+
return (task.output || [])
|
|
299
|
+
.filter((entry) => entry.type?.text === REVIEW_KEY)
|
|
300
|
+
.map(reviewOf)
|
|
301
|
+
.map((review, index) => ({ review, index, at: Date.parse(review.recordedAt ?? '') }))
|
|
302
|
+
.sort((a, b) => {
|
|
303
|
+
const left = Number.isFinite(a.at) ? a.at : -Infinity;
|
|
304
|
+
const right = Number.isFinite(b.at) ? b.at : -Infinity;
|
|
305
|
+
return left === right ? a.index - b.index : left - right;
|
|
306
|
+
})
|
|
307
|
+
.map(({ review }) => review);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function hasEvent(task, eventKey, slug) {
|
|
311
|
+
return (task?.output || []).some((entry) => extMap(entry)[slug] === eventKey);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const hasOutcomeEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.OUTCOME_EVENT);
|
|
315
|
+
|
|
316
|
+
function outcomeHistoryOf(task) {
|
|
317
|
+
return (task.output || [])
|
|
318
|
+
.filter((entry) => entry.type?.text === OUTCOME_KEY)
|
|
319
|
+
.map((entry) => {
|
|
320
|
+
const ext = extMap(entry);
|
|
321
|
+
return {
|
|
322
|
+
outcome: entry.valueCodeableConcept?.coding?.[0]?.code || entry.valueCodeableConcept?.text || null,
|
|
323
|
+
adherence: ext[RECOMMENDATION_EXT.OUTCOME_ADHERENCE] || null,
|
|
324
|
+
source: ext[RECOMMENDATION_EXT.OUTCOME_SOURCE] || null,
|
|
325
|
+
notes: ext[RECOMMENDATION_EXT.OUTCOME_NOTES] || null,
|
|
326
|
+
recordedAt: ext[RECOMMENDATION_EXT.OUTCOME_RECORDED_AT] || null,
|
|
327
|
+
};
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function mergedOutcome(task) {
|
|
332
|
+
const rows = outcomeHistoryOf(task);
|
|
333
|
+
if (!rows.length) return null;
|
|
334
|
+
const merged = rows.reduce((prior, row) => ({
|
|
335
|
+
outcome: row.outcome === 'unknown' && prior.outcome && prior.outcome !== 'unknown' ? prior.outcome : row.outcome,
|
|
336
|
+
adherence: row.adherence === null ? prior.adherence : row.adherence,
|
|
337
|
+
source: row.source === null ? prior.source : row.source,
|
|
338
|
+
notes: row.notes === null ? prior.notes : row.notes,
|
|
339
|
+
recordedAt: row.recordedAt === null ? prior.recordedAt : row.recordedAt,
|
|
340
|
+
}));
|
|
341
|
+
return {
|
|
342
|
+
outcome: merged.outcome,
|
|
343
|
+
adherence: merged.adherence,
|
|
344
|
+
source: merged.source || 'chat',
|
|
345
|
+
notes: merged.notes,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function fromFhir(resources, { patientId }) {
|
|
350
|
+
const elementsByRun = new Map();
|
|
351
|
+
const tasksById = new Map();
|
|
352
|
+
for (const resource of resources) {
|
|
353
|
+
if (resource.resourceType === 'ClinicalImpression') {
|
|
354
|
+
const elementsId = identifierValue(resource, RECOMMENDATION_ELEMENTS_SLUG);
|
|
355
|
+
if (elementsId) elementsByRun.set(elementsId.replace(/-palliative$/, ''), resource);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (resource.resourceType !== 'Task') continue;
|
|
359
|
+
const taskId = identifierValue(resource, RECOMMENDATION_REC_SLUG);
|
|
360
|
+
if (taskId) tasksById.set(taskId, resource);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const out = [];
|
|
364
|
+
for (const resource of resources) {
|
|
365
|
+
if (resource.resourceType !== 'CarePlan') continue;
|
|
366
|
+
const planId = identifierValue(resource, RECOMMENDATION_PLAN_SLUG);
|
|
367
|
+
if (!planId) continue;
|
|
368
|
+
const runId = planId.replace(/-careplan$/, '');
|
|
369
|
+
out.push(reconstruct({
|
|
370
|
+
plan: resource,
|
|
371
|
+
runId,
|
|
372
|
+
elements: elementsByRun.get(runId) || null,
|
|
373
|
+
tasksById,
|
|
374
|
+
patientId,
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
return out;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function reconstruct({ plan, runId, elements, tasksById, patientId }) {
|
|
381
|
+
const ext = extMap(plan);
|
|
382
|
+
return {
|
|
383
|
+
schemaVersion: '1',
|
|
384
|
+
runId,
|
|
385
|
+
patientId,
|
|
386
|
+
origin: ext[RECOMMENDATION_EXT.ORIGIN] || sourceOfRun(runId),
|
|
387
|
+
turnId: ext[RECOMMENDATION_EXT.TURN_ID] || null,
|
|
388
|
+
qualityWarnings: extValues(plan, RECOMMENDATION_EXT.QUALITY_WARNING)
|
|
389
|
+
.map(objectExtension)
|
|
390
|
+
.map(warningRecord)
|
|
391
|
+
.filter(Boolean),
|
|
392
|
+
producedBy: {
|
|
393
|
+
model: ext[RECOMMENDATION_EXT.PRODUCED_BY_MODEL] || null,
|
|
394
|
+
methodVersion: ext[RECOMMENDATION_EXT.METHOD_VERSION] || null,
|
|
395
|
+
},
|
|
396
|
+
createdAt: plan.created || null,
|
|
397
|
+
safetyGateRunId: plan.supportingInfo?.length ? runId : null,
|
|
398
|
+
takeaways: {
|
|
399
|
+
safetyConfirmationNeeded: ext[RECOMMENDATION_EXT.SAFETY_CONFIRMATION_NEEDED] ?? false,
|
|
400
|
+
safetyConfirmationQuestion: ext[RECOMMENDATION_EXT.SAFETY_CONFIRMATION_QUESTION] ?? null,
|
|
401
|
+
vitalRiskPossibleNow: ext[RECOMMENDATION_EXT.VITAL_RISK_POSSIBLE_NOW] ?? false,
|
|
402
|
+
summaryPatientFacing: plan.note?.[0]?.text || '',
|
|
403
|
+
summaryInternal: plan.description || elements?.summary || '',
|
|
404
|
+
},
|
|
405
|
+
elements: (elements?.finding || []).map((finding, index) => reconstructElement(finding, index, runId, tasksById)),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function reconstructElement(finding, index, runId, tasksById) {
|
|
410
|
+
const ext = extMap(finding);
|
|
411
|
+
const basis = hasElementExtensions(ext) ? EMPTY_BASIS : parseBasis(finding.basis);
|
|
412
|
+
const rank = ext[RECOMMENDATION_EXT.ELEMENT_RANK] ?? basis.rank ?? index + 1;
|
|
413
|
+
const task = taskFor(runId, rank, tasksById);
|
|
414
|
+
const noteMap = task ? recommendationNotesOf(task) : {};
|
|
415
|
+
const taskExt = task ? extMap(task) : {};
|
|
416
|
+
const groundedIn = extValues(finding, RECOMMENDATION_EXT.ELEMENT_GROUNDED_IN)
|
|
417
|
+
.filter((quote) => typeof quote === 'string' && quote.trim());
|
|
418
|
+
const quotes = groundedIn.length ? groundedIn : basis.groundedIn;
|
|
419
|
+
return {
|
|
420
|
+
rank,
|
|
421
|
+
type: ext[RECOMMENDATION_EXT.ELEMENT_TYPE] ?? basis.type ?? null,
|
|
422
|
+
nameShort: finding.item?.concept?.text || null,
|
|
423
|
+
timeWindow: ext[RECOMMENDATION_EXT.ELEMENT_TIME_WINDOW] ?? null,
|
|
424
|
+
symptoms: extValues(finding, RECOMMENDATION_EXT.ELEMENT_SYMPTOM).map(objectExtension).filter(Boolean),
|
|
425
|
+
targetedCtcaeTerms: (task?.code?.coding || []).map((coding) => coding.code).filter(Boolean),
|
|
426
|
+
whyRelevant: ext[RECOMMENDATION_EXT.ELEMENT_WHY_RELEVANT] ?? basis.whyRelevant ?? '',
|
|
427
|
+
qolImpact: ext[RECOMMENDATION_EXT.ELEMENT_QOL_IMPACT] ?? basis.qolImpact ?? null,
|
|
428
|
+
improvementCapacity: ext[RECOMMENDATION_EXT.ELEMENT_IMPROVEMENT_CAPACITY] ?? null,
|
|
429
|
+
characterizationNeeded: noteMap.characterizationNeeded === undefined ? null : noteMap.characterizationNeeded === 'true',
|
|
430
|
+
minCharacterizationVariables: characterizationVariablesOf(noteMap.minCharacterizationVariables),
|
|
431
|
+
escalation: {
|
|
432
|
+
urgentUnder24h: ext[RECOMMENDATION_EXT.ELEMENT_ESCALATION_URGENT] ?? false,
|
|
433
|
+
maxActionTimeHours: ext[RECOMMENDATION_EXT.ELEMENT_ESCALATION_MAX_HOURS] ?? null,
|
|
434
|
+
routes: extValues(finding, RECOMMENDATION_EXT.ELEMENT_ESCALATION_ROUTE),
|
|
435
|
+
clinicalCriteria: ext[RECOMMENDATION_EXT.ELEMENT_ESCALATION_CRITERIA] ?? null,
|
|
436
|
+
},
|
|
437
|
+
recommendation: {
|
|
438
|
+
symptomsPatientFacing: extValues(finding, RECOMMENDATION_EXT.ELEMENT_SYMPTOM_PATIENT_FACING),
|
|
439
|
+
isPharmacologicalMedNeeded: noteMap.isPharmacologicalMedNeeded === 'true',
|
|
440
|
+
patient: {
|
|
441
|
+
mainRecommendation: task?.description || null,
|
|
442
|
+
whenToEscalate: noteMap.whenToEscalate || null,
|
|
443
|
+
contraindications: noteMap.contraindications || null,
|
|
444
|
+
expectedEffectiveness: noteMap.expectedEffectiveness || null,
|
|
445
|
+
},
|
|
446
|
+
otcOffer: objectExtension(taskExt[RECOMMENDATION_EXT.REC_OTC_OFFER]),
|
|
447
|
+
followup: taskExt[RECOMMENDATION_EXT.REC_FOLLOWUP] ?? null,
|
|
448
|
+
followupUrgency: taskExt[RECOMMENDATION_EXT.REC_FOLLOWUP_URGENCY] ?? null,
|
|
449
|
+
},
|
|
450
|
+
groundedIn: quotes,
|
|
451
|
+
evidence: reconstructEvidence(finding, quotes),
|
|
452
|
+
recommendationId: task ? identifierValue(task, RECOMMENDATION_REC_SLUG) : null,
|
|
453
|
+
latestOutcome: task ? mergedOutcome(task) : null,
|
|
454
|
+
outcomeHistory: task ? outcomeHistoryOf(task) : [],
|
|
455
|
+
reviewHistory: task ? reviewHistoryOf(task) : [],
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function reconstructEvidence(finding, quotes) {
|
|
460
|
+
const stored = new Map();
|
|
461
|
+
const conflicted = new Set();
|
|
462
|
+
for (const raw of extValues(finding, RECOMMENDATION_EXT.ELEMENT_EVIDENCE)) {
|
|
463
|
+
const parsed = objectExtension(raw);
|
|
464
|
+
if (typeof parsed?.text !== 'string') continue;
|
|
465
|
+
const anchored = typeof parsed.anchored === 'boolean' ? parsed.anchored : null;
|
|
466
|
+
if (!stored.has(parsed.text)) {
|
|
467
|
+
stored.set(parsed.text, anchored);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (anchored === null || conflicted.has(parsed.text)) continue;
|
|
471
|
+
const prior = stored.get(parsed.text);
|
|
472
|
+
if (prior === null) {
|
|
473
|
+
stored.set(parsed.text, anchored);
|
|
474
|
+
} else if (prior !== anchored) {
|
|
475
|
+
conflicted.add(parsed.text);
|
|
476
|
+
stored.set(parsed.text, null);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return quotes.map((text) => ({ text, anchored: stored.has(text) ? stored.get(text) : null }));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const ELEMENT_EXT_SLUGS = [
|
|
483
|
+
RECOMMENDATION_EXT.ELEMENT_RANK,
|
|
484
|
+
RECOMMENDATION_EXT.ELEMENT_TYPE,
|
|
485
|
+
RECOMMENDATION_EXT.ELEMENT_WHY_RELEVANT,
|
|
486
|
+
RECOMMENDATION_EXT.ELEMENT_ESCALATION_URGENT,
|
|
487
|
+
];
|
|
488
|
+
|
|
489
|
+
const hasElementExtensions = (ext) => ELEMENT_EXT_SLUGS.some((slug) => ext[slug] !== undefined);
|
|
490
|
+
|
|
491
|
+
function taskFor(runId, rank, tasksById) {
|
|
492
|
+
const task = tasksById.get(recommendationId(runId, rank));
|
|
493
|
+
if (!task) return null;
|
|
494
|
+
const stamped = extMap(task)[RECOMMENDATION_EXT.REC_RUN_ID];
|
|
495
|
+
if (stamped !== undefined && stamped !== runId) return null;
|
|
496
|
+
return task;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function parseBasis(basis) {
|
|
500
|
+
const text = String(basis || '');
|
|
501
|
+
if (!text) return EMPTY_BASIS;
|
|
502
|
+
|
|
503
|
+
const marks = [];
|
|
504
|
+
let from = 0;
|
|
505
|
+
let isAmbiguous = false;
|
|
506
|
+
for (const [key, label] of Object.entries(BASIS_LABELS)) {
|
|
507
|
+
const needle = `${label}${NOTE_SEPARATOR}`;
|
|
508
|
+
const isFirst = text.startsWith(needle, from);
|
|
509
|
+
const at = isFirst ? from : text.indexOf(`${BASIS_SEPARATOR}${needle}`, from);
|
|
510
|
+
if (at < 0) continue;
|
|
511
|
+
const valueAt = isFirst ? from + needle.length : at + BASIS_SEPARATOR.length + needle.length;
|
|
512
|
+
if (text.indexOf(`${BASIS_SEPARATOR}${needle}`, valueAt) >= 0) isAmbiguous = true;
|
|
513
|
+
marks.push({ key, at, valueAt });
|
|
514
|
+
from = valueAt;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const out = {};
|
|
518
|
+
marks.forEach((mark, index) => {
|
|
519
|
+
const end = index + 1 < marks.length ? marks[index + 1].at : text.length;
|
|
520
|
+
out[mark.key] = text.slice(mark.valueAt, end);
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
const rank = Number.parseInt(out.rank, 10);
|
|
524
|
+
const parsed = {
|
|
525
|
+
rank: Number.isFinite(rank) ? rank : null,
|
|
526
|
+
type: out.type ?? null,
|
|
527
|
+
qolImpact: out.qolImpact ?? null,
|
|
528
|
+
whyRelevant: out.whyRelevant ?? null,
|
|
529
|
+
groundedIn: out.groundedIn ? out.groundedIn.split(BASIS_SEPARATOR) : [],
|
|
530
|
+
};
|
|
531
|
+
if (!isAmbiguous) return parsed;
|
|
532
|
+
|
|
533
|
+
const relevanceAt = marks.find((mark) => mark.key === 'whyRelevant');
|
|
534
|
+
return {
|
|
535
|
+
...parsed,
|
|
536
|
+
whyRelevant: relevanceAt ? text.slice(relevanceAt.valueAt) : parsed.whyRelevant,
|
|
537
|
+
groundedIn: [],
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
module.exports = {
|
|
542
|
+
toFhir,
|
|
543
|
+
fromFhir,
|
|
544
|
+
PROJECTOR_NAME,
|
|
545
|
+
recommendationNotesOf,
|
|
546
|
+
characterizationVariablesOf,
|
|
547
|
+
outcomeEntry,
|
|
548
|
+
hasOutcomeEvent,
|
|
549
|
+
outcomeHistoryOf,
|
|
550
|
+
mergedOutcome,
|
|
551
|
+
warningRecord,
|
|
552
|
+
reviewEntry,
|
|
553
|
+
hasReviewEvent,
|
|
554
|
+
reviewByEvent,
|
|
555
|
+
reviewHistoryOf,
|
|
556
|
+
REVIEW_VERDICTS,
|
|
557
|
+
};
|