@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,607 @@
|
|
|
1
|
+
const { v4: uuidv4 } = require('uuid');
|
|
2
|
+
|
|
3
|
+
const { getSupportCandidateModel } = require('../models/supportCandidateModel');
|
|
4
|
+
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
5
|
+
const { GROUP_INVITABLE } = require('./supportInvitability');
|
|
6
|
+
|
|
7
|
+
const COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000;
|
|
8
|
+
const DELIVERY_STATUSES = ['sent', 'delivered', 'read', 'failed', 'unknown'];
|
|
9
|
+
const INVITATION_CLASSES = ['first', 'followup'];
|
|
10
|
+
const ENGAGEMENT_STATES = ['notInvited', 'invited', 'registered', 'attended', 'declined'];
|
|
11
|
+
const OPERATIONAL_REASONS = ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'];
|
|
12
|
+
const OPERATIONAL_PLACEHOLDER_VERSION = 'operational-review-v1';
|
|
13
|
+
|
|
14
|
+
function evidenceKey(item) {
|
|
15
|
+
return `${item.source}:${item.sourceId}:${item.code}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function normalizeEvidence(items = []) {
|
|
19
|
+
const byKey = new Map();
|
|
20
|
+
for (const item of items) byKey.set(evidenceKey(item), { key: evidenceKey(item), ...item });
|
|
21
|
+
return [...byKey.values()];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function initialState(decision) {
|
|
25
|
+
return decision.disposition;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function nextState(existing, decision) {
|
|
29
|
+
if (decision.disposition === 'escalated' || existing?.disposition === 'escalated') return 'escalated';
|
|
30
|
+
return initialState(decision);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function candidatePatch(existing, recommendation, decision) {
|
|
34
|
+
const priorEvidence = normalizeEvidence(existing?.evidence || []);
|
|
35
|
+
const mergedEvidence = normalizeEvidence([...priorEvidence, ...decision.evidence]);
|
|
36
|
+
return {
|
|
37
|
+
disposition: nextState(existing, decision),
|
|
38
|
+
...(decision.disposition === 'escalated' && existing?.disposition !== 'escalated' ? {
|
|
39
|
+
escalation: { risk: decision.psychologyRisk || decision.nutritionRisk, sourceId: recommendation.sourceId, origin: recommendation.origin, detectedAt: new Date(recommendation.createdAt), clearedAt: null },
|
|
40
|
+
} : {}),
|
|
41
|
+
groupEligible: decision.groupEligible,
|
|
42
|
+
urgentIntakeEligible: decision.service === 'nutrition' ? decision.urgentIntakeEligible : false,
|
|
43
|
+
priority: decision.priority,
|
|
44
|
+
confidence: decision.confidence,
|
|
45
|
+
nutritionRisk: decision.service === 'nutrition' ? decision.nutritionRisk : null,
|
|
46
|
+
psychologyRisk: decision.service === 'psychology' ? decision.psychologyRisk : null,
|
|
47
|
+
reasonCodes: [...new Set([...(existing?.reasonCodes || []), ...decision.reasonCodes])],
|
|
48
|
+
evidence: mergedEvidence,
|
|
49
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
|
|
50
|
+
latestSourceId: recommendation.sourceId,
|
|
51
|
+
latestOrigin: recommendation.origin,
|
|
52
|
+
decisionVersion: recommendation.decisionVersion,
|
|
53
|
+
lastEvaluatedAt: new Date(recommendation.createdAt),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function isStaleRecommendation(existing, recommendation) {
|
|
58
|
+
if (!existing?.lastEvaluatedAt || existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION) return false;
|
|
59
|
+
return new Date(recommendation.createdAt).getTime() < new Date(existing.lastEvaluatedAt).getTime();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function historicalEvidencePatch(existing, recommendation, decision) {
|
|
63
|
+
return {
|
|
64
|
+
evidence: normalizeEvidence([...(existing?.evidence || []), ...decision.evidence]),
|
|
65
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function upsertDecision(recommendation, decision, options = {}) {
|
|
70
|
+
const Model = options.Model || getSupportCandidateModel();
|
|
71
|
+
const query = { patientId: recommendation.patientId, service: decision.service };
|
|
72
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
73
|
+
const existing = await Model.findOne(query).lean();
|
|
74
|
+
const stale = isStaleRecommendation(existing, recommendation);
|
|
75
|
+
const compareAndSet = existing
|
|
76
|
+
? {
|
|
77
|
+
...query,
|
|
78
|
+
...(existing.revision == null
|
|
79
|
+
? { $or: [{ revision: 0 }, { revision: { $exists: false } }] }
|
|
80
|
+
: { revision: existing.revision }),
|
|
81
|
+
}
|
|
82
|
+
: { ...query, candidateId: { $exists: false } };
|
|
83
|
+
try {
|
|
84
|
+
const updated = await Model.findOneAndUpdate(compareAndSet, {
|
|
85
|
+
$set: stale
|
|
86
|
+
? historicalEvidencePatch(existing, recommendation, decision)
|
|
87
|
+
: candidatePatch(existing, recommendation, decision),
|
|
88
|
+
$setOnInsert: {
|
|
89
|
+
candidateId: uuidv4(),
|
|
90
|
+
patientId: recommendation.patientId,
|
|
91
|
+
service: decision.service,
|
|
92
|
+
},
|
|
93
|
+
$inc: { revision: 1 },
|
|
94
|
+
}, { new: true, upsert: !existing, setDefaultsOnInsert: true });
|
|
95
|
+
if (updated) return stale ? null : updated;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error?.code !== 11000) throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
throw new Error('support candidate changed repeatedly during routing update');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function recordSupportRoutingRecommendation(rawRecommendation, options = {}) {
|
|
104
|
+
const recommendation = rawRecommendation instanceof SupportRoutingRecommendation
|
|
105
|
+
? rawRecommendation
|
|
106
|
+
: new SupportRoutingRecommendation(rawRecommendation);
|
|
107
|
+
const candidates = [];
|
|
108
|
+
for (const decision of recommendation.decisions) {
|
|
109
|
+
const candidate = await upsertDecision(recommendation, decision, options);
|
|
110
|
+
if (candidate) candidates.push(candidate);
|
|
111
|
+
}
|
|
112
|
+
return candidates;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function updateSupportOperationalReview({ patientId, service, reasonCode, sourceId, resolved = false, noClinicalDecision = false, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
116
|
+
if (typeof patientId !== 'string' || !patientId.trim() || !['nutrition', 'psychology'].includes(service)
|
|
117
|
+
|| !OPERATIONAL_REASONS.includes(reasonCode) || typeof sourceId !== 'string' || !sourceId.trim() || sourceId.length > 256) {
|
|
118
|
+
throw new Error('Valid support operational review identity is required');
|
|
119
|
+
}
|
|
120
|
+
const query = { patientId, service };
|
|
121
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
122
|
+
const existing = await Model.findOne(query).lean();
|
|
123
|
+
const reviews = existing?.operationalReviews || [];
|
|
124
|
+
const matches = (review) => review.reasonCode === reasonCode && review.sourceId === sourceId;
|
|
125
|
+
if (resolved && !reviews.some(matches)) return existing;
|
|
126
|
+
const updatedReviews = resolved ? reviews.filter((review) => !matches(review))
|
|
127
|
+
: reviews.some(matches) ? reviews : [...reviews, { reasonCode, sourceId, detectedAt: new Date(now) }];
|
|
128
|
+
const patch = { operationalReviews: updatedReviews.slice(0, 20) };
|
|
129
|
+
if (!resolved) Object.assign(patch, {
|
|
130
|
+
operationalReviewOverflow: existing?.operationalReviewOverflow === true || updatedReviews.length > 20,
|
|
131
|
+
evidence: normalizeEvidence([...(existing?.evidence || []), { source: 'triage', sourceId, code: `support_operational_${reasonCode}`, summary: null, confidence: null }]),
|
|
132
|
+
sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), sourceId])],
|
|
133
|
+
});
|
|
134
|
+
if (resolved && noClinicalDecision && reasonCode === 'classification_failed'
|
|
135
|
+
&& existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION && !updatedReviews.length && !existing.operationalReviewOverflow) {
|
|
136
|
+
patch.disposition = 'none';
|
|
137
|
+
}
|
|
138
|
+
const owner = existing ? { ...query, revision: existing.revision == null ? { $in: [0, null] } : existing.revision }
|
|
139
|
+
: { ...query, candidateId: { $exists: false } };
|
|
140
|
+
try {
|
|
141
|
+
const updated = await Model.findOneAndUpdate(owner, {
|
|
142
|
+
$set: patch,
|
|
143
|
+
...(!existing ? { $setOnInsert: {
|
|
144
|
+
candidateId: uuidv4(), patientId, service, disposition: 'reviewRequired',
|
|
145
|
+
// Review placeholders must remain ineligible even if the schema default changes.
|
|
146
|
+
groupEligible: false, urgentIntakeEligible: false, confidence: 0,
|
|
147
|
+
decisionVersion: OPERATIONAL_PLACEHOLDER_VERSION, latestSourceId: sourceId,
|
|
148
|
+
latestOrigin: 'triage', lastEvaluatedAt: new Date(now),
|
|
149
|
+
} } : {}),
|
|
150
|
+
$inc: { revision: 1 },
|
|
151
|
+
}, { new: true, upsert: !existing, setDefaultsOnInsert: true });
|
|
152
|
+
if (updated) return updated;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error?.code !== 11000) throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
throw new Error('support operational review changed repeatedly');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function requireGroupReview(reviewedRevision, reviewedRisk) {
|
|
161
|
+
if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
|
|
162
|
+
if (!['green', 'yellow'].includes(reviewedRisk)) throw new Error('reviewedRisk must be safe for group approval');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function reviewedGroupPatch(service, reviewedRisk, reviewedAt) {
|
|
166
|
+
return {
|
|
167
|
+
disposition: service === 'nutrition' && reviewedRisk === 'yellow' ? 'individual' : 'group',
|
|
168
|
+
groupEligible: true,
|
|
169
|
+
specialistClearedAt: reviewedAt,
|
|
170
|
+
[service === 'nutrition' ? 'nutritionRisk' : 'psychologyRisk']: reviewedRisk,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function approveCandidate(candidateId, {
|
|
175
|
+
reviewedRevision, reviewedRisk, Model = getSupportCandidateModel(),
|
|
176
|
+
} = {}) {
|
|
177
|
+
requireGroupReview(reviewedRevision, reviewedRisk);
|
|
178
|
+
const reviewedAt = new Date();
|
|
179
|
+
const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
|
|
180
|
+
for (const service of services) {
|
|
181
|
+
const approved = await Model.findOneAndUpdate(
|
|
182
|
+
{ candidateId, service, disposition: 'reviewRequired', revision: reviewedRevision },
|
|
183
|
+
{ $set: reviewedGroupPatch(service, reviewedRisk, reviewedAt), $inc: { revision: 1 } },
|
|
184
|
+
{ new: true },
|
|
185
|
+
);
|
|
186
|
+
if (approved) return approved;
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion }) {
|
|
192
|
+
return `${candidateId}:${invitationClass}:${invitationCycle}:${templateVersion}`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function claimEligibility({ candidateId, invitationClass, now }) {
|
|
196
|
+
return {
|
|
197
|
+
candidateId,
|
|
198
|
+
groupEligible: true,
|
|
199
|
+
$and: [{ $or: [
|
|
200
|
+
{ service: 'nutrition', disposition: { $in: ['group', 'individual'] } },
|
|
201
|
+
{ service: 'psychology', disposition: 'group', psychologyRisk: 'green' },
|
|
202
|
+
] }],
|
|
203
|
+
activeInvitationKey: null,
|
|
204
|
+
'engagement.state': { $in: ['notInvited', 'invited', 'registered', 'attended'] },
|
|
205
|
+
'engagement.attendanceEvidenceId': invitationClass === 'followup' ? { $ne: null } : null,
|
|
206
|
+
$or: [
|
|
207
|
+
{ 'engagement.cooldownUntil': null },
|
|
208
|
+
{ 'engagement.cooldownUntil': { $lte: now } },
|
|
209
|
+
],
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function claimInvitation({ candidateId, invitationClass, invitationCycle, templateVersion, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
214
|
+
if (!INVITATION_CLASSES.includes(invitationClass)) throw new Error(`invalid invitation class: ${invitationClass}`);
|
|
215
|
+
if (!invitationCycle) throw new Error('invitationCycle is required');
|
|
216
|
+
if (!templateVersion) throw new Error('templateVersion is required');
|
|
217
|
+
const claimedAt = new Date(now);
|
|
218
|
+
const idempotencyKey = invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion });
|
|
219
|
+
const eligibility = claimEligibility({ candidateId, invitationClass, now: claimedAt });
|
|
220
|
+
const claimed = await Model.findOneAndUpdate({
|
|
221
|
+
...eligibility,
|
|
222
|
+
'invitationAttempts.idempotencyKey': { $ne: idempotencyKey },
|
|
223
|
+
}, {
|
|
224
|
+
$set: { activeInvitationKey: idempotencyKey },
|
|
225
|
+
$push: {
|
|
226
|
+
invitationAttempts: {
|
|
227
|
+
idempotencyKey,
|
|
228
|
+
invitationClass,
|
|
229
|
+
invitationCycle,
|
|
230
|
+
templateVersion,
|
|
231
|
+
status: 'queued',
|
|
232
|
+
createdAt: claimedAt,
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
$inc: { revision: 1 },
|
|
236
|
+
}, { new: true });
|
|
237
|
+
if (claimed) return claimed;
|
|
238
|
+
return Model.findOneAndUpdate({
|
|
239
|
+
...eligibility,
|
|
240
|
+
invitationAttempts: { $elemMatch: { idempotencyKey, status: 'failed' } },
|
|
241
|
+
}, {
|
|
242
|
+
$set: {
|
|
243
|
+
activeInvitationKey: idempotencyKey,
|
|
244
|
+
'invitationAttempts.$[attempt].status': 'queued',
|
|
245
|
+
'invitationAttempts.$[attempt].providerMessageId': null,
|
|
246
|
+
'invitationAttempts.$[attempt].error': null,
|
|
247
|
+
'invitationAttempts.$[attempt].createdAt': claimedAt,
|
|
248
|
+
'invitationAttempts.$[attempt].settledAt': null,
|
|
249
|
+
},
|
|
250
|
+
$inc: { revision: 1 },
|
|
251
|
+
}, {
|
|
252
|
+
new: true,
|
|
253
|
+
arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': 'failed' }],
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function attemptSettlement({ status, providerMessageId, error, now }) {
|
|
258
|
+
return {
|
|
259
|
+
'invitationAttempts.$[attempt].status': status,
|
|
260
|
+
'invitationAttempts.$[attempt].settledAt': now,
|
|
261
|
+
'invitationAttempts.$[attempt].error': error,
|
|
262
|
+
...(providerMessageId ? { 'invitationAttempts.$[attempt].providerMessageId': providerMessageId } : {}),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function settleActiveAttempt({ candidateId, idempotencyKey, status, providerMessageId, error, now }, engagementStates, engagementPatch, Model) {
|
|
267
|
+
const priorStatuses = ['queued', 'unknown'];
|
|
268
|
+
return Model.findOneAndUpdate({
|
|
269
|
+
candidateId,
|
|
270
|
+
activeInvitationKey: idempotencyKey,
|
|
271
|
+
'engagement.state': { $in: engagementStates },
|
|
272
|
+
invitationAttempts: { $elemMatch: { idempotencyKey, status: { $in: priorStatuses } } },
|
|
273
|
+
}, {
|
|
274
|
+
$set: {
|
|
275
|
+
...attemptSettlement({ idempotencyKey, status, providerMessageId, error, now }),
|
|
276
|
+
...engagementPatch,
|
|
277
|
+
},
|
|
278
|
+
$inc: { revision: 1 },
|
|
279
|
+
}, {
|
|
280
|
+
new: true,
|
|
281
|
+
arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function settleFirstSuccess(args, Model) {
|
|
286
|
+
const cooldownUntil = new Date(args.now.getTime() + COOLDOWN_MS);
|
|
287
|
+
const deliveryPatch = {
|
|
288
|
+
activeInvitationKey: null,
|
|
289
|
+
cooldownInvitationKey: args.idempotencyKey,
|
|
290
|
+
'engagement.lastInvitedAt': args.now,
|
|
291
|
+
'engagement.cooldownUntil': cooldownUntil,
|
|
292
|
+
};
|
|
293
|
+
const invited = await settleActiveAttempt(
|
|
294
|
+
args,
|
|
295
|
+
['notInvited', 'invited'],
|
|
296
|
+
{ ...deliveryPatch, 'engagement.state': 'invited' },
|
|
297
|
+
Model,
|
|
298
|
+
);
|
|
299
|
+
if (invited) return invited;
|
|
300
|
+
return settleActiveAttempt(args, ['registered', 'attended', 'declined'], deliveryPatch, Model);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function advanceSuccessfulAttempt(args, Model) {
|
|
304
|
+
const priorStatuses = args.status === 'delivered' ? ['sent'] : ['sent', 'delivered'];
|
|
305
|
+
if (!['delivered', 'read'].includes(args.status)) return null;
|
|
306
|
+
return Model.findOneAndUpdate({
|
|
307
|
+
candidateId: args.candidateId,
|
|
308
|
+
invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: { $in: priorStatuses } } },
|
|
309
|
+
}, {
|
|
310
|
+
$set: attemptSettlement(args),
|
|
311
|
+
$inc: { revision: 1 },
|
|
312
|
+
}, {
|
|
313
|
+
new: true,
|
|
314
|
+
arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function settleSentFailure(args, Model) {
|
|
319
|
+
const query = {
|
|
320
|
+
candidateId: args.candidateId,
|
|
321
|
+
invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: 'sent' } },
|
|
322
|
+
};
|
|
323
|
+
const options = {
|
|
324
|
+
new: true,
|
|
325
|
+
arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': 'sent' }],
|
|
326
|
+
};
|
|
327
|
+
const ownedCooldown = await Model.findOneAndUpdate({
|
|
328
|
+
...query,
|
|
329
|
+
cooldownInvitationKey: args.idempotencyKey,
|
|
330
|
+
}, {
|
|
331
|
+
$set: {
|
|
332
|
+
...attemptSettlement(args),
|
|
333
|
+
cooldownInvitationKey: null,
|
|
334
|
+
'engagement.cooldownUntil': null,
|
|
335
|
+
},
|
|
336
|
+
$inc: { revision: 1 },
|
|
337
|
+
}, options);
|
|
338
|
+
if (ownedCooldown) return ownedCooldown;
|
|
339
|
+
return Model.findOneAndUpdate({
|
|
340
|
+
...query,
|
|
341
|
+
cooldownInvitationKey: { $ne: args.idempotencyKey },
|
|
342
|
+
}, {
|
|
343
|
+
$set: attemptSettlement(args),
|
|
344
|
+
$inc: { revision: 1 },
|
|
345
|
+
}, options);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function settleInvitation({ candidateId, idempotencyKey, status, providerMessageId = null, error = null, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
|
|
349
|
+
if (!DELIVERY_STATUSES.includes(status)) throw new Error(`invalid invitation outcome: ${status}`);
|
|
350
|
+
const args = { candidateId, idempotencyKey, status, providerMessageId, error, now: new Date(now) };
|
|
351
|
+
if (status === 'unknown') {
|
|
352
|
+
return settleActiveAttempt(args, ENGAGEMENT_STATES, {}, Model);
|
|
353
|
+
}
|
|
354
|
+
if (status === 'failed') {
|
|
355
|
+
const activeFailure = await settleActiveAttempt(args, ENGAGEMENT_STATES, {
|
|
356
|
+
activeInvitationKey: null,
|
|
357
|
+
cooldownInvitationKey: null,
|
|
358
|
+
'engagement.cooldownUntil': null,
|
|
359
|
+
}, Model);
|
|
360
|
+
return activeFailure || settleSentFailure(args, Model);
|
|
361
|
+
}
|
|
362
|
+
const firstSuccess = await settleFirstSuccess(args, Model);
|
|
363
|
+
return firstSuccess || advanceSuccessfulAttempt(args, Model);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function engagementPatch(state, evidenceId, occurredAt, preference) {
|
|
367
|
+
const patch = { 'engagement.state': state };
|
|
368
|
+
if (state === 'registered') {
|
|
369
|
+
patch['engagement.registrationEvidenceId'] = evidenceId;
|
|
370
|
+
patch['engagement.registeredAt'] = occurredAt;
|
|
371
|
+
} else if (state === 'attended') {
|
|
372
|
+
patch['engagement.attendanceEvidenceId'] = evidenceId;
|
|
373
|
+
if (occurredAt != null) patch['engagement.attendedAt'] = occurredAt;
|
|
374
|
+
} else if (state === 'declined') {
|
|
375
|
+
patch['engagement.declineEvidenceId'] = evidenceId;
|
|
376
|
+
patch['engagement.declinedAt'] = occurredAt;
|
|
377
|
+
patch['engagement.declinePreference'] = preference;
|
|
378
|
+
}
|
|
379
|
+
return patch;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function recordEngagement({ patientId, service, state, evidenceId = null, occurredAt = new Date(), preference = null }, { Model = getSupportCandidateModel(), historicalAttendance = false } = {}) {
|
|
383
|
+
if (!ENGAGEMENT_STATES.includes(state)) throw new Error(`invalid engagement state: ${state}`);
|
|
384
|
+
if (state === 'attended' && (typeof evidenceId !== 'string' || !evidenceId.trim())) {
|
|
385
|
+
throw new Error('attendance evidenceId is required');
|
|
386
|
+
}
|
|
387
|
+
const allowedPriorStates = state === 'invited'
|
|
388
|
+
? ['notInvited', 'invited']
|
|
389
|
+
: state === 'registered'
|
|
390
|
+
? ['notInvited', 'invited', 'registered']
|
|
391
|
+
: historicalAttendance ? ENGAGEMENT_STATES.filter((prior) => prior !== 'declined') : ENGAGEMENT_STATES;
|
|
392
|
+
return Model.findOneAndUpdate({
|
|
393
|
+
patientId,
|
|
394
|
+
service,
|
|
395
|
+
'engagement.state': { $in: allowedPriorStates },
|
|
396
|
+
}, {
|
|
397
|
+
$set: engagementPatch(state, evidenceId, occurredAt == null ? null : new Date(occurredAt), preference),
|
|
398
|
+
$inc: { revision: 1 },
|
|
399
|
+
}, { new: true });
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function markInvitedCandidateAccepted({ patientId, service, sessionId = null }, { Model = getSupportCandidateModel() } = {}) {
|
|
403
|
+
return Model.findOneAndUpdate({
|
|
404
|
+
patientId,
|
|
405
|
+
service,
|
|
406
|
+
activeInvitationKey: null,
|
|
407
|
+
cooldownInvitationKey: null,
|
|
408
|
+
$or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
|
|
409
|
+
'engagement.state': { $in: ['notInvited', 'invited', 'registered'] },
|
|
410
|
+
}, {
|
|
411
|
+
$set: engagementPatch('registered', sessionId, new Date(), null),
|
|
412
|
+
$inc: { revision: 1 },
|
|
413
|
+
}, { new: true });
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function markInvitedCandidateDeclined({ patientId, service, preference = 'not_now' }, { Model = getSupportCandidateModel() } = {}) {
|
|
417
|
+
if (!['another_date', 'not_now', 'never'].includes(preference)) throw new Error(`invalid decline preference: ${preference}`);
|
|
418
|
+
return Model.findOneAndUpdate({
|
|
419
|
+
patientId,
|
|
420
|
+
service,
|
|
421
|
+
activeInvitationKey: null,
|
|
422
|
+
cooldownInvitationKey: null,
|
|
423
|
+
$or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
|
|
424
|
+
'engagement.state': { $in: ENGAGEMENT_STATES },
|
|
425
|
+
}, {
|
|
426
|
+
$set: engagementPatch('declined', null, new Date(), preference),
|
|
427
|
+
$inc: { revision: 1 },
|
|
428
|
+
}, { new: true });
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const ANSWERABLE_INVITATION = [
|
|
432
|
+
{ activeInvitationKey: null, cooldownInvitationKey: { $ne: null }, 'engagement.state': 'invited' },
|
|
433
|
+
{ activeInvitationKey: { $ne: null }, cooldownInvitationKey: null, 'engagement.state': 'notInvited' },
|
|
434
|
+
];
|
|
435
|
+
|
|
436
|
+
async function recordSentInvitationResponse({ patientId, service, outcome, sessionId = null, preference = 'not_now' }, { Model = getSupportCandidateModel() } = {}) {
|
|
437
|
+
if (!['accepted', 'declined'].includes(outcome)) throw new Error(`invalid invitation outcome: ${outcome}`);
|
|
438
|
+
if (outcome === 'accepted' && !sessionId) throw new Error('sessionId is required for an acceptance');
|
|
439
|
+
if (outcome === 'declined' && !['another_date', 'not_now', 'never'].includes(preference)) {
|
|
440
|
+
throw new Error(`invalid decline preference: ${preference}`);
|
|
441
|
+
}
|
|
442
|
+
const patch = outcome === 'accepted'
|
|
443
|
+
? engagementPatch('registered', sessionId, new Date(), null)
|
|
444
|
+
: engagementPatch('declined', null, new Date(), preference);
|
|
445
|
+
return Model.findOneAndUpdate({
|
|
446
|
+
patientId,
|
|
447
|
+
service,
|
|
448
|
+
$or: ANSWERABLE_INVITATION,
|
|
449
|
+
}, { $set: patch, $inc: { revision: 1 } }, { new: true });
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function recordLegacyInvitationResponse({ patientId, service, outcome, sessionId = null, preference = 'not_now' }, options = {}) {
|
|
453
|
+
if (outcome === 'accepted') {
|
|
454
|
+
if (!sessionId) throw new Error('sessionId is required for a legacy acceptance');
|
|
455
|
+
return markInvitedCandidateAccepted({ patientId, service, sessionId }, options);
|
|
456
|
+
}
|
|
457
|
+
if (outcome === 'declined') return markInvitedCandidateDeclined({ patientId, service, preference }, options);
|
|
458
|
+
throw new Error(`invalid legacy invitation outcome: ${outcome}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function markCandidateAccepted(args, options = {}) {
|
|
462
|
+
return markInvitedCandidateAccepted(args, options);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async function markCandidateDeclined(args, options = {}) {
|
|
466
|
+
return markInvitedCandidateDeclined(args, options);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function rescheduleDeclinedCandidate(candidateId, { Model = getSupportCandidateModel() } = {}) {
|
|
470
|
+
return Model.findOneAndUpdate(
|
|
471
|
+
{ candidateId, 'engagement.state': 'declined', 'engagement.declinePreference': 'another_date' },
|
|
472
|
+
{
|
|
473
|
+
$set: { 'engagement.state': 'notInvited', 'engagement.declinePreference': null },
|
|
474
|
+
$inc: { revision: 1 },
|
|
475
|
+
},
|
|
476
|
+
{ new: true },
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async function clearCandidateEscalation(candidateId, {
|
|
481
|
+
reviewedRevision, approvedForGroup = false, reviewedRisk, Model = getSupportCandidateModel(),
|
|
482
|
+
} = {}) {
|
|
483
|
+
if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
|
|
484
|
+
if (approvedForGroup) requireGroupReview(reviewedRevision, reviewedRisk);
|
|
485
|
+
const reviewedAt = new Date();
|
|
486
|
+
if (approvedForGroup) {
|
|
487
|
+
const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
|
|
488
|
+
for (const service of services) {
|
|
489
|
+
const cleared = await Model.findOneAndUpdate(
|
|
490
|
+
{ candidateId, service, disposition: 'escalated', revision: reviewedRevision },
|
|
491
|
+
{
|
|
492
|
+
$set: {
|
|
493
|
+
...reviewedGroupPatch(service, reviewedRisk, reviewedAt),
|
|
494
|
+
'escalation.clearedAt': reviewedAt,
|
|
495
|
+
},
|
|
496
|
+
$inc: { revision: 1 },
|
|
497
|
+
},
|
|
498
|
+
{ new: true },
|
|
499
|
+
);
|
|
500
|
+
if (cleared) return cleared;
|
|
501
|
+
}
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
return Model.findOneAndUpdate(
|
|
505
|
+
{ candidateId, disposition: 'escalated', revision: reviewedRevision },
|
|
506
|
+
{
|
|
507
|
+
$set: {
|
|
508
|
+
disposition: 'reviewRequired',
|
|
509
|
+
groupEligible: false,
|
|
510
|
+
specialistClearedAt: reviewedAt,
|
|
511
|
+
'escalation.clearedAt': reviewedAt,
|
|
512
|
+
},
|
|
513
|
+
$inc: { revision: 1 },
|
|
514
|
+
},
|
|
515
|
+
{ new: true },
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// The states claimEligibility accepts. 'declined' is absent from both; the rest stay so a
|
|
520
|
+
// specialist can see who was already invited and not invite them twice.
|
|
521
|
+
const INVITABLE_ENGAGEMENT = { 'engagement.state': { $in: ['notInvited', 'invited', 'registered', 'attended'] } };
|
|
522
|
+
|
|
523
|
+
function dashboardFilter() {
|
|
524
|
+
return {
|
|
525
|
+
service: { $in: ['nutrition', 'psychology'] },
|
|
526
|
+
$or: [
|
|
527
|
+
...GROUP_INVITABLE.map((clause) => ({ ...INVITABLE_ENGAGEMENT, ...clause })),
|
|
528
|
+
{ disposition: { $in: ['reviewRequired', 'escalated'] } },
|
|
529
|
+
{ service: 'psychology', disposition: 'individual', psychologyRisk: 'orange' },
|
|
530
|
+
{ 'operationalReviews.0': { $exists: true } },
|
|
531
|
+
{ operationalReviewOverflow: true },
|
|
532
|
+
{ invitationAttempts: { $elemMatch: { status: { $in: ['failed', 'unknown'] } } } },
|
|
533
|
+
],
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const DASHBOARD_READ_LIMIT = 2000;
|
|
538
|
+
|
|
539
|
+
// No `evidence`: reasonCodes carry the "why", so the patient's own wording stays in the store.
|
|
540
|
+
const DASHBOARD_FIELDS = Object.freeze([
|
|
541
|
+
'candidateId', 'patientId', 'service', 'disposition', 'groupEligible', 'nutritionRisk',
|
|
542
|
+
'psychologyRisk', 'confidence', 'priority', 'engagement.state', 'engagement.lastInvitedAt',
|
|
543
|
+
'engagement.cooldownUntil', 'activeInvitationKey', 'escalation', 'operationalReviews',
|
|
544
|
+
'operationalReviewOverflow', 'reasonCodes', 'createdAt', 'lastEvaluatedAt',
|
|
545
|
+
'invitationAttempts.invitationCycle', 'invitationAttempts.status', 'invitationAttempts.createdAt',
|
|
546
|
+
]);
|
|
547
|
+
|
|
548
|
+
const DASHBOARD_PROJECTION = Object.freeze({
|
|
549
|
+
_id: 0,
|
|
550
|
+
...Object.fromEntries(DASHBOARD_FIELDS.map((field) => [field, 1])),
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
const DASHBOARD_RANK = {
|
|
554
|
+
$switch: {
|
|
555
|
+
branches: [
|
|
556
|
+
{ case: { $eq: ['$disposition', 'escalated'] }, then: 0 },
|
|
557
|
+
{ case: { $eq: ['$disposition', 'reviewRequired'] }, then: 1 },
|
|
558
|
+
{ case: { $gt: [{ $size: { $ifNull: ['$operationalReviews', []] } }, 0] }, then: 2 },
|
|
559
|
+
{ case: { $eq: ['$operationalReviewOverflow', true] }, then: 2 },
|
|
560
|
+
],
|
|
561
|
+
default: 3,
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
const boundedLimit = (limit) => {
|
|
566
|
+
const requested = Number.isInteger(limit) && limit > 0 ? limit : DASHBOARD_READ_LIMIT;
|
|
567
|
+
return Math.min(requested, DASHBOARD_READ_LIMIT);
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
async function readSupportDashboardCandidates({ limit = DASHBOARD_READ_LIMIT } = {}) {
|
|
571
|
+
return getSupportCandidateModel().aggregate([
|
|
572
|
+
{ $match: dashboardFilter() },
|
|
573
|
+
{ $project: { ...DASHBOARD_PROJECTION, dashboardRank: DASHBOARD_RANK } },
|
|
574
|
+
{ $sort: { dashboardRank: 1, lastEvaluatedAt: -1, candidateId: 1 } },
|
|
575
|
+
{ $limit: boundedLimit(limit) },
|
|
576
|
+
{ $unset: 'dashboardRank' },
|
|
577
|
+
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function readSupportDashboardCandidate(candidateId) {
|
|
581
|
+
if (!candidateId) return null;
|
|
582
|
+
return getSupportCandidateModel().findOne({ ...dashboardFilter(), candidateId })
|
|
583
|
+
.select(DASHBOARD_PROJECTION).maxTimeMS(10000).lean();
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
module.exports = {
|
|
587
|
+
recordSentInvitationResponse,
|
|
588
|
+
updateSupportOperationalReview,
|
|
589
|
+
readSupportDashboardCandidates,
|
|
590
|
+
readSupportDashboardCandidate,
|
|
591
|
+
DASHBOARD_READ_LIMIT,
|
|
592
|
+
approveCandidate,
|
|
593
|
+
candidatePatch,
|
|
594
|
+
claimInvitation,
|
|
595
|
+
clearCandidateEscalation,
|
|
596
|
+
evidenceKey,
|
|
597
|
+
initialState,
|
|
598
|
+
markCandidateAccepted,
|
|
599
|
+
markCandidateDeclined,
|
|
600
|
+
nextState,
|
|
601
|
+
normalizeEvidence,
|
|
602
|
+
recordEngagement,
|
|
603
|
+
recordLegacyInvitationResponse,
|
|
604
|
+
recordSupportRoutingRecommendation,
|
|
605
|
+
rescheduleDeclinedCandidate,
|
|
606
|
+
settleInvitation,
|
|
607
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
const { mexicoIsoWeek } = require('../../utils/dateUtils');
|
|
2
|
+
|
|
3
|
+
/* Who may be invited to a collective support session, and how a support light may change.
|
|
4
|
+
*
|
|
5
|
+
* Lives apart from supportCandidateService and supportActionService because those two are
|
|
6
|
+
* mocked by each other's tests, and a safety rule that can be mocked away is not a rule.
|
|
7
|
+
*
|
|
8
|
+
* A nutrition yellow is invitable at disposition 'individual': routing sends it to an
|
|
9
|
+
* individual consult and keeps it group-eligible at the same time.
|
|
10
|
+
*/
|
|
11
|
+
const GROUP_INVITABLE = Object.freeze([
|
|
12
|
+
Object.freeze({ service: 'nutrition', groupEligible: true, nutritionRisk: 'green', disposition: 'group' }),
|
|
13
|
+
Object.freeze({ service: 'nutrition', groupEligible: true, nutritionRisk: 'yellow', disposition: 'individual' }),
|
|
14
|
+
Object.freeze({ service: 'psychology', groupEligible: true, psychologyRisk: 'green', disposition: 'group' }),
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
function isSafeGroupCandidate(candidate) {
|
|
18
|
+
return GROUP_INVITABLE.some((clause) => Object.entries(clause)
|
|
19
|
+
.every(([field, value]) => candidate[field] === value));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const LIGHT_SCALE = Object.freeze({
|
|
23
|
+
nutrition: Object.freeze(['green', 'yellow', 'red']),
|
|
24
|
+
psychology: Object.freeze(['green', 'orange', 'red']),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
function lightRank(service, color) {
|
|
28
|
+
return LIGHT_SCALE[service]?.indexOf(color) ?? -1;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function assertLight(service, color) {
|
|
32
|
+
if (!LIGHT_SCALE[service]) throw new Error(`invalid support service: ${service}`);
|
|
33
|
+
if (color !== 'unknown' && lightRank(service, color) === -1) throw new Error(`invalid ${service} light: ${color}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function nextLight(current, { service, color, source }) {
|
|
37
|
+
assertLight(service, color);
|
|
38
|
+
if (!['ai', 'human'].includes(source)) throw new Error(`invalid light source: ${source}`);
|
|
39
|
+
const currentColor = current?.color ?? 'unknown';
|
|
40
|
+
const pendingColor = current?.pendingImprovement?.color ?? null;
|
|
41
|
+
if (source === 'human') return { outcome: 'applied', color, source, pendingImprovement: null };
|
|
42
|
+
if (color === 'unknown') return { outcome: 'unchanged' };
|
|
43
|
+
if (color === currentColor) return pendingColor ? { outcome: 'withdrawn', pendingImprovement: null } : { outcome: 'unchanged' };
|
|
44
|
+
if (currentColor === 'unknown' || lightRank(service, color) > lightRank(service, currentColor)) {
|
|
45
|
+
return { outcome: 'applied', color, source, pendingImprovement: null };
|
|
46
|
+
}
|
|
47
|
+
if (color === pendingColor) return { outcome: 'unchanged' };
|
|
48
|
+
return { outcome: 'pending', pendingImprovement: { color } };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const WEEKLY_COLLECTIVE_LIMIT = Object.freeze({ psychology: 1 });
|
|
52
|
+
|
|
53
|
+
// A patient in individual psycho-oncology therapy may join a group only when her psycho-oncology light is green, set by
|
|
54
|
+
// the AI or a specialist: the risk level decides, and no colour yet does not count as green.
|
|
55
|
+
function collectiveOffer({
|
|
56
|
+
service, color = 'unknown', isInvitationPaused = false, hasInvitationThisWeek = false,
|
|
57
|
+
collectivesThisWeek = 0, hasCapacity = false, isInIndividualTherapy = false,
|
|
58
|
+
psychologyColor = service === 'psychology' ? color : 'unknown',
|
|
59
|
+
}) {
|
|
60
|
+
assertLight(service, color);
|
|
61
|
+
assertLight('psychology', psychologyColor);
|
|
62
|
+
const refuse = (reason) => ({ allowed: false, reason });
|
|
63
|
+
if (color === 'red') return refuse('light_red');
|
|
64
|
+
if (service === 'psychology' && color === 'orange') return refuse('light_orange');
|
|
65
|
+
if (service === 'psychology' && color === 'unknown') return refuse('light_unconfirmed');
|
|
66
|
+
if (isInvitationPaused) return refuse('invitation_paused');
|
|
67
|
+
if (isInIndividualTherapy && psychologyColor !== 'green') return refuse('individual_therapy');
|
|
68
|
+
if (hasInvitationThisWeek) return refuse('already_invited_this_week');
|
|
69
|
+
const limit = WEEKLY_COLLECTIVE_LIMIT[service];
|
|
70
|
+
if (limit != null && collectivesThisWeek >= limit) return refuse('weekly_limit');
|
|
71
|
+
if (!hasCapacity) return refuse('no_capacity');
|
|
72
|
+
return { allowed: true, reason: null };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function supportWeek(date) {
|
|
76
|
+
return mexicoIsoWeek(date);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
module.exports = {
|
|
80
|
+
GROUP_INVITABLE,
|
|
81
|
+
isSafeGroupCandidate,
|
|
82
|
+
LIGHT_SCALE,
|
|
83
|
+
nextLight,
|
|
84
|
+
collectiveOffer,
|
|
85
|
+
supportWeek,
|
|
86
|
+
};
|