انتقل إلى المحتوى الرئيسي

Ledger

Purpose

The Ledger aggregate serves as the central configuration hub for the General Ledger module, orchestrating all financial transaction processing and dimensional structure management within an organization. It acts as the foundational blueprint that defines how financial data is structured, validated, and processed across the entire financial system.

This aggregate is fundamentally responsible for maintaining the critical relationships between the company's chart of accounts, fiscal calendar management, currency configurations, and most importantly, the collection of active DimensionHierarchy (Account Structure) entities that are used for all transaction validation and dimension combination resolution.

The Ledger aggregate ensures that all financial transactions conform to the organization's established dimensional structures, fiscal periods, and currency requirements, making it the cornerstone of financial data integrity and regulatory compliance.

Business Rules & Invariants

Core Business Rules

  1. Single Source of Configuration Truth: Each organization typically has one primary Ledger that serves as the central configuration for all financial operations, though the system supports multiple ledgers for complex organizational structures.

  2. Dimension Hierarchy Management: The Ledger maintains a curated collection of active DimensionHierarchy entities through LedgerStructure relationships. Only DimensionHierarchies assigned to the Ledger can be used for transaction validation and dimension combination resolution.

  3. Fiscal Calendar Integration: When a FiscalCalendar is assigned to a Ledger, the system automatically creates LedgerFiscalCalendarPeriod entities for all periods, enabling period-specific transaction control and financial reporting.

  4. Currency Configuration: The Ledger defines both Accounting and Reporting currencies, along with their respective exchange rate types, ensuring consistent currency conversion across all financial transactions.

  5. Constraint Overlap Prevention: When DimensionHierarchies are added to a Ledger, the system must validate that no critical MainAccount constraint overlaps exist that would create ambiguity in account structure resolution.

  6. Fiscal Period Control: Each fiscal period associated with the Ledger has its own status (Open, Closed, OnHold) that controls whether transactions can be posted to that period.

Domain Invariants

  • Accounting Currency Requirement: Every Ledger must have an AccountingCurrency defined for transaction processing
  • Fiscal Calendar Consistency: If a FiscalCalendar is assigned, all related periods must be properly initialized with appropriate statuses
  • Structure Uniqueness: A DimensionHierarchy cannot be associated with the same Ledger multiple times
  • Exchange Rate Configuration: If multiple currencies are used, appropriate ExchangeRateTypes must be configured
  • Period Status Integrity: Fiscal period statuses must be managed consistently to prevent posting to inappropriate periods

State Management

Ledger Lifecycle States

[Creation] → [Configuration] → [Active] → [Maintenance]

[Fiscal Period Management]

[Structure Management]

Fiscal Period Status Management

[New Calendar Assignment] → [All Periods Open] → [Period-by-Period Control]

[Open/Closed/OnHold]

Dimension Structure Management

[Structure Addition] → [Validation] → [Active Association] → [Constraint Resolution]

Aggregate Components

1. Ledger (Aggregate Root)

Properties:

  • Name: Human-readable identifier for the ledger configuration
  • AccountingCurrencyId: Primary currency for financial transactions and reporting
  • ReportingCurrencyId: Secondary currency for regulatory or parent company reporting
  • FiscalCalendarId: Associated fiscal calendar defining financial periods
  • AccountingCurrencyExchangeRateTypeId: Exchange rate methodology for accounting currency conversions
  • ReportingCurrencyExchangeRateTypeId: Exchange rate methodology for reporting currency conversions

Navigation Properties:

  • AccountingCurrency: Full Currency entity for accounting operations
  • ReportingCurrency: Full Currency entity for reporting operations
  • FiscalCalendar: Complete fiscal calendar with years and periods
  • LedgerStructures: Collection of associated DimensionHierarchy relationships
  • LedgerFiscalPeriods: Collection of period-specific status controls

Key Behaviors:

  • AssignFiscalCalendar(): Associates a fiscal calendar and initializes all period statuses
  • RemoveFiscalCalendar(): Removes fiscal calendar assignment and clears period statuses
  • AddDimensionHierarchy(): Associates a DimensionHierarchy with validation
  • RemoveDimensionHierarchy(): Removes DimensionHierarchy association with impact analysis
  • Update(): Modifies ledger configuration with validation

Central Configuration Role: The Ledger serves as the single point of configuration that coordinates:

  • Account Structure Resolution: Determines which DimensionHierarchies are available for transaction validation
  • Currency Management: Defines conversion rules and reporting requirements
  • Fiscal Control: Manages period-based posting controls and financial reporting boundaries
  • Dimensional Validation: Provides the context for all dimension combination creation and validation

2. LedgerStructure (Entity)

Purpose: Represents the many-to-many relationship between Ledger and DimensionHierarchy entities, enabling the Ledger to maintain a curated collection of account structures available for transaction processing.

Properties:

  • LedgerId: Reference to the parent Ledger
  • DimensionHierarchyId: Reference to the associated DimensionHierarchy
  • Ledger: Navigation property to the parent Ledger
  • DimensionHierarchy: Navigation property to the associated account structure

Key Behaviors:

  • Maintains referential integrity between Ledger and DimensionHierarchy
  • Enables efficient querying of structures associated with a specific Ledger
  • Supports constraint overlap detection across all structures within a Ledger

Business Significance: This relationship is critical for account structure resolution. When a transaction provides a MainAccount value, the system evaluates the constraint trees of all DimensionHierarchies associated with the Ledger through LedgerStructure relationships to determine the appropriate account structure.

3. LedgerFiscalCalendarPeriod (Entity)

Purpose: Represents the status and control mechanism for individual fiscal periods within the context of a specific Ledger, enabling period-by-period transaction posting control.

Properties:

  • FiscalCalendarPeriodId: Reference to the base FiscalCalendarPeriod
  • LedgerId: Reference to the controlling Ledger
  • Status: Current status (Open, Closed, OnHold) controlling transaction posting
  • FiscalCalendarPeriod: Navigation property to the base period definition

Key Behaviors:

  • CanPostTransactions(): Determines if transactions can be posted to this period
  • ChangeStatus(): Updates period status with business rule validation
  • Status change validation and domain event generation

Status Control:

  • Open: Transactions can be posted freely
  • Closed: No transactions can be posted (period closed)
  • OnHold: Transactions are temporarily suspended

Integration Points:

  • Links to base FiscalCalendarPeriod for date ranges and period definitions
  • Controls transaction posting through journal validation
  • Enables period-end closing procedures and financial reporting boundaries

4. LedgerFiscalCalendarYear (Entity)

Purpose: Represents the annual-level fiscal control mechanism, providing year-based status management that complements period-level controls.

Properties:

  • FiscalCalendarYearId: Reference to the base FiscalCalendarYear
  • Ledger: Reference to the controlling Ledger (using int for compatibility)
  • Status: Year-level status controlling annual operations
  • FiscalCalendarYear: Navigation property to the base year definition

Key Behaviors:

  • CanPostTransactions(): Determines if transactions can be posted to any period within this year
  • ChangeStatus(): Updates year-level status with cascading effects
  • Year-end closing and opening procedures

Hierarchical Control: Year-level status provides an additional layer of control above period-level status, enabling organization-wide year-end procedures and multi-period closing operations.

Domain Events

Ledger Structure Management Events

  • LedgerDimensionHierarchyAddedDomainEvent: Raised when a DimensionHierarchy is associated with a Ledger

    • Contains LedgerId and DimensionHierarchyId for integration tracking
    • Triggers constraint overlap validation processes
    • Enables cache invalidation for account structure resolution
  • LedgerDimensionHierarchyRemovedDomainEvent: Raised when a DimensionHierarchy association is removed

    • Enables impact analysis for existing transactions
    • Triggers validation of dependent dimension combinations
    • Supports audit trail maintenance

Fiscal Period Management Events

  • LedgerFiscalCalendarStatusChangedDomainEvent: Raised when fiscal period or year status changes
    • Tracks status transitions for audit and compliance
    • Enables workflow automation for period-end procedures
    • Supports regulatory reporting requirements

Integration and Audit Events

These events enable:

  • Compliance Tracking: Complete audit trail of configuration changes
  • Impact Analysis: Understanding downstream effects of structural changes
  • Cache Management: Intelligent invalidation of performance optimizations
  • Workflow Automation: Triggering period-end procedures and approval processes

Repository Contract

ILedgerRepository

Core Query Methods:

  • GetAllAsync(): Retrieves all ledgers in the system
  • GetCurrentSetupAsync(): Gets the primary ledger configuration (typically one main ledger per organization)
  • GetByIdAsync(): Retrieves ledger with optional structure inclusion
  • GetByIdWithConstraintTreesAsync(): Loads complete constraint tree data for account structure resolution

Specialized Query Methods:

  • GetByDimensionHierarchyAsync(): Finds ledgers using a specific DimensionHierarchy
  • GetCurrentSetupReportingCurrency(): Retrieves reporting currency for current setup
  • IsHierarchyInUseAsync(): Validates if a DimensionHierarchy is referenced by any ledger

Command Methods:

  • Add(): Persists new ledger with configuration validation
  • Update(): Updates existing ledger with change impact analysis

Performance Optimization:

  • Constraint Tree Loading: Specialized method for loading complete hierarchical data needed for account structure resolution
  • Selective Inclusion: Optional loading of related structures based on use case
  • Currency Optimization: Direct access to frequently used currency information

Domain Services

ILedgerFiscalCalendarService

Purpose: Provides fiscal period management and validation services that coordinate between Ledger and FiscalCalendar aggregates.

Key Methods:

  • GetCurrentFiscalPeriodAsync(): Determines current posting period based on today's date
  • GetFiscalPeriodForDateAsync(): Resolves appropriate fiscal period for any given date
  • CanPostToDateAsync(): Validates if transactions can be posted to a specific date
  • OpenFiscalPeriodAsync(): Opens a period for transaction posting
  • CloseFiscalPeriodAsync(): Closes a period and prevents further posting

Business Logic Integration:

  • Coordinates fiscal calendar dates with ledger-specific period controls
  • Validates posting rules based on period status and organizational policies
  • Manages period opening and closing procedures with proper validation

CurrencyConversionService (Integration)

Purpose: Utilizes Ledger currency configuration for transaction-level currency conversions.

Ledger Dependencies:

  • Retrieves accounting and reporting currency definitions from current ledger setup
  • Uses configured exchange rate types for conversion calculations
  • Applies ledger-specific rounding rules and currency precision

Usage Patterns

Initial Ledger Setup

// 1. Create primary ledger with currency configuration
var ledger = new Ledger(
"Primary Ledger",
accountingCurrencyId: usdCurrencyId,
reportingCurrencyId: eurCurrencyId,
fiscalCalendarId: standardCalendarId,
accountingExchangeRateTypeId: dailyRateTypeId,
reportingExchangeRateTypeId: monthEndRateTypeId);

// 2. Assign fiscal calendar (automatically creates period statuses)
ledger.AssignFiscalCalendar(standardFiscalCalendar);

// 3. Add account structures for transaction validation
ledger.AddDimensionHierarchy(primaryAccountStructureId);
ledger.AddDimensionHierarchy(projectAccountStructureId);

Account Structure Resolution Process

// 1. Retrieve ledger with full constraint tree data
var ledger = await repository.GetByIdWithConstraintTreesAsync(currentLedgerId);

// 2. Evaluate MainAccount against all associated structures
var matchingStructures = ledger.DimensionHierarchies
.Where(dh => dh.ConstraintTree.EvaluateMainAccountConstraints(mainAccountValue))
.ToList();

// 3. Resolve appropriate structure (should be exactly one due to overlap prevention)
var accountStructure = resolutionService.ResolveStructure(matchingStructures);

Fiscal Period Management

// 1. Validate posting date against fiscal periods
var canPost = await fiscalService.CanPostToDateAsync(ledgerId, transactionDate);

// 2. Get current posting period for new transactions
var currentPeriod = await fiscalService.GetCurrentFiscalPeriodAsync(ledgerId);

// 3. Period-end closing procedure
await fiscalService.CloseFiscalPeriodAsync(ledgerId, periodId);

Performance Considerations

Optimization Strategies

  • Constraint Tree Caching: Complete constraint trees cached at application level for account structure resolution
  • Current Setup Optimization: Primary ledger configuration cached for frequent access
  • Selective Loading: Repository methods support loading only required related data
  • Currency Lookup Optimization: Direct currency access methods avoid unnecessary joins

Scalability Metrics

  • Structure Resolution: <50ms for account structure resolution with cached constraint trees
  • Period Validation: <10ms for fiscal period status validation
  • Configuration Access: <5ms for cached current setup retrieval
  • Memory Footprint: ~5KB per ledger in optimized configuration

Database Optimization

  • Clustered indexes on ledger ID for efficient structure lookups
  • Foreign key indexes for fast DimensionHierarchy relationship queries
  • Specialized indexes for fiscal period date range queries
  • Connection pooling for high-frequency currency conversion operations

Integration with Other Aggregates

DimensionHierarchy Aggregate

  • Structure Management: Ledger curates which DimensionHierarchies are available for transaction processing
  • Constraint Validation: Account structure resolution operates within Ledger's associated structures
  • Overlap Prevention: ConstraintOverlapDetectionService validates across Ledger's structure collection

DimensionCombination Aggregate

  • Structure Context: All DimensionCombination creation requires Ledger context for structure resolution
  • Validation Scope: Combinations validate against DimensionHierarchies associated with the current Ledger
  • Resolution Foundation: Ledger provides the foundational structure set for dimension combination resolution

FiscalCalendar Aggregate

  • Period Management: Ledger extends FiscalCalendar with organization-specific period controls
  • Posting Control: LedgerFiscalCalendarPeriod entities control transaction posting capabilities
  • Reporting Boundaries: Fiscal periods define financial reporting boundaries and period-end procedures

Currency & ExchangeRateType Aggregates

  • Conversion Configuration: Ledger defines currency conversion rules and methodologies
  • Rate Type Selection: Configured exchange rate types determine conversion calculations
  • Multi-Currency Support: Accounting and reporting currency configurations enable multi-currency operations

LedgerJournal Aggregate

  • Context Provision: Journals operate within Ledger context for validation and processing
  • Period Validation: Journal posting validates against Ledger's fiscal period statuses
  • Structure Resolution: Journal line dimension validation uses Ledger's associated account structures

Design Patterns Applied

Domain-Driven Design Patterns

  • Aggregate Pattern: Ledger maintains consistency boundary for configuration management
  • Repository Pattern: Specialized data access with performance optimization
  • Domain Service Pattern: Cross-aggregate coordination for fiscal and currency management
  • Domain Events Pattern: Configuration change communication and audit trail maintenance

Enterprise Patterns

  • Configuration Hub Pattern: Central point for all financial system configuration
  • Context Provider Pattern: Provides operational context for transaction processing
  • Status Management Pattern: Sophisticated status control for fiscal periods and operations
  • Integration Gateway Pattern: Coordinates between multiple financial domain aggregates

Performance Patterns

  • Cache-Aside Pattern: Intelligent caching of frequently accessed configuration data
  • Lazy Loading Pattern: On-demand loading of related data based on use case requirements
  • Materialized View Pattern: Pre-computed constraint tree data for fast structure resolution
  • Connection Pooling Pattern: Optimized database access for high-frequency operations

Security and Compliance Considerations

Access Control

  • Configuration Security: Ledger configuration changes require elevated privileges
  • Period Control: Fiscal period status changes controlled through authorized workflows
  • Structure Management: DimensionHierarchy associations validated against organizational policies

Audit and Compliance

  • Complete Audit Trail: All configuration changes tracked through domain events
  • Regulatory Compliance: Fiscal period controls support regulatory reporting requirements
  • Change Management: Formal procedures for structural and configuration changes

Data Integrity

  • Referential Integrity: Strong foreign key relationships prevent orphaned configurations
  • Constraint Validation: Comprehensive validation prevents inconsistent configurations
  • Transaction Consistency: Unit of Work pattern ensures atomic configuration changes

Future Evolution

Planned Enhancements

  • Multi-Entity Support: Enhanced support for complex organizational structures with multiple legal entities
  • Advanced Workflow Integration: Formal approval workflows for configuration changes
  • Real-Time Analytics: Live monitoring of fiscal period status and transaction patterns
  • Cloud Optimization: Azure/AWS specific performance and scaling enhancements

Extensibility Points

  • Custom Period Types: Support for specialized fiscal period types beyond standard monthly/quarterly
  • Enhanced Currency Models: Support for cryptocurrency and multi-rate currency scenarios
  • Advanced Structure Rules: More sophisticated DimensionHierarchy association rules
  • Integration Extensibility: Pluggable integration points for third-party financial systems

Architectural Evolution

  • Microservice Readiness: Aggregate designed for potential service boundary extraction
  • Event Sourcing Compatibility: Events designed for potential event sourcing implementation
  • CQRS Enhancement: Specialized read models for complex reporting and analytics scenarios
  • Global Scale: Multi-region and multi-tenant architecture support