@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,5 +1,7 @@
|
|
|
1
1
|
const { fhirId, identifierSystem, extensionUrl } = require('./fhirHelper');
|
|
2
2
|
|
|
3
|
+
const EXTENSION_KEYS = new Set(['extension', 'modifierExtension']);
|
|
4
|
+
|
|
3
5
|
function identifier(slug, value) {
|
|
4
6
|
return { system: identifierSystem(slug), value };
|
|
5
7
|
}
|
|
@@ -12,6 +14,11 @@ function patientReference(patientId) {
|
|
|
12
14
|
return reference('Patient', patientId);
|
|
13
15
|
}
|
|
14
16
|
|
|
17
|
+
function recipientReference({ patientId, recipientKind = 'patient', recipientRefId = null }) {
|
|
18
|
+
if (recipientKind === 'related_person' && recipientRefId) return reference('RelatedPerson', recipientRefId);
|
|
19
|
+
return reference('Patient', patientId);
|
|
20
|
+
}
|
|
21
|
+
|
|
15
22
|
function codeableConcept(text, { code = null, system = null, display = null } = {}) {
|
|
16
23
|
const out = { text };
|
|
17
24
|
if (code !== null && system !== null) {
|
|
@@ -24,6 +31,15 @@ function extension(name, value) {
|
|
|
24
31
|
return { url: extensionUrl(name), ...value };
|
|
25
32
|
}
|
|
26
33
|
|
|
34
|
+
function notes(...texts) {
|
|
35
|
+
const present = texts.filter(Boolean).map((text) => ({ text }));
|
|
36
|
+
return present.length ? present : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function toInstant(value) {
|
|
40
|
+
return new Date(value).toISOString();
|
|
41
|
+
}
|
|
42
|
+
|
|
27
43
|
function toIso(value) {
|
|
28
44
|
if (value instanceof Date) return value.toISOString().replace(/\.000Z$/, 'Z');
|
|
29
45
|
const s = String(value);
|
|
@@ -32,11 +48,34 @@ function toIso(value) {
|
|
|
32
48
|
return `${s}Z`;
|
|
33
49
|
}
|
|
34
50
|
|
|
51
|
+
// FHIR ele-1/ext-1: no element may be empty or null, and an extension needs a value or child extensions.
|
|
52
|
+
function pruneEmptyElements(resource) {
|
|
53
|
+
const prune = (value, parentKey) => {
|
|
54
|
+
if (value === null || value === undefined || value === '') return undefined;
|
|
55
|
+
if (Array.isArray(value)) {
|
|
56
|
+
const items = value.map((item) => prune(item, parentKey)).filter((item) => item !== undefined);
|
|
57
|
+
return items.length ? items : undefined;
|
|
58
|
+
}
|
|
59
|
+
if (typeof value !== 'object') return value;
|
|
60
|
+
const entries = Object.entries(value)
|
|
61
|
+
.map(([key, child]) => [key, prune(child, key)])
|
|
62
|
+
.filter(([, child]) => child !== undefined);
|
|
63
|
+
if (!entries.length) return undefined;
|
|
64
|
+
if (EXTENSION_KEYS.has(parentKey) && entries.every(([key]) => key === 'url')) return undefined;
|
|
65
|
+
return Object.fromEntries(entries);
|
|
66
|
+
};
|
|
67
|
+
return prune(resource, null) ?? {};
|
|
68
|
+
}
|
|
69
|
+
|
|
35
70
|
module.exports = {
|
|
36
71
|
identifier,
|
|
37
72
|
reference,
|
|
38
73
|
patientReference,
|
|
74
|
+
recipientReference,
|
|
39
75
|
codeableConcept,
|
|
40
76
|
extension,
|
|
77
|
+
notes,
|
|
78
|
+
toInstant,
|
|
41
79
|
toIso,
|
|
80
|
+
pruneEmptyElements,
|
|
42
81
|
};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
const { getIdentBase, getExtBase, getCodesystemBase } = require('../config/fhirConfig');
|
|
2
2
|
|
|
3
|
+
const FHIR_ID_MAX = 64;
|
|
4
|
+
|
|
3
5
|
function fhirId(businessId) {
|
|
4
|
-
const id = String(businessId).replace(/[^A-Za-z0-9.-]/g, '-').slice(0,
|
|
6
|
+
const id = String(businessId).replace(/[^A-Za-z0-9.-]/g, '-').slice(0, FHIR_ID_MAX);
|
|
5
7
|
return id || 'x';
|
|
6
8
|
}
|
|
7
9
|
|
|
@@ -11,6 +13,7 @@ const codeSystemUrl = (name) => `${getCodesystemBase()}/${name}`;
|
|
|
11
13
|
|
|
12
14
|
module.exports = {
|
|
13
15
|
fhirId,
|
|
16
|
+
FHIR_ID_MAX,
|
|
14
17
|
identifierSystem,
|
|
15
18
|
extensionUrl,
|
|
16
19
|
codeSystemUrl,
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const { getExtBase } = require('../config/fhirConfig');
|
|
2
|
+
const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
3
|
+
const { identifierSystem, extensionUrl } = require('./fhirHelper');
|
|
4
|
+
|
|
5
|
+
const extensionValue = (ext) => ext.valueString ?? ext.valueCode ?? ext.valueDateTime ?? ext.valueBoolean ?? ext.valueInteger ?? ext.valueDecimal ?? null;
|
|
6
|
+
|
|
7
|
+
function extMap(resource) {
|
|
8
|
+
const base = getExtBase();
|
|
9
|
+
const out = {};
|
|
10
|
+
for (const ext of resource.extension || []) {
|
|
11
|
+
if (!String(ext.url || '').startsWith(base)) continue;
|
|
12
|
+
const name = ext.url.slice(base.length + 1);
|
|
13
|
+
out[name] = extensionValue(ext);
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function identifierValue(resource, slug) {
|
|
19
|
+
const system = identifierSystem(slug);
|
|
20
|
+
const match = (resource.identifier || []).find((id) => id.system === system);
|
|
21
|
+
return (match && match.value) || null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function objectExtension(raw) {
|
|
25
|
+
const parsed = safeParse(raw, null);
|
|
26
|
+
return isPlainObject(parsed) ? parsed : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function refToId(reference) {
|
|
30
|
+
if (!reference) return null;
|
|
31
|
+
return String(reference).split('/').slice(1).join('/') || null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function extValues(resource, name) {
|
|
35
|
+
const url = extensionUrl(name);
|
|
36
|
+
const values = [];
|
|
37
|
+
for (const ext of resource.extension || []) {
|
|
38
|
+
if (ext.url !== url) continue;
|
|
39
|
+
const value = extensionValue(ext);
|
|
40
|
+
if (value !== null) values.push(value);
|
|
41
|
+
}
|
|
42
|
+
return values;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function referencedId(node, slug, reference) {
|
|
46
|
+
return extValues(node, slug)[0] || refToId(reference);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function referencedIds(node, slug, references) {
|
|
50
|
+
const values = extValues(node, slug);
|
|
51
|
+
return values.length ? values : references.map(refToId).filter(Boolean);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = {
|
|
55
|
+
extMap,
|
|
56
|
+
identifierValue,
|
|
57
|
+
objectExtension,
|
|
58
|
+
refToId,
|
|
59
|
+
extValues,
|
|
60
|
+
referencedId,
|
|
61
|
+
referencedIds,
|
|
62
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const { createHash } = require('crypto');
|
|
2
|
+
|
|
3
|
+
const { FHIR_ID_MAX } = require('./fhirHelper');
|
|
4
|
+
|
|
5
|
+
const TRIAGE_RUN_PREFIX = 'recrun-triage-';
|
|
6
|
+
|
|
7
|
+
const sanitize = (value) => String(value).replace(/[^A-Za-z0-9.-]/g, '-');
|
|
8
|
+
|
|
9
|
+
const recommendationId = (runId, rank) => {
|
|
10
|
+
const suffix = `-rec${sanitize(rank)}`;
|
|
11
|
+
return `${sanitize(runId).slice(0, FHIR_ID_MAX - suffix.length)}${suffix}`;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// `recommendationId` fills the id budget, so appending would drop its `-recN` suffix.
|
|
15
|
+
const reviewProvenanceId = (recommendationId, discriminator) => {
|
|
16
|
+
const digest = createHash('sha1').update(`${recommendationId}|${discriminator}`).digest('hex');
|
|
17
|
+
return `rev-${digest.slice(0, 40)}`;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Sanitising alone maps `a_b@` and `a-b@` onto one id.
|
|
21
|
+
const REVIEWER_DIGEST_LENGTH = 12;
|
|
22
|
+
const reviewerId = (reviewer) => {
|
|
23
|
+
const digest = createHash('sha1').update(String(reviewer)).digest('hex').slice(0, REVIEWER_DIGEST_LENGTH);
|
|
24
|
+
return `${sanitize(reviewer).slice(0, FHIR_ID_MAX - digest.length - 1)}-${digest}`;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const runIdOf = (id) => id.replace(/-rec[^-]*$/, '');
|
|
28
|
+
|
|
29
|
+
const rankOf = (id) => {
|
|
30
|
+
const match = /-rec(\d+)$/.exec(id);
|
|
31
|
+
return match ? Number(match[1]) : 0;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const sourceOfRun = (runId) => (runId.startsWith(TRIAGE_RUN_PREFIX) ? 'triage' : 'chat');
|
|
35
|
+
|
|
36
|
+
module.exports = {
|
|
37
|
+
recommendationId,
|
|
38
|
+
reviewProvenanceId,
|
|
39
|
+
reviewerId,
|
|
40
|
+
runIdOf,
|
|
41
|
+
rankOf,
|
|
42
|
+
sourceOfRun,
|
|
43
|
+
TRIAGE_RUN_PREFIX,
|
|
44
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
function resourceDisplayText(resource) {
|
|
2
|
+
if (typeof resource?.description === 'string' && resource.description) return resource.description;
|
|
3
|
+
const code = resource?.code || resource?.medication?.concept;
|
|
4
|
+
if (typeof code?.text === 'string' && code.text) return code.text;
|
|
5
|
+
const coding = code?.coding?.[0];
|
|
6
|
+
return coding?.display || coding?.code || null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
module.exports = { resourceDisplayText };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const { getDeviceId, getOrganizationId, getSystems } = require('../config/fhirConfig');
|
|
2
|
+
const { fhirId } = require('./fhirHelper');
|
|
3
|
+
const { identifier, patientReference, reference, codeableConcept, toIso } = require('./elementHelper');
|
|
4
|
+
|
|
5
|
+
function baseResource(resourceType, id, slug, patientId = null) {
|
|
6
|
+
return {
|
|
7
|
+
resourceType,
|
|
8
|
+
id: fhirId(id),
|
|
9
|
+
identifier: [identifier(slug, id)],
|
|
10
|
+
...(patientId ? { subject: patientReference(patientId) } : {}),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function provenance({
|
|
15
|
+
provenanceId, targetRefs, recordedAt, activity,
|
|
16
|
+
agentDevice = null, onBehalfOf = null, agentWho = null,
|
|
17
|
+
}) {
|
|
18
|
+
return {
|
|
19
|
+
resourceType: 'Provenance',
|
|
20
|
+
id: fhirId(provenanceId),
|
|
21
|
+
target: targetRefs,
|
|
22
|
+
recorded: toIso(recordedAt),
|
|
23
|
+
agent: [{
|
|
24
|
+
who: agentWho || reference('Device', agentDevice || getDeviceId()),
|
|
25
|
+
onBehalfOf: reference('Organization', onBehalfOf || getOrganizationId()),
|
|
26
|
+
}],
|
|
27
|
+
activity,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function problemListCategory() {
|
|
32
|
+
const code = 'problem-list-item';
|
|
33
|
+
return codeableConcept(code, { code, system: getSystems().conditionCategory });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function observationCategory(code) {
|
|
37
|
+
const label = code.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
|
38
|
+
return codeableConcept(label, { code, system: getSystems().observationCategory, display: label });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = {
|
|
42
|
+
baseResource,
|
|
43
|
+
provenance,
|
|
44
|
+
problemListCategory,
|
|
45
|
+
observationCategory,
|
|
46
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const { termKey } = require('../utils/normalizeUtils');
|
|
2
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
3
|
+
const { getSymptom } = require('./terminologyHelper');
|
|
4
|
+
const { matchTerm } = require('./termMatchHelper');
|
|
5
|
+
|
|
6
|
+
const keyOf = (value) => termKey(foldAccents(value));
|
|
7
|
+
|
|
8
|
+
const symptomRecord = (catalog, term) => (term && catalog?.symptoms ? getSymptom(catalog, term) : null);
|
|
9
|
+
|
|
10
|
+
function aliasKeysOf(catalog, term) {
|
|
11
|
+
const keys = new Set();
|
|
12
|
+
const add = (value) => {
|
|
13
|
+
const key = keyOf(value);
|
|
14
|
+
if (key) keys.add(key);
|
|
15
|
+
};
|
|
16
|
+
add(term);
|
|
17
|
+
const record = symptomRecord(catalog, term);
|
|
18
|
+
if (record) {
|
|
19
|
+
add(record.en);
|
|
20
|
+
add(record.es);
|
|
21
|
+
add(record.ctcae_v5);
|
|
22
|
+
}
|
|
23
|
+
return keys;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolveTerm(catalog, value) {
|
|
27
|
+
const key = keyOf(value);
|
|
28
|
+
if (!key) return null;
|
|
29
|
+
const entries = Object.keys(catalog?.symptoms || {})
|
|
30
|
+
.map((term) => ({ term, keys: aliasKeysOf(catalog, term) }));
|
|
31
|
+
return matchTerm(key, entries);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function aliasClosure(catalog, value) {
|
|
35
|
+
const key = keyOf(value);
|
|
36
|
+
if (!key) return [];
|
|
37
|
+
const term = resolveTerm(catalog, value);
|
|
38
|
+
return term ? [...aliasKeysOf(catalog, term)] : [key];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function symptomKeySet(catalog, terms = []) {
|
|
42
|
+
const keys = new Set();
|
|
43
|
+
for (const term of terms) {
|
|
44
|
+
for (const key of aliasKeysOf(catalog, term)) keys.add(key);
|
|
45
|
+
}
|
|
46
|
+
return keys;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = {
|
|
50
|
+
keyOf,
|
|
51
|
+
resolveTerm,
|
|
52
|
+
symptomRecord,
|
|
53
|
+
aliasKeysOf,
|
|
54
|
+
aliasClosure,
|
|
55
|
+
symptomKeySet,
|
|
56
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const GENERIC_TOKENS = new Set(['syndrome', 'disorder', 'impairment', 'reaction']);
|
|
2
|
+
const MIN_FUZZY_TOKENS = 2;
|
|
3
|
+
|
|
4
|
+
const tokensOf = (key) => String(key || '').split('_').filter(Boolean);
|
|
5
|
+
|
|
6
|
+
const singular = (token) => (token.length > 3 && token.endsWith('s') && !token.endsWith('ss')
|
|
7
|
+
? token.slice(0, -1)
|
|
8
|
+
: token);
|
|
9
|
+
|
|
10
|
+
const foldKey = (key) => tokensOf(key).map(singular).join('_');
|
|
11
|
+
|
|
12
|
+
const contentTokens = (key) => new Set(tokensOf(key).map(singular).filter((token) => !GENERIC_TOKENS.has(token)));
|
|
13
|
+
|
|
14
|
+
const covers = (outer, inner) => inner.size >= MIN_FUZZY_TOKENS
|
|
15
|
+
&& outer.size >= MIN_FUZZY_TOKENS
|
|
16
|
+
&& [...inner].every((token) => outer.has(token));
|
|
17
|
+
|
|
18
|
+
const soleTerm = (hits) => (hits.length === 1 ? hits[0].term : null);
|
|
19
|
+
|
|
20
|
+
function matchTerm(key, entries) {
|
|
21
|
+
if (!key) return null;
|
|
22
|
+
const exact = entries.find((entry) => entry.keys.has(key));
|
|
23
|
+
if (exact) return exact.term;
|
|
24
|
+
|
|
25
|
+
const folded = foldKey(key);
|
|
26
|
+
const byFold = entries.filter((entry) => [...entry.keys].some((alias) => foldKey(alias) === folded));
|
|
27
|
+
if (byFold.length) return soleTerm(byFold);
|
|
28
|
+
|
|
29
|
+
const wanted = contentTokens(key);
|
|
30
|
+
const byTokens = entries.filter((entry) => [...entry.keys].some((alias) => {
|
|
31
|
+
const alternative = contentTokens(alias);
|
|
32
|
+
return covers(alternative, wanted) || covers(wanted, alternative);
|
|
33
|
+
}));
|
|
34
|
+
return soleTerm(byTokens);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const entriesOfKeys = (keys) => [...keys].map((key) => ({ term: key, keys: new Set([key]) }));
|
|
38
|
+
|
|
39
|
+
module.exports = {
|
|
40
|
+
matchTerm,
|
|
41
|
+
entriesOfKeys,
|
|
42
|
+
};
|
|
@@ -5,23 +5,27 @@ const { lookupValue, integerId, parseList, termKey } = require('../utils/normali
|
|
|
5
5
|
const { codeSystemUrl } = require('./fhirHelper');
|
|
6
6
|
|
|
7
7
|
const { safeParse } = require('../../utils/jsonUtils');
|
|
8
|
+
const { logger } = require('../../utils/logger');
|
|
8
9
|
|
|
9
10
|
const DIMENSION_SCALES = {
|
|
10
11
|
frequency: ['Nunca', 'Rara vez', 'A veces', 'A menudo', 'Casi siempre'],
|
|
11
12
|
intensity: ['Ninguna', 'Leve', 'Moderada', 'Intensa', 'Muy intensa'],
|
|
12
13
|
interference: ['Nada', 'Un poco', 'Algo', 'Mucho', 'Muchísimo'],
|
|
13
|
-
amount: ['
|
|
14
|
+
amount: ['Nada', 'Un poco', 'Algo', 'Mucho', 'Muchísimo'],
|
|
14
15
|
presence: ['No', 'Sí'],
|
|
15
16
|
};
|
|
16
17
|
|
|
17
18
|
const DIMENSION_ORDER = ['presence', 'frequency', 'intensity', 'interference', 'amount'];
|
|
18
19
|
|
|
19
20
|
const CANONICAL_SOURCE = 'original';
|
|
21
|
+
const SUPPLEMENTARY_SOURCE = 'extra-question';
|
|
20
22
|
|
|
21
23
|
function buildCatalog(items, composites = [], source = null) {
|
|
22
24
|
const symptoms = {};
|
|
23
25
|
const questionIndex = {};
|
|
26
|
+
const questionSource = {};
|
|
24
27
|
const answerMap = {};
|
|
28
|
+
const itemIndex = {};
|
|
25
29
|
|
|
26
30
|
for (const row of items) {
|
|
27
31
|
const questionId = integerId(row.question_id);
|
|
@@ -32,6 +36,9 @@ function buildCatalog(items, composites = [], source = null) {
|
|
|
32
36
|
if (!en) continue;
|
|
33
37
|
const term = termKey(en);
|
|
34
38
|
const dimension = row.dimension ?? null;
|
|
39
|
+
const itemNumber = String(row.item ?? '').trim();
|
|
40
|
+
if (itemNumber) itemIndex[itemNumber] = term;
|
|
41
|
+
const options = parseList(row.options);
|
|
35
42
|
|
|
36
43
|
const record = (symptoms[term] = symptoms[term] || {
|
|
37
44
|
term,
|
|
@@ -44,12 +51,24 @@ function buildCatalog(items, composites = [], source = null) {
|
|
|
44
51
|
});
|
|
45
52
|
record.dimensions.push({
|
|
46
53
|
dimension,
|
|
47
|
-
options: map ? [...(DIMENSION_SCALES[dimension] || [])] :
|
|
54
|
+
options: map ? [...(DIMENSION_SCALES[dimension] || [])] : options,
|
|
48
55
|
question_id: questionId != null ? String(questionId) : null,
|
|
49
56
|
source: row.source ?? null,
|
|
50
57
|
});
|
|
51
58
|
|
|
52
|
-
if (questionId != null && dimension)
|
|
59
|
+
if (questionId != null && dimension) {
|
|
60
|
+
if (gradeableOnScale(dimension, options, map)) {
|
|
61
|
+
questionIndex[String(questionId)] = [term, dimension];
|
|
62
|
+
questionSource[String(questionId)] = row.source ?? null;
|
|
63
|
+
} else {
|
|
64
|
+
logger.warn('[buildCatalog] question not indexed: no answer option grades on its dimension scale', {
|
|
65
|
+
questionId,
|
|
66
|
+
term,
|
|
67
|
+
dimension,
|
|
68
|
+
options,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
53
72
|
}
|
|
54
73
|
|
|
55
74
|
for (const record of Object.values(symptoms)) {
|
|
@@ -62,6 +81,7 @@ function buildCatalog(items, composites = [], source = null) {
|
|
|
62
81
|
source,
|
|
63
82
|
n_symptoms: Object.keys(symptoms).length,
|
|
64
83
|
n_items: Object.keys(questionIndex).length,
|
|
84
|
+
n_item_numbers: Object.keys(itemIndex).length,
|
|
65
85
|
n_mapped_items: Object.keys(answerMap).length,
|
|
66
86
|
n_composites: Object.keys(compositeGrades).length,
|
|
67
87
|
composite_table_hash: Object.keys(compositeGrades).length ? hashCompositeGrades(compositeGrades) : null,
|
|
@@ -69,6 +89,8 @@ function buildCatalog(items, composites = [], source = null) {
|
|
|
69
89
|
},
|
|
70
90
|
symptoms,
|
|
71
91
|
question_index: questionIndex,
|
|
92
|
+
question_source: questionSource,
|
|
93
|
+
item_index: itemIndex,
|
|
72
94
|
answer_map: answerMap,
|
|
73
95
|
composite_grades: compositeGrades,
|
|
74
96
|
};
|
|
@@ -79,12 +101,23 @@ function answerMapOf(row) {
|
|
|
79
101
|
return map && typeof map === 'object' && Object.keys(map).length ? map : null;
|
|
80
102
|
}
|
|
81
103
|
|
|
82
|
-
function
|
|
83
|
-
const
|
|
104
|
+
function gradeableOnScale(dimension, options, map) {
|
|
105
|
+
const scale = DIMENSION_SCALES[dimension] || [];
|
|
106
|
+
return options.some((option) => {
|
|
107
|
+
const label = mappedAnswer(map, option);
|
|
108
|
+
return ordinalIn(scale, label) !== null || (dimension === 'presence' && affirmative(label));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function mappedAnswer(map, answer) {
|
|
84
113
|
if (!map) return answer;
|
|
85
114
|
return map[String(answer).trim()] ?? answer;
|
|
86
115
|
}
|
|
87
116
|
|
|
117
|
+
function canonicalAnswer(catalog, questionId, answer) {
|
|
118
|
+
return mappedAnswer(catalog.answer_map[String(questionId).trim()], answer);
|
|
119
|
+
}
|
|
120
|
+
|
|
88
121
|
function pickCanonicalDimensions(dimensions) {
|
|
89
122
|
const best = {};
|
|
90
123
|
for (const d of dimensions) {
|
|
@@ -140,6 +173,20 @@ function itemForQuestionId(catalog, questionId) {
|
|
|
140
173
|
return Array.isArray(entry) && entry.length >= 2 ? [entry[0], entry[1]] : null;
|
|
141
174
|
}
|
|
142
175
|
|
|
176
|
+
function isSupplementaryQuestion(catalog, questionId) {
|
|
177
|
+
return (catalog.question_source || {})[String(questionId).trim()] === SUPPLEMENTARY_SOURCE;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isItemDimension(catalog, term, dimension) {
|
|
181
|
+
const rec = getSymptom(catalog, term);
|
|
182
|
+
return (rec ? rec.dimensions : [])
|
|
183
|
+
.some((d) => d.dimension === dimension && d.source !== SUPPLEMENTARY_SOURCE);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function termForItem(catalog, item) {
|
|
187
|
+
return catalog.item_index[String(item ?? '').trim()] || null;
|
|
188
|
+
}
|
|
189
|
+
|
|
143
190
|
function standardScale(catalog, dimension) {
|
|
144
191
|
return [...(catalog._meta.dimension_scales[dimension] || [])];
|
|
145
192
|
}
|
|
@@ -240,11 +287,50 @@ const ctcaeSlug = (value) =>
|
|
|
240
287
|
|
|
241
288
|
const COMPOSITE_DIMENSIONS = ['frequency', 'intensity', 'interference', 'amount'];
|
|
242
289
|
|
|
290
|
+
// Options the questionnaire offers that carry no ordinal. They are answers, not gaps: "no aplica"
|
|
291
|
+
// says the item cannot occur for this patient, "declined" says they chose not to say.
|
|
292
|
+
const SENTINEL_ANSWERS = {
|
|
293
|
+
'no tengo actividad sexual': 'not_applicable',
|
|
294
|
+
'no corresponde': 'not_applicable',
|
|
295
|
+
'prefiero no contestar': 'declined',
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
function sentinelKind(label) {
|
|
299
|
+
return SENTINEL_ANSWERS[String(label ?? '').trim().toLowerCase()] || null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// The table carries no interference-only code, so read it off the mildest row that isolates
|
|
303
|
+
// interference: lowest frequency, intensity 0. Derived, never hardcoded, so it cannot drift.
|
|
304
|
+
function interferenceOnlyGrade(catalog, ordinal) {
|
|
305
|
+
for (const frequency of ['1', '2', '3', '4']) {
|
|
306
|
+
const grade = catalog.composite_grades[`${frequency}0${ordinal}x`];
|
|
307
|
+
if (grade !== undefined) return grade;
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function singleDimensionGrade(catalog, dimension, ordinal) {
|
|
313
|
+
if (!Number.isInteger(ordinal)) return null;
|
|
314
|
+
if (dimension === 'interference') return interferenceOnlyGrade(catalog, ordinal);
|
|
315
|
+
const index = COMPOSITE_DIMENSIONS.indexOf(dimension);
|
|
316
|
+
if (index < 0) return null;
|
|
317
|
+
const code = COMPOSITE_DIMENSIONS.map((_, i) => (i === index ? String(ordinal) : 'x')).join('');
|
|
318
|
+
const grade = catalog.composite_grades[code];
|
|
319
|
+
return grade === undefined ? null : grade;
|
|
320
|
+
}
|
|
321
|
+
|
|
243
322
|
module.exports = {
|
|
323
|
+
SENTINEL_ANSWERS,
|
|
324
|
+
sentinelKind,
|
|
325
|
+
singleDimensionGrade,
|
|
244
326
|
buildCatalog,
|
|
245
327
|
allTerms,
|
|
246
328
|
compositeTableHash,
|
|
247
329
|
itemForQuestionId,
|
|
330
|
+
isSupplementaryQuestion,
|
|
331
|
+
isItemDimension,
|
|
332
|
+
termForItem,
|
|
333
|
+
getSymptom,
|
|
248
334
|
canonicalAnswer,
|
|
249
335
|
affirmative,
|
|
250
336
|
standardScale,
|
|
@@ -257,4 +343,5 @@ module.exports = {
|
|
|
257
343
|
ordinalValue,
|
|
258
344
|
codingsFor,
|
|
259
345
|
gradeConcept,
|
|
346
|
+
ctcaeSlug,
|
|
260
347
|
};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
const { logger } = require('../../utils/logger');
|
|
2
|
+
const { itemForQuestionId } = require('./terminologyHelper');
|
|
3
|
+
|
|
4
|
+
const QUESTION_COLUMN_RX = /^(\d+)_/;
|
|
5
|
+
|
|
6
|
+
const OTHER_SYMPTOMS_INTENSITY_SCALE = ['Leve', 'Moderada', 'Intensa', 'Muy intensa'];
|
|
7
|
+
const OTHER_SYMPTOMS_INTENSITY_RX = /^other_symptoms_interference_(\d+)$/;
|
|
8
|
+
|
|
9
|
+
function normalizeAnswerToken(value) {
|
|
10
|
+
if (value == null) return null;
|
|
11
|
+
const text = String(value).trim();
|
|
12
|
+
if (!text) return null;
|
|
13
|
+
return text.includes(' ') ? text : text.replace(/_/g, ' ');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const cleanList = (values) => (Array.isArray(values) ? values : [])
|
|
17
|
+
.map((entry) => String(entry).trim())
|
|
18
|
+
.filter(Boolean);
|
|
19
|
+
|
|
20
|
+
const cleanText = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
|
|
21
|
+
|
|
22
|
+
function normalizeOtherSymptomsIntensity(value) {
|
|
23
|
+
const text = cleanText(value);
|
|
24
|
+
if (!text) return null;
|
|
25
|
+
const match = OTHER_SYMPTOMS_INTENSITY_RX.exec(text);
|
|
26
|
+
if (match) {
|
|
27
|
+
const label = OTHER_SYMPTOMS_INTENSITY_SCALE[Number(match[1])];
|
|
28
|
+
if (label) return label;
|
|
29
|
+
} else if (OTHER_SYMPTOMS_INTENSITY_SCALE.includes(text)) {
|
|
30
|
+
return text;
|
|
31
|
+
}
|
|
32
|
+
logger.warn('[buildTriageResponse] unrecognized other-symptoms intensity kept verbatim', { value: text });
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function normalizePain(rawPain = {}) {
|
|
37
|
+
const options = cleanList(rawPain.options);
|
|
38
|
+
return {
|
|
39
|
+
hasPain: normalizeAnswerToken(rawPain.hasPain),
|
|
40
|
+
frequency: normalizeAnswerToken(rawPain.frequency),
|
|
41
|
+
intensity: normalizeAnswerToken(rawPain.intensity),
|
|
42
|
+
interference: normalizeAnswerToken(rawPain.interference),
|
|
43
|
+
locations: options.length ? options : cleanList(rawPain.locations),
|
|
44
|
+
mostImportant: cleanText(rawPain.mostImportant),
|
|
45
|
+
otherText: cleanText(rawPain.otherText),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildTriageResponse(catalog, payload = {}) {
|
|
50
|
+
const triageId = String(payload.triageRecordId ?? '').trim();
|
|
51
|
+
const patientId = String(payload.patientCode ?? '').trim();
|
|
52
|
+
if (!triageId) throw new Error('buildTriageResponse: triageRecordId is required');
|
|
53
|
+
if (!patientId) throw new Error('buildTriageResponse: patientCode is required');
|
|
54
|
+
const answers = {};
|
|
55
|
+
const unmappedQuestionIds = [];
|
|
56
|
+
for (const [rawKey, rawValue] of Object.entries(payload.answers || {})) {
|
|
57
|
+
const questionId = String(rawKey).trim();
|
|
58
|
+
if (!questionId) continue;
|
|
59
|
+
const token = normalizeAnswerToken(rawValue);
|
|
60
|
+
if (token === null) continue;
|
|
61
|
+
if (!itemForQuestionId(catalog, questionId)) {
|
|
62
|
+
unmappedQuestionIds.push(questionId);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
answers[questionId] = token;
|
|
66
|
+
}
|
|
67
|
+
const triageResponse = {
|
|
68
|
+
triageId,
|
|
69
|
+
patientId,
|
|
70
|
+
authored: payload.authored || null,
|
|
71
|
+
completed: true,
|
|
72
|
+
answers,
|
|
73
|
+
questionnaireId: payload.questionnaireRecordId || null,
|
|
74
|
+
cadence: payload.cadence || null,
|
|
75
|
+
pain: normalizePain(payload.pain),
|
|
76
|
+
additionalSymptoms: cleanList(payload.additionalSymptoms),
|
|
77
|
+
otherSymptomsText: cleanText(payload.otherSymptomsText),
|
|
78
|
+
otherSymptomsInterference: normalizeOtherSymptomsIntensity(payload.otherSymptomsInterference),
|
|
79
|
+
otherSymptomsNotProctcae: cleanList(payload.otherSymptomsNotProctcae),
|
|
80
|
+
nonIdentifiedSymptoms: cleanText(payload.nonIdentifiedSymptoms),
|
|
81
|
+
symptomsChange: cleanList(payload.symptomsChange),
|
|
82
|
+
};
|
|
83
|
+
return { triageResponse, unmappedQuestionIds };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function buildPayloadFromTriageRow(row = {}, { patientCode, triageRecordId, additionalSymptoms = [], painOptions = [] } = {}) {
|
|
87
|
+
const answers = {};
|
|
88
|
+
for (const [field, value] of Object.entries(row)) {
|
|
89
|
+
const match = QUESTION_COLUMN_RX.exec(field);
|
|
90
|
+
if (!match || value == null || String(value).trim() === '') continue;
|
|
91
|
+
answers[match[1]] = String(value);
|
|
92
|
+
}
|
|
93
|
+
const symptomsChange = String(row.symptoms_change || '')
|
|
94
|
+
.split(',')
|
|
95
|
+
.map((entry) => entry.trim())
|
|
96
|
+
.filter(Boolean);
|
|
97
|
+
const authoredMs = row.Date ? new Date(row.Date).getTime() : NaN;
|
|
98
|
+
const clean = (value) => String(value ?? '').trim() || null;
|
|
99
|
+
const rowCode = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
|
|
100
|
+
return {
|
|
101
|
+
triageRecordId: clean(triageRecordId) || clean(row.recordID),
|
|
102
|
+
patientCode: clean(patientCode) || clean(rowCode),
|
|
103
|
+
patientRecordId: Array.isArray(row.patient_id) ? row.patient_id[0] : row.patient_id || null,
|
|
104
|
+
questionnaireRecordId: Array.isArray(row.questionnaire_id) ? row.questionnaire_id[0] : row.questionnaire_id || null,
|
|
105
|
+
authored: Number.isNaN(authoredMs) ? null : new Date(authoredMs).toISOString(),
|
|
106
|
+
cadence: row.type_quest || null,
|
|
107
|
+
answers,
|
|
108
|
+
pain: {
|
|
109
|
+
hasPain: row.has_pain ?? null,
|
|
110
|
+
frequency: row.pain_frequency ?? null,
|
|
111
|
+
intensity: row.pain_intensity ?? null,
|
|
112
|
+
interference: row.pain_interference ?? null,
|
|
113
|
+
mostImportant: row.most_important_pain ?? null,
|
|
114
|
+
otherText: row.other_pain_text ?? null,
|
|
115
|
+
options: painOptions,
|
|
116
|
+
},
|
|
117
|
+
additionalSymptoms,
|
|
118
|
+
otherSymptomsText: row.other_symptoms || null,
|
|
119
|
+
otherSymptomsInterference: row.other_symptoms_interference || null,
|
|
120
|
+
otherSymptomsNotProctcae: cleanList(String(row.other_symptoms_not_proctcae || '').split(',')),
|
|
121
|
+
nonIdentifiedSymptoms: row.non_identified_symptoms || null,
|
|
122
|
+
adherence: [],
|
|
123
|
+
symptomsChange,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = {
|
|
128
|
+
cleanText,
|
|
129
|
+
normalizeAnswerToken,
|
|
130
|
+
buildTriageResponse,
|
|
131
|
+
buildPayloadFromTriageRow,
|
|
132
|
+
OTHER_SYMPTOMS_INTENSITY_SCALE,
|
|
133
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const {
|
|
2
|
+
DEFAULT_HALF_LIFE_DAYS,
|
|
3
|
+
SOURCE_ROLES,
|
|
4
|
+
UNKNOWN_ROLE,
|
|
5
|
+
VARIABLE_REGISTRY,
|
|
6
|
+
} = require('../constants/variableRegistry');
|
|
7
|
+
|
|
8
|
+
function ownerOf(variableId) {
|
|
9
|
+
return VARIABLE_REGISTRY[variableId]?.owner || 'doctor';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function halfLifeDaysOf(variableId) {
|
|
13
|
+
return VARIABLE_REGISTRY[variableId]?.halfLifeDays ?? DEFAULT_HALF_LIFE_DAYS;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// An unrecognised source gets its own role; casting it to either side invents a disagreement.
|
|
17
|
+
function sourceRole(source) {
|
|
18
|
+
return SOURCE_ROLES[String(source ?? '').trim().toLowerCase()] || UNKNOWN_ROLE;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = { ownerOf, halfLifeDaysOf, sourceRole };
|