# 🏗️ Multi-Currency & FX Module — Full System Analysis

## 📋 Document Purpose
Map the customer's "CarServPro Full Product Pricing, Multi-Currency Inventory, Treasury, FX, AP/AR" requirements against the **existing** CarServPro POS system, determine what already exists, what needs a **new module**, and what **minimal changes** are needed in existing files.

---

## 1. What the Customer Actually Wants (Distilled)

The requirements doc is 868 lines long and written in an enterprise-vision style. After cross-referencing with the **actual Arabic voice-note summary** at the bottom (lines 849-868), the **real, actionable requirements** are:

### 🎯 Core Functional Requirements

| # | Feature | Priority |
|---|---------|----------|
| 1 | **Activate multiple foreign currencies** (USD, EUR, SAR, AED) alongside EGP base | P0 |
| 2 | **Exchange rates**: Official (API) + Parallel/Black Market (manual field) | P0 |
| 3 | **Currency conversion (internal transfer)**: Convert FC ↔ Local cash in treasury | P0 |
| 4 | **Purchasing in FC**: Select currency when creating a purchase, store cost in both FC and EGP | P0 |
| 5 | **Selling in FC or EGP**: POS/Direct Sale can bill in foreign currency | P1 |
| 6 | **Receive payment from client in FC** | P1 |
| 7 | **Pay supplier in FC** (including advance payments) | P1 |
| 8 | **Client advance payments (deposits) in FC** | P1 |
| 9 | **Supplier advance payments in FC** | P1 |
| 10 | **Opening balances in FC** (Treasury already has opening balance feature) | P2 |
| 11 | **Product dual-currency cost tracking** (Foreign cost + EGP cost) | P2 |
| 12 | **Dynamic FX pricing** (auto-update selling price when rate changes) | P3 |
| 13 | **FX Gain/Loss tracking** | P3 |
| 14 | **Margin protection alerts** | P3 |
| 15 | **Currency wallets per branch** | P3 |

### ❌ Out of Scope / Future (Not in voice note, only in vision doc)
- AI Financial Optimization
- Full AP/AR accounting module (system already has contact ledger)
- Treasury weighted average costing for currency
- Landed cost automation

---

## 2. Current System Analysis — What Already Exists

### ✅ Currency Infrastructure (Partial)

| Component | Status | Details |
|-----------|--------|---------|
| `currencies` table | ✅ Exists | Fields: `country`, `currency`, `code`, `symbol`, `thousand_separator`, `decimal_separator` |
| `Currency` model | ✅ Exists | [Currency.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Currency.php) — empty model, no relationships |
| `business.currency_id` | ✅ Exists | Base currency for the business |
| `business.purchase_currency_id` | ✅ Exists | Optional separate purchase currency |
| `transactions.exchange_rate` | ✅ Exists | `decimal(8,3)` default 1 — already on every transaction |

### ✅ Treasury Module (Exists)

| Component | Status | Details |
|-----------|--------|---------|
| Treasury Dashboard | ✅ Full | [TreasuryController.php](file:///d:/pos-main/altrapos/new_pos/pos/Modules/Treasury/Http/Controllers/TreasuryController.php) — 1374 lines |
| Internal Transfers | ✅ Full | Payment method → Payment method transfers (same currency) |
| Opening Balances | ✅ Full | Treasury opening balance support |
| Due Transaction Tracking | ✅ Full | With SMS reminders |
| Service Architecture | ✅ Clean | Services + Repository + Validation layers |
| Sidebar Menu | ✅ Registered | In [AdminSidebarMenu.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Http/Middleware/AdminSidebarMenu.php) at line 964 |

### ✅ Transaction System

| Component | Status | Details |
|-----------|--------|---------|
| `Transaction` model | ✅ Full | [Transaction.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Transaction.php) — types: purchase, sell, expense, etc. |
| `TransactionPayment` model | ✅ Full | [TransactionPayment.php](file:///d:/pos-main/altrapos/new_pos/pos/app/TransactionPayment.php) — payment methods, accounts |
| `Contact` model | ✅ Full | [Contact.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Contact.php) — supplier/customer/both |
| Payment status tracking | ✅ Full | paid, due, partial, overdue |

### ✅ Product System

| Component | Status | Details |
|-----------|--------|---------|
| `Product` model | ✅ Full | [Product.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Product.php) — categories, brands, variations |
| `Variation` model | ✅ Full | [Variation.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Variation.php) — pricing per variation |
| Selling Price Groups | ✅ Exists | `VariationGroupPrice` — could be leveraged for FC pricing |

### ❌ What Does NOT Exist

| Gap | Impact |
|-----|--------|
| No **multi-currency rate management** (official/parallel/negotiated) | Need new tables + UI |
| No **currency selection on transactions** (buy/sell screen has no FC selector) | Need blade + controller changes |
| No **FC wallets in treasury** (current treasury tracks payment methods, not currencies) | Need new tables |
| No **FC on payments** (TransactionPayment has no currency field) | Need migration |
| No **product dual-currency cost** (Variation stores `default_purchase_price` and `dpp_inc_tax` in base currency only) | Need migration or new table |
| No **exchange rate history** | Need new table |
| No **FX gain/loss calculation** | Need new service |
| No **dynamic repricing engine** | Need new service |

---

## 3. Proposed Architecture — New `MultiCurrency` Module

### Module Name: `MultiCurrency`
### Module Path: `Modules/MultiCurrency/`

> [!IMPORTANT]
> The new module will be **self-contained** for all FX/multi-currency logic. It will only make **surgical additions** to existing blades and controllers via hooks, never modifying core business logic.

### 3.1 Module Structure

```
Modules/MultiCurrency/
├── Config/
│   └── config.php
├── Database/
│   ├── Migrations/
│   │   ├── 2026_05_03_000001_create_mc_exchange_rates_table.php
│   │   ├── 2026_05_03_000002_create_mc_exchange_rate_history_table.php
│   │   ├── 2026_05_03_000003_create_mc_currency_wallets_table.php
│   │   ├── 2026_05_03_000004_create_mc_wallet_transactions_table.php
│   │   ├── 2026_05_03_000005_create_mc_fx_conversions_table.php
│   │   ├── 2026_05_03_000006_add_currency_fields_to_transactions.php
│   │   ├── 2026_05_03_000007_add_currency_fields_to_transaction_payments.php
│   │   ├── 2026_05_03_000008_create_mc_product_currency_costs_table.php
│   │   ├── 2026_05_03_000009_add_default_currency_to_contacts.php
│   │   └── 2026_05_03_000010_create_mc_fx_gain_loss_table.php
│   └── Seeders/
├── Entities/
│   ├── ExchangeRate.php
│   ├── ExchangeRateHistory.php
│   ├── CurrencyWallet.php
│   ├── WalletTransaction.php
│   ├── FxConversion.php
│   ├── ProductCurrencyCost.php
│   └── FxGainLoss.php
├── Http/
│   ├── Controllers/
│   │   ├── ExchangeRateController.php
│   │   ├── CurrencyWalletController.php
│   │   ├── FxConversionController.php
│   │   ├── ProductFxController.php
│   │   └── FxReportController.php
│   └── Middleware/
├── Providers/
│   ├── MultiCurrencyServiceProvider.php
│   └── RouteServiceProvider.php
├── Resources/
│   ├── lang/
│   │   ├── en/
│   │   └── ar/
│   └── views/
│       ├── exchange_rates/
│       ├── wallets/
│       ├── conversions/
│       ├── reports/
│       └── partials/
│           ├── currency_selector.blade.php      ← reusable dropdown
│           ├── rate_display.blade.php           ← inline rate widget
│           └── product_fx_fields.blade.php      ← inject into product form
├── Routes/
│   ├── web.php
│   └── api.php
├── Services/
│   ├── ExchangeRateService.php
│   ├── CurrencyConversionService.php
│   ├── FxGainLossService.php
│   └── DynamicPricingService.php
├── module.json
└── composer.json
```

---

## 4. Database Schema Design

### 4.1 New Tables (Inside Module)

#### `mc_exchange_rates` — Active rates per currency pair
```sql
CREATE TABLE mc_exchange_rates (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    business_id     INT UNSIGNED NOT NULL,
    currency_id     INT UNSIGNED NOT NULL,         -- FK → currencies.id (the foreign currency)
    base_currency_id INT UNSIGNED NOT NULL,        -- FK → currencies.id (EGP usually)
    rate_type       ENUM('official','parallel','negotiated','treasury_cost') NOT NULL,
    buy_rate        DECIMAL(20,6) NOT NULL,        -- How much base currency to BUY 1 FC
    sell_rate       DECIMAL(20,6) NOT NULL,        -- How much base currency to SELL 1 FC
    source          VARCHAR(50) DEFAULT 'manual',  -- 'api', 'manual'
    is_active       TINYINT(1) DEFAULT 1,
    set_by          INT UNSIGNED NULL,             -- FK → users.id
    created_at      TIMESTAMP,
    updated_at      TIMESTAMP,
    INDEX(business_id, currency_id, rate_type)
);
```

#### `mc_exchange_rate_history` — Historical locked rates
```sql
CREATE TABLE mc_exchange_rate_history (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    business_id     INT UNSIGNED NOT NULL,
    currency_id     INT UNSIGNED NOT NULL,
    rate_type       VARCHAR(30) NOT NULL,
    buy_rate        DECIMAL(20,6) NOT NULL,
    sell_rate       DECIMAL(20,6) NOT NULL,
    source          VARCHAR(50),
    effective_date  DATE NOT NULL,
    set_by          INT UNSIGNED NULL,
    created_at      TIMESTAMP,
    INDEX(business_id, currency_id, effective_date)
);
```

#### `mc_currency_wallets` — Branch currency wallets
```sql
CREATE TABLE mc_currency_wallets (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    business_id     INT UNSIGNED NOT NULL,
    location_id     INT UNSIGNED NOT NULL,          -- FK → business_locations.id
    currency_id     INT UNSIGNED NOT NULL,           -- FK → currencies.id
    balance         DECIMAL(22,4) DEFAULT 0,
    avg_cost_rate   DECIMAL(20,6) DEFAULT 0,        -- Weighted avg cost in base currency
    is_active       TINYINT(1) DEFAULT 1,
    created_at      TIMESTAMP,
    updated_at      TIMESTAMP,
    UNIQUE(business_id, location_id, currency_id)
);
```

#### `mc_wallet_transactions` — Wallet movement log
```sql
CREATE TABLE mc_wallet_transactions (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    wallet_id       BIGINT UNSIGNED NOT NULL,
    type            ENUM('deposit','withdrawal','conversion_in','conversion_out','adjustment') NOT NULL,
    amount          DECIMAL(22,4) NOT NULL,
    rate_used       DECIMAL(20,6) NULL,
    rate_type       VARCHAR(30) NULL,
    reference_type  VARCHAR(50) NULL,               -- 'transaction', 'payment', 'conversion'
    reference_id    BIGINT UNSIGNED NULL,
    notes           TEXT NULL,
    created_by      INT UNSIGNED NOT NULL,
    created_at      TIMESTAMP,
    INDEX(wallet_id, created_at)
);
```

#### `mc_fx_conversions` — Currency conversion records
```sql
CREATE TABLE mc_fx_conversions (
    id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    business_id         INT UNSIGNED NOT NULL,
    location_id         INT UNSIGNED NOT NULL,
    from_currency_id    INT UNSIGNED NOT NULL,
    to_currency_id      INT UNSIGNED NOT NULL,
    from_amount         DECIMAL(22,4) NOT NULL,
    to_amount           DECIMAL(22,4) NOT NULL,
    rate_used           DECIMAL(20,6) NOT NULL,
    rate_type           VARCHAR(30) NOT NULL,
    fee_amount          DECIMAL(22,4) DEFAULT 0,
    fx_gain_loss        DECIMAL(22,4) DEFAULT 0,
    notes               TEXT NULL,
    created_by          INT UNSIGNED NOT NULL,
    created_at          TIMESTAMP,
    updated_at          TIMESTAMP,
    INDEX(business_id, created_at)
);
```

#### `mc_product_currency_costs` — Product dual-currency costs
```sql
CREATE TABLE mc_product_currency_costs (
    id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    variation_id        INT UNSIGNED NOT NULL,       -- FK → variations.id
    currency_id         INT UNSIGNED NOT NULL,       -- FK → currencies.id
    purchase_price_fc   DECIMAL(22,4) NOT NULL,      -- Cost in foreign currency
    rate_at_purchase    DECIMAL(20,6) NOT NULL,      -- Rate when purchased
    rate_type           VARCHAR(30) NOT NULL,
    selling_price_fc    DECIMAL(22,4) NULL,          -- Optional FC selling price
    dynamic_pricing     TINYINT(1) DEFAULT 0,
    margin_percent      DECIMAL(8,2) NULL,
    last_updated        TIMESTAMP NULL,
    created_at          TIMESTAMP,
    updated_at          TIMESTAMP,
    UNIQUE(variation_id, currency_id)
);
```

### 4.2 Migrations on Existing Tables (Additive Only)

#### On `transactions` table
```php
// Add nullable FC fields — won't break anything
$table->unsignedInteger('currency_id')->nullable()->after('exchange_rate');
$table->string('rate_type', 30)->nullable()->after('currency_id');
$table->decimal('rate_locked', 20, 6)->nullable()->after('rate_type');
```

#### On `transaction_payments` table
```php
$table->unsignedInteger('currency_id')->nullable();
$table->decimal('amount_in_fc', 22, 4)->nullable();
$table->decimal('exchange_rate_used', 20, 6)->nullable();
```

#### On `contacts` table
```php
$table->unsignedInteger('default_currency_id')->nullable();  // Supplier's default currency
```

> [!NOTE]
> All migrations on existing tables are **nullable additive columns** only. They will never break existing functionality. All existing queries will continue to work with `NULL` values in the new columns.

---

## 5. Files OUTSIDE the New Module That Need Changes

### 5.1 Existing Files to Modify (Minimal, Surgical)

| File | Change Type | What Changes |
|------|-------------|-------------|
| [AdminSidebarMenu.php](file:///d:/pos-main/altrapos/new_pos/pos/app/Http/Middleware/AdminSidebarMenu.php) | **Add menu items** | Add "Multi-Currency" dropdown under Treasury or standalone (lines ~989) |
| [role/create.blade.php](file:///d:/pos-main/altrapos/new_pos/pos/resources/views/role/create.blade.php) | **Add permissions** | Add `multicurrency.*` permission checkboxes |
| [role/edit.blade.php](file:///d:/pos-main/altrapos/new_pos/pos/resources/views/role/edit.blade.php) | **Add permissions** | Same as create |

### 5.2 Blades to Extend (Add FC selector partials)

| Blade File | Change | Details |
|------------|--------|---------|
| Purchase create form | **Include partial** | Add `@include('multicurrency::partials.currency_selector')` for FC selection on purchase |
| POS / Direct sell form | **Include partial** | Add FC selector for selling in foreign currency |
| Payment modal (`payment_row.blade.php`) | **Include partial** | Add FC amount + rate fields on payment |
| Contact create/edit | **Add field** | Default currency dropdown for suppliers |
| Product create/edit | **Include partial** | Dual-currency cost fields |
| Treasury dashboard | **Include partial** | FC wallet balances widget |

### 5.3 Controllers That Need Minor Additions

| Controller | Change | Details |
|------------|--------|---------|
| `PurchaseController` | **Add 3-5 lines** | Save `currency_id`, `rate_type`, `rate_locked` on transaction create/update |
| `SellController` / `SellPosController` | **Add 3-5 lines** | Same as above for sell transactions |
| `ContactController` | **Add 1 line** | Save `default_currency_id` |
| `ProductController` | **Add 5-10 lines** | Save FC cost data to `mc_product_currency_costs` |
| `BusinessController` | **Add section** | Business settings for enabled currencies, default rate source |

### 5.4 Utils That May Need Extension

| Util | Change | Details |
|------|--------|---------|
| `TransactionUtil` | **Add helper method** | `convertToBaseCurrency($amount, $currency_id, $rate)` |
| `Util` (CommonUtil) | **Add method** | `getActiveCurrencies($business_id)` |

---

## 6. What Does NOT Change

> [!TIP]
> The following core systems remain **completely untouched**:

- ✅ Existing Treasury dashboard logic and calculations
- ✅ Existing transaction flow (purchase, sell, expense, returns)
- ✅ Existing payment processing
- ✅ Existing product management
- ✅ Existing reports
- ✅ Existing accounting module
- ✅ Existing CRM module
- ✅ All other modules (Repair, Survey, TimeManagement, etc.)

---

## 7. Phased Implementation Plan

### Phase 1: Currency Core + Rate Management (Foundation)
**Estimated: 3-4 days**

```mermaid
graph LR
    A[Create MultiCurrency Module Scaffold] --> B[Exchange Rate Tables + Models]
    B --> C[Rate Management UI]
    C --> D[API Rate Fetching Service]
    D --> E[Rate History + Locking]
```

**Deliverables:**
1. Module scaffold (providers, routes, config)
2. `mc_exchange_rates` + `mc_exchange_rate_history` tables
3. Exchange Rate CRUD (manage official + parallel rates)
4. Rate display widget (reusable partial)
5. Sidebar menu integration
6. Permissions: `multicurrency.manage_rates`, `multicurrency.view_rates`

### Phase 2: Treasury Currency Wallets + Conversion
**Estimated: 3-4 days**

```mermaid
graph LR
    A[Currency Wallet Tables] --> B[Wallet Dashboard UI]
    B --> C[FX Conversion Form]
    C --> D[Wallet Transaction Log]
    D --> E[Treasury Dashboard Widget]
```

**Deliverables:**
1. `mc_currency_wallets` + `mc_wallet_transactions` + `mc_fx_conversions` tables
2. Wallet management per branch
3. Currency conversion UI (EGP → USD and vice versa)
4. Rate type selection (official/parallel/manual)
5. Widget in existing Treasury dashboard
6. Opening balance support for FC wallets
7. Permissions: `multicurrency.manage_wallets`, `multicurrency.convert`

### Phase 3: Multi-Currency Purchases + Supplier Payments
**Estimated: 4-5 days**

**Deliverables:**
1. Migration: add `currency_id`, `rate_type`, `rate_locked` to `transactions`
2. Migration: add FC fields to `transaction_payments`
3. Migration: add `default_currency_id` to `contacts`
4. Currency selector partial in purchase create form
5. Supplier default currency field
6. Supplier payment in FC
7. Supplier advance payment in FC
8. Rate locking on transaction save

### Phase 4: Multi-Currency Sales + Client Payments
**Estimated: 3-4 days**

**Deliverables:**
1. Currency selector in Direct Sell / POS
2. Client payment in FC
3. Client deposit/advance in FC
4. Invoice display with currency + rate info
5. Receipt template updates (show FC amounts)

### Phase 5: Product Dual-Currency + Dynamic Pricing
**Estimated: 3-4 days**

**Deliverables:**
1. `mc_product_currency_costs` table
2. Product form: FC cost fields
3. Dynamic pricing engine (auto-recalc selling price on rate change)
4. Margin protection alerts
5. Product report: FC cost columns

### Phase 6: FX Intelligence + Reports
**Estimated: 2-3 days**

**Deliverables:**
1. `mc_fx_gain_loss` table
2. FX Gain/Loss calculation service
3. Treasury FX Report
4. Product FX Exposure Report
5. Supplier Foreign Obligations Report
6. Rate History Report

---

## 8. Permission Structure

```
multicurrency.view_rates
multicurrency.manage_rates
multicurrency.set_parallel_rate
multicurrency.manage_wallets
multicurrency.convert
multicurrency.override_conversion_rate
multicurrency.view_fx_reports
multicurrency.manage_product_fx
multicurrency.dynamic_reprice
multicurrency.manage_settings
```

---

## 9. Risk Assessment

| Risk | Mitigation |
|------|------------|
| Exchange rate field on `transactions` is only `decimal(8,3)` — too small for some rates | New `rate_locked` column is `decimal(20,6)`. Existing `exchange_rate` left as-is for backward compat |
| Adding FC to payments could break existing payment calculations | All new fields are **nullable**. Existing code reads `amount` which stays in base currency. FC is supplementary |
| Dynamic repricing could change prices unexpectedly | Requires explicit permission + confirmation. Products must opt-in to dynamic pricing |
| API rate fetching could fail | Fallback to manual entry. Parallel rate is always manual |

---

## 10. Summary Decision Matrix

| Requirement from Doc | Implementation Location | Impact on Existing |
|----------------------|------------------------|--------------------|
| Currency master | Existing `currencies` table (already has what we need) | **None** |
| Exchange rates (official/parallel) | **New** `mc_exchange_rates` table | **None** |
| Treasury wallets by currency | **New** `mc_currency_wallets` table | **None** |
| Internal currency conversion | **New** `mc_fx_conversions` table | Widget added to Treasury dashboard |
| Purchase in FC | **New** migration adds nullable columns to `transactions` | 3-5 lines in PurchaseController |
| Sell in FC | Same as above | 3-5 lines in SellController/SellPosController |
| FC payments | **New** migration adds nullable columns to `transaction_payments` | Payment modal gets optional FC fields |
| Product dual-currency cost | **New** `mc_product_currency_costs` table | Product form gets extra section |
| Dynamic repricing | **New** service in module | **None** to existing |
| FX Gain/Loss | **New** table + service | **None** to existing |
| Reports | **New** views in module | **None** to existing |
| Margin alerts | **New** service in module | **None** to existing |

> [!CAUTION]
> **Do NOT attempt to build Phases 3-6 before Phase 1-2 are stable.** The rate management and wallet system are the foundation everything else depends on.

---

## ✅ Next Steps

Please review this analysis and confirm:

1. **Do you want to proceed with Phase 1** (Currency Core + Rate Management)?
2. **Should the module be a sub-section under Treasury** in the sidebar, or a **standalone top-level menu**?
3. **Which currencies** should be seeded as defaults? (USD, EUR, SAR, AED?)
4. **Do you have a preferred exchange rate API** to integrate, or should we start with manual-only?
5. **Should we support Arabic UI** from the start? (lang files for `ar` and `en`)
