# POST_ROADMAP_IMPROVEMENTS.md
# ERPdash — Improvement & Hardening Execution Plan
# Execute AFTER all Tasks 01–27 and HR/Finance Expansion tasks are complete
# Date created: 2026-05-02

---

## PURPOSE

This file documents every gap, bug, and missing feature found by reading
all project planning files, QA reports, and test results.
It is the single source of truth for what to fix and build next.

Execute each phase in order.
Stop after each step and wait for confirmation before continuing.

---

## KNOWN CONFIRMED BUGS (fix first)

---

### BUG-01 — Blade syntax error in accounts/create.blade.php

**File:**
`resources/views/dashboard/finance/accounts/create.blade.php`

**Line:** 26

**Problem:**
```blade
class="form-control @error('code') is-invalid @error"
```
The closing `@error` should be `@enderror`.

**Fix:**
```blade
class="form-control @error('code') is-invalid @enderror"
```

**Impact:** Finance Accounts create form returns HTTP 500.

**Action:**
Search all blade files under `resources/views/dashboard/` for any other `@error` directives
missing their `@enderror` closing tag. Fix all occurrences in a single pass.

---

### BUG-02 — Cost Centers module has no registered routes

**Evidence:**
`php artisan route:list --path=cost-center` returns nothing.
`app/Http/Controllers/Admin/Finance/CostCenterController.php` exists.

**Fix:**
Add missing resource routes for Cost Centers inside `routes/admin.php`:

```php
Route::resource('finance/cost-centers', Admin\Finance\CostCenterController::class)
    ->names('admin.finance.cost-centers');
```

**Then:** Add Cost Centers CRUD feature test in `tests/Feature/Finance/FinanceCrudFormsTest.php`.

---

### BUG-03 — Number sequence off-by-one error

**File:**
`app/Models/Core/NumberSequence.php` — `generateFormattedNumber()`

**Problem:**
`getNextNumber()` increments `current_number` first, then `generateFormattedNumber()`
formats the already-incremented value, producing the next number instead of the current one.
First generated number returns `00002` instead of `00001`.

**Fix:**
In `generateFormattedNumber()`, use the value **before** the increment, not after.
Fetch the current value, format it, then increment — or restructure the method to:
1. Read current value
2. Format it
3. Then increment and save

**Failing tests:**
`tests/Feature/NumberSequenceTest.php` — 8 failing cases.

---

### BUG-04 — Branch and Settings tests: GET routes returning 302 instead of 200/403

**Affected files:**
- `tests/Feature/BranchTest.php` — 3 failing
- `tests/Feature/Core/SettingTest.php` — 2 failing

**Root cause:**
Legacy tests do not account for the localization middleware that redirects GET requests
to a locale-prefixed URL before authentication middleware fires.

**Fix options (choose one consistently):**

Option A — Align tests with localized route behavior:
Assert `302` redirect to `/en/admin/...` and follow redirects.

Option B — Disable localization middleware in tests (same approach used in Task 27 new tests):
```php
$this->withoutMiddleware(\App\Http\Middleware\LocalizationMiddleware::class);
```

Apply the same strategy used in the passing Task 27 tests to all legacy failing tests.

---

## PHASE 1 — ENVIRONMENT FIXES

Execute these before any further manual QA.

---

### ENV-01 — Apply all pending migrations

Run:
```bash
php artisan migrate
```

Pending migrations from QA report:
- `create_journal_entries_table`
- `create_journal_entry_lines_table`
- `create_account_period_balances_table`
- `add_posting_columns_to_journal_entries_table`
- `create_warehouses_table`
- `create_items_table`
- `create_stock_movements_table`
- `create_customers_table`
- `create_sales_orders_table`
- `create_sales_order_lines_table`
- `create_invoices_table`
- `create_invoice_lines_table`
- `create_employees_table`
- `create_payrolls_table`
- `create_notifications_table`
- `create_activity_logs_table`
- `create_fiscal_periods_table`

Also run HR expansion migrations created in tasks 02–76.

---

### ENV-02 — Link storage

```bash
php artisan storage:link
```

Required for document/attachment uploads (HR contracts, employee documents, expense attachments, etc.)

---

### ENV-03 — Install frontend dependencies

```bash
npm install
npm run build
```

Required for Vite assets and Metronic UI to render correctly in browser testing.

---

### ENV-04 — Set correct timezone

In `.env` or `config/app.php`:
```php
'timezone' => 'Africa/Cairo',
```

This matters for payroll periods, attendance timestamps, fiscal period date checks,
and any date-sensitive operation in a Cairo-timezone context.

---

### ENV-05 — Seed permissions after all migrations

After applying all migrations and completing all module builds:
```bash
php artisan db:seed --class=RolePermissionSeeder
```

Verify these permission groups exist:
- `core.*`
- `finance.*`
- `reports.*`
- `inventory.*`
- `sales.*`
- `hr.*`
- `system.*`
- `portal.*`

---

## PHASE 2 — MISSING TEST COVERAGE

Add dedicated feature tests for all modules that currently have no test file.

Execute one group at a time. Stop after each group.

---

### TEST-01 — Finance: Chart of Accounts

File: `tests/Feature/Finance/AccountModuleTest.php`

Cover:
- account CRUD with permission checks
- translated name (ar + en) saves correctly
- parent/child hierarchy level auto-calculation
- postable/non-postable flag enforcement in journal entries
- unique code validation
- soft delete / restore if applicable

---

### TEST-02 — Finance: Journals

File: `tests/Feature/Finance/JournalModuleTest.php`

Cover:
- journal CRUD
- unique code validation
- journal appears in journal entry dropdown

---

### TEST-03 — Finance: Trial Balance

File: `tests/Feature/Finance/TrialBalanceTest.php`

Cover:
- report requires branch + fiscal year + fiscal period
- posted entries affect balances
- draft entries do NOT affect trial balance
- opening/period/closing balance columns sum correctly
- empty result when no data exists

---

### TEST-04 — Finance: Income Statement

File: `tests/Feature/Finance/IncomeStatementTest.php`

Cover:
- income accounts (type=income) appear in revenue section
- expense accounts (type=expense) appear in expense section
- net profit = revenues - expenses when revenues > expenses
- net loss = revenues - expenses when expenses > revenues
- period amounts used (not closing balance)

---

### TEST-05 — Finance: General Ledger

File: `tests/Feature/Finance/GeneralLedgerTest.php`

Cover:
- only posted entries appear
- draft entries excluded
- running balance calculation is correct
- date range filter works
- account filter is required

---

### TEST-06 — Inventory: Warehouses

File: `tests/Feature/Inventory/WarehouseModuleTest.php`

Cover:
- warehouse CRUD with permission checks
- unique code validation
- inactive warehouse not selectable in stock movement forms

---

### TEST-07 — Inventory: Items

File: `tests/Feature/Inventory/ItemModuleTest.php`

Cover:
- item CRUD with permission checks
- unique code validation
- type=service item rejected in stock movement
- type=stock item accepted in stock movement
- translated name saves correctly

---

### TEST-08 — Inventory: Stock Report

File: `tests/Feature/Inventory/StockReportTest.php`

Cover:
- `in` movements increase net quantity
- `out` movements decrease net quantity
- filter by warehouse works
- filter by item works
- aggregation is grouped per item+warehouse pair

---

### TEST-09 — Sales: Customers

File: `tests/Feature/Sales/CustomerModuleTest.php`

Cover:
- customer CRUD with permission checks
- unique code validation
- translated name and address save correctly
- inactive customer cannot be used in new orders (if enforced)

---

### TEST-10 — Sales: Sales Orders

File: `tests/Feature/Sales/SalesOrderModuleTest.php`

Cover:
- order CRUD with permission checks
- order number generated by number sequence
- line_total = quantity * unit_price
- at least one line required
- status transitions (draft → confirmed → cancelled)

---

### TEST-11 — Sales: Sales Report

File: `tests/Feature/Sales/SalesReportTest.php`

Cover:
- report filters by branch, customer, date range
- only confirmed invoices shown (if that rule is active)
- totals are correct sums of filtered rows
- empty result handled safely

---

### TEST-12 — HR: Employees

File: `tests/Feature/HR/EmployeeModuleTest.php`

Cover:
- employee CRUD with permission checks
- unique code validation
- translated name and job title save correctly
- inactive employee not shown in payroll forms

---

### TEST-13 — HR: Payroll Calculations

Extend: `tests/Feature/HR/PayrollModuleTest.php`

Cover:
- net_salary = basic_salary + allowances - deductions
- status transitions (draft → approved → paid)
- payroll number generated by number sequence
- payroll month is required
- negative net salary should fail validation

---

### TEST-14 — System: Cost Centers (currently no routes)

File: `tests/Feature/Finance/CostCenterModuleTest.php`

**Prerequisite:** BUG-02 must be fixed first.

Cover:
- cost center CRUD with permission checks
- parent/child hierarchy saves correctly
- translated name saves correctly
- branch assignment works

---

### TEST-15 — System: Notifications

Extend: `tests/Feature/System/SystemModuleTest.php`

Cover:
- notification list accessible with `system.notifications.view`
- 403 without permission
- mark as read changes `read_at`
- unread count decreases after mark as read

---

### TEST-16 — System: Audit Logs

Extend: `tests/Feature/System/SystemModuleTest.php`

Cover:
- audit log list accessible with `system.audit_logs.view`
- 403 without permission
- filter by event works
- filter by date range works

---

## PHASE 3 — MISSING FEATURES (not yet planned in any task file)

These features were referenced in the SRS, architecture docs, or HR super prompt
but have no dedicated task file yet. Build them in order.

---

### FEAT-01 — Soft Delete + Restore for core masters

**Scope:** Branches, Cost Centers, Accounts, Journals, Warehouses, Items, Customers, Employees

**Why:** The test report confirms branches have soft-delete/restore tests.
Other masters may be missing `SoftDeletes` trait and restore routes.

**Steps:**
1. Verify which models have `SoftDeletes` already
2. Add `deleted_at` column via migration for any missing
3. Add `withTrashed()` and restore route/action in respective controllers
4. Add permission `*.restore` if needed
5. Add `trashed` filter to index views

---

### FEAT-02 — Fiscal Period: strict open/closed validation in Journal Entries

**Current state:** Task 08 notes say period validation can be basic now.
Task 09 (posting engine) enforces it for posting but not for draft creation.

**Improvement:**
In `JournalEntryService`, when creating or updating a draft entry,
validate that `fiscal_period_id` belongs to an **open** fiscal year.
Closed periods should reject new entries entirely, not just posting.

---

### FEAT-03 — Invoice Confirmation and Financial Posting hook

**Current state:** Invoices exist with `draft/confirmed/cancelled` status but
no posting action is implemented.

**New task:** Create `InvoicePostingService` that:
1. Validates invoice is `confirmed`
2. Creates journal entry via existing `JournalPostingService`
3. Uses a configurable posting profile (debit: receivable account, credit: revenue account)
4. Marks invoice as posted with `posted_journal_entry_id`
5. Blocks editing after posting

---

### FEAT-04 — Sales Invoice Collections (finance_receipt_vouchers integration)

**Defined in:** `32_sales_invoice_collection_mapping.md`, `33_sales_invoice_auto_receipts.md`

**Current state:** These task files exist in the Finance Expansion plan but
there is no evidence they have been built.

**Build:**
1. Add `sales_invoice_collections` table if not already present:
   - invoice_id, amount, payment_method_id, receipt_voucher_id (nullable), collected_at, notes
2. Create `InvoiceCollectionService`
3. When a collection is saved, auto-trigger `ReceiptVoucherService` to create a receipt voucher
4. Support partial collections (multiple payments per invoice)
5. Invoice status updates: `draft → confirmed → partially_paid → paid`

---

### FEAT-05 — Expense Payment → Auto Payment Voucher

**Defined in:** `34_expense_payment_auto_payments.md`

**Build:**
1. When an expense record is marked as paid, call `PaymentVoucherService`
2. One payment event = one payment voucher
3. Support partial payments (expense can be `paid_partial` before `paid_full`)
4. Prevent duplicate voucher creation on retry

---

### FEAT-06 — Receipt Voucher Full Implementation

**Defined in:** Tasks 15–22 of Finance Expansion

**Verify and complete:**
- `finance_receipt_vouchers` table exists and migrated
- `ReceiptVoucher` model with relations
- `ReceiptVoucherService`: create, approve, post, reverse
- `ReceiptVoucherPostingService`: creates journal entry on post action
- `VoucherReversalService`: creates reverse journal entry
- Admin CRUD views under `resources/views/dashboard/finance/receipts/`
- Routes and permissions registered
- Add feature test: `tests/Feature/Finance/ReceiptVoucherTest.php`

---

### FEAT-07 — Payment Voucher Full Implementation

**Defined in:** Tasks 23–30 of Finance Expansion

**Verify and complete:**
- `finance_payment_vouchers` table exists and migrated
- `PaymentVoucher` model with relations
- `PaymentVoucherService`: create, approve, post, reverse
- `PaymentVoucherPostingService`: creates journal entry on post action
- Admin CRUD views under `resources/views/dashboard/finance/payments/`
- Routes and permissions registered
- Add feature test: `tests/Feature/Finance/PaymentVoucherTest.php`

---

### FEAT-08 — Finance Expansion Reports

**Defined in:** Tasks 36–40 of Finance Expansion

Reports not yet confirmed as built:
- Receipt voucher register (filter: branch, date, status, payment method)
- Payment voucher register (filter: branch, date, beneficiary, status)
- Expense register (filter: branch, date, category, item, status)
- Cash movement report (receipts - payments for cash accounts)
- Bank movement report (receipts - payments for bank accounts)
- Expenses by item
- Expenses by cost center

**Build each as its own Service + Controller + View + Route.**

---

### FEAT-09 — HR Module: Full Expansion (Tasks 01–76)

The HR Expansion plan (files `01_hr_setup_overview.md` through `76_analytics_routes_permissions.md`)
is fully designed but execution is not confirmed beyond the basic Tasks 21–23
(Employees, Payroll, Payroll Summary) that were in the original roadmap.

**Remaining HR phases to execute in order:**

#### HR Phase 1 — Setup Masters
Execute tasks:
- `02_hr_setup_tables_master_1.md` — departments, designations, grades, contract types
- `03_hr_setup_tables_master_2.md` — leave types, permission types, loan types, bonus, penalty, earning, deduction types
- `04_hr_setup_tables_workflow.md` — request workflows + workflow steps
- `05_hr_setup_tables_payroll_profiles.md` — payroll posting profiles
- `06_hr_setup_models_core.md` — models for core setup
- `07_hr_setup_models_types.md` — models for type tables
- `08_hr_setup_models_workflow.md` — workflow models
- `09_hr_setup_services.md` — setup services
- `10_hr_setup_admin_crud.md` — admin CRUD for all setup masters

#### HR Phase 2 — Recruitment
Execute tasks:
- `12_recruitment_tables_job_requests_candidates.md`
- `13_recruitment_tables_interviews_offers.md`
- `14_recruitment_models_core.md`
- `15_recruitment_services.md`
- `16_recruitment_form_requests.md`
- `17_recruitment_admin_controllers.md`
- `18_recruitment_views_routes_permissions.md`

#### HR Phase 3 — Employee Master (extended)
Execute tasks:
- `20_employee_tables_core.md` — employees, contracts, documents
- `21_employee_tables_financial.md` — salary profiles, allowances, deductions, bank accounts
- `22_employee_tables_history.md` — transfers, secondments, status histories
- `23_employee_models_core.md`
- `24_employee_models_financial.md`
- `25_employee_models_history.md`
- `26_employee_services_core.md`
- `27_employee_services_history_salary.md`
- `28_employee_form_requests.md`
- `29_employee_admin_controllers.md`
- `30_employee_views_routes_permissions.md`

#### HR Phase 4 — Attendance
Execute tasks:
- `32_attendance_tables.md`
- `33_attendance_models.md`
- `34_attendance_services.md`
- `35_attendance_controllers_requests.md`
- `36_attendance_views_routes_permissions.md`

#### HR Phase 5 — HR Requests
Execute tasks:
- `38_requests_tables_leave_permission.md`
- `39_requests_tables_financial.md`
- `40_requests_tables_employee_actions.md`
- `41_requests_tables_approvals.md`
- `42_requests_models_core.md`
- `43_requests_models_other.md`
- `44_requests_services_core.md`
- `45_requests_services_other.md`
- `46_requests_form_requests.md`
- `47_requests_admin_controllers.md`
- `48_requests_views_routes_permissions.md`

#### HR Phase 6 — Payroll (extended)
Execute tasks:
- `50_payroll_tables_periods_runs.md`
- `51_payroll_tables_lines_items.md`
- `52_payroll_tables_payments_postings.md`
- `53_payroll_models_core.md`
- `54_payroll_services_engine.md`
- `55_payroll_services_posting_eos.md`
- `56_payroll_form_requests.md`
- `57_payroll_admin_controllers.md`
- `58_payroll_views_routes_permissions.md`
- `59_payroll_finance_mapping.md`
- `60_payroll_reports.md`

#### HR Phase 7 — Employee Portal
Execute tasks:
- `62_portal_auth_routes_layout.md`
- `63_portal_profile_requests.md`
- `64_portal_attendance_payroll.md`
- `65_portal_tasks_documents.md`
- `66_portal_submission_forms.md`
- `67_portal_notifications_status.md`
- `68_portal_permissions.md`

#### HR Phase 8 — HR Tasks
Build:
- migrations: `hr_tasks`, `hr_task_comments`, `hr_task_attachments`
- models: `Task`, `TaskComment`, `TaskAttachment`
- `TaskService`
- admin controller
- views under `resources/views/dashboard/hr/tasks/`
- permissions: `hr.tasks.view`, `hr.tasks.create`, `hr.tasks.assign`, `hr.tasks.close`

#### HR Phase 9 — HR Analytics
Execute tasks:
- `74_analytics_queries.md`
- `75_analytics_dashboard_views.md`
- `76_analytics_routes_permissions.md`

---

### FEAT-10 — Contract Renewal Alert (30-day warning)

**Referenced in:** `AI_SUPER_PROMPT.md` rule 20

**Build:**
1. Create `ContractExpiryAlertService`
2. Scheduled command (daily): query `hr_employee_contracts` where `end_date` is within 30 days
3. Create a notification for the HR manager
4. Optionally create an audit log entry
5. Register in `app/Console/Kernel.php` schedule

---

### FEAT-11 — Number Sequences: branch-scoped sequences for vouchers

**Defined in:** `35_number_sequences_and_period_validation.md`

**Build:**
1. Ensure `finance_receipt_vouchers` and `finance_payment_vouchers` use `NumberSequenceService`
2. Voucher number must be branch-scoped (each branch has its own counter)
3. Number sequence names must be configurable per voucher type
4. Validate no duplicate numbers exist after fix of BUG-03

---

### FEAT-12 — Balance Sheet Report

**Current state:** Income Statement exists. Balance Sheet does not.

**Build:**
Service: `app/Services/Finance/Reports/BalanceSheetService.php`

Logic:
- Assets section: accounts with type = `asset`, use closing_debit - closing_credit
- Liabilities section: accounts with type = `liability`, use closing_credit - closing_debit
- Equity section: accounts with type = `equity`, use closing_credit - closing_debit
- Net result from Income Statement carries into equity

Controller, view, route, permission: `reports.balance_sheet.view`

---

### FEAT-13 — Customer Aging Report

**Referenced in:** `erp_modules_map.md` (Sales module includes Aging Report in Reports module)

**Build:**
Service: `app/Services/Sales/Reports/AgingReportService.php`

Logic:
- Group unpaid/partially-paid invoices by customer
- Bucket by age: 0–30, 31–60, 61–90, 90+ days overdue
- Filter by branch, customer, as-of date

Controller, view, route, permission: `sales.reports.aging.view`

---

### FEAT-14 — Inventory: Stock Adjustment as signed movement

**Current state:** `stock_movements.movement_type` includes `adjustment` but
calculation rules say "depends on implementation strategy."

**Clarify and enforce:**
1. Add a `quantity_signed` concept OR use `movement_type` direction rules:
   - `in` → always positive
   - `out` → always negative (reject if would make stock negative if negative stock is disabled)
   - `adjustment` → can be positive or negative (add `direction` enum: `increase` / `decrease`)
2. Update `StockReportService` to handle signed adjustments
3. Update stock movement validation to require direction for adjustment type

---

### FEAT-15 — PDF Export for key documents

**Referenced in:** `AI_SUPER_PROMPT.md` (contract PDF generation)

**Build using existing PDF skill:**

Priority documents for PDF export:
1. Employee Contract (`hr_employee_contracts`)
2. Payroll Slip (per employee per month)
3. Invoice (sales invoice printable version)
4. Journal Entry (printable accounting voucher)

Use a `PdfExportService` base class.
Each document type extends it with its own template.
Routes: `GET /admin/hr/contracts/{id}/pdf`, etc.

---

### FEAT-16 — Excel Import for Attendance

**Referenced in:** `AI_SUPER_PROMPT.md` rule 23 and `31_attendance_overview.md`

**Build:**
1. Create `AttendanceImportService` using `maatwebsite/excel` or similar
2. Define expected Excel template columns: employee_code, date, check_in, check_out
3. Validate rows before insert, reject with error report if employee_code not found
4. Create `hr_attendance_import_batches` record per import
5. Admin UI: upload form, batch history list, error log per batch
6. Permission: `hr.attendance.import`

---

## PHASE 4 — ARCHITECTURE IMPROVEMENTS

These are code quality and consistency improvements, not new features.

---

### ARCH-01 — Standardize API response format for AJAX calls

Some views likely use AJAX (invoice line calculation, payroll net calculation).
Ensure all AJAX responses follow a single format:

```json
{
  "success": true,
  "data": {},
  "message": "OK"
}
```

Create a `JsonResponseTrait` usable in controllers.

---

### ARCH-02 — Consistent soft delete across all resource controllers

All resource controllers (finance, inventory, sales, HR masters) should:
1. Use `SoftDeletes` on models where data must not be permanently lost
2. Have a `restore` route
3. Show a `trashed` filter tab on index views
4. Permission: `module.resource.restore`

---

### ARCH-03 — Consistent `created_by` / `updated_by` auto-fill

All models with `created_by` / `updated_by` fields should auto-fill from `Auth::id()`.

Create a `RecordsAdminAudit` trait:
```php
protected static function bootRecordsAdminAudit(): void
{
    static::creating(fn ($m) => $m->created_by = Auth::id());
    static::updating(fn ($m) => $m->updated_by = Auth::id());
}
```

Apply to all relevant models.

---

### ARCH-04 — Global permission middleware assertion helper

Add a test helper method in a base test class:

```php
protected function assertRequiresPermission(string $method, string $url, string $permission): void
```

This reduces duplication across all 200+ permission test cases.

---

### ARCH-05 — Centralize status constants

Each model that has a `status` field currently uses inline strings.
Create enum-style PHP 8.1 Enums or const classes:

Examples:
- `app/Enums/JournalEntryStatus.php` → `DRAFT`, `POSTED`, `REVERSED`
- `app/Enums/InvoiceStatus.php` → `DRAFT`, `CONFIRMED`, `CANCELLED`
- `app/Enums/PayrollStatus.php` → `DRAFT`, `APPROVED`, `PAID`
- `app/Enums/VoucherStatus.php` → `DRAFT`, `APPROVED`, `POSTED`, `REVERSED`
- `app/Enums/ExpenseStatus.php` → `DRAFT`, `APPROVED`, `PAID_PARTIAL`, `PAID_FULL`, `CANCELLED`
- `app/Enums/HrRequestStatus.php` → `PENDING`, `APPROVED`, `REJECTED`, `CANCELLED`

Use these in models, services, and validation rules.

---

## PHASE 5 — PERMISSIONS AUDIT

---

### PERM-01 — Add missing permissions to seeder and map

The following permissions are referenced in task files but may be missing
from `permissions_map.md` and the `RolePermissionSeeder`:

```
finance.receipts.view
finance.receipts.create
finance.receipts.post
finance.receipts.reverse
finance.payments.view
finance.payments.create
finance.payments.post
finance.payments.reverse
finance.expenses.view
finance.expenses.create
finance.expenses.approve
reports.balance_sheet.view
reports.aging.view
reports.receipts.view
reports.payments.view
reports.expenses.view
reports.cash_movement.view
hr.departments.view
hr.departments.create
hr.departments.update
hr.departments.delete
hr.designations.view
hr.grades.view
hr.contract_types.view
hr.leave_types.view
hr.attendance.view
hr.attendance.import
hr.leaves.view
hr.leaves.approve
hr.loans.view
hr.loans.approve
hr.payroll.post
hr.payroll.eos
hr.tasks.view
hr.tasks.create
hr.tasks.assign
hr.dashboard.view
hr.reports.view
portal.profile.view
portal.requests.create
portal.requests.view
portal.attendance.view
portal.payroll.view
portal.tasks.view
```

**Action:**
1. Update `permissions_map.md` with all of the above
2. Add them all to `RolePermissionSeeder`
3. Run seeder after update

---

## PHASE 6 — FULL REGRESSION TEST SUITE

After all bugs are fixed and missing features are built:

---

### REGRESS-01 — Fix and re-run full test suite

Target: `151 passed, 36 failed, 1 risky` → target `0 failed`

Steps:
1. Fix BUG-01 through BUG-04 first
2. Run only the task-linked tests to confirm baseline passes
3. Address `FormSecurityTest`, `FormSubmissionTest`, `FormValidationTest` failures:
   - Align XSS/injection expectations with actual sanitization behavior
   - Align redirect expectations with localized route behavior
   - Align logout redirect with current middleware stack
4. Run full suite: `php artisan test`
5. Document any remaining known-acceptable failures separately

---

### REGRESS-02 — Add integration flow tests

These tests simulate real end-to-end business flows (from QA report Flow A–F):

File: `tests/Feature/Integration/ErpFlowTest.php`

Flows to test:
- Flow B: create account → create journal → create entry → post → check trial balance + general ledger
- Flow C: create warehouse → create item → create stock movement → check stock report
- Flow D: create customer → create order → create invoice → confirm → check sales report
- Flow E: create employee → create payroll → check net salary → check payroll summary
- Flow F: dashboard renders all KPI cards without exception

---

## EXECUTION ORDER SUMMARY

```
Phase 0 — Fix confirmed bugs
  BUG-01  Blade @enderror fix
  BUG-02  Cost Center routes missing
  BUG-03  Number sequence off-by-one
  BUG-04  Localization redirect in tests

Phase 1 — Environment fixes
  ENV-01  Apply pending migrations
  ENV-02  Storage link
  ENV-03  npm install + build
  ENV-04  Set Cairo timezone
  ENV-05  Re-seed permissions

Phase 2 — Missing test coverage
  TEST-01 through TEST-16

Phase 3 — Missing features
  FEAT-01  Soft delete restore for masters
  FEAT-02  Fiscal period strict validation
  FEAT-03  Invoice posting hook
  FEAT-04  Sales invoice collections
  FEAT-05  Expense payment auto-voucher
  FEAT-06  Receipt voucher full build
  FEAT-07  Payment voucher full build
  FEAT-08  Finance expansion reports
  FEAT-09  HR full expansion (phases 1–9)
  FEAT-10  Contract renewal alert
  FEAT-11  Voucher number sequences
  FEAT-12  Balance sheet report
  FEAT-13  Customer aging report
  FEAT-14  Stock adjustment direction
  FEAT-15  PDF export for key docs
  FEAT-16  Excel import for attendance

Phase 4 — Architecture improvements
  ARCH-01 through ARCH-05

Phase 5 — Permissions audit
  PERM-01  Add all missing permissions

Phase 6 — Full regression
  REGRESS-01  Fix and re-run full suite
  REGRESS-02  Integration flow tests
```

---

## RULES FOR AI EXECUTING THIS FILE

1. Execute one item at a time.
2. Stop after each item and wait for confirmation.
3. Do not modify existing working code unless fixing a confirmed bug.
4. Do not generate tests during feature build steps (feature build first, tests separately).
5. Follow the existing architecture: Controllers → Services → Models → Database.
6. Controllers stay thin.
7. All business logic goes in Services.
8. Validation uses FormRequest classes.
9. Use snake_case for all database names.
10. All translatable fields use HasTranslations and JSON column type.

---

*End of POST_ROADMAP_IMPROVEMENTS.md*
