PHPackages                             azaharizaman/nexus-accounting - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. azaharizaman/nexus-accounting

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

azaharizaman/nexus-accounting
=============================

Nexus Accounting Package - Financial statement generation, period close, consolidation, and variance analysis

v0.1.0-alpha1(2mo ago)001MITPHPPHP ^8.3

Since May 5Pushed 2mo agoCompare

[ Source](https://github.com/azaharizaman/nexus-accounting)[ Packagist](https://packagist.org/packages/azaharizaman/nexus-accounting)[ RSS](/packages/azaharizaman-nexus-accounting/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (2)Versions (2)Used By (1)

Nexus\\Accounting
=================

[](#nexusaccounting)

**Financial statement generation, period close, consolidation, and variance analysis for the Nexus ERP monorepo.**

---

Table of Contents
-----------------

[](#table-of-contents)

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Architecture](#architecture)
- [Directory Structure](#directory-structure-ddd-layered-architecture)
- [Domain Layer Components](#domain-layer-components)
    - [Entities](#entities)
    - [Value Objects](#value-objects)
    - [Domain Events](#domain-events)
    - [Contracts (CQRS Repository Interfaces)](#contracts-cqrs-repository-interfaces)
    - [Domain Services](#domain-services)
    - [Policies](#policies)
    - [Exceptions](#exceptions)
- [Application Layer Components](#application-layer-components)
    - [DTOs (Data Transfer Objects)](#dtos-data-transfer-objects)
    - [Commands (Write Operations)](#commands-write-operations)
    - [Queries (Read Operations)](#queries-read-operations)
    - [Handlers](#handlers)
    - [Application Services](#application-services)
- [Infrastructure Layer Components](#infrastructure-layer-components)
    - [InMemory Repositories](#inmemory-repositories)
    - [Mappers](#mappers)
- [Architectural Rules](#architectural-rules)
- [Usage Examples](#usage-examples)
- [Required Dependencies](#required-dependencies)
- [Compliance Standards](#compliance-standards)
- [Export Formats](#export-formats)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Documentation](#-documentation)
- [Roadmap](#roadmap)
- [Support](#support)

---

Overview
--------

[](#overview)

The Accounting package provides comprehensive financial reporting capabilities including balance sheet, income statement, and cash flow statement generation, along with period-end closing procedures, multi-entity consolidation, and budget variance analysis.

Features
--------

[](#features)

- **Financial Statement Generation**

    - Balance Sheet (Assets = Liabilities + Equity)
    - Income Statement (P&amp;L with multi-level grouping)
    - Cash Flow Statement (Direct and Indirect methods)
    - Multi-period comparative statements
- **Period Close Operations**

    - Month-end close with validation
    - Year-end close with closing entries
    - Period reopening with audit trail
    - Trial balance verification
- **Consolidation Engine**

    - Full consolidation method
    - Proportional consolidation
    - Equity method
    - Intercompany eliminations
    - Non-controlling interest calculation
- **Variance Analysis**

    - Budget vs actual comparison
    - Significant variance filtering
    - Multi-period trend analysis
    - Variance summary reports
- **Compliance Support**

    - GAAP compliance templates
    - IFRS compliance templates
    - Custom compliance standards
    - Required disclosure tracking

Installation
------------

[](#installation)

This package is part of the Nexus monorepo. Add it to your application's `composer.json`:

```
composer require azaharizaman/nexus-accounting:"*@dev"
```

Architecture
------------

[](#architecture)

This package follows the **Nexus Monorepo Architecture**:

- **Pure PHP Logic**: No Laravel dependencies in the package
- **Contract-Driven**: All external dependencies defined as interfaces
- **Framework-Agnostic**: Can be used in any PHP application
- **Dependency Injection**: All services injected via constructor

Directory Structure (DDD-Layered Architecture)
----------------------------------------------

[](#directory-structure-ddd-layered-architecture)

This package follows the **Complex Atomic Package** pattern with DDD layers:

```
src/
├── Domain/                 # THE TRUTH (Pure Business Logic)
│   ├── Contracts/          # Repository Interfaces (CQRS)
│   ├── Entities/           # Domain Entities
│   ├── ValueObjects/       # Immutable Value Objects
│   ├── Events/             # Domain Events
│   ├── Enums/              # Native PHP Enums
│   ├── Services/           # Domain Services
│   ├── Policies/           # Business Rules
│   └── Exceptions/         # Domain Exceptions
│
├── Application/            # THE USE CASES
│   ├── DTOs/               # Data Transfer Objects
│   ├── Commands/           # Write Operations
│   ├── Queries/            # Read Operations
│   ├── Handlers/           # Command/Query Handlers
│   └── Services/           # Application Services
│
└── Infrastructure/         # INTERNAL ADAPTERS
    ├── InMemory/           # In-memory repositories for testing
    └── Mappers/            # Domain-to-DTO mapping

```

---

Domain Layer Components
-----------------------

[](#domain-layer-components)

> **Purpose:** Contains the core business logic, entities, value objects, events, contracts, services, and policies. This layer represents "THE TRUTH" - pure business logic with no framework dependencies.

### Entities

[](#entities)

EntityPurposeKey PropertiesStatus`FinancialStatement`Base class for all financial statementsperiod, generatedAt, preparedBy✅ Completed`BalanceSheet`Assets = Liabilities + Equity statementassets, liabilities, equity, sections✅ Completed`IncomeStatement`Revenue - Expenses = Net Incomerevenue, expenses, netIncome, sections✅ Completed`CashFlowStatement`Operating, investing, financing activitiesoperatingCash, investingCash, financingCash✅ Completed`TrialBalance`Debit/Credit balance verificationaccounts, totalDebits, totalCredits📋 Planned`StatementSection`Grouping of line itemsname, lineItems, subtotal✅ Completed`StatementLineItem`Individual line in statementaccountCode, description, amount✅ Completed### Value Objects

[](#value-objects)

Value ObjectPurposePropertiesStatus`Period`Fiscal period representationstartDate, endDate, periodType📋 Planned`PeriodType`Enum for period typesMONTHLY, QUARTERLY, ANNUAL, CUSTOM📋 Planned`Money`Monetary value with currencyamount, currency📋 Planned`AccountBalance`Account with balanceaccountId, accountCode, accountName, debit, credit, balance📋 Planned`StatementMetadata`Statement generation infoversion, approvedBy, approvedAt, notes📋 Planned`ConsolidationEntity`Entity in consolidationentityId, name, currency, ownershipPercentage📋 Planned`ReportingPeriod`Reporting period with comparativesstartDate, endDate, comparativeStartDate✅ Completed`StatementSection`Section grouping in statementname, lineItems, subtotal, displayOrder✅ Completed`LineItem`Individual line itemaccountCode, description, amount, indent✅ Completed### Domain Events

[](#domain-events)

EventTriggerPurposeStatus`FinancialStatementGeneratedEvent`Statement createdNotify subscribers of new statement📋 Planned`PeriodClosedEvent`Period closedTrigger end-of-period processes📋 Planned`ConsolidationCompletedEvent`Consolidation doneNotify completion of multi-entity consolidation📋 Planned`VarianceDetectedEvent`Budget varianceAlert on significant variance📋 Planned### Contracts (CQRS Repository Interfaces)

[](#contracts-cqrs-repository-interfaces)

InterfacePurposeStatus`AccountingPeriodQueryInterface`Read accounting period data📋 Planned`AccountingPeriodPersistInterface`Write accounting period data📋 Planned`FinancialStatementQueryInterface`Query financial statements📋 Planned`FinancialStatementPersistInterface`Persist financial statements📋 Planned`ConsolidationQueryInterface`Query consolidation data📋 Planned`ConsolidationPersistInterface`Persist consolidation data📋 Planned`FinancialStatementInterface`Financial statement entity contract✅ Completed`AccountInterface`Account entity contract✅ Completed### Domain Services

[](#domain-services)

ServicePurposeStatus`BalanceSheetGenerator`Generate balance sheet from trial balance📋 Planned`IncomeStatementGenerator`Generate income statement📋 Planned`CashFlowStatementGenerator`Generate cash flow statement📋 Planned`TrialBalanceCalculator`Calculate trial balance from GL📋 Planned`FinancialRatioCalculator`Calculate financial ratios📋 Planned`IntercompanyEliminator`Eliminate intercompany transactions📋 Planned### Policies

[](#policies)

PolicyPurposeStatus`PeriodClosePolicy`Rules for closing accounting periods📋 Planned`StatementApprovalPolicy`Rules for statement approval workflow📋 Planned`ConsolidationPolicy`Rules for multi-entity consolidation📋 Planned### Exceptions

[](#exceptions)

ExceptionPurposeStatus`PeriodNotClosedException`Thrown when period is not closed📋 Planned`StatementGenerationException`Thrown during statement generation errors📋 Planned`ConsolidationException`Thrown during consolidation errors📋 Planned`ComplianceViolationException`Thrown for compliance violations📋 Planned`InvalidReportingPeriodException`Thrown for invalid period data📋 Planned`StatementVersionConflictException`Thrown for version conflicts📋 Planned---

Application Layer Components
----------------------------

[](#application-layer-components)

> **Purpose:** Contains the use cases, DTOs, commands, queries, and handlers that orchestrate the Domain layer. This layer represents "THE USE CASES" - application-specific business logic that coordinates domain operations.

### DTOs (Data Transfer Objects)

[](#dtos-data-transfer-objects)

DTOPurposePropertiesStatus`BalanceSheetDTO`Balance sheet data transfersections, totals, metadata📋 Planned`IncomeStatementDTO`Income statement data transferrevenue, expenses, netIncome📋 Planned`CashFlowStatementDTO`Cash flow data transferoperating, investing, financing📋 Planned`PeriodCloseRequestDTO`Period close request dataperiodId, userId, options📋 Planned`ConsolidationRequestDTO`Consolidation request dataentityIds, method, options📋 Planned### Commands (Write Operations)

[](#commands-write-operations)

CommandPurposeStatus`GenerateBalanceSheetCommand`Generate a new balance sheet📋 Planned`GenerateIncomeStatementCommand`Generate a new income statement📋 Planned`GenerateCashFlowStatementCommand`Generate a new cash flow statement📋 Planned`ClosePeriodCommand`Close an accounting period📋 Planned`ReopenPeriodCommand`Reopen a closed period📋 Planned`ConsolidateStatementsCommand`Consolidate multi-entity statements📋 Planned### Queries (Read Operations)

[](#queries-read-operations)

QueryPurposeStatus`GetBalanceSheetQuery`Retrieve a balance sheet📋 Planned`GetIncomeStatementQuery`Retrieve an income statement📋 Planned`GetCashFlowStatementQuery`Retrieve a cash flow statement📋 Planned`GetTrialBalanceQuery`Retrieve trial balance data📋 Planned`GetVarianceReportQuery`Retrieve variance analysis📋 Planned`GetConsolidatedStatementQuery`Retrieve consolidated statement📋 Planned### Handlers

[](#handlers)

HandlerPurposeStatus`GenerateBalanceSheetHandler`Handles balance sheet generation command📋 Planned`GenerateIncomeStatementHandler`Handles income statement generation command📋 Planned`ClosePeriodHandler`Handles period close command📋 Planned`ConsolidateStatementsHandler`Handles consolidation command📋 Planned### Application Services

[](#application-services)

ServicePurposeStatus`AccountingManager`Main entry point for accounting operations📋 Planned`StatementCoordinator`Coordinates statement generation workflow📋 Planned`PeriodCloseCoordinator`Coordinates period close workflow📋 Planned---

Infrastructure Layer Components
-------------------------------

[](#infrastructure-layer-components)

> **Purpose:** Contains internal adapters for testing and mapping between domain objects and external representations. This layer provides INTERNAL ADAPTERS - implementations used for testing and data transformation within the package.

### InMemory Repositories

[](#inmemory-repositories)

RepositoryPurposeImplementsStatus`InMemoryFinancialStatementRepository`Testing financial statement persistence`FinancialStatementQueryInterface`, `FinancialStatementPersistInterface`📋 Planned`InMemoryAccountingPeriodRepository`Testing period management`AccountingPeriodQueryInterface`, `AccountingPeriodPersistInterface`📋 Planned`InMemoryConsolidationRepository`Testing consolidation data`ConsolidationQueryInterface`, `ConsolidationPersistInterface`📋 Planned### Mappers

[](#mappers)

MapperPurposeStatus`BalanceSheetMapper`Maps BalanceSheet entity to BalanceSheetDTO📋 Planned`IncomeStatementMapper`Maps IncomeStatement entity to IncomeStatementDTO📋 Planned`CashFlowStatementMapper`Maps CashFlowStatement entity to CashFlowStatementDTO📋 Planned`PeriodMapper`Maps Period value object to array/JSON📋 Planned`StatementMetadataMapper`Maps metadata to/from external formats📋 Planned**InMemory Repositories are provided for:**

1. **Unit Testing:** Fast, isolated tests without database dependencies
2. **Integration Testing:** Test application layer without external infrastructure
3. **Development:** Quick prototyping without database setup
4. **Documentation:** Reference implementations of repository contracts

**Mappers are used for:**

1. **DTO Conversion:** Transform domain entities to DTOs for API responses
2. **Serialization:** Prepare domain objects for JSON/array serialization
3. **Deserialization:** Reconstruct domain objects from external data
4. **View Models:** Create presentation-specific representations

> **Note on External Adapters:** Database adapters (Eloquent, Doctrine) belong in the `adapters/` folder at the monorepo root, NOT in this Infrastructure layer.

---

Architectural Rules
-------------------

[](#architectural-rules)

### Domain Layer Rules

[](#domain-layer-rules)

1. **No Framework Dependencies:** The Domain layer MUST NOT use any framework-specific code
2. **Pure PHP 8.3+:** Use modern PHP features (readonly, enums, match expressions)
3. **Immutable Entities:** All entities should be immutable where possible
4. **Interface-Driven:** All external dependencies defined via interfaces
5. **Event-Driven:** State changes emit domain events
6. **CQRS Separation:** Read (Query) and Write (Persist) interfaces are separated

### Application Layer Rules

[](#application-layer-rules)

1. **Orchestration Only:** Application layer coordinates Domain layer, never bypasses it
2. **DTOs for Data Transfer:** Use DTOs to transfer data between layers
3. **Command/Query Separation:** Commands change state, Queries read state (CQRS)
4. **Handler Pattern:** Each command/query has a dedicated handler
5. **No Direct Persistence:** Use Domain repositories via dependency injection

### Infrastructure Layer Rules

[](#infrastructure-layer-rules)

1. **Internal Use Only:** This layer is for internal package use, not public API
2. **Test Support:** InMemory repositories are primarily for testing
3. **No Business Logic:** Mappers only transform data, no business rules
4. **Implement Domain Contracts:** InMemory repos implement Domain contracts exactly
5. **Stateless Mappers:** All mappers are stateless, pure transformations

Usage Examples
--------------

[](#usage-examples)

### Generate a Balance Sheet

[](#generate-a-balance-sheet)

```
use Nexus\Accounting\Domain\ValueObjects\Period;
use Nexus\Accounting\Domain\Contracts\FinancialStatementQueryInterface;
use Nexus\Accounting\Domain\Services\BalanceSheetGenerator;

$period = Period::forMonth(2025, 11);

$balanceSheet = $balanceSheetGenerator->generate(
    entityId: 'entity-123',
    period: $period,
    options: ['include_comparatives' => true]
);

echo "Total Assets: " . $balanceSheet->getTotalAssets();
echo "Total Equity: " . $balanceSheet->getTotalEquity();
echo "Balanced: " . ($balanceSheet->verifyBalance() ? 'Yes' : 'No');
```

### Close a Month-End Period

[](#close-a-month-end-period)

```
use Nexus\Accounting\Domain\Services\PeriodCloseService;
use Nexus\Accounting\Domain\Policies\PeriodClosePolicy;

// Validate readiness using policy
$validation = $periodClosePolicy->validateReadiness('period-202511');

if ($validation['ready']) {
    $periodCloseService->closeMonth('period-202511');
} else {
    print_r($validation['issues']);
}
```

### Calculate Budget Variance

[](#calculate-budget-variance)

```
use Nexus\Accounting\Domain\Services\VarianceCalculator;

$variance = $varianceCalculator->calculateAccountVariance(
    accountId: 'account-4000',
    period: $period
);

echo "Actual: " . $variance->getActualAmount();
echo "Budget: " . $variance->getBudgetAmount();
echo "Variance: " . $variance->formatVariance();
echo "Status: " . $variance->getStatus(isRevenueAccount: true);
```

### Consolidate Multi-Entity Statements

[](#consolidate-multi-entity-statements)

```
use Nexus\Accounting\Domain\Enums\ConsolidationMethod;
use Nexus\Accounting\Domain\Services\ConsolidationEngine;

$consolidated = $consolidationEngine->consolidateStatements(
    entityIds: ['parent-1', 'subsidiary-1', 'subsidiary-2'],
    period: $period,
    method: ConsolidationMethod::FULL,
    options: ['calculate_nci' => true]
);

echo "Consolidated Total Assets: " . $consolidated->getTotalAssets();
```

Required Dependencies
---------------------

[](#required-dependencies)

The Accounting package requires these contracts to be implemented by the consuming application:

### From `Nexus\Finance`

[](#from-nexusfinance)

- `LedgerRepositoryInterface` - Read GL data, account balances
- `JournalEntryServiceInterface` - Create closing entries

### From `Nexus\Period`

[](#from-nexusperiod)

- `PeriodManagerInterface` - Fiscal period validation, locking

### From `Nexus\QueryEngine`

[](#from-nexusqueryengine)

- `BudgetRepositoryInterface` - Budget data for variance analysis

### From `Nexus\Setting`

[](#from-nexussetting)

- `SettingsManagerInterface` - Report templates, precision config

### From `Nexus\AuditLogger`

[](#from-nexusauditlogger)

- `AuditLoggerInterface` - Log all operations

### PSR Standards

[](#psr-standards)

- `Psr\Log\LoggerInterface` - Logging (PSR-3)

Compliance Standards
--------------------

[](#compliance-standards)

The package supports multiple accounting standards:

```
use Nexus\Accounting\Domain\ValueObjects\ComplianceStandard;

$usGaap = ComplianceStandard::usGAAP('2024');
$ifrs = ComplianceStandard::ifrs('2024');
$custom = ComplianceStandard::custom('Malaysian FRS', '2024', 'MY');
```

Export Formats
--------------

[](#export-formats)

Financial statements can be exported to multiple formats:

```
use Nexus\Accounting\Domain\Enums\StatementFormat;

$format = StatementFormat::PDF;      // application/pdf
$format = StatementFormat::EXCEL;    // .xlsx spreadsheet
$format = StatementFormat::CSV;      // Plain text CSV
$format = StatementFormat::JSON;     // JSON for APIs
```

Testing
-------

[](#testing)

(Test suite to be implemented in Phase 5)

```
composer test
```

Contributing
------------

[](#contributing)

This package follows strict architectural guidelines:

1. **No Laravel dependencies** - Keep the package framework-agnostic
2. **Contract-driven design** - Define interfaces for all external needs
3. **Immutable value objects** - Use `readonly` properties
4. **Modern PHP 8.3+** - Use native enums, constructor promotion, match expressions
5. **Comprehensive exceptions** - Provide clear error messages

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

📖 Documentation
---------------

[](#-documentation)

### Package Documentation

[](#package-documentation)

- **[Getting Started Guide](docs/getting-started.md)** - Quick start guide with prerequisites, concepts, and first integration
- **[API Reference](docs/api-reference.md)** - Complete documentation of all interfaces, value objects, and exceptions
- **[Integration Guide](docs/integration-guide.md)** - Laravel and Symfony integration examples
- **[Basic Usage Example](docs/examples/basic-usage.php)** - Simple usage patterns
- **[Advanced Usage Example](docs/examples/advanced-usage.php)** - Advanced scenarios and patterns

### Additional Resources

[](#additional-resources)

- `IMPLEMENTATION_SUMMARY.md` - Implementation progress and metrics
- `REQUIREMENTS.md` - Detailed requirements (139 requirements)
- `TEST_SUITE_SUMMARY.md` - Test coverage and results
- `VALUATION_MATRIX.md` - Package valuation metrics ($350K+ value)
- See root `ARCHITECTURE.md` for overall system architecture

---

Roadmap
-------

[](#roadmap)

- Phase 1: Foundation Layer (Domain Contracts, Value Objects, Enums, Exceptions)
- Phase 2: Core Engines (Statement Generators, Period Close, Consolidation, Variance)
- Phase 3: DDD Refactoring (Domain/Application/Infrastructure layers)
- Phase 4: Application Layer (DTOs, Commands, Queries, Handlers)
- Phase 5: Test Suite (185+ tests planned - December 2024)

Support
-------

[](#support)

For questions or issues, please refer to the main Nexus monorepo documentation.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance84

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 Bus Factor1

Top contributor holds 76.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

81d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/117408?v=4)[Azahari Zaman](/maintainers/azaharizaman)[@azaharizaman](https://github.com/azaharizaman)

---

Top Contributors

[![azaharizaman](https://avatars.githubusercontent.com/u/117408?v=4)](https://github.com/azaharizaman "azaharizaman (469 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (140 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/azaharizaman-nexus-accounting/health.svg)

```
[![Health](https://phpackages.com/badges/azaharizaman-nexus-accounting/health.svg)](https://phpackages.com/packages/azaharizaman-nexus-accounting)
```

###  Alternatives

[symfony/lock

Creates and manages locks, a mechanism to provide exclusive access to a shared resource

515139.2M711](/packages/symfony-lock)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k38.9k](/packages/matomo-matomo)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

564576.7k54](/packages/ecotone-ecotone)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k46](/packages/civicrm-civicrm-core)[illuminate/broadcasting

The Illuminate Broadcasting package.

7127.2M221](/packages/illuminate-broadcasting)[logiscape/mcp-sdk-php

Model Context Protocol SDK for PHP

367116.8k12](/packages/logiscape-mcp-sdk-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
