# Bank Transfer Payment Flow - Complete Process

## Overview
This document explains the complete flow of a bank transfer payment from submission to approval, including what happens to the proof of payment file and all system updates.

---

## Step 1: Customer Uploads Proof of Payment

### What the Customer Does:
1. Opens payment modal for an invoice/order/quotation
2. Selects "Bank Transfer" payment method
3. Fills in the form:
   - Payment reference (bank transaction reference)
   - Payment date
   - Uploads proof of payment file (PDF, JPG, PNG - max 5MB)
   - Optional notes
4. Clicks "Submit Proof"

### What Happens in the System:

#### A. File Storage (Local)
```
Location: storage/app/private/proof_of_payments/
Filename: pop_[INVOICE_NUMBER]_[TIMESTAMP].[extension]
Example: pop_INV-2024-001_1708264800.pdf
```

#### B. Database Record Created
```php
Payment Record:
- payment_reference: Customer's bank reference
- customer_id: Customer ID
- invoice_id: Invoice ID (if invoice payment)
- sales_order_id: Order ID (if order payment)
- quotation_id: Quotation ID (if quotation payment)
- amount: Payment amount
- payment_method: 'bank_transfer'
- status: 'pending' ⚠️ IMPORTANT: Awaiting approval
- notes: Customer's notes
- gateway_response: {
    proof_file_path: 'proof_of_payments/pop_INV-2024-001_1708264800.pdf',
    proof_file_name: 'pop_INV-2024-001_1708264800.pdf',
    payment_date: '2026-02-18'
  }
```

#### C. Odoo Integration (Invoice Payments Only)
**YES - The file DOES go to Odoo!**

```php
IF invoice exists AND invoice has odoo_invoice_id:
  1. Read file content from uploaded file
  2. Call OdooService->uploadAttachment()
     - Model: 'account.move' (Odoo invoice model)
     - Record ID: invoice.odoo_invoice_id
     - Filename: pop_INV-2024-001_1708264800.pdf
     - Description: 'Proof of payment - [BANK_REFERENCE]'
  3. Store Odoo attachment ID in payment record
  4. Log success/failure
```

**Result**: The proof of payment file is attached to the invoice in Odoo and visible to finance team in Odoo interface.

#### D. Email Notifications

**Email 1: Finance Team (NOC@afinet.africa)**
- Subject: "New Proof of Payment Received - Invoice #[NUMBER]"
- Includes:
  - Customer information (name, email, phone, ID)
  - Payment details (reference, amount, date)
  - Invoice information (number, Odoo ID)
  - Order information (if exists - number, Odoo ID, status, total)
  - Customer notes
  - **PROOF OF PAYMENT FILE ATTACHED** 📎
- Action required: Review and approve/reject

**Email 2: Customer Confirmation**
- Subject: "Proof of Payment Received - Invoice #[NUMBER]"
- Includes:
  - Payment details
  - Invoice/order information
  - Status: "Pending Verification"
  - What happens next (24-48 hour verification)
- **NO FILE ATTACHED** (customer already has it)

#### E. Customer Sees Success Message
```
"Proof of payment uploaded successfully. 
Your payment will be verified within 24 hours."
```

---

## Step 2: Finance Team Reviews Payment

### Where They Review:
1. **Email**: Receive notification with attached proof of payment
2. **Odoo**: See attachment on invoice record
3. **Admin Panel**: `/admin/payments/[ID]` (if implemented)

### What They Check:
- ✓ Proof of payment document is valid
- ✓ Amount matches invoice
- ✓ Bank transaction is visible in company account
- ✓ Payment reference matches

---

## Step 3: Finance Team Approves Payment

### Approval Endpoint:
```
POST /api/payments/{id}/approve
```

### What Happens After Approval:

#### A. Payment Record Updated
```php
Payment:
- status: 'pending' → 'completed' ✅
- processed_at: Current timestamp
- notes: Appended with "Approved by finance team on [DATE]"
```

#### B. Invoice Updated (If Exists)
```php
Invoice:
- status: 'unpaid' → 'paid' ✅
- paid_date: Payment processed timestamp
- payment_method: 'bank_transfer'
- payment_reference: Bank reference
```

#### C. Odoo Payment Recorded (If Invoice Has Odoo ID)
```php
Calls: OdooService->recordPayment()
Creates payment record in Odoo:
- Amount: Payment amount
- Payment date: Processed date
- Reference: Payment reference
- Notes: "Payment via Bank Transfer"
- Links to invoice in Odoo
```

**Result**: Invoice is marked as paid in Odoo, payment is recorded, and invoice status updates.

#### D. Sales Order Updated (If Exists)
```php
SalesOrder:
- payment_status: 'unpaid' → 'paid' ✅
- approved_at: Payment processed timestamp

IF order has odoo_order_id:
  - Calls Odoo to confirm order (action_confirm)
  - Order moves to next stage in Odoo workflow
```

#### E. Quotation Updated (If Exists)
```php
Quotation:
- status: → 'paid' ✅
- workflow_stage: → 'completed' ✅
```

#### F. Email Notifications Sent

**Email 1: Customer - Payment Approved**
- Subject: "Payment Approved - Invoice #[NUMBER]"
- Confirms payment has been verified and approved
- Invoice marked as paid
- Service activated/continued

**Email 2: Customer - Payment Confirmation**
- Subject: "Payment Confirmation - Invoice #[NUMBER]"
- Receipt of payment
- Payment details
- Invoice details

**Email 3: Company Notification**
- Subject: "Payment Received - Invoice #[NUMBER]"
- Internal notification
- Payment method: Bank Transfer
- Customer details

---

## Complete Flow Diagram

```
┌─────────────────────────────────────────────────────────────┐
│ STEP 1: CUSTOMER UPLOADS PROOF OF PAYMENT                   │
└─────────────────────────────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 1. File stored locally                │
        │    storage/app/private/proof_of_payments/ │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 2. Payment record created             │
        │    Status: PENDING                    │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 3. File uploaded to Odoo              │
        │    Attached to invoice record         │
        │    (Only if invoice has Odoo ID)      │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 4. Emails sent                        │
        │    → Finance team (with attachment)   │
        │    → Customer (confirmation)          │
        └───────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ STEP 2: FINANCE TEAM REVIEWS (24-48 hours)                  │
└─────────────────────────────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ Finance team checks:                  │
        │ • Email attachment                    │
        │ • Odoo attachment                     │
        │ • Bank account                        │
        └───────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│ STEP 3: FINANCE TEAM APPROVES PAYMENT                       │
└─────────────────────────────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 1. Payment status: COMPLETED          │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 2. Invoice marked as PAID             │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 3. Payment recorded in Odoo           │
        │    Invoice status updated in Odoo     │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 4. Sales Order marked as PAID         │
        │    Order confirmed in Odoo            │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 5. Quotation marked as COMPLETED      │
        └───────────────────────────────────────┘
                            ↓
        ┌───────────────────────────────────────┐
        │ 6. Emails sent                        │
        │    → Customer (payment approved)      │
        │    → Customer (payment confirmation)  │
        │    → Company (payment received)       │
        └───────────────────────────────────────┘
```

---

## Summary: Does the File Go to Odoo?

### ✅ YES - For Invoice Payments

**When**: Customer uploads proof of payment for an invoice
**Where**: Attached to the invoice record in Odoo (account.move model)
**How**: Via OdooService->uploadAttachment() method
**Visible**: Finance team can see it in Odoo interface on the invoice

### ❌ NO - For Test Payments (Order/Quotation without Invoice)

**When**: Customer uploads proof for direct order/quotation payment
**Where**: Only stored locally in Laravel storage
**Why**: Test mode - no Odoo integration for non-invoice payments

---

## File Locations Summary

| Location | Purpose | When |
|----------|---------|------|
| **Local Storage** | `storage/app/private/proof_of_payments/` | Always - all payments |
| **Odoo Attachment** | Attached to invoice record | Only invoice payments with Odoo ID |
| **Email Attachment** | Sent to finance team | Only invoice payments |
| **Database** | File path stored in payment.gateway_response | Always - all payments |

---

## Important Notes

1. **Payment Status Flow**:
   - Upload: `pending` (awaiting approval)
   - Approval: `completed` (payment verified)
   - Rejection: `failed` (payment rejected - if implemented)

2. **Odoo Integration**:
   - File upload happens immediately on proof submission
   - Payment recording happens only after finance approval
   - Both operations are logged and have error handling

3. **Email Notifications**:
   - 2 emails on upload (finance + customer)
   - 3 emails on approval (customer x2 + company)
   - Total: 5 emails per successful bank transfer payment

4. **Error Handling**:
   - If Odoo upload fails: Payment still created, logged as warning
   - If email fails: Payment still processed, logged as warning
   - System continues even if external services fail

5. **Test Payments** (Order/Quotation without Invoice):
   - No Odoo integration
   - No email notifications
   - Only logged for tracking
   - File stored locally only

---

## API Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/payments/upload-proof` | POST | Upload proof of payment |
| `/api/payments/{id}/approve` | POST | Approve payment (finance only) |
| `/api/payments/{id}/reject` | POST | Reject payment (if implemented) |
| `/api/payments/{id}` | GET | Get payment details |
| `/api/payments/` | GET | List all payments |

---

## Next Steps for Finance Team

After receiving proof of payment notification:

1. ✓ Check email for proof of payment attachment
2. ✓ Verify in Odoo (attachment visible on invoice)
3. ✓ Check bank account for transaction
4. ✓ Verify amount and reference match
5. ✓ Approve payment via admin panel or API
6. ✓ Customer receives confirmation automatically
7. ✓ Invoice/order status updates automatically
8. ✓ Odoo records payment automatically
