# Full-System Simulation & Validation Plan

## Goal

Build a deterministic, repeatable simulation dataset that exercises the complete microfinance system and proves that operational screens, accounting movements, dashboards, reports, exports, branch isolation, permissions, and end-to-end loan workflows agree with independently calculated control totals.

This is a validation harness, not ordinary demo data. Simulation seeding remains opt-in and is never added to `DatabaseSeeder`.

## Principles

1. **Deterministic data** — fixed identifiers, dates, amounts, roles and branch assignments. Random factory data is not used for financial control totals.
2. **Independent expected totals** — report assertions use known scenario inputs/control totals rather than reusing the report service calculation being tested.
3. **Idempotent execution** — rerunning a phase updates/reuses its simulation records instead of multiplying them.
4. **Production safety** — simulation seeding requires `SIMULATION_DATA_ENABLED=true` outside the test environment.
5. **Real service boundaries** — transactional phases use the application's services for approvals, disbursement, payments, accounting, payroll, expenses, fixed assets and loan adjustments wherever possible.
6. **Branch isolation** — every phase includes cross-branch negative tests and system-wide positive tests.
7. **Authorization parity** — staff use canonical Spatie roles/permissions and Laravel `can()`/policies; no legacy authorization bridge is reintroduced.
8. **Traceable records** — simulation identifiers use the `SIM-` prefix so records and failures are easy to recognize.
9. **Fixed clock** — financial scenarios will use a fixed anchor date so arrears, penalties, schedules and period reports have stable expected results.
10. **Reconciliation before UI assertions** — database/accounting control totals are established first, then dashboards/reports/exports are compared against them.

## Validation Matrix

| Area | Simulation coverage | Primary validation |
|---|---|---|
| Business & branches | Three branches, branch managers, cross-branch users | Counts, assignment, isolation |
| Roles & staff | Manager, loan officer, inspector, cashier, accountant, collector, HR/payroll, auditor | Canonical role + branch access |
| Customers | NIN/non-NIN, active/inactive, branch distribution | Counts, identity modes, scope |
| Loan products | Multiple fee/penalty/collateral combinations | Product rules/calculation inputs |
| Financial accounts | Cash, bank, mobile money and other operational account types | Opening/current balance controls |
| Loan origination | Draft/pending/approved/rejected | Workflow and permission checks |
| Collateral & guarantors | Secured/unsecured scenarios | Custody, documents, branch scope |
| Contracts | Preview/generated/signed | Authorization and document surface |
| Disbursement | Multiple branches/accounts | Account + ledger reconciliation |
| Repayments | On-time, partial, advance, late | Allocation and balance reconciliation |
| Remote payments | Pending/approved/rejected | Verification workflow + receipt linkage |
| Arrears & penalties | Current, overdue, excused deadline, penalties | Days overdue and penalty controls |
| Top-ups | Eligible/ineligible/override/executed | Old/new loan and accounting controls |
| Early settlement | Normal and adjusted settlement | Settlement amount + ledger controls |
| Restructuring | Proposed/approved/rejected | New schedule and outstanding balances |
| Write-off & recovery | Requested/approved/rejected/recovered | Portfolio + accounting controls |
| Expenses | Draft/approved/rejected/recurring | Expense and account balances |
| Transfers & capital | Capital injection and inter-account transfer | Double-entry/account balance controls |
| Payroll | Draft/approved/paid + maker/checker | Payroll totals and account movement |
| Fixed assets | Purchase/opening, depreciation, maintenance | Book value and report controls |
| Daily closing | Balanced/short/over + confirmation | Reconciliation and maker/checker |
| Tasks/calendar | Tasks, appointments, status changes | Branch/user scope |
| Notifications | Reminder logs/retry states | Operational state and permissions |
| Management alerts | Multiple severities/statuses | Threshold/scope/action controls |
| Audit/security | Representative audit events and access | Visibility and immutable evidence |
| Dashboard | KPIs, account balances, portfolio, branch filters | Independent control totals |
| Financial reports | P&L, cash flow/account summaries and advanced reports | Independent control totals |
| Loan/branch reports | Portfolio, arrears, collections, disbursement, branch performance | Independent control totals |
| Fixed-asset reports | Register/depreciation/maintenance | Independent control totals |
| Exports | CSV/PDF where applicable | Same totals as screen/service output |
| Global search | Customers/loans/collateral/payments/remote refs | Permission + branch side-channel checks |

## Phases

### Phase 0 — Inventory & control design

- Map models, services, routes, reports and existing tests.
- Define scenario naming, fixed clock and expected-value strategy.
- Keep this document as the execution checklist.

**Exit:** every major system surface has a planned scenario and reconciliation target.

### Phase 1 — Deterministic simulation foundation

Create the opt-in simulation seed framework and foundation dataset:

- business baseline/authorization seed dependencies;
- Dar es Salaam, Mwanza and Arusha simulation branches;
- representative staff for all operational system roles;
- canonical role and branch assignments;
- known opening balances across financial accounts;
- NIN and non-NIN customers distributed across branches;
- representative loan products;
- a machine-readable expectations/control class;
- feature tests for idempotency, counts, balances, role assignment and branch isolation.

**Exit:** repeatable foundation data with exact known opening controls.

### Phase 2 — Loan lifecycle & customer risk simulation

Build loans covering pending, approved, rejected, active and completed states. Exercise collateral, guarantors, approval paths, contracts, disbursements, schedules, payments, remote payments, arrears, penalties and collection follow-ups.

**Exit:** every ordinary loan lifecycle path has deterministic expected balances and dates.

### Phase 3 — Advanced loan adjustments

Exercise top-up, early settlement, restructuring, write-off and write-off recovery including rejection/override/maker-checker paths.

**Exit:** adjusted portfolio balances reconcile to underlying transactions and customer statements.

### Phase 4 — Accounting & operational finance

Exercise capital, transfers, expenses/recurring expenses, payroll, fixed assets/depreciation/maintenance and daily closing.

**Exit:** account balances and accounting ledger reconcile exactly from opening balance + movements.

### Phase 5 — Operations, alerts, notifications & audit

Create tasks, appointments, reminder notifications, management alerts and representative audit/security records.

**Exit:** operational lists/actions respect permissions and branch scope.

### Phase 6 — Reports & dashboard reconciliation

For each supported report and dashboard period:

- calculate expected controls independently from the scenario specification;
- call the actual report/dashboard services;
- assert totals, subtotals and branch filters;
- verify cross-report consistency;
- verify exports match on-screen/service totals.

Key reconciliations include:

- opening balance + capital + collections - disbursements - expenses - payroll +/- transfers = closing account balances;
- loan principal disbursed - principal collected - principal settled/written off adjustments = outstanding principal;
- interest/fees/penalties recognized and collected reconcile between loan and financial reports;
- branch totals sum to the system-wide total;
- dashboard period KPIs equal the corresponding detailed reports.

**Exit:** no unexplained variance in any report/control total.

### Phase 7 — Full end-to-end regression & CI gate

- Fresh database -> standard seed -> simulation seed -> full validation suite.
- Run on SQLite test path and MySQL CI path where applicable.
- Produce a final validation matrix listing PASS/FAIL and any discovered defects.
- Add a non-production CI simulation job only after execution time and stability are acceptable.

**Exit:** reproducible green full-system simulation with documented remaining defects (if any).

## First execution slice

Phase 1 starts immediately on branch `feat/full-system-simulation-validation`. No simulation seeder will be wired into normal production seeding. After Phase 1 is green, Phase 2 will use these stable branch/users/accounts/customers/products as its base.