# Codebase Architecture & Domain Workflow Analysis

*This document is generated by directly analyzing the PHP source files, Eloquent model triggers, database query builders, and backend services, bypassing static documentation.*

---

## 1. System Execution Scaffolding

The application operates as a **monolithic Laravel 12 portal** with role-based routing partitions, using Inertia.js to render a Vue 3 SPA frontend. It is structured around a service-oriented backend architecture where business transactions are extracted into dedicated service classes.

```mermaid
graph TD
    UserClient[Vue 3 SPA client] -->|Auth Session / Sanctum API| WebRoutes[routes/web.php & routes/api.php]
    WebRoutes -->|Role Middleware validation| Controllers[Http Controllers Admin, Customer, Seller]
    Controllers -->|Transactional Execution| Services[Services CustomerPurchase, Payment, Wallet, Reservation]
    Services -->|Persist State| Models[Eloquent Models Vehicle, Order, Payment, Reservation]
    Models -->|Emit Events saving/saved/creating| Observers[Model boot Lifecycle Hooks]
```

### Authentication & Role Isolation
Middleware filters requests in [routes/web.php](file:///d:/Git%20Clone/jetstream-app/routes/web.php) under three distinct roles:
1.  **Customer (`role:customer`)**: Manages consignee/remitter profile data, shopping cart checkout, and payment allocations.
2.  **Seller (`role:seller`)**: CRUD access to owned vehicle inventory, custom customer creations, offline-to-online reservations, and ledger credit updates.
3.  **Admin (`role:admin`)**: Configuration control over pricing rules, ports, shipping rates, global attributes, and wire transfer approvals.

---

## 2. Low-Level Database Schema & Domain Layers

The database consists of 40 Eloquent models mapped across five primary functional domains. 

### A. Core Inventory Domain
*   `Vehicle`: Represents a marketplace listing. Uses boot observers to dynamically sync text fields `make` and `model` from `make_id` and `model_id` relations on save. Automatically calculates `price_with_discount` (taking `discount_amount` into account) and maps its route key through a base64/hashed slug generator.
*   `VehicleImage` & `VehicleDocument`: Store asset media and files (mime-type restricted: pdf, png, jpeg, jpg).

### B. EAV (Entity-Attribute-Value) Specification Catalog
Instead of adding columns to the `vehicles` table, the platform implements an EAV schema:
*   `Make` & `VehicleModel`: Standard catalog taxonomy tables.
*   `VehicleAttribute`: Defines attribute schema. Supported types are: `select`, `multi_select`, `range`, `boolean`.
*   `AttributeValue`: Allows selecting values for `select` or `multi_select` attributes.
*   `ModelAttribute` & `MakeAttribute`: Defines which attributes apply to a make/model, mapping default values (`default_value` JSON) and constraint limits (`min_value`, `max_value`).
*   `VehicleAttributeValue`: Per-vehicle stored specification values, linking `vehicle_id` and `attribute_id` to either a `value_id` (dictionary key) or a `raw_value` (ranges/booleans).

### C. Commerce & Checkout Domain
*   `Cart`: Customer-held basket item mapping `user_id` and `vehicle_id` via a composite unique key.
*   `Order`: Main historical ledger. It locks prices and address structures at transaction time, preserving customer consignee and remitter details on snapshot columns to ensure orders are immutable.
*   `OrderItem`: Represents order items, linking orders and vehicles.
*   `VehicleReservation`: Represents a customer reservation. Contains custom price variables: `admin_price` (wholesale/auction cost), `commission_amount` (seller markup), and `seller_price` (sum price charged to customer).

### D. Payments & Financial Transactions
*   `Payment`: Stores gateway and wire transactions. Methods: `card` (processed via `PaymentGatewayService` Stripe integration) and manual `bank_transfer` (supports `payment_proof` uploading).
*   `PaymentAllocation`: Maps payments to specific orders or vehicle list items.
*   `WalletTransaction`: Customer digital currency ledger tracking `credit` and `debit` operations.
*   `RemittanceAllocation`: Allocates wallet debits back to specific credited bank wires.
*   `Remittance`: Wire transfers uploaded by sellers on behalf of customers.

---

## 3. End-to-End Core Workflows

### Workflow 3.1: Auction Car Intake & Product Readiness

```
[Admin registers AuctionCar]
          │
          ▼
[AuctionVehicleSyncService::syncMinimalVehicle()]
          │
          ▼
[Generates Vehicle: status = draft, is_locked = 1, is_ready_for_sale = 0]
          │
          ▼
[Admin or Seller fills specs using dynamic EAV forms]
          │
          ▼
[Vehicle::syncDynamicAttributes() stores values & mirrors deprecated columns]
          │
          ▼
[Published to public catalog (status = published, is_ready_for_sale = 1)]
```

1.  **Registration**: Admin registers a vehicle in the `auction_cars` table with an acquisition price, chassis number, and destination country.
2.  **Initialization**: `AuctionVehicleSyncService::syncMinimalVehicle()` checks if a vehicle exists with the matching `auction_car_id`. If not, it creates a new record:
    - Sets `status` to `draft`, `is_locked` to `true`, and `is_ready_for_sale` to `false`.
    - Generates a unique record identifier using `Vehicle::generateRecNo()` (format: `XX-9999`).
    - Mirrors text values `make` and `model` from normalized relationships.
3.  **Attribute Templating**: When editing the listing, the form queries `ModelAttributeController` to fetch specifications corresponding to the `model_id`.
4.  **Serialization**: On submit, the system calls `Vehicle::syncDynamicAttributes($attributes)`. This deletes previous records in `vehicle_attribute_values` and creates new rows mapping input selections.
5.  **Backward Compatibility Hook**: The model automatically triggers `syncDeprecatedCatalogColumns()` and `syncEngineCapacityColumn()` during save. These methods extract EAV values (e.g., "Color", "Fuel Type", "Engine CC") and update the legacy columns in the `vehicles` table to prevent breaking older database endpoints.

---

### Workflow 3.2: Reservation Mechanics (Offline/Online Lock)

```
[Seller reserves vehicle for Customer]
          │
          ▼
[VehicleReservationService::reserveForCustomer()]
          │
          ▼
[Sets Vehicle status = reserved & is_locked = 1]
          │
          ▼
          ├────────── (Checkout / Payment within 3 Days) ──────────┐
          │                                                        │
          ▼                                                        ▼
[Checkout fails/expires]                                  [Checkout completed]
          │                                                        │
          ▼                                                        ▼
[expires_at passes / released]                            [Reservation status = Converted]
          │                                                        │
          ▼                                                        ▼
[Vehicle returned to catalog (status = published)]         [Seller seller_id assigned to Vehicle]
```

1.  **Initiation**: A seller submits a reservation for a customer using `VehicleReservationService::reserveForCustomer()`.
2.  **Validation Check**: The system executes `guardNoDuplicateReservation()` to verify no other active reservations (`status: active`, `status: pending_approval`, or `status: converted`) exist for the target vehicle.
3.  **Inventory Locking**:
    - The vehicle's `status` is updated to `reserved` and `is_locked` is set to `1` (which filters it out from the public homepage search builder).
    - Sets `expires_at` using the `reservation_expiry_days` setting (defaults to 3 days).
4.  **Seller Pricing Split**: Sets the wholesale cost (`admin_price`), seller commission (`commission_amount`), and the final buyer price (`seller_price` $= \text{admin\_price} + \text{commission\_amount}$).
5.  **Expiration Handler**: Every new reservation triggers `expireStaleForTarget()`, which sets expired reservations' status to `expired`. The vehicle's `status` is reset to `available` and `is_locked` is set to `0` to make it browseable again.

---

### Workflow 3.3: Customer Cart Checkout & CIF formulation

```
                        [Customer clicks Buy on Checkout page]
                                          │
                                          ▼
                [Verify stock_status = available & Check Reservations]
                                          │
                                          ▼
                 [ShippingService::calculate() returns Quote]
                 - Resolves freight cost from shipping_rates matrix
                 - Resolves inspection/insurance from pricing_rules
                                          │
                                          ▼
                      [Generate Pricing & Deposit Calculations]
                      - Price = base + freight + inspection + insurance (CIF Total)
                      - Minimum deposit = 30% of CIF total
                                          │
                                          ▼
                     [CustomerPurchaseService::createVehiclePurchase()]
                     - Deducts wallet balance (if selected)
                     - Creates pending Payment (if bank wire)
                     - Writes Order snapshot (locking CIF & address details)
```

1.  **Integrity Lock**: `CustomerPurchaseService::createVehiclePurchase()` locks the `vehicles` row in the database using `lockForUpdate()`. It verifies that `stock_status` is `available` and that no conflicting reservation exists.
2.  **Shipping & Markup Formulas**: The system calls `ShippingService::calculate()`. It:
    - Finds the base freight rate in `shipping_rates` based on target `country_id`, `port_id`, `vehicle_type`, and `shipping_type` (RORO or Container).
    - Fetches markup rules via `resolvePricingRule()`.
    - Computes inspection and insurance fees using `resolveRuleAmount()`. Rules configured as `percentage` calculate fees relative to (Vehicle Price + Freight). Fixed rules use a flat rate.
3.  **Deposit Calculation**: `PricingService::calculateDepositData($cifTotal)` calculates the required deposit (configured in `deposit_settings`, defaulting to 30%).
4.  **Creation**:
    - Creates an `Order` using `Order::create()`.
    - Captures a snapshot of all pricing details (`vehicle_price`, `freight_cost`, `inspection_fee`, `insurance_fee`, `cif_total`, `deposit_percentage`, `min_deposit_amount`).
    - Snapshots consignee/remitter details directly onto the order to ensure historical immutability.
    - Creates a corresponding `OrderItem` mapping the vehicle to the order.
    - Sets the vehicle's `stock_status` to `sold` and `status` to `reserved`.

---

### Workflow 3.4: Payment Reconciliation & Ledger Auditing

Reconciliation is managed through `PaymentService` to track partial payments, bank wires, card payments, and wallet allocations:

```
[Approved payment verified by Admin]
               │
               ▼
[PaymentService::updatePaymentStatus($payment, 'completed')]
               │
               ▼
[createAllocationsForPayment() generates PaymentAllocation logs]
               │
               ▼
[syncOrderPaymentTotals() updates Order paid_amount & remaining_balance]
               │
               ▼
[Check balance status]
               │
               ├─► Balance > 0  ──► [Order status = payment_pending]
               │
               └─► Balance <= 0 ──► [Order status = paid, Vehicle status = sold]
```

1.  **Wire Verification**: Customer uploads a deposit slip. A `Payment` record is logged as `status: pending`. Once the admin approves the transfer, the controller calls `PaymentService::updatePaymentStatus($payment, 'completed')`.
2.  **Allocation**: The payment's `amount` is converted into a `PaymentAllocation` row. If the payment was made with a digital wallet, the amount is debited via `WalletService::debit()` and linked using `RemittanceAllocation`.
3.  **Ledger Reconciliation**:
    - `PaymentService::syncOrderPaymentTotals()` compiles all completed payments.
    - It adjusts `paid_amount` and decreases `remaining_balance`.
    - If `remaining_balance <= 0`, the order is marked `status: paid` and the linked vehicle is updated to `status: sold`.
    - Active reservations are automatically converted to `converted` (released from locking rules).

---

### Workflow 3.5: Ledger-Based Digital Wallet & FIFO Allocation
The digital wallet uses an auditing system to map debits to the specific credits that funded them:

```
[Wallet Debit Requested] ──► [Verify Balance >= Debit Amount] ──► [FIFO Credit Selection Query]
                                                                                │
                                                                                ▼
[Debit completed] ◄── [RemittanceAllocation maps allocation to debit] ◄── [Allocate amount via FIFO]
```

1.  **Deduction Validation**: `WalletService::debit()` locks wallet transactions for the user. It calculates the user's balance (`credits` - `debits`) and throws an exception if the balance is insufficient.
2.  **FIFO Querying**:
    - Queries all credit transactions (`type: credit`).
    - Sorts transactions by priority: oldest priority date (derived from the bank remittance's `received_date`) first, falling back to the `created_at` timestamp and transaction ID.
3.  **Consumption Logic**:
    - Computes the remaining unallocated balance for each credit transaction by subtracting its allocated debits (`RemittanceAllocation` sum).
    - Allocates the debit amount across credit sources starting from the oldest available credit.
    - Creates a `RemittanceAllocation` row for each slice, linking `credit_wallet_transaction_id` and `debit_wallet_transaction_id` to maintain a clear audit trail.

---

## 4. Key Services Directory

| Service Class | Source Path | Core Operations |
| :--- | :--- | :--- |
| **CustomerPurchaseService** | [CustomerPurchaseService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/CustomerPurchaseService.php) | Orchestrates checkout, CIF price locking, snapshot validation, and wallet integration. |
| **PaymentService** | [PaymentService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/PaymentService.php) | Manages payment allocations, ledger reconciliation, order balance updates, refunds, and gateway mapping. |
| **ShippingService** | [ShippingService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/ShippingService.php) | Computes freight quotes based on vehicle type and shipping method. Maps geographic routes. |
| **VehicleReservationService**| [VehicleReservationService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/VehicleReservationService.php) | Controls time-bound vehicle reservations, reservation expirations, and custom seller prices. |
| **VehicleFilterService** | [VehicleFilterService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/VehicleFilterService.php) | Generates dynamic faceted search queries for EAV attributes, price brackets, and countries. |
| **AuctionVehicleSyncService**| [AuctionVehicleSyncService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/AuctionVehicleSyncService.php) | Manages the translation pipeline between auction acquisitions and draft listings. |
| **OrderService** | [OrderService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/OrderService.php) | Handles order creations, state transitions, and backwards-compatibility mapping. |
| **WalletService** | [WalletService.php](file:///d:/Git%20Clone/jetstream-app/app/Services/WalletService.php) | Computes ledger balances, records transactions, and allocates debits to credits using a FIFO algorithm. |
