# Supplier Purchase Orders from Customer POs - API Guide

## Overview
This API collection provides endpoints for creating Supplier Purchase Orders from approved Customer Purchase Orders with approved Supplier Quotations.

## Prerequisites
1. Customer Purchase Order must be **approved** (`status = 'approved'`)
2. Supplier Quotations must have **approved** status (`supplier_approval_status = 'approved'`)
3. Valid authentication token

## Collection Variables
Before using the collection, set these variables in Postman:
- `BASE_URL`: Your API base URL (default: `http://localhost:8000/api/v1`)
- `access_token`: Your authentication token
- `customer_po_id`: Customer Purchase Order ID (for testing)
- `supplier_po_id`: Supplier Purchase Order ID (for testing)

## Endpoints

### 1. List Orders Ready for Supplier PO Creation
**GET** `/supply/orders-ready-for-supplier-po`

Get a paginated list of orders ready for supplier PO creation.

**Query Parameters:**
- `per_page` (optional): Items per page (default: 15)
- `page` (optional): Page number (default: 1)
- `customer_id` (optional): Filter by customer ID
- `date_from` (optional): Filter from date
- `date_to` (optional): Filter to date

**Response:** Paginated list of Customer Purchase Orders with approved status and approved supplier quotations.

---

### 2. Get Order Details Ready for PO Creation
**GET** `/supply/customer-purchase-orders/{customerPO}/supplier-purchase-orders/ready`

Get full details of an order ready for supplier PO creation.

**Response includes:**
- Customer PO information
- Quotation details
- Order information
- Suppliers grouped with their items
- Items that already have POs
- Supplier payment methods
- Approved quantities

---

### 3. Create Single Supplier PO
**POST** `/supply/customer-purchase-orders/{customerPO}/supplier-purchase-orders/create-single`

Create a single Supplier Purchase Order for all supplier items.

**Request Body:**
```json
{
    "supplier_id": null,  // Optional: If not provided, uses supplier from first quote
    "items": [
        {
            "supplier_quote_id": 1,  // Required
            "quantity": 10,          // Required: Cannot exceed approved quotation quantity
            "notes": "Optional notes"
        }
    ],
    "expected_start_date": "2026-03-01",      // Required
    "expected_delivery_date": "2026-03-15",   // Required: Must be >= start date
    "receiving_person_id": 1,                // Required: User ID
    "delivery_notes": "Optional delivery notes",
    "payment_method": "Bank Transfer",        // Optional: Uses supplier default if not provided
    "discount_amount": 100.00,                // Optional
    "tax_rate": 15.0                          // Optional: 0-100
}
```

**Validation Rules:**
- Customer PO must be approved
- All supplier quotes must be approved
- Quantities cannot exceed approved quotation quantities
- All required fields must be provided

---

### 4. Create Multiple Supplier POs by Delivery Time
**POST** `/supply/customer-purchase-orders/{customerPO}/supplier-purchase-orders/create-multiple`

Create multiple Supplier Purchase Orders grouped by delivery time.

**Use Case:** When items have different delivery times, group them and create separate POs for each delivery time group.

**Request Body:**
```json
{
    "delivery_groups": [
        {
            "supplier_id": null,
            "items": [
                {
                    "supplier_quote_id": 1,
                    "quantity": 10,
                    "notes": "Fast delivery items"
                }
            ],
            "expected_start_date": "2026-03-01",
            "expected_delivery_date": "2026-03-05",
            "receiving_person_id": 1,
            "delivery_notes": "Urgent delivery",
            "payment_method": "Cash",
            "discount_amount": 50.00,
            "tax_rate": 15.0
        },
        {
            "supplier_id": null,
            "items": [
                {
                    "supplier_quote_id": 2,
                    "quantity": 5,
                    "notes": "Standard delivery items"
                }
            ],
            "expected_start_date": "2026-03-10",
            "expected_delivery_date": "2026-03-20",
            "receiving_person_id": 1,
            "delivery_notes": "Standard delivery",
            "payment_method": "Bank Transfer",
            "discount_amount": 0,
            "tax_rate": 15.0
        }
    ],
    "expected_start_date": "2026-03-01",      // Fallback if not in group
    "expected_delivery_date": "2026-03-20",    // Fallback if not in group
    "receiving_person_id": 1                   // Fallback if not in group
}
```

**Response:** Array of created Purchase Orders.

---

### 5. Create Partial Supplier PO
**POST** `/supply/customer-purchase-orders/{customerPO}/supplier-purchase-orders/create-partial`

Create a partial Supplier Purchase Order for only selected items.

**Use Case:** When you want to create a PO for only some items from the order, not all of them.

**Request Body:**
```json
{
    "selected_item_ids": [1, 2],  // Required: Array of supplier_quote_id values
    "supplier_id": null,
    "items": [
        {
            "supplier_quote_id": 1,  // Must be in selected_item_ids
            "quantity": 10,
            "notes": "Selected item 1"
        },
        {
            "supplier_quote_id": 2,  // Must be in selected_item_ids
            "quantity": 5,
            "notes": "Selected item 2"
        }
    ],
    "expected_start_date": "2026-03-01",
    "expected_delivery_date": "2026-03-15",
    "receiving_person_id": 1,
    "delivery_notes": "Partial order",
    "payment_method": "Bank Transfer",
    "discount_amount": 0,
    "tax_rate": 15.0
}
```

**Note:** Only items in `selected_item_ids` will be included in the PO.

---

### 6. Approve Supplier PO Internally
**POST** `/supply/purchase-orders/{po}/approve`

Approve a Supplier Purchase Order internally.

**Request Body:**
```json
{
    "notes": "Approved by purchasing manager after review"  // Optional
}
```

**Response:** Returns the approved PO with updated approval information including `approved_by` and `approved_at`.

---

### 7. Get Supplier PO Details
**GET** `/supply/purchase-orders/{po}`

Get detailed information about a Supplier Purchase Order.

**Response includes:**
- PO details (number, dates, status)
- Customer PO linkage
- Supplier information
- Items with quotation links
- Delivery details (receiving person, notes)
- Approval status
- Financial totals (subtotal, discount, tax, gross total)

---

## Response Format

All endpoints return responses in the following format:

**Success Response:**
```json
{
    "success": true,
    "message": "Operation completed successfully",
    "data": {
        // Response data
    },
    "status_code": 200
}
```

**Error Response:**
```json
{
    "success": false,
    "message": "Error message",
    "errors": {
        // Validation errors if applicable
    },
    "status_code": 422
}
```

## Common Error Codes

- `422`: Validation error (e.g., Customer PO not approved, quantities exceed approved amounts)
- `404`: Resource not found
- `500`: Server error

## Workflow Example

1. **List Ready Orders**: Get list of orders ready for PO creation
   ```
   GET /supply/orders-ready-for-supplier-po
   ```

2. **Get Order Details**: Get full details for a specific order
   ```
   GET /supply/customer-purchase-orders/{id}/supplier-purchase-orders/ready
   ```

3. **Create Supplier PO**: Choose one of three methods:
   - Single PO: All items in one PO
   - Multiple POs: Grouped by delivery time
   - Partial PO: Only selected items

4. **Approve PO**: Approve the created PO internally
   ```
   POST /supply/purchase-orders/{id}/approve
   ```

## Notes

- After creating a Supplier PO, the Supply Order status is automatically updated to `awaiting_supply`
- Quantities in PO items cannot exceed the approved quantity from the quotation
- Payment method can be provided or will default to supplier's payment method
- All dates should be in `YYYY-MM-DD` format
- Tax rate is a percentage (0-100), not a decimal
