# Order Status Integrity Fix

## Problem
Order status was inconsistent across different views:
- Orders list showed "Completed" (based on Odoo `state: 'sale'`)
- Order details showed "Approved" (awaiting payment)
- Order tracking showed "Awaiting Payment" (step 3 in progress)
- Reality: Subscription was already created, meaning service is active and paid

## Root Cause
The system wasn't considering subscription existence when determining order status. When a subscription is created in Odoo, it means:
1. Payment has been received
2. Installation has been completed
3. Service is active

But the portal was only checking `payment_status` and `actual_installation_date` fields, which may not be set for Odoo orders.

## Solution

### 1. Backend Changes

#### Include Subscription Relationship
Updated controllers to load subscription data:

**SalesOrderController.php**
```php
$order = SalesOrder::with([
    'productPackage', 
    'feasibilityCheck', 
    'customer', 
    'subscription' // Added
])->where('order_number', $orderNumber)->first();
```

**OrderWorkflowController.php**
```php
$order = SalesOrder::with([
    'customer', 
    'serviceAddress', 
    'orderLines.product', 
    'quotation',
    'validationLogs',
    'payments',
    'subscription' // Added
])->where('id', $orderId)->first();
```

### 2. Frontend Changes

#### Order Tracking Dashboard
Updated `getTrackingSteps()` to consider subscription:

```javascript
// Check if subscription exists (means service is active and paid)
const hasSubscription = !!order.subscription || !!order.subscription_id;

// Payment is considered complete if subscription exists
const isPaid = order.payment_status === 'paid' || 
               order.payment_status === 'completed' || 
               order.payment_status === 'invoiced' ||
               hasSubscription;

// Installation is considered complete if subscription exists
const isInstalled = !!order.actual_installation_date || hasSubscription;
```

#### Order Details Page
Updated `getStatusConfig()` to show "Active" when subscription exists:

```javascript
const hasSubscription = order?.subscription || order?.subscription_id;

if (hasSubscription) {
  return {
    icon: CheckCircle,
    label: 'Active',
    description: 'Service is active and running'
  };
}
```

Updated payment button logic to hide when subscription exists:

```javascript
const canPay = order.order_status === 'completed' &&
               order.payment_status !== 'paid' && 
               order.payment_status !== 'completed' &&
               order.payment_status !== 'invoiced' &&
               !hasSubscription; // Don't show if subscription exists
```

#### Orders List Page
Updated `getCustomerStatus()` to prioritize subscription status:

```javascript
// Check if subscription exists (means service is active)
const hasSubscription = order.subscription || order.subscription_id;

// If subscription exists, service is active regardless of other statuses
if (hasSubscription) {
  return { status: 'active', label: 'Active', color: 'green', icon: CheckCircle };
}
```

Added "Active Services" stat:
```javascript
{
  title: 'Active Services',
  icon: CheckCircle,
  color: 'green',
  value: orders.filter(o => getCustomerStatus(o).status === 'active').length,
}
```

## Status Priority Logic

The new status determination follows this priority:

1. **Cancelled** - If order is cancelled
2. **Active** - If subscription exists (highest priority for active orders)
3. **Completed** - If order status is completed/done
4. **In Progress** - If order is in progress
5. **Paid** - If payment received but not yet installed
6. **Pending Payment** - If approved but not paid
7. **Approved** - If order is confirmed (Odoo 'sale' status)
8. **Draft** - If order is still in draft

## Payment Status Mapping

Payment is considered complete if ANY of these conditions are true:
- `payment_status === 'paid'`
- `payment_status === 'completed'`
- `payment_status === 'invoiced'` (Odoo status)
- Subscription exists

## Installation Status Mapping

Installation is considered complete if ANY of these conditions are true:
- `actual_installation_date` is set
- Subscription exists (subscription implies installation was completed)

## Testing

Test scenarios:
1. ✅ Order with subscription shows "Active" everywhere
2. ✅ Order approved but not paid shows "Approved" / "Awaiting Payment"
3. ✅ Order paid but not installed shows "Paid" / "Installation Scheduled"
4. ✅ Order completed without subscription shows "Completed"
5. ✅ Payment button hidden when subscription exists
6. ✅ Tracking shows all steps complete when subscription exists

## Files Modified

### Backend
- `app/Http/Controllers/API/SalesOrderController.php`
- `app/Http/Controllers/API/OrderWorkflowController.php`

### Frontend
- `src/app/(portal)/orders/page.js`
- `src/app/(portal)/orders/[order_number]/page.js`
- `src/components/sections/orders/order-tracking-dashboard.js`

## Benefits

1. **Consistent Status** - Same status shown across all views
2. **Accurate Tracking** - Tracking reflects actual service state
3. **Better UX** - No confusing "awaiting payment" when service is active
4. **Correct Actions** - Payment button hidden when already paid
5. **Clear Metrics** - "Active Services" stat shows real active subscriptions

## Related Documentation
- `ORDER_TRACKING_FIX.md` - Order tracking for Odoo orders
- `ODOO_ORDER_VIEWING.md` - View Details functionality
- `UNIFIED_ORDER_SYSTEM.md` - Order creation and sync
