# Green Zone (High Feasibility) Order Automation Analysis

## Current Flow Overview

### What Happens Now for High Feasibility Orders

1. **Coverage Check** → User checks address, gets "high" feasibility status
2. **Package Selection** → User browses packages available for high feasibility
3. **Add to Cart** → User adds package to cart
4. **Checkout** → User fills out installation details, payment info
5. **Order Creation** → Order created in portal database
6. **Odoo Sync** → Order synced to Odoo (without order lines due to missing product IDs)
7. **Payment** → User pays via Pesepay
8. **Manual Review** → Staff must manually add order lines in Odoo
9. **Installation** → Installation scheduled after manual review

### Current Automation Status

#### ✅ What's Already Automated
- Feasibility calculation (high/medium/low based on KMZ coverage)
- Package filtering (only shows packages available for feasibility level)
- Order creation in portal database
- Order sync to Odoo (creates sale.order record)
- Payment processing via Pesepay
- Installation record creation
- Email notifications

#### ❌ What's NOT Automated (Manual Steps Required)
- **Order line creation in Odoo** (staff must manually add products)
- **Pricing in Odoo** (shows $0.00 until staff adds lines)
- **Order approval** (requires manual review even for high feasibility)
- **Installation scheduling** (requires staff to schedule)
- **Service activation** (requires manual activation in Odoo)

## Automation Opportunities for Green Zone Orders

### 1. Auto-Approval Based on Feasibility

**Current State:**
```php
// In SalesOrderController
'auto_approved' => false, // Always false, requires manual review
```

**Proposed Automation:**
```php
// Auto-approve if:
// - Feasibility is HIGH
// - Customer account is active
// - No outstanding balance issues
// - Standard package (not custom)
$autoApprove = (
    $feasibilityCheck->feasibility_status === 'high' &&
    $customer->account_status === 'active' &&
    $customer->outstanding_balance < ($customer->credit_limit * 0.8) &&
    !$package->requires_custom_quote
);

$salesOrder->auto_approved = $autoApprove;
$salesOrder->approved_at = $autoApprove ? now() : null;
$salesOrder->order_status = $autoApprove ? 'pending_payment' : 'pending';
```

### 2. Skip Quotation Route for High Feasibility

**Current State:**
- All orders go through same flow regardless of feasibility
- Medium/low feasibility creates quotations
- High feasibility still requires manual review

**Proposed Flow:**
```
HIGH FEASIBILITY:
Coverage Check → Package Selection → Cart → Checkout → Payment → Auto-Approved Order → Installation

MEDIUM FEASIBILITY:
Coverage Check → Quotation Request → Sales Review → Quotation Sent → Accept → Order → Payment → Installation

LOW FEASIBILITY:
Coverage Check → Custom Quote Request → Sales Team Contact → Custom Solution
```

### 3. Automatic Order Line Creation in Odoo

**Current Problem:**
```php
// In UnifiedOrderService::createOrder()
// Order created in Odoo WITHOUT order lines because:
// - Packages don't have odoo_product_id set
// - No mapping between portal packages and Odoo products
```

**Solution Options:**

#### Option A: Generic Product Mapping (Recommended)
```php
// Create a generic "Internet Service" product in Odoo
// Map all portal packages to this generic product
// Include package details in order notes

$odooOrderLines = [
    [
        'product_id' => config('services.odoo.generic_product_id'), // Generic "Internet Service"
        'name' => $package->name . ' - ' . $package->speed_mbps . ' Mbps',
        'product_uom_qty' => 1,
        'price_unit' => $order->total_amount,
        'tax_id' => [[6, 0, [config('services.odoo.vat_tax_id')]]],
    ]
];
```

#### Option B: Create Products in Odoo Programmatically
```php
// Automatically create Odoo products for each portal package
// Store odoo_product_id in portal database
// Use actual products when creating orders

$odooProductId = $this->getOrCreateOdooProduct($package);
$package->update(['odoo_product_id' => $odooProductId]);
```

#### Option C: Detailed Order Notes (Current Workaround)
```php
// Already implemented - adds detailed pricing breakdown to notes
// Staff can manually create order lines from notes
// Not fully automated but provides all info needed
```

### 4. Automatic Installation Scheduling

**Current State:**
- Installation record created but not scheduled
- Staff must manually schedule in Odoo

**Proposed Automation:**
```php
// For high feasibility orders:
// - Auto-schedule installation 7-14 days from order date
// - Assign to available technician
// - Send confirmation email to customer

if ($feasibilityCheck->feasibility_status === 'high' && $autoApproved) {
    $installationDate = now()->addDays(rand(7, 14));
    
    $installation = Installation::create([
        'sales_order_id' => $salesOrder->id,
        'status' => 'scheduled',
        'scheduled_date' => $installationDate,
        'scheduled_time' => '09:00:00',
        'site_survey_completed' => true, // No survey needed for high feasibility
    ]);
    
    // Update Odoo order with installation date
    $odooService->updateOrderWithInstallation($odooOrderId, $installationDate);
    
    // Send confirmation email
    Mail::to($customer->email)->send(new InstallationScheduledEmail($installation));
}
```

### 5. Automatic Service Activation After Payment

**Current State:**
- Payment received but service not activated
- Staff must manually activate in Odoo

**Proposed Automation:**
```php
// In PaymentController::handlePesepayCallback()
// After successful payment for high feasibility order:

if ($payment->status === 'completed' && $order->auto_approved) {
    // Create subscription in Odoo
    $subscriptionId = $odooService->createSubscription([
        'partner_id' => $customer->odoo_partner_id,
        'template_id' => $package->odoo_subscription_template_id,
        'recurring_amount' => $order->monthly_subscription,
        'date_start' => $installation->scheduled_date ?? now()->addDays(7),
    ]);
    
    // Update order status
    $order->update([
        'order_status' => 'completed',
        'subscription_id' => $subscriptionId,
    ]);
    
    // Send activation email
    Mail::to($customer->email)->send(new ServiceActivatedEmail($order));
}
```

## Implementation Roadmap

### Phase 1: Auto-Approval (Quick Win)
**Effort:** Low | **Impact:** Medium | **Timeline:** 1-2 days

1. Add auto-approval logic based on feasibility status
2. Update order creation to set `auto_approved = true` for high feasibility
3. Skip manual review step for auto-approved orders
4. Send different email notifications for auto-approved vs manual review

**Files to Modify:**
- `app/Services/UnifiedOrderService.php`
- `app/Http/Controllers/API/SalesOrderController.php`
- Email templates

### Phase 2: Generic Product Mapping (Medium Win)
**Effort:** Medium | **Impact:** High | **Timeline:** 3-5 days

1. Create generic "Internet Service" product in Odoo
2. Update order creation to include order lines with generic product
3. Add detailed package info to order line description
4. Test order sync with pricing

**Files to Modify:**
- `app/Services/UnifiedOrderService.php`
- `app/Services/OdooService.php`
- Add migration for `odoo_generic_product_id` config

### Phase 3: Auto-Installation Scheduling (Medium Win)
**Effort:** Medium | **Impact:** Medium | **Timeline:** 3-5 days

1. Auto-schedule installations for high feasibility orders
2. Update Odoo with installation dates
3. Send confirmation emails
4. Add calendar integration

**Files to Modify:**
- `app/Services/UnifiedOrderService.php`
- `app/Services/OdooService.php`
- `app/Mail/InstallationScheduledEmail.php`

### Phase 4: Auto-Service Activation (High Win)
**Effort:** High | **Impact:** High | **Timeline:** 5-7 days

1. Create subscriptions in Odoo after payment
2. Activate services automatically
3. Handle edge cases (failed activation, rollback)
4. Add monitoring and alerts

**Files to Modify:**
- `app/Http/Controllers/API/PaymentController.php`
- `app/Services/OdooService.php`
- `app/Observers/PaymentObserver.php`

## Configuration Flags

Add these to `.env` for gradual rollout:

```env
# Green Zone Automation Flags
AUTO_APPROVE_HIGH_FEASIBILITY=true
AUTO_CREATE_ORDER_LINES=true
AUTO_SCHEDULE_INSTALLATION=true
AUTO_ACTIVATE_SERVICE=false  # Keep false until fully tested

# Odoo Product Mapping
ODOO_GENERIC_PRODUCT_ID=123  # ID of generic "Internet Service" product
ODOO_VAT_TAX_ID=1  # ID of VAT tax in Odoo
```

## Risk Mitigation

### 1. Gradual Rollout
- Start with auto-approval only
- Monitor for issues before adding more automation
- Keep manual override option available

### 2. Validation Checks
```php
// Before auto-approving, validate:
- Customer account is active
- No outstanding balance issues
- Feasibility is genuinely HIGH (not edge case)
- Package is standard (not custom)
- Payment method is valid
```

### 3. Monitoring & Alerts
```php
// Log all auto-approved orders
Log::info('Order auto-approved', [
    'order_id' => $order->id,
    'feasibility' => $feasibility->status,
    'customer_id' => $customer->id,
]);

// Alert if auto-approval rate is unusual
if ($autoApprovalRate < 0.5) {
    // Send alert to admin
}
```

### 4. Manual Override
```php
// Staff can always override auto-approval
// Add "Requires Manual Review" flag in admin panel
$order->update([
    'requires_manual_review' => true,
    'manual_review_reason' => 'Customer requested custom installation',
]);
```

## Expected Benefits

### Customer Experience
- ✅ Faster order processing (minutes vs hours/days)
- ✅ Immediate confirmation for high feasibility areas
- ✅ Clear timeline expectations
- ✅ Less waiting for manual approvals

### Operational Efficiency
- ✅ Reduce manual order processing by 60-80%
- ✅ Free up staff for complex cases (medium/low feasibility)
- ✅ Reduce errors from manual data entry
- ✅ Faster time-to-revenue

### Business Metrics
- ✅ Higher conversion rate (less drop-off during waiting)
- ✅ Better customer satisfaction scores
- ✅ Lower operational costs
- ✅ Scalable growth (can handle more orders without more staff)

## Summary

**Current State:** High feasibility orders require same manual review as complex cases

**Proposed State:** High feasibility orders are fully automated from checkout to installation scheduling

**Key Automation Points:**
1. ✅ Auto-approval based on feasibility + customer status
2. ✅ Automatic order line creation in Odoo
3. ✅ Auto-schedule installation (7-14 days)
4. ✅ Auto-activate service after payment

**Recommended Approach:** Phased rollout starting with auto-approval, then adding more automation as confidence builds

**No Changes Made Yet** - This is analysis only. Ready to implement when you approve!
