# Prolex Technical Documentation

This document provides a comprehensive technical overview of the Prolex system, encompassing its database schema, core workflows, architectural design, and developer setup instructions.

## Table of Contents
1. [Core Module Breakdown](#1-core-module-breakdown)
2. [The Matter Lifecycle](#2-the-matter-lifecycle)
3. [Full Billing Workflow](#3-full-billing-workflow)
4. [Lexa AI Architecture](#4-lexa-ai-architecture)
5. [Security & RBAC Model](#5-security--rbac-model)
6. [Accounting ERP Logic & ERD](#6-accounting-erp-logic--erd)
7. [System Maintenance & Configuration](#7-system-maintenance--configuration)
8. [Database Catalog](#8-database-catalog)
9. [Developer Onboarding Guide](#9-developer-onboarding-guide)

---

## 1. Core Module Breakdown

### Case Management
- **Workflow**: Create Matter -> Define Case Type/Category -> Assign Lawyers -> Track Status.
- **Rules**: Matter numbers are auto-generated based on firm prefixes. Leads cannot be deleted if active cases exist.
- **Key Entity**: `Matter` is the parent; `LegalCase` handles specific litigation/advisory details.

### Accounting (ERP)
- **Workflow**: Chart of Accounts setup -> Journal Entry -> Ledger Posting.
- **Rules**: Double-entry is strictly enforced via `journal_lines` (Total Debits must equal Total Credits). Control accounts (Parent GL) aggregate Sub-account balances.
- **Trust Control**: Mixed trust/business transactions are prohibited; trust funds must specifically move via `trust_transfers`.

### Billing
- **Workflow**: Time Recording -> Quotation -> Invoice -> Receipt.
- **Rules**: Invoices are derived from `Tariffs` (Hourly, Fixed, or Per-Appearance). Discounting is capped by system settings. 

### Lexa AI
- **Workflow**: User input -> LexaController -> AI Backend -> History Record.
- **Rules**: Conversations are gated by `lexa_chat_settings` (max tokens, session timeout). History is stored persistently for audit.

---

## 2. The Matter Lifecycle

The lifecycle of a **Matter** is the core of the Prolex system's data flow.

1.  **Ingestion & Conflicts**: A conflict search is performed against existing clients and parties.
2.  **Creation**: A Matter record is created. 
    - **Trigger**: `Matter::creating` event calls `DocumentNumberHelper::nextMatterNumber()` to generate a unique firm-wide identifier (e.g., `MAT-2026-001`).
3.  **Assignment**: Lead and associate lawyers are assigned via the `matter_lawyers` pivot table.
4.  **Work (Case Linkage)**: One or more `LegalCase` records are linked to the Matter. Time-logs (`tariff_time_logs`) are recorded against these cases.
5.  **Billing Cycle**: WIP (Work-In-Progress) is tracked via the `vw_unbilled_wip` view. Once ready, WIP is converted into Invoices.
6.  **Resolution**: Upon legal conclusion, a `MatterOutcome` is recorded.
7.  **Archiving**: The status is updated to `Closed`. Logic prevents archiving if unpaid invoices or open trust balances remain.

---

## 3. Full Billing Workflow

The billing engine moves through four distinct states.

### Step A: Quotation
- **Action**: Generated by `ClientQuotationController`.
- **Status**: `draft` -> `sent`.
- **Technical Note**: Lines utilize `Tariff` snapshots to ensure price volatility doesn't affect sent quotes.

### Step B: Invoicing
- **Action**: Converting a Quote or WIP into a `ClientInvoice`.
- **Status**: `draft` -> `sent`.
- **Logic**: The `ModuleController::storeClientInvoice` calculates tax per line item, disbursement totals, and generates a PDF via `DomPDF`.

### Step C: Receipting
- **Action**: Staff records a `ClientReceipt`.
- **Status**: `draft` -> `processed`.
- **Workflow**: Receipt lines are allocated to outstanding invoices (`applyReceiptLinesToInvoices`).

### Step D: Trust Disbursement
- **Trigger**: `applyTrustEffectForReceipt`
- **Logic**: If the payment method is `trust_transfer`, the system automatically moves funds from the `TrustAccount` to the `BusinessAccount`, creating a `trust_transfers` record and balancing the `trust_ledger_entries`.

---

## 4. Lexa AI Architecture

Lexa AI is designed as a stateless AI agent with stateful database persistence.

- **Frontend**: A Vue.js interactive chat interface (`lexa.index`).
- **Controller**: `LexaController::chat` method.
- **Model Selection**: Uses a prioritized fallback list:
  1.  Hugging Face Router (`https://router.huggingface.co/v1`)
  2.  Hugging Face Inference (`https://api-inference.huggingface.co/models/...`)
  3.  Google Gemini (via `GeminiService.php`)
- **Persistence**: 
    - **Session**: `lexa_conversations` (Title, Token counts, Active status).
    - **History**: `lexa_chat_history` (Role, Message, Tokens, Latency).

---

## 5. Security & RBAC Model

The Role-Based Access Control (RBAC) model is evaluated at runtime during every request.

### Evaluation Hierarchy
1.  **User Overrides**: If a specific `UserPermission` exists for a feature, it takes precedence.
2.  **Tier Permissions**: If no user override, the system checks `user_tiers` (e.g., Senior Management, Junior Clerk).
3.  **Group Permissions**: If no tier, the `user_groups` default permissions are applied.
4.  **Feature Defaults**: Finally, if none of the above are set, the system uses the default settings in the `permission_features` table.

### Middleware Stack
Every protected route passes through:
1.  `Authenticate`: Evaluates the Laravel session.
2.  `FeaturePermissionMiddleware`: Resolves the "Feature Slug" and calls `PermissionResolverService::hasPermission`.

---

## 6. Accounting ERP Logic & ERD

### General Ledger Structure
The system uses a parent-subaccount hierarchy to manage the Chart of Accounts (COA).
- **Parent Account** (`general_ledger_parent_accounts`): Defines the control group and financial category (Assets, Liabilities, Equity, Income, Expenses).
- **Sub-Account** (`general_ledger_subaccounts`): The posting-level account where actual transactions are recorded.

### Transaction Core (ERD Level)
- **Journal Header**: Contains the transaction metadata (Date, Reference, Narration).
- **Journal Line**: The atomic entry. Every header has at least two lines.
- **Relationship**: `JournalHeader (1) <-> (N) JournalLine (N) <-> (1) GeneralLedgerSubaccount (N) <-> (1) GeneralLedgerParentAccount`.

---

## 7. System Maintenance & Configuration

### Error Handling
Prolex utilizes Laravel 12's streamlined exception handling in `bootstrap/app.php`.
- **Logging**: Uses the `stack` driver, logging to `storage/logs/laravel.log`.

### Multi-tenancy & Firm Configuration
- **Architecture**: The system is **Single-Firm**.
- **Configuration**: Managed via the `law_firm_information` table.

---

## 8. Database Catalog

### Functional Groups
- **Legal**: `matters`, `cases`, `clients`, `lawyers`, `judges`, `courts`.
- **Accounting**: `general_ledger_parent_accounts`, `general_ledger_subaccounts`, `journal_headers`, `journal_lines`, `trust_accounts`.
- **Billing**: `client_quotations`, `client_invoices`, `client_receipts`, `tariffs`, `taxes`.
- **Communication**: `chat_rooms`, `chat_messages`, `lexa_conversations`.
- **Diary**: `diary`, `diary_reminders`, `diary_attachments`.

### SQL Views
| View Name | Purpose |
| :--- | :--- |
| `vw_active_tariffs` | Currently billable rates |
| `vw_invoice_detail` | Detailed invoice breakdown |
| `vw_lawyer_earnings` | Profitability by lawyer |
| `vw_outstanding_invoices` | Aging analysis |
| `v_gl_subaccount_display` | Human-readable COA hierarchy |

---

## 9. Developer Onboarding Guide

### Prerequisites
- **PHP 8.2+**, **Composer**, **Node.js (v18+)**, **SQLite**.

### Initialization
```bash
composer install
npm install
cp .env.example .env
php artisan key:generate
touch database/database.sqlite
php artisan migrate --seed
```

### Running the App
```bash
# Terminal 1
php artisan serve
# Terminal 2
npm run dev
```

---
*Analysis generated by Antigravity AI - 2026-04-22*
