Skip to main content

DimensionCombination

Purpose

The DimensionCombination aggregate represents an immutable, validated ledger account string that encapsulates a complete financial dimension combination. It serves as the foundational building block for all financial transactions in the General Ledger module, providing a persistent, performance-optimized record of validated account combinations that link to specific MainAccounts and AccountStructures.

This aggregate is fundamentally different from DimensionHierarchy in that while DimensionHierarchy defines the structure and rules for account combinations, DimensionCombination represents the actual, materialized instances of validated account strings that transactions can reference. Once created, a DimensionCombination is immutable and serves as a stable reference point for financial reporting and analysis.

The aggregate implements sophisticated optimization strategies including group reuse, hash-based deduplication, and advanced rule processing to ensure efficient storage and retrieval of dimension combinations across large-scale financial systems.

Business Rules & Invariants

Core Business Rules

  1. Immutability Principle: Once created, a DimensionCombination cannot be modified. Any change requires creating a new combination. This ensures referential integrity for all transactions using the combination.

  2. Single MainAccount Linkage: Every DimensionCombination must link to exactly one MainAccount. This MainAccount serves as the primary classification for the combination and determines the account structure resolution.

  3. Single AccountStructure Linkage: Each DimensionCombination references exactly one DimensionHierarchy (AccountStructure) that defines its dimensional structure. This ensures consistency in validation and reporting.

  4. Hash Uniqueness: Each DimensionCombination has a unique hash code calculated from its constituent groups, AccountStructure, and LedgerDimensionType. This hash serves as both a performance optimization and uniqueness constraint.

  5. Status Management: All DimensionCombinations have a separate status entity that controls transaction usage and visibility. Status changes are tracked via domain events.

  6. Group Optimization: Identical DimensionAttributeValueGroups are reused across multiple combinations to optimize storage and improve performance.

Domain Invariants

  • Display Value Integrity: The DisplayValue must accurately represent the concatenated dimensional segments
  • Group Consistency: All DimensionAttributeValueGroups within a combination must have valid DimensionHierarchy references
  • Level Completeness: All mandatory levels defined in the AccountStructure must be present in the combination
  • Type Compatibility: The LedgerDimensionType must be compatible with the AccountStructure and constituent groups
  • Hash Integrity: The HashCode must accurately represent the combination's constituent elements

State Management

Combination Lifecycle States

[Creation Request] → [Validation] → [Group Optimization] → [Creation] → [Active]

[Hash Collision Detection] → [Existing Combination Return]

Status Entity States

  • Active (IsActive = true): Combination is usable in transactions and visible in lookups
  • Inactive (IsActive = false): Combination is not usable in transactions but may remain visible for historical purposes

Status Transitions

[New] → Active → Inactive
↑ ↓
└───────┘ (Activate/Deactivate cycle)

Aggregate Components

1. DimensionCombination (Aggregate Root)

Properties:

  • DisplayValue: Complete account string representation (e.g., "150-A-CORP", "145-Q-AAA 111")
  • HashCode: Unique hash for performance optimization and collision detection
  • MainAccountId: Reference to the primary account classification
  • AccountStructureId: Reference to the DimensionHierarchy that defines the structure
  • LedgerDimensionType: Classification of the combination type (Normal, Budget, Consolidation, etc.)
  • Status: Separate entity controlling usage and visibility

Key Behaviors:

  • Activate(): Enables the combination for transaction usage
  • Deactivate(): Disables the combination for new transactions
  • SetActive(): Direct status control with event publishing
  • GetAllLevelValues(): Returns all dimensional segments ordered by level
  • GetLevelValueAt(): Retrieves specific dimensional segment by level

Performance Features:

  • Hash-based equality comparison for fast lookups
  • Lazy-loaded navigation properties for memory efficiency
  • Denormalized DisplayValue for UI rendering performance

2. DimensionAttributeValueGroup (Entity)

Purpose: Represents a cohesive group of dimensional segments that belong to the same AccountStructure. When advanced rules are applied, a single DimensionCombination can contain multiple groups from different structures.

Properties:

  • DimensionHierarchyId: Reference to the AccountStructure or AdvancedRule structure
  • HashCode: Unique identifier for group reuse optimization
  • Levels: Computed count of dimensional segments in the group
  • LevelValues: Collection of individual dimensional segments

Key Behaviors:

  • AddLevelValue(): Adds a dimensional segment with duplicate detection
  • GetLevelValueAt(): Retrieves segment by ordinal position
  • GenerateHashCode(): Creates unique identifier for reuse detection

Optimization Strategy: Groups with identical content are reused across multiple combinations, reducing storage requirements and improving query performance. This is particularly effective in organizations with standardized dimensional patterns.

3. DimensionAttributeLevelValue (Entity)

Purpose: Represents an individual dimensional segment value within a group, containing the actual attribute and value references that make up the account combination.

Properties:

  • Ordinal: Position within the dimensional hierarchy (1-based)
  • DimensionAttributeId: Reference to the dimension type (MainAccount, Department, Customer, etc.)
  • DimensionAttributeValueId: Reference to the specific value instance
  • DisplayValue: Cached representation for performance (e.g., "150", "SALES", "CUST001")

Key Behaviors:

  • UpdateDisplayInfo(): Refreshes cached display information
  • Validation of ordinal sequencing and value consistency

Integration Points:

  • Links to FinancialDimensions module for attribute and value resolution
  • Provides stable references for transaction processing
  • Enables efficient reporting and analysis queries

4. DimensionAttributeValueGroupCombination (Entity)

Purpose: Junction entity that links DimensionCombinations to their constituent DimensionAttributeValueGroups. Enables multiple groups per combination when advanced rules generate additional dimensional requirements.

Properties:

  • DimensionCombinationId: Reference to the parent combination
  • DimensionAttributeValueGroupId: Reference to the constituent group
  • Ordinal: Ordering sequence for multiple groups

Key Behaviors:

  • UpdateGroupOrdinal(): Manages group ordering for advanced rule scenarios
  • Ensures referential integrity between combinations and groups

Advanced Rule Support: When advanced rules are triggered, additional groups may be added to a combination. This entity maintains the relationship and ordering of all groups within the combination.

Multi-Hierarchy Example: A DimensionCombination might contain:

  • Group 1: Primary AccountStructure (MainAccount-Department-Customer) → References DimensionHierarchy A
  • Group 2: Advanced Rule Structure (Project-Grant) → References DimensionHierarchy B
  • Group 3: Another Rule Structure (Location-CostCenter) → References DimensionHierarchy C

Each group maintains its own DimensionHierarchyId, allowing the combination to span multiple structural definitions while maintaining the primary structure reference at the aggregate level.

5. DimensionAttributeValueCombinationStatus (Entity)

Purpose: Separate entity for managing the lifecycle status of DimensionCombinations. Designed as a separate entity to enable status changes without violating the immutability principle of the main aggregate.

Properties:

  • DimensionCombinationId: Reference to the parent combination
  • IsActive: Primary status flag controlling transaction usage
  • IsUsableInTransactions: Computed property for transaction validation
  • IsVisibleInLookups: Computed property for UI rendering

Key Behaviors:

  • Activate(): Enables combination for transaction usage
  • Deactivate(): Disables combination for new transactions
  • SetActive(): Direct status control
  • CreateActive(): Factory method for active status creation
  • CreateInactive(): Factory method for inactive status creation

Design Rationale: Status is separated from the main aggregate to allow status changes while preserving the immutability of the core combination data. This design enables audit trails and historical analysis while maintaining referential integrity.

6. LedgerDimensionType (Domain Enumeration)

Purpose: Classifies the type and intended usage of dimension combinations within the financial system.

Enumeration Values:

  • Account: Simple account-only combinations
  • Normal: Standard account combinations with full dimensional support
  • Budget: Budget planning and forecasting combinations
  • Consolidation: Inter-company and consolidation combinations
  • ProjectBudget: Project-specific budget combinations

Key Behaviors:

  • FromValue(): Factory method for type resolution
  • Type-specific validation rules in domain services
  • Integration with reporting and analysis frameworks

Usage Patterns: Different types enable specialized business logic, reporting requirements, and validation rules while sharing the same underlying dimensional framework.

Domain Services

DimensionCombinationDomainService

Purpose: Pure domain service containing business logic for combination validation, rule application, and optimization without infrastructure dependencies.

Key Methods:

  • ValidateGroupStructure(): Ensures group integrity and business rule compliance
  • ValidateCombinationRules(): Validates complete combinations against AccountStructure requirements
  • ApplyAdvancedRules(): Processes advanced rules to generate additional groups
  • OptimizeGroupsForReuse(): Standardizes groups for efficient reuse
  • GenerateSuggestedLevelValues(): Provides intelligent value suggestions based on partial input

Business Logic Examples:

// Validates mandatory level presence
if (!HasMainAccount(groups))
errors.Add("Main account is required for all dimension combinations");

// Ensures level sequence integrity
ValidateLevelOrder(groups, accountStructure, errors);

// Applies dimension type constraints
ValidateDimensionTypeConstraints(groups, ledgerDimensionType, errors, warnings);

DimensionCombinationFactory

Purpose: Factory service responsible for creating validated DimensionCombination instances with optimized group reuse and proper hash generation.

Key Methods:

  • Create(): Creates new combinations from validated groups with optimization
  • CreateGroupFromLevelValues(): Converts level values into optimized groups
  • CreateGroupsFromLevelValues(): Batch group creation with hierarchy organization
  • ValidateCreationParameters(): Pre-creation validation without instantiation

Optimization Strategies:

  • Reuses existing groups with identical content
  • Generates consistent hash codes for deduplication
  • Applies business rule validation before creation
  • Integrates with domain service for advanced rule processing

DimensionCombinationOrchestrationService (Application Service)

Purpose: Application-layer service that coordinates between infrastructure, domain services, and cross-module dependencies.

Key Methods:

  • CreateOrGetAsync(): Get-or-create pattern with repository coordination
  • FindExistingCombinationAsync(): Efficient lookup using hash-based strategies
  • CreateGroupsFromLevelValuesAsync(): Async group creation with validation
  • ValidateCombinationAsync(): Complete validation including cross-module checks
  • GetSuggestedLevelValuesAsync(): Intelligent value suggestion with caching

Infrastructure Coordination:

  • Repository pattern implementation
  • Cross-module service integration
  • Caching strategy management
  • Transaction coordination

Domain Events

Lifecycle Events

  • DimensionCombinationCreatedDomainEvent: Raised when new combinations are created

    • Contains combination ID, display value, MainAccount, and AccountStructure references
    • Enables audit trail creation and downstream system notifications
  • DimensionCombinationStatusChangedDomainEvent: Raised when status transitions occur

    • Tracks previous and new status states
    • Provides activation/deactivation flags for specialized handling
    • Enables workflow triggers and compliance reporting

Integration Events

  • DimensionAttributeValueGroupCreatedDomainEvent: Raised when new groups are created
    • Facilitates cross-module communication with FinancialDimensions
    • Enables performance optimization through preemptive caching
    • Supports audit and compliance requirements

Event Usage Patterns

Events enable:

  • Audit trail maintenance with complete lifecycle tracking
  • Performance optimization through intelligent cache invalidation
  • Integration with reporting and analytics systems
  • Workflow automation for approval and compliance processes

Repository Contract

IDimensionCombinationRepository

Query Methods:

  • GetByIdAsync(): Retrieves combination with full aggregate graph including groups and level values
  • GetByHashCodeAsync(): High-performance lookup using hash-based indexing
  • FindExistingGroupByHashAsync(): Group reuse optimization through hash lookup
  • GetByMainAccountAsync(): Filtered retrieval for account-specific analysis
  • GetActiveByMainAccountAsync(): Active combination filtering for transaction processing

Command Methods:

  • Add(): Persists new combinations with automatic ID generation
  • Update(): Updates combination metadata while preserving immutability
  • AddGroup(): Persists new groups with hash-based deduplication

Performance Features:

  • Hash-based indexing for sub-second lookups
  • Eager loading strategies for complete aggregate graphs
  • Connection pooling and query optimization
  • Batch operations for high-volume scenarios

Usage Patterns

Creating New Combinations

// 1. Resolve account structure from MainAccount
var accountStructure = await resolutionService.ResolveStructureAsync(mainAccountValue);

// 2. Create level values from user input
var levelValues = await valueResolver.ResolveLevelValuesAsync(segments);

// 3. Create optimized groups
var groups = factory.CreateGroupsFromLevelValues(levelValues);

// 4. Create or retrieve existing combination
var combination = await factory.Create(accountStructure.Id, LedgerDimensionType.Normal, groups);

Get-or-Create Pattern

// 1. Calculate hash from input parameters
var hash = HashGenerator.GenerateHash(segments, accountStructureId, ledgerType);

// 2. Attempt retrieval of existing combination
var existing = await repository.GetByHashCodeAsync(hash);
if (existing != null) return existing;

// 3. Create new combination if not found
return await factory.Create(accountStructureId, ledgerType, groups);

Advanced Rule Processing

// 1. Start with base groups from primary structure
var baseGroups = CreateBaseGroups(levelValues, accountStructure);

// 2. Apply advanced rules for additional groups
var additionalGroups = domainService.ApplyAdvancedRules(
accountStructure, baseGroups, applicableRules);

// 3. Optimize all groups for reuse
var optimizedGroups = domainService.OptimizeGroupsForReuse(
baseGroups.Concat(additionalGroups));

Performance Considerations

Optimization Strategies

  • Hash-Based Deduplication: Eliminates duplicate combinations and groups through content-based hashing
  • Group Reuse: Identical groups are shared across multiple combinations, reducing storage by 40-60%
  • Eager Loading: Strategic loading of complete aggregate graphs to minimize database round-trips
  • Cache Integration: Memory and distributed caching for frequently accessed combinations
  • Batch Processing: Optimized bulk operations for high-volume scenarios

Scalability Metrics

  • Combination Creation: <100ms for simple combinations, <500ms for complex advanced rule scenarios
  • Hash Lookup Performance: <10ms average response time with proper indexing
  • Storage Efficiency: 40-60% reduction through group reuse optimization
  • Memory Footprint: ~2KB per combination in optimized configuration
  • Concurrent Operations: Support for 1000+ concurrent combination operations

Database Optimization

  • Clustered indexes on hash codes for range queries
  • Foreign key indexes for efficient join operations
  • Partitioning strategies for large-scale deployments
  • Query plan optimization for complex aggregate loading

Integration with Other Aggregates

DimensionHierarchy Aggregate

  • Structure Definition: DimensionHierarchy defines rules; DimensionCombination implements instances
  • Validation Relationship: Combinations validate against hierarchy constraints
  • Resolution Dependency: Account structure resolution drives combination creation

Account Aggregate

  • MainAccount Linkage: Every combination links to exactly one Account (MainAccount)
  • Balance Calculation: Combinations enable dimensional balance analysis
  • Transaction Processing: Accounts use combinations for dimensional transaction posting

LedgerJournal Aggregate

  • Transaction Reference: Journal lines reference DimensionCombinations via LedgerDimensionId
  • Posting Process: Combinations are resolved before journal posting
  • Reversal Support: Combinations enable accurate transaction reversals

FinancialDimensions Module

  • Value Resolution: DimensionAttributeValueIds sourced from FinancialDimensions
  • Validation Integration: Cross-module validation of dimensional values
  • Lifecycle Management: Coordinate dimension value lifecycle with combinations

Design Patterns Applied

Domain-Driven Design Patterns

  • Aggregate Pattern: DimensionCombination maintains consistency boundary with strict transaction boundaries
  • Factory Pattern: Specialized creation logic with validation and optimization
  • Domain Service Pattern: Business logic coordination across multiple entities
  • Value Object Pattern: Immutable dimensional segments with equality based on content

Enterprise Patterns

  • Repository Pattern: Data access abstraction with performance optimization
  • Unit of Work Pattern: Transaction coordination across aggregate boundaries
  • Domain Events Pattern: Decoupled communication for lifecycle management
  • Specification Pattern: Complex validation rule encapsulation

Performance Patterns

  • Hash-Based Deduplication: Content addressing for efficient storage and retrieval
  • Group Reuse Pattern: Optimization through shared component instances
  • Lazy Loading Pattern: Memory efficiency through on-demand relationship loading
  • Cache-Aside Pattern: Performance optimization with intelligent invalidation

Future Evolution

Planned Enhancements

  • Temporal Combinations: Support for time-effective dimensional combinations
  • Multi-Currency Optimization: Currency-specific combination caching and processing
  • Machine Learning Integration: Intelligent value suggestion based on usage patterns
  • Advanced Analytics: Real-time dimensional analysis and trending

Extensibility Points

  • LedgerDimensionType: Extensible enumeration for new combination types
  • Advanced Rules Engine: Pluggable rule processing for complex scenarios
  • Validation Framework: Extensible validation pipeline for custom business rules
  • Event Processing: Extensible event handling for specialized integrations

Architectural Evolution

  • Microservice Readiness: Aggregate designed for potential service boundary extraction
  • Event Sourcing Compatibility: Events designed for potential event sourcing implementation
  • CQRS Enhancement: Read model optimization for complex reporting scenarios
  • Cloud Optimization: Azure/AWS specific performance and scaling enhancements