Skip to main content
Version: 3.0.0

Kit Configuration Design

Document Type: Domain Design (Tier 2) Domain: KITCFG Domain Character: Configuration-heavy SRS Reference: kitcfg.md Status: Draft Last Updated: 2026-01-28


1. Overview

1.1 Purpose

The Kit Configuration subsystem provides centralized management of assay and instrument configurations used in PCR analysis workflows. It is the configuration backbone of the system—rules, controls, calibrations, and outcome mappings all depend on KITCFG entities.

This domain is characterized by:

  • CRUD-heavy operations with extensive validation
  • Import/export functionality via Excel for bulk configuration
  • Multi-entity relationships (mixes → targets → rules → outcomes)
  • Multi-site isolation for tenant-specific configurations
  • Audit trail integration for all changes

1.2 Requirements Covered

REQ IDTitleCategory
REQ-KITCFG-001Manage Mix and Target ConfigurationCore Config
REQ-KITCFG-002Import and Export Mix ConfigurationImport/Export
REQ-KITCFG-003Manage Extraction InstrumentsInstruments
REQ-KITCFG-004Manage Thermocycler InstrumentsInstruments
REQ-KITCFG-005Manage Error CodesError Handling
REQ-KITCFG-006Manage Error ResolutionsError Handling
REQ-KITCFG-007Manage Control LabelsAnalysis Config
REQ-KITCFG-008Manage Run TagsOrganization
REQ-KITCFG-009Manage LIMS Export MappingsIntegration
REQ-KITCFG-010Provide Unified Assay Configuration InterfaceUI
REQ-KITCFG-011Manage Combined Outcome RulesAnalysis Config
REQ-KITCFG-012Manage Westgard SettingsQC Config
REQ-KITCFG-013Manage Cross Contamination LimitsQC Config
REQ-KITCFG-014Manage Curve Control LimitsQC Config
REQ-KITCFG-015Manage Known QuantitiesQuantification
REQ-KITCFG-016Manage Reporting Cut-offsReporting
REQ-KITCFG-017Manage Test CodesSample Config
REQ-KITCFG-018Manage QIR Quantification SettingsQuantification
REQ-KITCFG-019Manage Delta CT ConfigurationsAnalysis Config
REQ-KITCFG-020Perform Assay Calibration AnalysisCalibration
REQ-KITCFG-021Manage Calibration BoundariesCalibration
REQ-KITCFG-022Manage Calibration VersionsCalibration
REQ-KITCFG-023Display Calibration in Run ReportsCalibration
REQ-KITCFG-024Manage Rule MappingsAnalysis Config
REQ-KITCFG-025Manage Rule SettingsAnalysis Config
REQ-KITCFG-026Manage Prepend CyclesAnalysis Config
REQ-KITCFG-027Support Multi-Site ConfigurationMulti-Site
REQ-KITCFG-028Manage Help Item TagsSupport
REQ-KITCFG-029Manage Dye ConfigurationReference Data
REQ-KITCFG-030Manage Westgard Event CodesQC Config
REQ-KITCFG-031Manage Specimen TypesReference Data

1.3 Constraints

Tier 2 Constraint: This document describes ownership, patterns, and design rationale. It links to reference docs for full schemas. It does not duplicate validation rules documented in the SRS acceptance criteria.

1.4 Dependencies

DirectionDomain/ComponentPurpose
Provides toFILEIMPORTMix matching, control label classification
ANALYTICSRule mappings, execution order
RULESQC thresholds, combined outcomes, calibration
REPORTSMix/target structure, reporting cut-offs
RUNRPTMix/target display, LIMS mappings
ConsumesDxAI PCR APICalibration analysis results
Excel filesBulk configuration import

2. Component Architecture

2.1 Component Diagram

2.2 Component Responsibilities

ComponentTypeResponsibilityREQ Trace
MixesControllerControllerMix CRUD, enable/disableREQ-KITCFG-001
TargetsControllerControllerTarget properties, prepend cyclesREQ-KITCFG-001, 026
KitsControllerControllerUnified config interfaceREQ-KITCFG-010
GlobalMixMapperActionCascade config to related entitiesREQ-KITCFG-001, 007, 012-014
*ImportSheetImportExcel parsing and validationREQ-KITCFG-002, 007, 011, 012
*MapperActionEntity-specific configuration logicVarious
AssayCalibrationModelCalibration state and boundariesREQ-KITCFG-020-023

2.3 Architectural Patterns

Pattern: Configuration Cascade

When a mix is created or modified, related entities may need updates:

Mix Created/Modified
├── ControlLabelMapper → Update control label defaults
├── WestgardLimitsMapper → Initialize QC ranges
├── RuleMapper → Apply default rule mappings
└── GlobalMixMapper → Orchestrate all mappers

Pattern: Site-Scoped Queries

All configuration queries are scoped by site for multi-site clients:

// All KITCFG queries include site scope
Mix::where('site_id', $currentSite->id)->get();

Pattern: Audit Event Emission

All configuration changes emit audit events:

// Models implement AuditableEvent interface
event(new MixCreated($mix)); // → LogIntoDatabase listener

3. Data Design

3.1 Entity Ownership

This domain owns the following entities:

EntityTablePurposeKey Relationships
MixmixesAssay definition→ targets, control_labels, combined_outcomes
TargettargetsDetection target→ mix, rule_mappings
ControlLabelcontrol_labelsSample classification rules→ mix, roles
RolerolesControl/sample type→ control_labels
WestgardSettingwestgard_settingsQC statistical parameters→ mix, target, role
CombinedOutcomecombined_outcomesOutcome mapping rules→ mix, targets, lims_status
ErrorCodeerror_codesError definitions→ error_resolutions
ErrorResolutionerror_resolutionsResolution actions→ error_code
ExtractionModelextraction_modelsExtraction instrument groups→ extraction_instruments
ExtractionInstrumentextraction_instrumentsIndividual extractors→ extraction_model
ThermocyclerModelthermocycler_modelsThermocycler groups→ thermocyclers
ThermocyclerthermocyclersIndividual thermocyclers→ thermocycler_model
CurveControlLimitcurve_control_limitsBCC rule thresholds→ mix, target, role
CrossContaminationLimitadjacentsADJ rule thresholds→ mix, target
KnownQuantityknown_quantitiesQuantification standards→ role, mix, target
ReportingCutoffquantitative_reportingsRQUANT boundaries→ mix, target
TestCodetest_codesSpecimen type mappings→ mix
QIRSettingqir_settingsQuantification parameters→ targets
DeltaCTConfigdelta_ct_configurationsCT delta thresholds→ target pairs
AssayCalibrationassay_calibrationsCalibration data→ mix, target
RuleMappingrule_mappingsRule → observation binding→ rule, mix, target, role
TagtagsRun organization(standalone)
LimsStatuslims_statusesLIMS export codes→ combined_outcomes
HelpItemhelp_itemsContext help entries(standalone)
DyedyesFluorescent reporter definitions→ targets (via observations)
WestgardEventwestgard_eventsQC event code definitions→ westgard_limits
SpecimenspecimensSample type classifications→ test_codes, reportings, combined_outcomes

See Database Reference for full schema.

3.2 Entity Relationship Overview

3.3 State Management

Mix State Machine:

Calibration State Machine:


4. Interface Design

4.1 APIs Provided

EndpointMethodPurposeREQ Trace
/api/mixesGET/POSTList/create mixesREQ-KITCFG-001
/api/mixes/{id}PUT/DELETEUpdate/delete mixREQ-KITCFG-001
/api/targets/{id}PUTUpdate target propertiesREQ-KITCFG-001
/api/kit-configurations/importPOSTImport Excel configREQ-KITCFG-002
/api/kit-configurations/exportGETExport Excel configREQ-KITCFG-002
/api/control-labelsGET/POST/PUT/DELETEControl label CRUDREQ-KITCFG-007
/api/combined-outcomesGET/POST/PUT/DELETECombined outcome CRUDREQ-KITCFG-011
/api/westgard-settingsGET/POST/PUTWestgard CRUDREQ-KITCFG-012
/api/assay-calibrationsGET/POSTCalibration managementREQ-KITCFG-020-022
/api/rule-mappingsGET/PUTRule mapping managementREQ-KITCFG-024

4.2 APIs Consumed

ServicePurposeREQ Trace
DxAI PCR APICalibration analysisREQ-KITCFG-020

4.3 Events Published

EventPayloadPurposeListener
MixCreatedmix_id, site_id, user_idAudit trailLogIntoDatabase
MixEnabledmix_id, site_id, user_idAudit trailLogIntoDatabase
MixDisabledmix_id, site_id, user_idAudit trailLogIntoDatabase
TargetCreatedtarget_id, mix_id, user_idAudit trailLogIntoDatabase
RuleCreatedrule_id, mapping, user_idAudit trailLogIntoDatabase
WestgardSettingChangedsetting_id, old, newAudit + re-analysis triggerLogIntoDatabase, ResetWestgardFailures

5. Behavioral Design

5.1 Import Engine Architecture

Algorithm: Process Kit Configuration Import

Inputs:
- file: Excel file with multiple sheets
- site_id: Target site for import
- user: Authenticated user

Outputs:
- result: ImportResult with per-row status

Assumptions:
- File format matches expected template
- User has MANAGER or SUPER_ADMIN role
- Site exists and user has access

Steps:
1. Parse Excel file into sheet collection
2. For each sheet in import order:
a. Identify sheet type (mixes, control_labels, etc.)
b. Instantiate appropriate ImportSheet handler
c. For each row:
- Validate required fields
- Validate field formats (see SRS acceptance criteria)
- Check business rules (e.g., duplicates, references)
- If valid: create/update entity, status = "Imported"
- If invalid: skip entity, status = "Ignored", capture reason
d. Collect row results
3. Emit audit events for successful imports
4. Return aggregated ImportResult

Notes:
- Import order matters: mixes before control_labels before rules
- Partial failures allowed: valid rows imported, invalid rows skipped
- Existing entities may be updated (upsert behavior)

Import Sheet Order:

OrderSheetDependencies
1DyesNone
2SpecimensNone
3Mixes and TargetsDyes
4Extraction InstrumentsNone
5ThermocyclersNone
6Control LabelsMixes, Roles
7Rule MappingsMixes, Targets, Roles
8Combined OutcomesMixes, Targets, LIMS Statuses, Specimens
9Westgard LimitsMixes, Targets, Roles
10Westgard EventsNone
11Error CodesNone
12Error ResolutionsError Codes

5.2 Calibration Flow

Algorithm: Execute Assay Calibration

Inputs:
- mix_id: Selected mix
- target_id: Selected target
- run_ids: Selected runs for analysis
- use_machine_cls: Whether to use machine classification

Outputs:
- calibration: AssayCalibration with observations and boundaries

Assumptions:
- Selected runs contain data for mix/target
- DxAI PCR API is accessible
- User has appropriate permissions

Steps:
1. Create AssayCalibration record (status: InProgress)
2. Extract observation data from selected runs
3. Send observation data to DxAI PCR API
4. Receive classification parameters
5. Store parameters in AssayCalibration
6. Update status to Completed
7. Return calibration for boundary adjustment

Notes:
- Concurrent calibrations allowed for different targets
- User can cancel during API call
- Failed calibrations retain Error status with message

5.3 Global Configuration Cascade

Algorithm: Apply Global Mix Mapping

Inputs:
- mix: Mix being created/modified
- action: create|update|enable|disable

Outputs:
- void (side effects on related entities)

Assumptions:
- Mix is valid and persisted
- Mapper classes are registered

Steps:
1. Instantiate GlobalMixMapper with mix
2. For each registered mapper:
a. ControlLabelMapper: Create default labels if none exist
b. WestgardLimitsMapper: Initialize ranges for new targets
c. RuleMapper: Apply default rule mappings
d. Each mapper emits own audit events
3. If action == disable:
- Do NOT delete related config (preserve for re-enable)
- Related entities remain but are inactive

Notes:
- Cascade is synchronous (same transaction)
- Failures in one mapper do not roll back others
- Disabled mix config is preserved, not deleted

5.4 Role Alias Migration Workflow

This algorithm creates a new Role from an existing control-label alias and migrates all dependent quality-control configuration. It allows laboratories to promote an alias already in use on control labels into a fully-fledged role without manually recreating every dependent mapping.

Entry Points:

ComponentLocation
API RoutePOST /api/role-alias-to-role
ControllerRoleAliasToRoleController
ActionMapRoleAliasToNewRoleAction::execute()

Transactional Workflow (6 steps):

MapRoleAliasToNewRoleAction runs inside a single database transaction to ensure atomicity:

  1. Gather Source Data - Load control labels matching alias and original role, fetch associated rule mappings and combined outcomes scoped to user's site

  2. Create Target Role - Clone key fields (type, has_extraction, resolution_priority) from source role using authenticated user's site

  3. Relink Control Ecosystem - Update matched control labels and wells to reference new role, restore soft-deleted Westgard limits

  4. Duplicate Rule Configuration - Copy RuleMapping records with new UUIDs, preserve original timestamps

  5. Clone Combined Outcomes - Create new outcome records, suffix names/codes with -<role_name>-clone

  6. Commit or Rollback - Success commits, any exception rolls back

Data Dependencies:

EntityPurpose
ControlLabelSource of alias, provides mix_id for target scoping
WellHistorical data references new role
RuleMappingCopied to retain rule behavior
WestgardLimitQC thresholds reactivated
OutcomeToLimsStatusMappingCombined outcome logic preserved

5.5 Feature Toggle Cascade System

The Feature Toggle system provides import and cascade handling for feature configuration. When features have parent-child dependencies, disabling a parent automatically cascades to disable all children.

Architecture:

Validation Rules:

CategoryRules
Feature CodeRequired, string, max 255, must exist in system
Feature ValueBoolean (true/false, 1/0, yes/no)
Parent DependencyRecursive chain validation when enabling
RestrictionsCertain features cannot be modified via import

Cascade Behavior:

ActionResult
Disable ParentAuto-disable all children (recursive)
Enable ParentChildren remain unchanged (manual control)

Import Process (4 phases):

  1. Excel Processing - Read file, process in 1000-row chunks
  2. Validation - Feature code, value, and parent dependency validation
  3. Update - Apply changes, trigger cascades
  4. Status Reporting - Report success/failure per feature

5.6 Dye Configuration (REQ-KITCFG-029)

Dyes define the fluorescent reporters and quenchers used in PCR analysis. They are associated with targets within mixes, enabling proper signal detection and identification during runfile processing.

Data Model:

ColumnTypeConstraintsDescription
iduuidPKPrimary key
dye_namestringrequiredDye identifier (e.g., FAM, VIC)
quencherstringnullableQuencher molecule name
colourstringrequiredDisplay color
site_iduuidFK, requiredMulti-site isolation
created_attimestampCreation timestamp
updated_attimestampLast modification

Import/Export:

OperationSheetColumnsLogic
ImportDyesDYE NAME, QUENCHER, COLOURfirstOrNew by dye_name + site_id; upsert quencher/colour
ExportDyesDYE NAME, QUENCHER, COLOURAll site dyes

Relationships:

  • Targets reference dyes via observations (observations.dye_id)
  • Rule mappings use dyes to identify targets

Implementation:

ComponentTypePath
DyeModelapp/Dye.php
DyeImportSheetImportapp/Imports/Sheets/DyeImportSheet.php
DyeExportExportapp/Exports/Config/DyeExport.php
DyeCreatedEventapp/Events/DyeCreated.php

5.7 Westgard Event Codes (REQ-KITCFG-030)

Westgard event codes define the error messages generated when Westgard statistical rules detect out-of-control conditions. They provide descriptive messages that appear in quality control reports and alerts.

Data Model:

ColumnTypeConstraintsDescription
iduuidPKPrimary key
codestringrequiredUnique event code identifier
messagestringrequiredHuman-readable error message
site_iduuidFK, requiredMulti-site isolation
created_attimestampCreation timestamp
updated_attimestampLast modification

Import/Export:

OperationSheetColumnsLogic
ImportWestgard EventsCODE, MESSAGEupdateOrCreate by code + site_id
ExportWestgard EventsCODE, MESSAGEAll site event codes

Relationships:

  • Westgard settings (REQ-KITCFG-012) reference event codes for rule evaluation
  • QC failures display event code messages in reports

Implementation:

ComponentTypePath
WestgardEventModelapp/WestgardEvent.php
WestgardEventsImportSheetImportapp/Imports/Sheets/WestgardEventsImportSheet.php
WestgardEventsExportExportapp/Exports/Config/WestgardEventsExport.php

5.8 Specimen Types (REQ-KITCFG-031)

Specimen types provide a classification layer for samples, enabling configuration of test codes, reporting cut-offs, and combined outcomes based on sample categories. Labs define specimen types specific to their workflows (e.g., "Nasopharyngeal Swab", "Plasma", "Serum").

Data Model:

ColumnTypeConstraintsDescription
iduuidPKPrimary key
specimen_namestringrequired, unique per siteSpecimen type name
site_iduuidFK, requiredMulti-site isolation
created_attimestampCreation timestamp
updated_attimestampLast modification

Import/Export:

OperationSheetColumnsLogic
ImportSpecimensSPECIMEN NAMEfirstOrNew by specimen_name + site_id; deduplicates on import
ExportSpecimensSPECIMEN NAMEAll site specimens

Relationships:

  • Test codes (REQ-KITCFG-017) map sample labels to specimen classifications
  • Reporting cut-offs (REQ-KITCFG-016) define specimen-specific quantitative groupings
  • Combined outcomes (REQ-KITCFG-011) enable specimen-aware outcome rules
  • Specimen-to-mix mappings track which specimens are valid for which mixes

Implementation:

ComponentTypePath
SpecimenModelapp/Specimen.php
SpecimensImportSheetImportapp/Imports/Sheets/SpecimensImportSheet.php
SpecimensExportExportapp/Exports/Config/SpecimensExport.php
SpecimenCreatedEventapp/Events/SpecimenCreated.php
SpecimenToMixMappingModelapp/SpecimenToMixMapping.php

6. Error Handling

ConditionDetectionResponseUser Impact
Import validation failureField validationSkip row, status = "Ignored"Row not imported, reason shown
Duplicate entityUnique constraintSkip row or update (upsert)Depends on entity type
Referenced entity missingForeign key lookupSkip rowRow not imported
API timeout (calibration)HTTP timeoutSet status = ErrorCalibration failed, can retry
Concurrent modificationOptimistic lockingReturn 409 ConflictUser must refresh and retry

7. Configuration

This domain defines configuration, but also has meta-configuration for its own behavior:

SettingLocationDefaultEffectREQ Trace
unknown_mix_enabledclient_configurationstrueAuto-create Unknown mixes on import001
ct_discrepancy_deltaclient_configurations2Default CT discrepancy threshold001
thermocycler_auto_populateclient_configurationsfalseAuto-create thermocyclers from runfiles004
use_sample_typeclient_configurationsfalseEnable specimen type in mappings016, 017, 024
hide_unused_rulesclient_configurationstrueHide unassigned rules in UI024

See Configuration Reference for full list.


8. Implementation Mapping

8.1 Code Locations

ComponentTypePath
MixesControllerControllerapp/Http/Controllers/MixesController.php
TargetsControllerControllerapp/Http/Controllers/TargetsController.php
KitsControllerControllerapp/Http/Controllers/Kits/KitsController.php
ControlLabelsControllerControllerapp/Http/Controllers/ControlLabelsController.php
WestgardSettingsControllerControllerapp/Http/Controllers/WestgardSettingsController.php
AssayCalibrateableRunsControllerControllerapp/Http/Controllers/AssayCalibrations/AssayCalibrateableRunsController.php
KitConfigurationsExportControllerControllerapp/Http/Controllers/KitConfigurationsExportController.php
GlobalMixMapperActionapp/Actions/GlobalMappers/GlobalMixMapper.php
ControlLabelMapperMapperapp/Actions/GlobalMappers/Mappers/ControlLabelMapper.php
WestgardLimitsMapperMapperapp/Actions/GlobalMappers/Mappers/WestgardLimitsMapper.php
RuleMapperMapperapp/Actions/GlobalMappers/Mappers/RuleMapper.php
MixAndTargetsImportSheetImportapp/Imports/Sheets/MixAndTargetsImportSheet.php
ControlLabelsImportSheetImportapp/Imports/Sheets/ControlLabelsImportSheet.php
CombinedOutcomesImportSheetImportapp/Imports/Sheets/CombinedOutcomesImportSheet.php
DyeImportSheetImportapp/Imports/Sheets/DyeImportSheet.php
WestgardEventsImportSheetImportapp/Imports/Sheets/WestgardEventsImportSheet.php
SpecimensImportSheetImportapp/Imports/Sheets/SpecimensImportSheet.php

8.2 Requirement Traceability

REQ IDDesign SectionPrimary Code
REQ-KITCFG-001§3.1, §5.3MixesController, TargetsController, GlobalMixMapper
REQ-KITCFG-002§5.1MixAndTargetsImportSheet, KitConfigurationsExportController
REQ-KITCFG-007§5.3ControlLabelsController, ControlLabelMapper
REQ-KITCFG-011§3.1OutcomeToLimsStatusMappingsController, CombinedOutcomesImportSheet
REQ-KITCFG-012§5.3WestgardSettingsController, WestgardLimitsMapper
REQ-KITCFG-020-023§5.2AssayCalibrateableRunsController, DxAI integration
REQ-KITCFG-024-025§5.3RuleMapper, RulesMappingImportSheet
REQ-KITCFG-027§2.3 (Site-Scoped)All controllers (middleware scoping)
REQ-KITCFG-029§5.6DyeImportSheet, DyeExport
REQ-KITCFG-030§5.7WestgardEventsImportSheet, WestgardEventsExport
REQ-KITCFG-031§5.8SpecimensImportSheet, SpecimensExport, SpecimensController

9. Design Decisions

DecisionRationaleAlternatives Considered
Excel for import/exportCustomer familiarity, offline editingJSON/YAML (rejected: less accessible), UI-only (rejected: slow for bulk)
Soft-disable for mixesPreserve config for re-enableHard delete (rejected: loses history)
Synchronous cascadeConsistency, simpler error handlingAsync jobs (rejected: eventual consistency issues)
Site-scoped at query levelTransparent multi-tenancySeparate databases (rejected: operational complexity)
Preserve instruments on deleteHistorical data integrityAllow delete (rejected: breaks run references)
Import order enforcementDependency resolutionTopological sort (rejected: over-engineering)

10. Performance Considerations

ScenarioConcernMitigation
Large import (1000+ rows)Memory, timeoutChunked processing, queue for very large
Many mixes (100+)Dropdown render timePaginated API, client-side caching
Calibration with many runsAPI timeoutProgress tracking, cancellation support
Multi-site with many sitesQuery performanceSite index on all config tables

DocumentRelevant Sections
SRS: kitcfg.mdRequirements source
SDS: ArchitectureMulti-site architecture
SDS: Data ArchitectureEntity model
SDS: RULES DomainRule mapping consumers
SDS: FILEIMPORT DomainMix matching
SDS: Combined Outcomes RuleOutcome configuration consumers