@peopl-health/nexus 6.0.0-dev.718 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
const { logger } = require('../../utils/logger');
|
|
4
|
+
const { clampToHourWindow } = require('../../utils/scheduleUtils');
|
|
5
|
+
const { readContingencies, readSymptomCases, storeContingency } = require('../../fhir');
|
|
6
|
+
const { ContingencySafetyNet, ACTIVE_CARE_PLAN_STATUSES, RESOLVED_REASONS, RESOLVES_ON, ARMED_BY, isNetActive } = require('../../shared/dtos/ContingencySafetyNet');
|
|
7
|
+
const { recordReminder, hasPendingContingencyRow, recordContingencyEscalation, cancelContingencyRows } = require('./clinicalAirtableService');
|
|
8
|
+
const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
|
|
9
|
+
const { isShadowRun } = require('../helpers/shadowHelper');
|
|
10
|
+
|
|
11
|
+
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
|
|
12
|
+
// Net check-ins start an hour later: 08:00–09:00 is when the daily symptom forms reach patients.
|
|
13
|
+
const CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, startHour: 9 };
|
|
14
|
+
// asap check-ins only hold 23:00–08:00: the case is still hot and someone may be awake.
|
|
15
|
+
const ASAP_CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, endHour: 23 };
|
|
16
|
+
const MS_PER_MINUTE = 60 * 1000;
|
|
17
|
+
const MS_PER_HOUR = 60 * MS_PER_MINUTE;
|
|
18
|
+
const EXPIRY_WINDOW_MULTIPLIER = 6;
|
|
19
|
+
const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
|
|
20
|
+
const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
|
|
21
|
+
const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
|
|
22
|
+
// Nets armed before the change keep their level until they expire (stat 120, asap 180).
|
|
23
|
+
const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
|
|
24
|
+
const OPEN_CEILING_SILENCE_MINUTES = 720;
|
|
25
|
+
const OPEN_CEILING_ORIGIN = 'open_ceiling';
|
|
26
|
+
const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
|
|
27
|
+
const ESCALATION_AWAITING = 'cómo evolucionó el síntoma escalado: si empeoró, mejoró o apareció un signo de alarma';
|
|
28
|
+
const ESCALATION_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo te sientes ahora con lo que me contaste?';
|
|
29
|
+
const FIRED_STATUS_BY_STAGE = { patient: 'fired_reminder', team: 'fired_team' };
|
|
30
|
+
const STATUS_RANK = { armed: 0, fired_reminder: 1, fired_team: 2 };
|
|
31
|
+
const TEAM_WINDOW_FRACTION = 0.5;
|
|
32
|
+
const TEAM_WINDOW_FLOOR_MS = 2 * MS_PER_HOUR;
|
|
33
|
+
const TEAM_WINDOW_CEILING_MS = 6 * MS_PER_HOUR;
|
|
34
|
+
const TEAM_ACTION_REQUESTED = 'Contactar activamente a la paciente: no respondió al check-in de contingencia.';
|
|
35
|
+
|
|
36
|
+
function rawDueAt(createdAt, firesAfterSilenceMinutes) {
|
|
37
|
+
return new Date(new Date(createdAt).getTime() + (firesAfterSilenceMinutes * MS_PER_MINUTE));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function checkInWindowFor(urgencyLevel) {
|
|
41
|
+
return urgencyLevel === 'asap' ? ASAP_CHECK_IN_WINDOW : CHECK_IN_WINDOW;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function dueAt(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
|
|
45
|
+
const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
|
|
46
|
+
return (clampToHourWindow(raw, window) || raw).toISOString();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
|
|
50
|
+
const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
|
|
51
|
+
const clamped = clampToHourWindow(raw, window);
|
|
52
|
+
if (!clamped) return 0;
|
|
53
|
+
return Math.round((clamped.getTime() - raw.getTime()) / MS_PER_MINUTE);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function teamWindowMinutes(firesAfterSilenceMinutes) {
|
|
57
|
+
const raw = TEAM_WINDOW_FRACTION * (firesAfterSilenceMinutes || 0) * MS_PER_MINUTE;
|
|
58
|
+
const clamped = Math.min(Math.max(raw, TEAM_WINDOW_FLOOR_MS), TEAM_WINDOW_CEILING_MS);
|
|
59
|
+
return Math.round(clamped / MS_PER_MINUTE);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function teamDueAt(firedAt, firesAfterSilenceMinutes) {
|
|
63
|
+
return new Date(new Date(firedAt).getTime() + (teamWindowMinutes(firesAfterSilenceMinutes) * MS_PER_MINUTE)).toISOString();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function teamHandoffMessage(carePlan) {
|
|
67
|
+
const concern = carePlan.concern || 'contingencia sin detalle';
|
|
68
|
+
const awaited = carePlan.awaitingCharacterization;
|
|
69
|
+
return awaited ? `${concern} — se esperaba: ${awaited}.` : `${concern}.`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function armTeamStage({ patientCode, net, firedAt, trace = null, isLive = null }) {
|
|
73
|
+
const { carePlan, patientReminder } = net;
|
|
74
|
+
const silence = patientReminder?.firesAfterSilenceMinutes;
|
|
75
|
+
if (await hasPendingContingencyRow({ planId: carePlan.planId })) {
|
|
76
|
+
return { armed: false, reason: 'handoff_already_queued' };
|
|
77
|
+
}
|
|
78
|
+
const written = await recordContingencyEscalation({
|
|
79
|
+
code: patientCode,
|
|
80
|
+
trace,
|
|
81
|
+
isLive,
|
|
82
|
+
planId: carePlan.planId,
|
|
83
|
+
dueAtUtc: teamDueAt(firedAt, silence),
|
|
84
|
+
firesAfterSilenceMinutes: teamWindowMinutes(silence),
|
|
85
|
+
expiresAtUtc: carePlan.expiresAt,
|
|
86
|
+
concern: carePlan.concern,
|
|
87
|
+
message: teamHandoffMessage(carePlan),
|
|
88
|
+
actionRequested: patientReminder?.actionRequested || TEAM_ACTION_REQUESTED,
|
|
89
|
+
priority: patientReminder?.priority || null,
|
|
90
|
+
});
|
|
91
|
+
if (!written) return { armed: false, reason: 'queue_write_failed' };
|
|
92
|
+
|
|
93
|
+
const still = (await readActiveNets(patientCode)).some((n) => n.carePlan.planId === carePlan.planId);
|
|
94
|
+
if (!still) {
|
|
95
|
+
await cancelContingencyRows({ code: patientCode, trace, planId: carePlan.planId, standDownReason: 'plan resuelto antes de que la cola del equipo se armara' });
|
|
96
|
+
return { armed: false, reason: 'plan_retired_mid_handoff' };
|
|
97
|
+
}
|
|
98
|
+
return { armed: true };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function computeExpiresAt(createdAt, firesAfterSilenceMinutes) {
|
|
102
|
+
const raw = EXPIRY_WINDOW_MULTIPLIER * (firesAfterSilenceMinutes || 0) * MS_PER_MINUTE;
|
|
103
|
+
const clamped = Math.min(Math.max(raw, EXPIRY_FLOOR_MS), EXPIRY_CEILING_MS);
|
|
104
|
+
return new Date(new Date(createdAt).getTime() + clamped).toISOString();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null, checkInWindow = CHECK_IN_WINDOW }) {
|
|
108
|
+
const existing = Array.isArray(trace?.signals?.contingencyPlans) ? trace.signals.contingencyPlans : [];
|
|
109
|
+
trace?.setSignals?.({
|
|
110
|
+
contingencyPlans: [...existing, {
|
|
111
|
+
planId,
|
|
112
|
+
relatedCaseId,
|
|
113
|
+
relatedClusterId,
|
|
114
|
+
concern,
|
|
115
|
+
awaitingCharacterization,
|
|
116
|
+
resolvesOn,
|
|
117
|
+
patientFiresAfterSilenceMinutes: firesAfterSilenceMinutes,
|
|
118
|
+
quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, checkInWindow),
|
|
119
|
+
windowReasoning,
|
|
120
|
+
...(extra || {}),
|
|
121
|
+
}],
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function onsetOf(managedSymptom) {
|
|
126
|
+
const at = managedSymptom.condition.onsetAt;
|
|
127
|
+
return at ? new Date(at).getTime() : 0;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const TOUCHES_A_CASE = new Set(['openCondition', 'recordClinicalImpression', 'updateConditionStatus']);
|
|
131
|
+
|
|
132
|
+
function casesTouchedThisTurn(trace) {
|
|
133
|
+
const ids = new Set();
|
|
134
|
+
for (const step of trace?.steps || []) {
|
|
135
|
+
if (!TOUCHES_A_CASE.has(step?.tool_name)) continue;
|
|
136
|
+
const output = String(step?.tool_output || '');
|
|
137
|
+
if (step?.success !== true || /"success"\s*:\s*false/.test(output)) continue;
|
|
138
|
+
const fromArgs = step?.tool_arguments?.case_id;
|
|
139
|
+
if (typeof fromArgs === 'string' && fromArgs) ids.add(fromArgs);
|
|
140
|
+
const fromOutput = output.match(/"case_id":"(case_[a-f0-9]+)"/);
|
|
141
|
+
if (fromOutput) ids.add(fromOutput[1]);
|
|
142
|
+
}
|
|
143
|
+
return ids;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function escalationNetTarget(patientCode, { stepsAside = () => false, touched = new Set() } = {}) {
|
|
147
|
+
const open = (await readSymptomCases({ patientId: patientCode }))
|
|
148
|
+
.filter((managedSymptom) => OPEN_STATUSES.includes(managedSymptom.condition.clinicalStatus));
|
|
149
|
+
const worked = open.filter((managedSymptom) => touched.has(managedSymptom.condition.conditionId));
|
|
150
|
+
const pool = worked.length ? worked : open;
|
|
151
|
+
const caseId = pool.length
|
|
152
|
+
? pool.slice().sort((a, b) => (onsetOf(b) - onsetOf(a))
|
|
153
|
+
|| a.condition.conditionId.localeCompare(b.condition.conditionId))[0].condition.conditionId
|
|
154
|
+
: null;
|
|
155
|
+
const held = (await readActiveNets(patientCode)).filter((n) => !stepsAside(n));
|
|
156
|
+
if (held.length) return { skip: 'active_net_exists', caseId, openCases: open.length };
|
|
157
|
+
return { caseId, openCases: open.length };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function commitMachineNet({ patientCode, contingency, caseId, trace, isLive, planId, stepsAside = () => false }) {
|
|
161
|
+
if (isShadowRun()) return { armed: false, reason: 'shadow_run', planId };
|
|
162
|
+
if (isLive && !isLive()) return { armed: false, reason: 'turn_superseded', planId };
|
|
163
|
+
|
|
164
|
+
await storeContingency({ patientId: patientCode, contingency });
|
|
165
|
+
const raced = (await readActiveNets(patientCode, caseId))
|
|
166
|
+
.find((n) => n.carePlan.planId !== planId && !stepsAside(n));
|
|
167
|
+
if (raced) {
|
|
168
|
+
await resolveContingency({ patientCode, net: contingency, status: 'auto_resolved', resolvedReason: RESOLVED_REASONS.SUPERSEDED_BY_AGENT, trace, requireRowsDown: false });
|
|
169
|
+
return { armed: false, reason: 'lost_race_to_another_net', planId, winningPlanId: raced.carePlan.planId };
|
|
170
|
+
}
|
|
171
|
+
if (!await armContingency({ contingency, patientCode, trace, isLive })) {
|
|
172
|
+
await resolveContingency({ patientCode, net: contingency, status: 'auto_resolved', resolvedReason: RESOLVED_REASONS.NO_LONGER_RELEVANT, trace, requireRowsDown: false });
|
|
173
|
+
return { armed: false, reason: 'reminder_not_armed', planId };
|
|
174
|
+
}
|
|
175
|
+
return { armed: true, planId };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const SETTLED_LADDER = new Set(['none', 'ninguno', 'ninguna', 'nada', 'n/a', 'na', 'no', '-', 'sin pendientes', 'nada pendiente']);
|
|
179
|
+
|
|
180
|
+
function isSettledLadder(missing) {
|
|
181
|
+
const normalised = String(missing || '')
|
|
182
|
+
.toLowerCase()
|
|
183
|
+
.normalize('NFD')
|
|
184
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
185
|
+
.replace(/[.,;:!¡?¿'"]/g, '')
|
|
186
|
+
.trim();
|
|
187
|
+
return !normalised || SETTLED_LADDER.has(normalised);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function armOpenCeilingNet({ patientCode, caseId, symptom, missing, grade = null, checkIn = null, trace = null, isLive = null }) {
|
|
191
|
+
const awaited = String(missing || '').trim();
|
|
192
|
+
if (!caseId) return { armed: false, reason: 'no_case' };
|
|
193
|
+
await sweepOrphanCeilingNets({ patientCode, trace, isLive });
|
|
194
|
+
if (isSettledLadder(awaited)) return { armed: false, reason: 'nothing_missing', caseId };
|
|
195
|
+
const held = await readActiveNets(patientCode);
|
|
196
|
+
if (held.length) {
|
|
197
|
+
return {
|
|
198
|
+
armed: false,
|
|
199
|
+
reason: held.some((n) => n.carePlan.relatedCaseId === caseId) ? 'active_net_exists' : 'patient_already_watched',
|
|
200
|
+
caseId,
|
|
201
|
+
heldBy: held[0].carePlan.relatedCaseId,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const now = new Date().toISOString();
|
|
206
|
+
const planId = `plan_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
207
|
+
const concern = symptom || 'evolución del caso';
|
|
208
|
+
const contingency = new ContingencySafetyNet({
|
|
209
|
+
carePlan: {
|
|
210
|
+
planId,
|
|
211
|
+
patientId: patientCode,
|
|
212
|
+
relatedCaseId: caseId,
|
|
213
|
+
concern,
|
|
214
|
+
awaitingCharacterization: awaited,
|
|
215
|
+
armedBy: ARMED_BY.OPEN_CEILING,
|
|
216
|
+
creationReasoning: OPEN_CEILING_ORIGIN,
|
|
217
|
+
resolvesOn: RESOLVES_ON.OBSERVATION,
|
|
218
|
+
createdAt: now,
|
|
219
|
+
expiresAt: computeExpiresAt(now, OPEN_CEILING_SILENCE_MINUTES),
|
|
220
|
+
},
|
|
221
|
+
patientReminder: {
|
|
222
|
+
recipient: 'patient',
|
|
223
|
+
message: String(checkIn || '').trim() || OPEN_CEILING_CHECK_IN,
|
|
224
|
+
firesAfterSilenceMinutes: OPEN_CEILING_SILENCE_MINUTES,
|
|
225
|
+
windowReasoning: 'La impresión dejó el techo del grado abierto: si la paciente calla, se le pregunta el dato que lo decidiría.',
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
stampContingencyPlan({
|
|
230
|
+
trace,
|
|
231
|
+
planId,
|
|
232
|
+
relatedCaseId: caseId,
|
|
233
|
+
relatedClusterId: null,
|
|
234
|
+
concern,
|
|
235
|
+
awaitingCharacterization: awaited,
|
|
236
|
+
resolvesOn: RESOLVES_ON.OBSERVATION,
|
|
237
|
+
createdAt: now,
|
|
238
|
+
firesAfterSilenceMinutes: OPEN_CEILING_SILENCE_MINUTES,
|
|
239
|
+
windowReasoning: contingency.patientReminder.windowReasoning,
|
|
240
|
+
extra: { armedBy: 'open_ceiling', grade },
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const out = await commitMachineNet({ patientCode, contingency, caseId: null, trace, isLive, planId });
|
|
244
|
+
return out.armed ? { ...out, relatedCaseId: caseId } : out;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function isCeilingNet(net) {
|
|
248
|
+
const plan = net?.carePlan;
|
|
249
|
+
return plan?.armedBy === ARMED_BY.OPEN_CEILING || plan?.creationReasoning === OPEN_CEILING_ORIGIN;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function retireNets({ patientCode, trace, isLive, select, context }) {
|
|
253
|
+
if (isShadowRun()) return [];
|
|
254
|
+
if (isLive && !isLive()) return [];
|
|
255
|
+
const targets = select(await readActiveNets(patientCode));
|
|
256
|
+
const retired = [];
|
|
257
|
+
for (const net of targets) {
|
|
258
|
+
if (isLive && !isLive()) return retired;
|
|
259
|
+
try {
|
|
260
|
+
await resolveContingency({
|
|
261
|
+
patientCode,
|
|
262
|
+
net,
|
|
263
|
+
status: 'auto_resolved',
|
|
264
|
+
resolvedReason: RESOLVED_REASONS.NO_LONGER_RELEVANT,
|
|
265
|
+
trace,
|
|
266
|
+
requireRowsDown: false,
|
|
267
|
+
});
|
|
268
|
+
retired.push(net.carePlan.planId);
|
|
269
|
+
} catch (error) {
|
|
270
|
+
logger.warn(`[contingency] net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return retired;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function orphanCeilingNets(active) {
|
|
277
|
+
const ceiling = active.filter(isCeilingNet);
|
|
278
|
+
return ceiling.length === active.length ? [] : ceiling;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireNets({
|
|
282
|
+
patientCode, trace, isLive, select: orphanCeilingNets, context: 'while sweeping an orphan',
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireNets({
|
|
286
|
+
patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
// A patient sent to urgencias gets no later check-in, neither the ceiling one nor one left by a lower escalation.
|
|
290
|
+
const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
|
|
291
|
+
patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
function escalationUrgencyOf(net) {
|
|
295
|
+
if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
|
|
296
|
+
const silence = net?.patientReminder?.firesAfterSilenceMinutes;
|
|
297
|
+
const levels = Object.keys(ESCALATION_SILENCE_MINUTES);
|
|
298
|
+
return levels.find((level) => ESCALATION_SILENCE_MINUTES[level] === silence)
|
|
299
|
+
|| levels.find((level) => LEGACY_ESCALATION_SILENCE_MINUTES[level] === silence)
|
|
300
|
+
|| null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
|
|
304
|
+
if (!Object.hasOwn(ESCALATION_SILENCE_MINUTES, urgencyLevel)) return { armed: false, reason: 'urgency_not_covered' };
|
|
305
|
+
const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
|
|
306
|
+
// stat gets no check-in of its own; it only clears the check-ins already armed.
|
|
307
|
+
if (!silence) {
|
|
308
|
+
const superseded = await supersedeForStat({ patientCode, trace, isLive }).catch((error) => {
|
|
309
|
+
logger.warn('[contingency] check-ins not retired for a stat escalation', { patientCode, error: error?.message });
|
|
310
|
+
return [];
|
|
311
|
+
});
|
|
312
|
+
return { armed: false, reason: 'level_without_check_in', superseded };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
await sweepOrphanCeilingNets({ patientCode, trace, isLive });
|
|
316
|
+
const target = await escalationNetTarget(patientCode, { stepsAside: isCeilingNet, touched: casesTouchedThisTurn(trace) });
|
|
317
|
+
if (target.skip) return { armed: false, reason: target.skip, caseId: target.caseId, openCases: target.openCases };
|
|
318
|
+
|
|
319
|
+
const now = new Date().toISOString();
|
|
320
|
+
const planId = `plan_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
321
|
+
const concern = suspectedCondition ? `${symptom} — ${suspectedCondition}` : symptom;
|
|
322
|
+
const contingency = new ContingencySafetyNet({
|
|
323
|
+
carePlan: {
|
|
324
|
+
planId,
|
|
325
|
+
patientId: patientCode,
|
|
326
|
+
relatedCaseId: target.caseId,
|
|
327
|
+
concern,
|
|
328
|
+
awaitingCharacterization: ESCALATION_AWAITING,
|
|
329
|
+
armedBy: ARMED_BY.ESCALATION,
|
|
330
|
+
createdAt: now,
|
|
331
|
+
expiresAt: computeExpiresAt(now, silence),
|
|
332
|
+
},
|
|
333
|
+
patientReminder: {
|
|
334
|
+
recipient: 'patient',
|
|
335
|
+
message: String(checkIn || '').trim() || ESCALATION_CHECK_IN,
|
|
336
|
+
firesAfterSilenceMinutes: silence,
|
|
337
|
+
windowReasoning: `Escalación ${urgencyLevel}: se vuelve a buscar a la paciente si no hay señal suya.`,
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
stampContingencyPlan({
|
|
342
|
+
trace,
|
|
343
|
+
planId,
|
|
344
|
+
relatedCaseId: target.caseId,
|
|
345
|
+
relatedClusterId: null,
|
|
346
|
+
concern,
|
|
347
|
+
awaitingCharacterization: ESCALATION_AWAITING,
|
|
348
|
+
createdAt: now,
|
|
349
|
+
firesAfterSilenceMinutes: silence,
|
|
350
|
+
windowReasoning: contingency.patientReminder.windowReasoning,
|
|
351
|
+
extra: { armedBy: 'escalation', escalationUrgency: urgencyLevel },
|
|
352
|
+
checkInWindow: checkInWindowFor(urgencyLevel),
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
const out = await commitMachineNet({ patientCode, contingency, caseId: null, trace, isLive, planId, stepsAside: isCeilingNet });
|
|
356
|
+
if (!out.armed) return out;
|
|
357
|
+
const superseded = await supersedeForEscalation({ patientCode, trace, isLive });
|
|
358
|
+
return { ...out, relatedCaseId: target.caseId, firesAfterSilenceMinutes: silence, superseded };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function armContingency({ contingency, patientCode, trace = null, isLive = null, actionType = 'create' }) {
|
|
362
|
+
const { carePlan, patientReminder } = contingency;
|
|
363
|
+
|
|
364
|
+
if (patientReminder?.firesAfterSilenceMinutes) {
|
|
365
|
+
return recordReminder({
|
|
366
|
+
code: patientCode,
|
|
367
|
+
trace,
|
|
368
|
+
isLive,
|
|
369
|
+
actionType,
|
|
370
|
+
reminderId: `${carePlan.planId}-patient`,
|
|
371
|
+
reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes, checkInWindowFor(escalationUrgencyOf(contingency))),
|
|
372
|
+
reminderType: 'contingency',
|
|
373
|
+
description: patientReminder.message,
|
|
374
|
+
firesAfterSilenceMinutes: patientReminder.firesAfterSilenceMinutes,
|
|
375
|
+
expiresAtUtc: carePlan.expiresAt,
|
|
376
|
+
concern: carePlan.concern,
|
|
377
|
+
windowReasoning: patientReminder.windowReasoning,
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return false;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function resolveContingency({ patientCode, net, resolvedReason, resolutionNote = null, trace = null, status = 'cancelled', requireRowsDown = true }) {
|
|
384
|
+
const planId = net.carePlan.planId;
|
|
385
|
+
if (!await cancelContingencyRows({ code: patientCode, trace, planId, standDownReason: resolutionNote || resolvedReason })) {
|
|
386
|
+
if (requireRowsDown) {
|
|
387
|
+
logger.warn('[contingencyDispatch] stand-down failed; leaving the net armed to retry', { patientCode, planId, resolvedReason });
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
logger.warn('[contingencyDispatch] rows not stood down; retiring the plan anyway', { patientCode, planId, resolvedReason });
|
|
391
|
+
}
|
|
392
|
+
await storeContingency({
|
|
393
|
+
patientId: patientCode,
|
|
394
|
+
contingency: new ContingencySafetyNet({
|
|
395
|
+
...net,
|
|
396
|
+
carePlan: { ...net.carePlan, status, resolvedAt: new Date().toISOString(), resolvedReason },
|
|
397
|
+
}),
|
|
398
|
+
});
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function autoResolveNets({ patientCode, nets, resolvedReason, trace = null }) {
|
|
403
|
+
const autoResolvedPlans = [];
|
|
404
|
+
const cascadeErrors = [];
|
|
405
|
+
for (const net of nets.filter((n) => isNetActive(n))) {
|
|
406
|
+
try {
|
|
407
|
+
if (!await resolveContingency({ patientCode, net, status: 'auto_resolved', resolvedReason, trace })) {
|
|
408
|
+
throw new Error(`stand-down failed for ${net.carePlan.planId}; plan left armed to retry`);
|
|
409
|
+
}
|
|
410
|
+
autoResolvedPlans.push(net.carePlan.planId);
|
|
411
|
+
} catch (error) {
|
|
412
|
+
cascadeErrors.push(`contingency_auto_resolve_failed: ${error?.message || error}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return { autoResolvedPlans, cascadeErrors };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function readActiveNets(patientCode, caseId = null) {
|
|
419
|
+
const nets = await readContingencies({ patientId: patientCode, caseId });
|
|
420
|
+
return nets.filter((net) => isNetActive(net));
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async function cancelContingencies({ patientCode, trace = null }) {
|
|
424
|
+
const active = await readActiveNets(patientCode);
|
|
425
|
+
if (!active.length) return { cancelled: [], surviving: [] };
|
|
426
|
+
|
|
427
|
+
const cancelled = [];
|
|
428
|
+
const surviving = [];
|
|
429
|
+
for (const net of active) {
|
|
430
|
+
if (net.carePlan.resolvesOn === RESOLVES_ON.OBSERVATION) {
|
|
431
|
+
surviving.push(net);
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
const ok = await resolveContingency({ patientCode, net, resolvedReason: RESOLVED_REASONS.PATIENT_REPLIED, trace });
|
|
435
|
+
(ok ? cancelled : surviving).push(net);
|
|
436
|
+
}
|
|
437
|
+
return { cancelled, surviving };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async function snapshotContingencies({ patientCode }) {
|
|
441
|
+
return { cancelled: [], surviving: await readActiveNets(patientCode) };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function applyContingencyEvent({ patientCode, planId, stage, event, at = null }) {
|
|
445
|
+
if (event === 'fired' && !FIRED_STATUS_BY_STAGE[stage]) return { applied: false, reason: 'unknown_stage' };
|
|
446
|
+
if (!['fired', 'expired'].includes(event)) return { applied: false, reason: 'unknown_event' };
|
|
447
|
+
|
|
448
|
+
const nets = await readContingencies({ patientId: patientCode });
|
|
449
|
+
const net = nets.find((n) => n.carePlan.planId === planId);
|
|
450
|
+
if (!net) return { applied: false, reason: 'plan_not_found' };
|
|
451
|
+
|
|
452
|
+
const plan = net.carePlan;
|
|
453
|
+
if (plan.resolvedAt != null || !ACTIVE_CARE_PLAN_STATUSES.includes(plan.status)) {
|
|
454
|
+
return { applied: false, reason: 'already_terminal', status: plan.status };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const stamp = at && !Number.isNaN(new Date(at).getTime()) ? new Date(at).toISOString() : new Date().toISOString();
|
|
458
|
+
|
|
459
|
+
if (event === 'expired') {
|
|
460
|
+
const { superseded } = await storeContingency({
|
|
461
|
+
patientId: patientCode,
|
|
462
|
+
ifStillActive: true,
|
|
463
|
+
contingency: new ContingencySafetyNet({
|
|
464
|
+
...net,
|
|
465
|
+
carePlan: { ...plan, status: 'auto_resolved', resolvedAt: stamp, resolvedReason: RESOLVED_REASONS.EXPIRED },
|
|
466
|
+
}),
|
|
467
|
+
});
|
|
468
|
+
if (superseded) return { applied: false, reason: 'already_terminal', status: plan.status };
|
|
469
|
+
return { applied: true, status: 'auto_resolved' };
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const next = FIRED_STATUS_BY_STAGE[stage];
|
|
473
|
+
if (STATUS_RANK[next] <= STATUS_RANK[plan.status]) {
|
|
474
|
+
return { applied: false, reason: 'out_of_order', status: plan.status };
|
|
475
|
+
}
|
|
476
|
+
const { superseded } = await storeContingency({
|
|
477
|
+
patientId: patientCode,
|
|
478
|
+
ifStillActive: true,
|
|
479
|
+
contingency: new ContingencySafetyNet({ ...net, carePlan: { ...plan, status: next } }),
|
|
480
|
+
});
|
|
481
|
+
if (superseded) return { applied: false, reason: 'already_terminal', status: plan.status };
|
|
482
|
+
if (stage !== 'patient') return { applied: true, status: next };
|
|
483
|
+
|
|
484
|
+
let handoff;
|
|
485
|
+
try {
|
|
486
|
+
handoff = await armTeamStage({ patientCode, net, firedAt: stamp, trace: null });
|
|
487
|
+
} catch (error) {
|
|
488
|
+
handoff = { armed: false, reason: error.message };
|
|
489
|
+
}
|
|
490
|
+
if (!handoff.armed) {
|
|
491
|
+
logger.error('[contingencyDispatch] team stage not armed', { planId, patientCode, reason: handoff.reason });
|
|
492
|
+
}
|
|
493
|
+
return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const { getSymptom } = require('../../fhir/helpers/terminologyHelper');
|
|
2
|
+
const { termKey } = require('../../fhir/utils/normalizeUtils');
|
|
3
|
+
const { matchTerm, entriesOfKeys } = require('../../fhir/helpers/termMatchHelper');
|
|
4
|
+
const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
|
|
5
|
+
|
|
6
|
+
const CRITICAL_FIELD_GAPS = {
|
|
7
|
+
functional_impact: 'la interferencia del PRO-CTCAE es una escala de 5 puntos, no la limitación de '
|
|
8
|
+
+ 'actividades instrumentales/autocuidado que exige la cláusula',
|
|
9
|
+
intensity_nrs: 'la intensidad del PRO-CTCAE es verbal, no una escala 0–10',
|
|
10
|
+
};
|
|
11
|
+
const QUESTIONNAIRE_GAP = 'el cuestionario no pregunta este dato';
|
|
12
|
+
|
|
13
|
+
function candidateKeys(catalog, term) {
|
|
14
|
+
const keys = [termKey(term)];
|
|
15
|
+
const ctcaeV5 = getSymptom(catalog, term)?.ctcae_v5;
|
|
16
|
+
if (ctcaeV5) keys.push(termKey(String(ctcaeV5).split('\n')[0]));
|
|
17
|
+
return keys.filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function ladderKeyFor(curatedKeys, catalog, term) {
|
|
21
|
+
const entries = entriesOfKeys(curatedKeys);
|
|
22
|
+
for (const candidate of candidateKeys(catalog, term)) {
|
|
23
|
+
const hit = matchTerm(candidate, entries);
|
|
24
|
+
if (hit) return hit;
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function ladderFor(catalog, term) {
|
|
30
|
+
let curated;
|
|
31
|
+
try {
|
|
32
|
+
curated = getCtcaeCatalog().getCuratedSymptomsByTerm();
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
const key = ladderKeyFor(new Set(curated.keys()), catalog, term);
|
|
37
|
+
const entry = key ? curated.get(key) : null;
|
|
38
|
+
const grades = entry?.grades;
|
|
39
|
+
if (!grades || !Object.keys(grades).length) return null;
|
|
40
|
+
return { ctcaeTerm: key, grades, criticalField: entry.criticalField || null };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function renderLadder(ladder, grade, { indent = ' ' } = {}) {
|
|
44
|
+
const lines = [
|
|
45
|
+
`${indent}Escala CTCAE de ${ladder.ctcaeTerm}. El grado de arriba es una APROXIMACIÓN calculada a partir `
|
|
46
|
+
+ 'del PRO-CTCAE, no una lectura de estas cláusulas: contrasta lo que el paciente describe contra '
|
|
47
|
+
+ 'ellas antes de darlo por confirmado. Si la evidencia sostiene otra cláusula, ese es el grado.',
|
|
48
|
+
];
|
|
49
|
+
for (const [level, clause] of Object.entries(ladder.grades)) {
|
|
50
|
+
const description = String(clause?.description ?? '').trim();
|
|
51
|
+
if (!description || Number(level) < 1) continue;
|
|
52
|
+
const marker = Number(level) === Number(grade) ? ' <- grado calculado' : '';
|
|
53
|
+
lines.push(`${indent} G${level}: ${description}${marker}`);
|
|
54
|
+
}
|
|
55
|
+
if (ladder.criticalField) {
|
|
56
|
+
lines.push(
|
|
57
|
+
`${indent}Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
|
|
58
|
+
+ `No capturado por el cuestionario (${CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP}): `
|
|
59
|
+
+ 'pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo '
|
|
60
|
+
+ 'presentes como grado CTCAE ni lo uses para confirmar un umbral.',
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
return lines;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = {
|
|
67
|
+
ladderKeyFor,
|
|
68
|
+
ladderFor,
|
|
69
|
+
renderLadder,
|
|
70
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
|
|
2
|
+
|
|
3
|
+
const FREE_TERM = 'other';
|
|
4
|
+
|
|
5
|
+
// listed, not inferred: a prefix rule would pull chest_wall_pain into pain
|
|
6
|
+
const KNOWN_ALIASES = {
|
|
7
|
+
rash: 'skin_rash',
|
|
8
|
+
palmar_plantar_erythrodysesthesia_syndrome: 'palmar_plantar_erythrodysesthesia',
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
function normalise(term) {
|
|
12
|
+
return String(term || '').trim().toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function curatedAliasFor(ctcaeTerm) {
|
|
16
|
+
const term = String(ctcaeTerm || '').trim().toLowerCase();
|
|
17
|
+
if (!term || term === FREE_TERM) return null;
|
|
18
|
+
let keys;
|
|
19
|
+
try {
|
|
20
|
+
const catalog = getCtcaeCatalog();
|
|
21
|
+
if (catalog.lookupEntry(term)?.found) return null;
|
|
22
|
+
keys = [...catalog.getCuratedSymptomsByTerm().keys()];
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
const alias = KNOWN_ALIASES[term];
|
|
27
|
+
if (alias && keys.includes(alias)) return alias;
|
|
28
|
+
const wanted = normalise(term);
|
|
29
|
+
return keys.find((key) => normalise(key) === wanted) || null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ctcaeTermError(ctcaeTerm) {
|
|
33
|
+
const alias = curatedAliasFor(ctcaeTerm);
|
|
34
|
+
if (!alias) return null;
|
|
35
|
+
return {
|
|
36
|
+
error: `'${ctcaeTerm}' is the catalog term '${alias}' written differently. Use '${alias}' so this case joins the existing one and carries its grade scale.`,
|
|
37
|
+
useInstead: alias,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = {
|
|
42
|
+
curatedAliasFor,
|
|
43
|
+
ctcaeTermError,
|
|
44
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const { chemoStatus } = require('../helpers/chemoContextHelper');
|
|
2
|
+
const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
3
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
4
|
+
|
|
5
|
+
// long enough for immunotherapy or a hormone depot given every three months
|
|
6
|
+
const UNIT_WINDOW_DAYS = 100;
|
|
7
|
+
const CONFIRMED_DAYS = 90;
|
|
8
|
+
const FACTS_WINDOW_DAYS = 60;
|
|
9
|
+
const ORAL_VARIABLE = 'oral_onco_summary';
|
|
10
|
+
const RADIOTHERAPY_VARIABLE = 'radiotherapy_summary';
|
|
11
|
+
const TREATMENT_VARIABLES = Object.freeze(['injectable_onco_summary', ORAL_VARIABLE, RADIOTHERAPY_VARIABLE]);
|
|
12
|
+
// order headings the unit's parser can leave in a regimen: a kind of treatment, not a drug
|
|
13
|
+
const GENERIC_ENTRY = /^(citotoxicos?|biologicos?|inmunoterapia|quimioterapia)$/;
|
|
14
|
+
|
|
15
|
+
const isTreatment = (row) => TREATMENT_VARIABLES.includes(row.variableId);
|
|
16
|
+
const isOral = (row) => row.variableId === ORAL_VARIABLE;
|
|
17
|
+
const within = (row, until, days) => {
|
|
18
|
+
const since = mexicoDay(row.validTime);
|
|
19
|
+
return since !== null && daysBetween(since, until) <= days;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// an ongoing oral is rarely restated, so an old one is kept but marked unconfirmed rather than dropped
|
|
23
|
+
const withOralAge = (row, today) => (within(row, today, CONFIRMED_DAYS) ? row : { ...row, unconfirmed: true });
|
|
24
|
+
|
|
25
|
+
function uniqueDrugs(esquema) {
|
|
26
|
+
const key = (drug) => foldAccents(drug).toLowerCase().replace(/[.\s]+$/, '');
|
|
27
|
+
const drugs = esquema.map((entry) => entry.farmaco.trim()).filter((drug) => !GENERIC_ENTRY.test(key(drug)));
|
|
28
|
+
return [...new Map(drugs.map((drug) => [key(drug), drug])).values()];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function unitRegimen(chemo, today) {
|
|
32
|
+
const last = chemo?.ultimaAplicacion?.fecha;
|
|
33
|
+
if (!last) return null;
|
|
34
|
+
const next = chemo.proximaSesion?.fecha >= today ? chemo.proximaSesion.fecha : null;
|
|
35
|
+
return {
|
|
36
|
+
drugs: uniqueDrugs(chemo.esquema),
|
|
37
|
+
since: chemo.inicioEsquema?.fecha ?? null,
|
|
38
|
+
lastApplication: last,
|
|
39
|
+
nextSession: next,
|
|
40
|
+
current: chemoStatus(chemo, today, UNIT_WINDOW_DAYS).active,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function currentRegimen({ chemo, facts, today = mexicoDay(new Date()) }) {
|
|
45
|
+
const rows = Array.isArray(facts) ? facts : [];
|
|
46
|
+
const others = rows.filter((row) => !isTreatment(row));
|
|
47
|
+
const orals = rows.filter(isOral).map((row) => withOralAge(row, today));
|
|
48
|
+
const unit = unitRegimen(chemo, today);
|
|
49
|
+
if (unit) {
|
|
50
|
+
const radiotherapy = rows.filter((row) => row.variableId === RADIOTHERAPY_VARIABLE && within(row, today, CONFIRMED_DAYS));
|
|
51
|
+
return { source: 'unit', unit, facts: [...orals, ...radiotherapy, ...others] };
|
|
52
|
+
}
|
|
53
|
+
const treatments = rows.filter(isTreatment);
|
|
54
|
+
const newest = treatments.map((row) => mexicoDay(row.validTime)).filter((day) => day && day <= today).sort().at(-1) ?? today;
|
|
55
|
+
const kept = treatments.filter((row) => !isOral(row) && within(row, newest, FACTS_WINDOW_DAYS));
|
|
56
|
+
const source = chemo === undefined ? 'unreadable' : kept.length || orals.length ? 'facts' : 'none';
|
|
57
|
+
return { source, unit: null, facts: [...kept, ...orals, ...others] };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { currentRegimen };
|