# ✅ Verification: Complete Linking Chain

## Database Relationships Confirmed

### The Complete Chain:

```
Quotation (quotations table)
    ↓ quotation_id
Sales Order (sales_orders table)
    ↓ sales_order_id
Invoice (invoices table)
    ↓ invoice_id
Payment (payments table)
```

---

## 1. Quotation → Sales Order Link

**Table**: `sales_orders`
**Column**: `quotation_id` (foreign key)

```php
// SalesOrder Model
public function quotation(): BelongsTo
{
    return $this->belongsTo(Quotation::class);
}
```

**Created in**: `QuotationController::accept()`
```php
$salesOrder = SalesOrder::create([
    'order_number' => 'AFINET-SO-' . strtoupper(uniqid()),
    'customer_id' => $quotation->customer_id,
    'quotation_id' => $quotation->id,  // ✅ LINKED HERE
    // ... other fields
]);
```

---

## 2. Sales Order → Invoice Link

**Table**: `invoices`
**Column**: `sales_order_id` (foreign key)

```php
// Invoice Model
public function salesOrder()
{
    return $this->belongsTo(SalesOrder::class);
}
```

**Created in**: `QuotationController::accept()` (after sales order creation)
```php
$invoice = Invoice::create([
    'invoice_number' => $invoiceDetails['name'],
    'customer_id' => $customer->id,
    'sales_order_id' => $salesOrder->id,  // ✅ LINKED HERE
    'total_amount' => $invoiceDetails['amount_total'],
    'odoo_invoice_id' => $invoiceId,
    // ... other fields
]);
```

---

## 3. Invoice → Payment Link

**Table**: `payments`
**Columns**: 
- `invoice_id` (foreign key) - PRIMARY link
- `sales_order_id` (foreign key) - SECONDARY link for reference
- `quotation_id` (foreign key) - TERTIARY link for reference

```php
// Payment Model
public function invoice()
{
    return $this->belongsTo(Invoice::class);
}

public function salesOrder()
{
    return $this->belongsTo(SalesOrder::class);
}

public function quotation()
{
    return $this->belongsTo(Quotation::class);
}
```

**Created in**: `PaymentController::uploadProofOfPayment()`
```php
$payment = Payment::create([
    'payment_reference' => $request->payment_reference,
    'customer_id' => $customer->id,
    'invoice_id' => $invoice->id,              // ✅ PRIMARY LINK
    'sales_order_id' => $invoice->sales_order_id,  // ✅ SECONDARY LINK
    'amount' => $request->amount,
    'payment_method' => 'bank_transfer',
    'status' => 'pending',
    // ... other fields
]);
```

---

## Complete Flow Verification

### Old Flow (INCORRECT - Paying on Quotation):
```
❌ Quotation → Payment (quotation_id)
   No invoice involved
   No sales order tracking
```

### New Flow (CORRECT - Paying on Invoice):
```
✅ Quotation 
    ↓ (accepted)
   Sales Order (created in Odoo)
    ↓ (invoice generated)
   Invoice (created in Odoo & Portal)
    ↓ (payment made)
   Payment (linked to invoice, sales_order, and quotation)
```

---

## Database Schema Verification

### Quotations Table
```sql
CREATE TABLE quotations (
    id BIGINT PRIMARY KEY,
    customer_id BIGINT,
    reference VARCHAR(255),
    status ENUM('pending', 'sent', 'accepted', 'declined'),
    total_amount DECIMAL(10,2),
    -- ... other fields
);
```

### Sales Orders Table
```sql
CREATE TABLE sales_orders (
    id BIGINT PRIMARY KEY,
    order_number VARCHAR(255),
    customer_id BIGINT,
    quotation_id BIGINT,  -- ✅ Links to quotation
    total_amount DECIMAL(10,2),
    odoo_order_id INT,
    -- ... other fields
    FOREIGN KEY (quotation_id) REFERENCES quotations(id)
);
```

### Invoices Table
```sql
CREATE TABLE invoices (
    id BIGINT PRIMARY KEY,
    invoice_number VARCHAR(255),
    customer_id BIGINT,
    sales_order_id BIGINT,  -- ✅ Links to sales order
    total_amount DECIMAL(10,2),
    odoo_invoice_id INT,
    status ENUM('draft', 'sent', 'paid', 'cancelled'),
    -- ... other fields
    FOREIGN KEY (sales_order_id) REFERENCES sales_orders(id)
);
```

### Payments Table
```sql
CREATE TABLE payments (
    id BIGINT PRIMARY KEY,
    payment_reference VARCHAR(255),
    customer_id BIGINT,
    invoice_id BIGINT,        -- ✅ PRIMARY: Links to invoice
    sales_order_id BIGINT,    -- ✅ SECONDARY: Links to sales order
    quotation_id BIGINT,      -- ✅ TERTIARY: Links to quotation
    amount DECIMAL(10,2),
    payment_method ENUM('pesepay', 'bank_transfer', 'cash', 'other'),
    status ENUM('pending', 'pending_verification', 'completed', 'failed'),
    -- ... other fields
    FOREIGN KEY (invoice_id) REFERENCES invoices(id),
    FOREIGN KEY (sales_order_id) REFERENCES sales_orders(id),
    FOREIGN KEY (quotation_id) REFERENCES quotations(id)
);
```

---

## Code Flow Verification

### Step 1: Quotation Accepted
**File**: `QuotationController.php`
```php
public function accept(Request $request, $id)
{
    // 1. Update quotation status
    $quotation->update(['status' => 'accepted']);
    
    // 2. Create sales order
    $salesOrder = SalesOrder::create([
        'quotation_id' => $quotation->id,  // ✅ LINK 1
        // ...
    ]);
    
    // 3. Convert to Odoo sales order
    $odooOrderId = $odooService->convertQuotationToSaleOrder($quotation->odoo_quotation_id);
    
    // 4. Generate invoice in Odoo
    $invoiceId = $odooService->generateInvoice($odooOrderId);
    
    // 5. Create local invoice
    $invoice = Invoice::create([
        'sales_order_id' => $salesOrder->id,  // ✅ LINK 2
        'odoo_invoice_id' => $invoiceId,
        // ...
    ]);
    
    // 6. Return invoice to customer
    return response()->json([
        'data' => [
            'quotation' => $quotation,
            'sales_order' => $salesOrder,
            'invoice' => $invoice,  // ✅ Customer pays this
        ]
    ]);
}
```

### Step 2: Customer Makes Payment
**File**: `PaymentController.php`
```php
public function uploadProofOfPayment(Request $request)
{
    // 1. Get invoice
    $invoice = Invoice::where('id', $request->invoice_id)
        ->where('customer_id', $customer->id)
        ->first();
    
    // 2. Create payment linked to invoice
    $payment = Payment::create([
        'invoice_id' => $invoice->id,              // ✅ LINK 3 (PRIMARY)
        'sales_order_id' => $invoice->sales_order_id,  // ✅ LINK 4 (SECONDARY)
        'amount' => $request->amount,
        'payment_method' => 'bank_transfer',
        // ...
    ]);
    
    // 3. Upload POP to Odoo invoice
    $odooService->uploadAttachment(
        $filename,
        $fileContent,
        'account.move',
        $invoice->odoo_invoice_id  // ✅ Attached to invoice in Odoo
    );
}
```

---

## Query Examples

### Get Complete Chain for a Payment
```php
$payment = Payment::with([
    'invoice.salesOrder.quotation',
    'customer'
])->find($paymentId);

// Access the complete chain:
$quotation = $payment->invoice->salesOrder->quotation;
$salesOrder = $payment->invoice->salesOrder;
$invoice = $payment->invoice;
```

### Get All Payments for an Invoice
```php
$invoice = Invoice::with('payments')->find($invoiceId);
$totalPaid = $invoice->payments->sum('amount');
$isPaid = $totalPaid >= $invoice->total_amount;
```

### Get Invoice from Sales Order
```php
$salesOrder = SalesOrder::with('quotation')->find($orderId);
$invoice = Invoice::where('sales_order_id', $salesOrder->id)->first();
```

### Get All Related Records from Quotation
```php
$quotation = Quotation::with([
    'salesOrders.invoices.payments'
])->find($quotationId);

// Access everything:
foreach ($quotation->salesOrders as $order) {
    foreach ($order->invoices as $invoice) {
        foreach ($invoice->payments as $payment) {
            echo "Payment: {$payment->amount}\n";
        }
    }
}
```

---

## API Response Structure

### After Quotation Acceptance
```json
{
  "success": true,
  "message": "Quotation accepted successfully",
  "data": {
    "quotation": {
      "id": 123,
      "reference": "QUO-2026-001",
      "status": "accepted",
      "total_amount": 1500.00
    },
    "sales_order": {
      "id": 456,
      "order_number": "AFINET-SO-001",
      "quotation_id": 123,
      "odoo_order_id": 1521,
      "total_amount": 1500.00
    },
    "invoice": {
      "id": 789,
      "invoice_number": "INV/2026/0001",
      "sales_order_id": 456,
      "odoo_invoice_id": 5678,
      "total_amount": 1500.00,
      "status": "sent",
      "due_date": "2026-02-23"
    }
  },
  "next_steps": "Invoice generated. Proceed to payment to complete your order."
}
```

### After Payment Upload
```json
{
  "success": true,
  "message": "Proof of payment uploaded successfully...",
  "data": {
    "payment_id": 999,
    "payment_reference": "BANK-REF-12345",
    "status": "pending",
    "invoice": {
      "id": 789,
      "invoice_number": "INV/2026/0001",
      "sales_order_id": 456,
      "amount": 1500.00
    }
  }
}
```

---

## Summary

### ✅ Confirmed Linking Chain:

1. **Quotation → Sales Order**: `sales_orders.quotation_id`
2. **Sales Order → Invoice**: `invoices.sales_order_id`
3. **Invoice → Payment**: `payments.invoice_id` (primary)
4. **Payment → Sales Order**: `payments.sales_order_id` (secondary reference)
5. **Payment → Quotation**: `payments.quotation_id` (tertiary reference)

### ✅ Payment is Now Made On:
- **PRIMARY**: Invoice (not quotation)
- **LINKED TO**: Sales Order and Quotation for tracking

### ✅ Benefits:
1. Proper accounting flow (Quotation → Order → Invoice → Payment)
2. Invoice generated in Odoo for proper bookkeeping
3. Payment linked to invoice for reconciliation
4. Complete audit trail maintained
5. Can track multiple payments per invoice
6. Can track invoice status independently

### ✅ Old vs New:

**OLD (Incorrect)**:
```
Quotation → Payment
(No invoice, no proper accounting)
```

**NEW (Correct)**:
```
Quotation → Sales Order → Invoice → Payment
(Proper accounting flow with Odoo integration)
```

---

## All Relationships Are Correct! ✅

The implementation ensures:
- Customers pay invoices (not quotations)
- Invoices are linked to sales orders
- Sales orders are linked to quotations
- Payments are linked to invoices (with references to orders and quotations)
- Complete traceability throughout the entire flow
