# Odoo Order Viewing Support

## Overview

Customers can now view their Odoo orders directly in the customer portal. The backend automatically fetches order details from Odoo when an Odoo order number is detected.

## How It Works

### Order Detection

The system detects Odoo orders by checking if the order number does NOT start with `AFINET-SO-`:

- **Portal Orders**: `AFINET-SO-12345` (created in the portal)
- **Odoo Orders**: `DFAZ-SO-1503`, `S00123`, etc. (created in Odoo)

### Backend Flow

When a customer views an order:

1. **Check Order Number Format**
   - If it starts with `AFINET-SO-` → Look in local database
   - If it doesn't → Try Odoo first, then local database

2. **Fetch from Odoo** (if applicable)
   - Get all customer orders from Odoo using `odoo_partner_id`
   - Find the specific order by matching order number
   - Transform Odoo data to match portal format

3. **Fallback to Local Database**
   - If not found in Odoo, search local `sales_orders` table
   - Try multiple variations of the order number

### Data Transformation

Odoo orders are transformed to match the portal's expected format:

```php
[
    'id' => $odooOrder['id'],
    'order_number' => $odooOrder['name'],
    'order_status' => mapOdooOrderStatus($odooOrder['state']),
    'payment_status' => mapOdooInvoiceStatus($odooOrder['invoice_status']),
    'total_amount' => $odooOrder['amount_total'],
    'created_at' => $odooOrder['date_order'],
    'source' => 'odoo',
    // ... other fields
]
```

### Status Mapping

**Order Status:**
- `draft`, `sent` → `pending`
- `sale` → `completed`
- `done` → `completed`
- `cancel` → `cancelled`

**Payment Status:**
- `invoiced` → `paid`
- `to invoice` → `pending`
- `no` → `pending`

## Frontend Behavior

### Orders List Page

**All Orders (Odoo + Portal):**
- ✅ View Details icon - Active for ALL orders (fetches from Odoo if needed)
- ⚠️ Track Order icon - Only active for portal orders (Odoo tracking not supported yet)

### Order Details Page

**Odoo Orders:**
- Shows order number, status, amount
- Shows payment status
- Limited installation details (not available from Odoo)
- Address shown if available from Odoo partner data

**Portal Orders:**
- Full details including package, installation schedule, etc.
- Complete tracking information
- Payment integration

## Limitations

### What's Available for Odoo Orders:
- ✅ Order number
- ✅ Order status
- ✅ Payment status
- ✅ Total amount
- ✅ Creation date
- ✅ Basic address (from partner data)

### What's NOT Available for Odoo Orders:
- ❌ Package details (speed, features)
- ❌ Installation schedule
- ❌ Detailed pricing breakdown
- ❌ Special instructions
- ❌ Order tracking timeline
- ❌ Payment integration

## API Endpoints

### Get Order by Number

```
GET /api/orders/{orderNumber}
```

**Supports:**
- Portal orders: `AFINET-SO-12345`
- Odoo orders: `DFAZ-SO-1503`, `S00123`, etc.

**Response:**
```json
{
    "success": true,
    "data": {
        "id": 1503,
        "order_number": "DFAZ-SO-1503",
        "order_status": "completed",
        "payment_status": "paid",
        "total_amount": 500.00,
        "source": "odoo",
        ...
    }
}
```

## Error Handling

### Order Not Found

If an order is not found in either Odoo or the local database:

```json
{
    "success": false,
    "message": "Order not found"
}
```

### Odoo Connection Error

If Odoo is unavailable, the system:
1. Logs a warning
2. Falls back to local database
3. Returns 404 if not found locally

### Unauthorized Access

If a customer tries to view another customer's order:

```json
{
    "error": "Unauthorized"
}
```

## Future Enhancements

### Phase 1 (Current)
- ✅ View Odoo order basic details
- ✅ See order status and payment status
- ✅ View order amount

### Phase 2 (Planned)
- 🔄 Sync Odoo orders to local database for better performance
- 🔄 Cache Odoo order data
- 🔄 Support order tracking for Odoo orders

### Phase 3 (Future)
- 📋 Full order details from Odoo (products, lines, etc.)
- 📋 Installation scheduling for Odoo orders
- 📋 Payment integration for Odoo orders

## Testing

### Test Scenarios

1. **View Portal Order**
   - Create order in portal
   - Click "View Details"
   - Should show full order details

2. **View Odoo Order**
   - Customer has order in Odoo (e.g., `DFAZ-SO-1503`)
   - Click "View Details" on orders page
   - Should fetch from Odoo and display basic details

3. **Order Not Found**
   - Try to view non-existent order
   - Should show "Order not found" error

4. **Unauthorized Access**
   - Try to view another customer's order
   - Should show "Unauthorized" error

## Troubleshooting

### "Order Not Found" for Odoo Orders

**Possible Causes:**
1. Customer not linked to Odoo (`odoo_partner_id` is null)
2. Order doesn't belong to this customer in Odoo
3. Odoo connection error

**Solution:**
- Check customer's `odoo_partner_id` in database
- Verify order exists in Odoo for this partner
- Check Odoo service logs for connection errors

### Missing Order Details

**Cause:** Odoo orders have limited data available

**Solution:** This is expected behavior. Odoo orders show basic info only.

### Slow Loading

**Cause:** Fetching from Odoo on every request

**Solution:** Implement caching or sync Odoo orders to local database (Phase 2)

## Code References

### Backend
- `app/Http/Controllers/API/SalesOrderController.php` - `show()` method
- `app/Services/OdooService.php` - `getCustomerOrders()` method

### Frontend
- `src/app/(portal)/orders/page.js` - Orders list with view links
- `src/app/(portal)/orders/[order_number]/page.js` - Order details page
- `src/hooks/use-orders.js` - `useOrder()` hook

## Monitoring

### Logs to Watch

- `Order fetched from Odoo` - Successful Odoo fetch
- `Failed to fetch Odoo order` - Odoo fetch error
- `Order not found` - Order doesn't exist

### Metrics to Track

- Odoo order view requests
- Odoo API response times
- Order not found errors
- Unauthorized access attempts
