# Quotation Pricing Flow Analysis

## Current Issue

When packages have `pricing_model = 'custom'`, the portal creates quotations with **$0 pricing** and sends them to Odoo. The expectation is that:

1. Quotation is sent to Odoo (with $0 or placeholder pricing)
2. Sales team in Odoo adds products/services and sets actual pricing
3. Quotation is converted to Sales Order in Odoo
4. Invoice is generated in Odoo with the actual pricing
5. Portal syncs the invoice and shows the customer the real price to pay

## Actual Flow (As Designed)

### Step 1: Customer Requests Quotation (Portal)
```
Customer → Portal: Request quotation for package
Portal → PricingService: Calculate pricing
```

**For custom pricing packages:**
- `requires_custom_quote = true`
- All prices set to $0
- Status: `pending_review`

**For other packages:**
- Prices calculated based on pricing model
- Status: `pending` or `sent`

### Step 2: Quotation Created in Odoo
```php
// QuotationController.php - Line ~200
$odooQuotationData = [
    'partner_id' => $customer->odoo_partner_id,
    'state' => 'draft',
    'validity_date' => $quotation->valid_until,
    'note' => $notes, // Contains requirements and feasibility info
    'client_order_ref' => $quotation->reference,
    'order_lines' => [
        [
            'quantity' => 1,
            'unit_price' => $quotation->total_amount, // $0 for custom pricing
            'description' => $package->name,
        ]
    ],
];

$odooQuotationId = $odooService->createQuotation($odooQuotationData);
```

**Problem:** The `createQuotation` method in OdooService **DOES NOT** actually send order lines to Odoo:

```php
// OdooService.php - Line 327
public function createQuotation(array $quotationData)
{
    // Adds order line info to NOTES only
    // Does NOT create actual sale.order.line records
    
    $odooData = [
        'partner_id' => $quotationData['partner_id'],
        'state' => 'draft',
        'validity_date' => $quotationData['valid_until'],
        'note' => $notes, // Order lines in notes, not as actual lines
        'client_order_ref' => $quotationData['reference'],
        // NO order_line field sent to Odoo!
    ];
    
    $quotationId = $this->call('sale.order', 'create', $odooData);
}
```

### Step 3: Sales Team Works in Odoo
- Sales team receives quotation in Odoo (draft state)
- Adds products/services manually
- Sets pricing based on requirements
- Sends quotation to customer (state: 'sent')
- Customer accepts → Confirms quotation (state: 'sale')

### Step 4: Quotation Becomes Sales Order
When confirmed in Odoo, webhook should trigger:
```
Odoo → Portal Webhook: 'sale.order.confirmed'
Portal → syncSalesOrder(): Creates/updates SalesOrder record
```

**Current sync behavior:**
```php
// OdooController.php - Line 219
private function syncSalesOrder($orderData)
{
    $salesOrder = SalesOrder::updateOrCreate(
        ['odoo_order_id' => $orderData['id']],
        [
            'customer_id' => $customer->id,
            'quotation_id' => $quotation->id, // Links to quotation
            'total_amount' => $orderData['amount_total'], // REAL PRICE from Odoo
            'order_status' => 'confirmed',
            // ... other fields
        ]
    );
    
    // Updates quotation status
    if ($quotation) {
        $quotation->status = 'accepted';
        $quotation->save();
    }
}
```

### Step 5: Invoice Generated in Odoo
When invoice is created in Odoo, webhook triggers:
```
Odoo → Portal Webhook: 'invoice.created'
Portal → syncInvoice(): Creates Invoice record
```

**Current sync behavior:**
```php
// OdooController.php - Line 347
private function syncInvoice($invoiceData)
{
    $invoice = Invoice::updateOrCreate(
        ['odoo_invoice_id' => $invoiceData['id']],
        [
            'customer_id' => $customer->id,
            'sales_order_id' => $salesOrder->id, // Links to sales order
            'invoice_number' => $invoiceData['name'],
            'total_amount' => $invoiceData['amount_total'], // REAL PRICE from Odoo
            'status' => 'pending',
            // ... other fields
        ]
    );
}
```

### Step 6: Customer Pays Invoice
Customer sees invoice with real pricing and pays:
```
Customer → Portal: View invoice (real price from Odoo)
Customer → Portal: Make payment for invoice amount
Portal → Odoo: Record payment on invoice
```

## The Problem

### Issue 1: Quotation Pricing Not Updated
When a quotation is confirmed in Odoo and becomes a sales order:
- Portal creates `SalesOrder` record with correct pricing from Odoo
- Portal updates `Quotation.status = 'accepted'`
- **BUT:** Portal does NOT update `Quotation.total_amount` with the real price from Odoo

**Result:** Quotation still shows $0 in portal, even though sales order has real price.

### Issue 2: Missing Quotation Price Sync
There's no mechanism to sync pricing updates from Odoo back to the quotation:
- No webhook handler for `quotation.updated`
- `syncQuotation()` method exists but only called for create/update events
- No periodic sync to fetch updated quotation pricing

### Issue 3: Customer Experience Gap
For custom pricing packages:
1. Customer requests quotation → sees $0 or "pending review"
2. Sales team prices it in Odoo → customer has no visibility
3. Quotation confirmed → becomes sales order (customer may not know)
4. Invoice created → customer finally sees real price

**Gap:** Customer doesn't see the approved quotation price before invoice.

## Recommended Fixes

### Fix 1: Update Quotation Pricing When Sales Order Syncs
```php
// OdooController.php - syncSalesOrder()
if ($quotation) {
    $quotation->update([
        'status' => 'accepted',
        'responded_at' => now(),
        // ADD: Update pricing from sales order
        'total_amount' => $orderData['amount_total'],
        'monthly_price' => $orderData['monthly_subscription'] ?? 0,
        'installation_fee' => $orderData['installation_fee'] ?? 0,
        'equipment_cost' => $orderData['equipment_cost'] ?? 0,
        'extension_cost' => $orderData['extension_cost'] ?? 0,
    ]);
}
```

### Fix 2: Sync Quotation Pricing Updates from Odoo
Add webhook handler for quotation updates:
```php
// OdooController.php - handleWebhook()
case 'quotation.updated':
    $this->syncQuotationPricing($data['quotation']);
    break;
```

Implement pricing sync:
```php
private function syncQuotationPricing($quotationData)
{
    $quotation = Quotation::where('odoo_quotation_id', $quotationData['id'])->first();
    
    if ($quotation) {
        $quotation->update([
            'total_amount' => $quotationData['amount_total'],
            'monthly_price' => $quotationData['amount_untaxed'] ?? 0,
            'status' => $this->mapQuotationStatus($quotationData['state']),
            'sent_at' => $quotationData['state'] === 'sent' ? now() : null,
        ]);
    }
}
```

### Fix 3: Add Quotation Price Notification
When quotation is priced in Odoo and sent to customer:
```php
// Send email notification to customer
Mail::to($customer->email)->send(
    new QuotationPricedNotification($quotation)
);
```

### Fix 4: Update Frontend to Show Quotation Status
Display quotation journey:
- Pending Review → Priced → Sent → Accepted → Sales Order → Invoice

## Summary

**Current State:**
- Custom pricing quotations created with $0
- Sent to Odoo for manual pricing
- Sales order synced with real price
- Invoice synced with real price
- **Quotation never updated with real price**

**Needed:**
1. Update quotation pricing when sales order is synced
2. Add webhook handler for quotation pricing updates
3. Notify customer when quotation is priced
4. Show clear quotation → order → invoice flow in UI

**Priority:** HIGH - Customers need to see approved quotation price before invoice is generated.
