# Payment Status Update Flow

## Overview
When a payment is completed (either via Pesepay or bank transfer verification), the system updates multiple entities in a cascading manner to maintain data consistency across the portal and Odoo.

## Update Cascade Flow

```
Payment Completed
    ↓
┌───────────────────────────────────────────────────────────┐
│  handleSuccessfulPayment() Method                         │
│  Location: PaymentController.php                          │
└───────────────────────────────────────────────────────────┘
    ↓
    ├─→ 1. UPDATE INVOICE (Primary Entity)
    │       ├─ status: 'paid'
    │       ├─ paid_date: now()
    │       ├─ payment_method: 'pesepay' or 'bank_transfer'
    │       └─ payment_reference: payment reference number
    │       ↓
    │   SYNC TO ODOO:
    │       └─ recordPayment() in Odoo
    │           ├─ Creates account.payment record
    │           ├─ Posts payment
    │           └─ Reconciles with invoice
    │
    ├─→ 2. UPDATE SALES ORDER (Secondary Entity)
    │       ├─ payment_status: 'paid'
    │       └─ approved_at: now()
    │       ↓
    │   SYNC TO ODOO:
    │       └─ action_confirm() on sale.order
    │           └─ Confirms order in Odoo
    │
    ├─→ 3. UPDATE QUOTATION (Tertiary Entity)
    │       ├─ status: 'paid'
    │       └─ workflow_stage: 'completed'
    │
    └─→ 4. SEND NOTIFICATIONS
            ├─ Email to customer (PaymentConfirmation)
            └─ SMS to customer (TODO)
```

## Detailed Update Process

### 1. Invoice Update (Primary)

**Portal Database:**
```php
Invoice::update([
    'status' => 'paid',
    'paid_date' => now(),
    'payment_method' => 'pesepay', // or 'bank_transfer'
    'payment_reference' => 'PAY-123456',
]);
```

**Odoo Sync:**
```php
// Record payment in Odoo
$odooService->recordPayment($invoice->odoo_invoice_id, [
    'amount' => $payment->amount,
    'payment_date' => '2024-02-15',
    'reference' => 'PAY-123456',
    'notes' => 'Payment via Pesepay - PESE-789',
]);
```

**What happens in Odoo:**
1. Creates `account.payment` record
2. Links payment to invoice (`account.move`)
3. Posts the payment (makes it official)
4. Reconciles payment with invoice
5. Invoice `payment_state` changes to 'paid'
6. Invoice `amount_residual` becomes 0

### 2. Sales Order Update (Secondary)

**Portal Database:**
```php
SalesOrder::update([
    'payment_status' => 'paid',
    'approved_at' => now(),
]);
```

**Odoo Sync:**
```php
// Confirm order in Odoo (if not already confirmed)
$odooService->call('sale.order', 'action_confirm', [$salesOrder->odoo_order_id]);
```

**What happens in Odoo:**
1. Order state changes to 'sale' (confirmed)
2. Triggers delivery order creation (if applicable)
3. Locks the order for processing
4. Updates order workflow

### 3. Quotation Update (Tertiary)

**Portal Database:**
```php
Quotation::update([
    'status' => 'paid',
    'workflow_stage' => 'completed',
]);
```

**Purpose:**
- Marks the quotation lifecycle as complete
- Prevents further modifications
- Provides audit trail

### 4. Customer Notifications

**Email Notification:**
```php
Mail::to($customer->email)
    ->send(new PaymentConfirmation($payment, $invoice, $customer));
```

**Email Content:**
- Payment confirmation
- Payment details (reference, amount, date)
- Invoice details (number, status)
- Next steps (installation, activation)
- Link to view invoice

## Payment Triggers

### Trigger 1: Pesepay Webhook
```
Pesepay Gateway
    ↓
POST /api/payments/webhook
    ↓
PaymentController::webhook()
    ↓
Update payment status to 'completed'
    ↓
handleSuccessfulPayment()
    ↓
Updates cascade
```

### Trigger 2: Bank Transfer Verification (Manual)
```
Finance Team Reviews POP
    ↓
Approves payment in admin panel
    ↓
Payment status → 'completed'
    ↓
handleSuccessfulPayment()
    ↓
Updates cascade
```

### Trigger 3: Test Mode Auto-Complete
```
Payment initiated in test mode
    ↓
PaymentController::initiatePayment()
    ↓
Auto-complete payment immediately
    ↓
handleSuccessfulPayment()
    ↓
Updates cascade
```

## Status Values

### Invoice Status
- `draft` - Invoice created but not sent
- `sent` - Invoice sent to customer
- `paid` - ✅ Payment received and confirmed
- `cancelled` - Invoice cancelled
- `overdue` - Past due date and unpaid

### Sales Order Payment Status
- `pending` - Awaiting payment
- `partial` - Partially paid
- `paid` - ✅ Fully paid
- `refunded` - Payment refunded

### Quotation Status
- `draft` - Being prepared
- `sent` - Sent to customer
- `accepted` - Customer accepted
- `paid` - ✅ Payment completed
- `declined` - Customer declined
- `expired` - Past validity date

### Payment Status
- `pending` - Payment initiated, awaiting completion
- `completed` - ✅ Payment successful
- `failed` - Payment failed
- `pending_verification` - Bank transfer awaiting verification
- `refunded` - Payment refunded
- `cancelled` - Payment cancelled

## Database Relationships

```sql
-- Payment links to all entities
payments
├─ invoice_id → invoices (PRIMARY)
├─ sales_order_id → sales_orders (SECONDARY)
└─ quotation_id → quotations (TERTIARY)

-- Invoice links to order
invoices
└─ sales_order_id → sales_orders

-- Order links to quotation
sales_orders
└─ quotation_id → quotations

-- Complete chain
quotations → sales_orders → invoices → payments
```

## Odoo Models Affected

### 1. account.move (Invoice)
```python
{
    'state': 'posted',
    'payment_state': 'paid',  # ← Updated
    'amount_residual': 0.0,   # ← Updated
}
```

### 2. account.payment (Payment Record)
```python
{
    'partner_id': customer_id,
    'amount': 150.00,
    'payment_type': 'inbound',
    'state': 'posted',  # ← Created and posted
    'ref': 'PAY-123456',
}
```

### 3. sale.order (Sales Order)
```python
{
    'state': 'sale',  # ← Confirmed
    'invoice_status': 'invoiced',
}
```

## Error Handling

### Odoo Sync Failures
```php
try {
    $odooService->recordPayment($invoiceId, $paymentData);
} catch (\Exception $e) {
    Log::error('Failed to record payment in Odoo', [
        'invoice_id' => $invoiceId,
        'error' => $e->getMessage(),
    ]);
    // Continue with portal updates
    // Don't fail the entire process
}
```

**Strategy:**
- Portal updates always succeed
- Odoo sync failures are logged but don't block
- Manual reconciliation can be done later if needed
- Alerts sent to admin for failed syncs

### Transaction Rollback
```php
DB::beginTransaction();
try {
    // Update invoice
    // Update order
    // Update quotation
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    Log::error('Payment processing failed', ['error' => $e->getMessage()]);
}
```

## Verification & Audit Trail

### Payment Record
```json
{
  "id": 456,
  "payment_reference": "PAY-123456",
  "invoice_id": 123,
  "sales_order_id": 789,
  "quotation_id": 101,
  "amount": 150.00,
  "status": "completed",
  "processed_at": "2024-02-15 14:30:00",
  "gateway_response": {
    "pesepay_reference": "PESE-789",
    "transaction_id": "TXN-456"
  }
}
```

### Audit Log Entries
```
[INFO] Payment completed: payment_id=456
[INFO] Invoice marked as paid: invoice_id=123
[INFO] Payment recorded in Odoo: odoo_payment_id=999
[INFO] Sales order marked as paid: order_id=789
[INFO] Sales order confirmed in Odoo: odoo_order_id=888
[INFO] Quotation marked as completed: quotation_id=101
[INFO] Payment confirmation email sent: customer_id=42
```

## Testing Checklist

### Manual Testing
- [ ] Complete Pesepay payment
- [ ] Verify invoice status → 'paid'
- [ ] Verify order status → 'paid'
- [ ] Verify quotation status → 'paid'
- [ ] Check Odoo invoice payment_state → 'paid'
- [ ] Check Odoo order state → 'sale'
- [ ] Verify customer receives email
- [ ] Check payment record has all links

### Bank Transfer Testing
- [ ] Upload proof of payment
- [ ] Finance team verifies
- [ ] Same cascade updates occur
- [ ] Customer receives confirmation

### Error Scenario Testing
- [ ] Odoo connection fails → Portal updates still work
- [ ] Email fails → Payment still processes
- [ ] Partial failures logged correctly

## API Response After Payment

```json
{
  "success": true,
  "message": "Payment completed successfully",
  "data": {
    "payment": {
      "id": 456,
      "status": "completed",
      "amount": 150.00
    },
    "invoice": {
      "id": 123,
      "status": "paid",
      "paid_date": "2024-02-15"
    },
    "order": {
      "id": 789,
      "payment_status": "paid"
    },
    "quotation": {
      "id": 101,
      "status": "paid"
    }
  }
}
```

## Summary

When a payment is completed:

1. ✅ **Payment** status → `completed`
2. ✅ **Invoice** status → `paid` (Portal + Odoo)
3. ✅ **Sales Order** payment_status → `paid` (Portal + Odoo)
4. ✅ **Quotation** status → `paid`, workflow_stage → `completed`
5. ✅ **Odoo Payment** record created and reconciled
6. ✅ **Customer** receives confirmation email
7. ✅ **Audit logs** created for all updates

This ensures complete data consistency across the portal and Odoo, with proper error handling and notifications.
