# Advance Payments API - New Changes

## Important: Frontend Should Send Entity Type

**The frontend should always send the `entityType` parameter** (either "customer" or "vendor") when calling the advance payments API. This ensures accurate data retrieval and avoids potential errors.

---

## New Feature: Automatic Entity Type Inference

While the backend can auto-infer `entityType` from the `entityId`, it's recommended that the frontend explicitly provides it for reliability.

**How auto-inference works (fallback):**
- If `entityId` exists in AccountReceivable → `entityType = "customer"`
- If `entityId` exists in AccountPayable → `entityType = "vendor"`

---

## API Endpoints

### Base URL
- `/api/advance-payments`
- `/api/v1/advance-payments`

---

### 1. Get Advance Payments History

**GET** `/api/advance-payments`

**Query Parameters:**
- `entityId` (required): Customer or Vendor ID
- `entityType` (recommended): "customer" or "vendor"
- `page` (optional): Page number (default: 1)
- `limit` (optional): Items per page (default: 10, max: 200)
- `startDate` (optional): Filter by start date (ISO format)
- `endDate` (optional): Filter by end date (ISO format)
- `search` (optional): Search in reference field

**Response:**
```json
{
  "success": true,
  "data": {
    "payments": [...],
    "pagination": {
      "total": 10,
      "page": 1,
      "limit": 10,
      "totalPages": 1
    }
  }
}
```

**Frontend Usage:**
```javascript
// Recommended - with entityType
GET /api/advance-payments?entityId=xxx&entityType=customer

// Fallback - without entityType (auto-inferred)
GET /api/advance-payments?entityId=xxx
```

---

### 2. Get Current Balance

**GET** `/api/advance-payments/balance`

**Query Parameters:**
- `entityId` (required): Customer or Vendor ID
- `entityType` (recommended): "customer" or "vendor"

**Response:**
```json
{
  "success": true,
  "data": {
    "balance": 1500,
    "entityId": "xxx",
    "entityType": "customer"
  }
}
```

---

### 3. Create Advance Payment

**POST** `/api/advance-payments`

**Request Body:**
```json
{
  "entityId": "string",
  "entityType": "customer|vendor",
  "amount": number,
  "paymentDate": "ISO Date",
  "paymentType": "in|out",
  "reference": "string",
  "status": "active"
}
```

**Payment Types:**
- `"in"`: Advance received (customer/vendor gives money to business)
- `"out"`: Advance used (business deducts from advance)

---

### 4. Update Advance Payment

**PUT** `/api/advance-payments/:id`

**Request Body:**
```json
{
  "amount": number,
  "paymentDate": "ISO Date",
  "reference": "string",
  "status": "active|cancelled|deleted"
}
```

---

### 5. Delete Advance Payment

**DELETE** `/api/advance-payments/:id`

---

## Automatic Overpayment Handling (Accounts Payable)

When adding a payment to a vendor's payable record:

**If payment amount > record's outstanding amount:**
- The excess amount is automatically added as an advance payment for the vendor
- No additional API call needed
- Response includes advance payment details

**Example:**
- Vendor payable record: $500
- Payment made: $700
- System automatically:
  - Marks $500 as paid for the record
  - Creates advance payment of $200 for the vendor
  - Vendor's advance balance increases by $200

---

## Data Model

```javascript
{
  "_id": "string",
  "entityId": "string",              // Customer ID or Vendor ID
  "entityType": "customer|vendor",   // Entity type
  "amount": number,                  // Transaction amount
  "paymentDate": "Date",            // Date of transaction
  "paymentType": "in|out",          // "in" or "out"
  "reference": "string",            // Optional reference/notes
  "status": "active",               // Transaction status
  "balanceAfterTransaction": number, // Running balance
  "createdBy": "string",            // User who created
  "createdAt": "Date",
  "updatedAt": "Date"
}
```

---

## Error Handling

All endpoints return consistent error format:
```json
{
  "success": false,
  "error": "Error details"
}
```

Common errors:
- `400`: Invalid input, insufficient balance
- `401`: Not authenticated
- `404`: Advance payment not found
- `500`: Server error
