# Full Repository Audit Report
Date: 2026-03-05
Project: AKRSera MLM ERP (Laravel)
Scope: routes, controllers, models, migrations, services, middleware, payments, MLM logic, wallet, orders, admin panel, DB query patterns

## Executive Summary
- Codebase is feature-rich and close to production shape in core MLM/wallet flow.
- High-risk issues remain in routing architecture, controller thickness, payment gateway standardization, missing policy mappings, and schema/index gaps for future scale.
- Several critical issues were already patched in this session before this report: idempotency hardening (payments/ledger), placement race conditions, tree cycle guards, withdrawal race locking, and OTP leak mitigation.

## Findings By Area

### 1. Routing
Severity: High
- Dynamic admin route prefix using `{adminSlug}` in `routes/admin.php` increases complexity and leaks route parameter into controller signatures.
- Admin routes are oversized (200+ lines) and not modularized.
- Middleware stack on admin group uses `auth, role:admin` but not `verified`.

### 2. Controllers
Severity: High
- Business logic remains in multiple controllers (notably `Admin/OrderController`, `Admin/FranchiseController`) with transaction and domain rules directly embedded.
- Some controller actions still depend on `$adminSlug` signature coupling.

### 3. Payment Gateway Layer
Severity: High
- Payment gateway schema currently uses `config_json`, `is_enabled`; does not include normalized `status`, `config`, `environment` fields requested for multi-env consistency.
- Razorpay flow in `Admin/RazorpayController` is partly SDK-driven but lacks strict request validation and centralized verification service usage.
- Gateway route binding uses default ID binding; operationally better to bind by `code`.

### 4. Wallet & Ledger
Severity: Medium
- User wallet ledger pattern is mostly correct (`wallet_transactions` immutable + references + transactional updates).
- Franchise wallet still uses direct scalar `franchises.wallet_balance` with transaction logs in `franchise_transactions` (acceptable for franchise domain but not fully normalized as ledger-first accounting).

### 5. MLM / Commission Engine
Severity: High
- `IncomeService` is a TODO (empty service).
- Commission logic is split across matching/binary + franchise commission services but lacks unified `CommissionEngine` API requested.
- Event-driven commission flow is incomplete/fragmented and lacks a dedicated commission ledger table.

### 6. Binary Tree / Member Structure
Severity: Medium
- Existing fields are `placement_parent_id` and `placement_leg`; requested `placement_id`, `position`, `left_count`, `right_count` are missing.
- Sponsor index exists implicitly in some cases but explicit future-proof indexing for new columns is missing.

### 7. Database & Query Efficiency
Severity: Medium
- Some heavy queries use broad `get()` in admin/export/service paths.
- Required high-load indexes for future growth are partially present but not complete for requested schema.

### 8. Fraud Detection
Severity: High
- No dedicated fraud log table for cross-signal risk events (IP/device/KYC/bank collision evidence).

### 9. Security Layer
Severity: Medium
- CSRF and throttling exist; policy mappings are empty.
- Admin routes should consistently enforce `verified` where applicable.

### 10. Queue / Async
Severity: Medium
- Queue jobs exist and `database` queue works.
- No dedicated async commission pipeline job for order-approval post-processing.

## Risk Prioritization
P0
- Route architecture + `$adminSlug` coupling
- Payment gateway hardening + schema normalization
- Missing unified commission engine
- Missing fraud log framework

P1
- Policy mapping and route middleware tightening
- Additional indexes and tree schema compatibility columns
- Controller-to-service/repository decomposition

P2
- Query pagination and cleanup of non-critical `get()` usage in non-export flows
- Naming/consistency/PSR cleanup pass

## Refactor Plan (Applied Next)
1. Modularize admin routes and replace dynamic slug with config-driven prefix.
2. Create architecture folders (`Repositories`, `Actions`, `Policies`) and move gateway/order business logic into service/repository layers.
3. Harden payment gateway verification and route model binding by `code`.
4. Implement `CommissionEngine` service and event-driven order approval commission processing.
5. Add fraud logs + service hooks.
6. Add compatibility migrations for tree columns and required indexes.
7. Enforce stronger admin middleware and policy registration.

## Note
This report is generated from repository-wide static and manual high-risk flow analysis. It is followed by concrete safe refactors preserving backward compatibility.

## Correction Execution Summary (Applied)
Date Applied: 2026-03-05

### Routing and Middleware
- Replaced dynamic admin prefix with config-driven prefix (`config('app.admin_slug', 'admin')`).
- Split admin routes into modules and restored all admin view route names.
- Added missing modules: `routes/admin/settings.php`, `routes/admin/misc.php`.
- Enforced admin middleware stack with `auth`, `verified`, and `role:admin`.
- Verified route registration (`php artisan route:list`), including middleware for `admin.dashboard`.

### Architecture and Refactor Scaffolding
- Added architecture layers: `app/Repositories`, `app/Actions`, `app/Policies`.
- Added repositories/actions for gateway, payment transaction and order approval event dispatch.
- Added policy registration in `AuthServiceProvider` and event mapping in `EventServiceProvider`.

### Payment Gateway Hardening
- Added secure Razorpay signature verification action usage in admin pay-in flow.
- Normalized gateway handling through repository and code-based route binding.
- Added backward-compatible route key behavior on `PaymentGateway` (`code`).
- Added missing `admin.razorpay.payout` endpoint to prevent broken route in existing view (returns guarded message).
- Added gateway UI fields for `environment` and `webhook_secret`.

### Wallet / Commission / Fraud Controls
- Added `CommissionEngine` event-driven flow via `OrderApprovedEvent` listener.
- Added `CommissionLedger` model integration with wallet credits and safety caps.
- Added `FraudDetectionService` hooks to login/registration/KYC surfaces.
- Added `FraudLog` model integration.

### Schema and Index Hardening
- Added migration: `create_fraud_logs_table`.
- Added migration: `create_commission_ledgers_table`.
- Added migration: `normalize_payment_gateways_table` (`status`, `environment`, `config` with backfill).
- Added migration: `add_tree_columns_and_audit_indexes` (compatibility tree columns + high-load indexes).

### Compatibility and Config
- Added `admin_slug` to app config and `.env.example` (`ADMIN_SLUG`).
- Updated `AppServiceProvider` to hydrate `app.admin_slug` from settings table at runtime.
- Set queue fallback default to `database` in `config/queue.php`.

### Stability Verification
- Project-level syntax check passed (`app`, `routes`, `database`, `config`, `tests`).
- Test suite passed: 37/37.

## Residual Risks / Remaining Work
- Some large controllers (notably `Admin\OrderController`, `Admin\FranchiseController`) still contain substantial business logic and should be decomposed further into services/actions for full clean-architecture compliance.
- Legacy `EnsureAdminSlug` middleware remains registered in kernel but is not required by current admin route stack.
- Franchise wallet domain still uses scalar balance + transaction table model rather than immutable ledger-first reconciliation equivalent to user wallet design.
