# Brix Accounting API — Bill Payments

API reference for vendor bill payments (accounts payable payment recording and bill allocation).

**Attachments:** Upload files before save using [staged-attachments.md](./staged-attachments.md) (`intended_attachable_type: bill_payment`), or attach after create via [attachments.md](./attachments.md).

---

## Base URL

```
{BASE_URL}/api/v1/bill-payments
```

| Environment | Example |
|-------------|---------|
| Local | `http://127.0.0.1:8000/api/v1/bill-payments` |

---

## Authentication

All endpoints require:

| Header | Value |
|--------|-------|
| `Authorization` | `Bearer {token}` |
| `Accept` | `application/json` |
| `Content-Type` | `application/json` | On `POST` |

Obtain a token via `POST /api/v1/login`. See [auth-and-users.md](./auth-and-users.md).

**Middleware:** `auth:sanctum`, `company` — records are scoped to the authenticated user's company.

---

## Role permissions

| Action | ADMIN | ACCOUNTANT | MANAGER | CASHIER |
|--------|-------|------------|---------|---------|
| List bill payments | ✓ | ✓ | ✓ | ✓ |
| View bill payment | ✓ | ✓ | ✓ | ✓ |
| Create bill payment | ✓ | ✓ | ✗ | ✗ |
| Edit bill payment | ✓ | ✓ | ✗ | ✗ |
| Apply unapplied credit | ✓ | ✓ | ✗ | ✗ |
| Void bill payment | ✓ | ✗ | ✗ | ✗ |

---

## Bill payment object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `payment_number` | string | **Yes** | Auto-generated (`BPAY-0001`, …) unless overridden |
| `vendor_id` | integer | No* | Vendor being paid |
| `txn_date` | date | No* | Payment date |
| `total_amount` | decimal string | No* | Total payment amount |
| `applied_amount` | decimal string | **Yes** | Sum of `amount_applied` across allocations |
| `unapplied_amount` | decimal string | **Yes** | `total_amount` minus `applied_amount` (vendor prepayment credit on this payment) |
| `payment_method` | string | No* | `CASH`, `CARD`, `BANK_TRANSFER`, `CHEQUE`, `ONLINE` |
| `ref_number` | string \| null | No* | Bank/cheque reference |
| `memo` | string \| null | No* | Notes |
| `status` | string | **Yes** | `POSTED` or `VOIDED` |
| `voided_at` | datetime \| null | **Yes** | When voided |
| `voided_by` | object \| null | **Yes** | User who voided (when loaded) |
| `void_reason` | string \| null | **Yes** | Optional audit note |
| `vendor` | object | Yes | Nested vendor when loaded |
| `allocations` | array | Yes | Bill allocations when loaded |
| `created_at` | datetime | Yes | — |
| `updated_at` | datetime | Yes | — |

\* Set on create only.

**Defaults on create:** `payment_number` auto-assigned per company if omitted.

### Allocation object

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Allocation primary key |
| `bill_transaction_id` | integer | Spine transaction of the bill |
| `bill_id` | integer | Bill ID (when `bill` relation loaded) |
| `amount_applied` | decimal string | Amount applied to the bill |
| `bill` | object | Nested bill when loaded |
| `created_at` | datetime | — |

### Payment number generation

- Format: `BPAY-` + 4-digit sequence → `BPAY-0001`, `BPAY-0002`, …
- Scoped per company.
- Optional `payment_number` on create if you need a custom reference (must be unique per company).

### Side effects on create

For each allocation:

- Creates a `BillPaymentAllocation` linking payment → bill.
- Reduces `bill.balance` and the vendor's running `balance` by `amount_applied`.
- Updates bill `status`: `OPEN` → `PARTIAL` → `PAID`.

When `unapplied_amount` > 0 (no allocations or partial apply):

- No bill or vendor `balance` change for the unapplied portion.
- Unapplied credit is derived as `total_amount - SUM(allocations.amount_applied)` — not stored in a separate column.

Always on create:

- Posts GL journal entry for the **full** `total_amount`: **Dr Accounts Payable** (with `VENDOR` entity), **Cr Cash/Bank**.

---

# Endpoints

## List bill payments

```
GET /bill-payments
```

Returns bill payments for the company, sorted by `txn_date` descending.

### Query parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `vendor_id` | integer | Limit to one vendor's payments |
| `unapplied` | boolean | When `true`, only payments with `unapplied_amount > 0`; when `false`, only fully allocated payments |

### Example request

```http
GET /api/v1/bill-payments
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 1,
      "payment_number": "BPAY-0001",
      "vendor_id": 2,
      "txn_date": "2026-06-12T00:00:00.000000Z",
      "total_amount": "590.0000",
      "payment_method": "BANK_TRANSFER",
      "ref_number": "TXN-001",
      "memo": "Full payment",
      "created_at": "2026-06-12T10:00:00.000000Z",
      "updated_at": "2026-06-12T10:00:00.000000Z",
      "vendor": {
        "id": 2,
        "display_name": "Acme Suppliers"
      },
      "allocations": [
        {
          "id": 1,
          "bill_transaction_id": 5,
          "amount_applied": "590.0000",
          "bill_id": 1,
          "created_at": "2026-06-12T10:00:00.000000Z"
        }
      ]
    }
  ]
}
```

---

## Create bill payment

```
POST /bill-payments
```

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `vendor_id` | integer | **Yes** | Must exist in the same company |
| `payment_number` | string | No | Max 50, unique per company |
| `txn_date` | date | **Yes** | Payment date |
| `total_amount` | number | **Yes** | Min `0.01` |
| `payment_method` | string | **Yes** | `CASH`, `CARD`, `BANK_TRANSFER`, `CHEQUE`, `ONLINE` |
| `ref_number` | string | No | Max 100 |
| `memo` | string | No | — |
| `allocations` | array | No | Optional; omit or pass `[]` for vendor prepayment with no bill apply |
| `allocations.*.bill_id` | integer | **Yes** when allocating | Open/partial bill for same vendor |
| `allocations.*.amount_applied` | number | **Yes** when allocating | Min `0.01`, ≤ bill `balance` |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on create; see [staged-attachments.md](./staged-attachments.md) |

**Validation rules:**

- Each bill must belong to `vendor_id`.
- Each bill must have `status` = `OPEN` or `PARTIAL`.
- Sum of `amount_applied` must be **≤** `total_amount` (difference becomes `unapplied_amount`).
- Bills must be **received** first (`POST /bills/{id}/receive`).

### Example request

```http
POST /api/v1/bill-payments
Authorization: Bearer {token}
Content-Type: application/json

{
  "vendor_id": 2,
  "txn_date": "2026-06-12",
  "total_amount": 590.00,
  "payment_method": "BANK_TRANSFER",
  "ref_number": "TXN-001",
  "memo": "Payment for BILL-0001",
  "allocations": [
    {
      "bill_id": 1,
      "amount_applied": 590.00
    }
  ]
}
```

### Success response — `201 Created`

Bill payment object in `data` with `allocations` and `vendor`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `422` | Validation failed (wrong vendor, bill not open, amount exceeds balance) |

---

## Apply unapplied credit

```
POST /bill-payments/{id}/allocations
```

Apply existing unapplied credit from a prior bill payment to open bills. **No new cash movement** and **no new journal entry** — AP was already debited when the payment was recorded.

**Required role:** `ADMIN` or `ACCOUNTANT`

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `allocations` | array | **Yes** | Min 1 allocation |
| `allocations.*.bill_id` | integer | **Yes** | Open/partial bill for the **same vendor** as the payment |
| `allocations.*.amount_applied` | number | **Yes** | Min `0.01`, ≤ bill `balance`, ≤ payment `unapplied_amount` |

### Success response — `200 OK`

Updated bill payment with new `allocations`, `applied_amount`, and `unapplied_amount`.

---

## Get bill payment

```
GET /bill-payments/{id}
```

### Example request

```http
GET /api/v1/bill-payments/1
Authorization: Bearer {token}
Accept: application/json
```

### Success response — `200 OK`

Single bill payment with `allocations.bill` and `vendor` loaded.

### Error responses

| Status | Condition |
|--------|-----------|
| `404` | Payment not found or belongs to another company |

---

## Validation error format — `422`

```json
{
  "message": "The allocations.0.amount_applied field...",
  "errors": {
    "allocations.0.amount_applied": [
      "The amount applied exceeds the bill balance."
    ]
  }
}
```

---

## `PUT /bill-payments/{id}/allocations` — Replace all allocations

Atomically removes all existing allocations on a bill payment and replaces them with the new set provided. The GL journal entry is **never touched** — only bill balances and the vendor sub-ledger are adjusted.

**Required role:** `ADMIN`

### Request body

```json
{
  "allocations": [
    { "bill_id": 5, "amount_applied": 400.00 },
    { "bill_id": 9, "amount_applied": 190.00 }
  ]
}
```

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `allocations` | array | Yes | Empty array `[]` allowed (fully unapplied prepayment) |
| `allocations.*.bill_id` | integer | Yes | Must belong to the payment's vendor |
| `allocations.*.amount_applied` | numeric | Yes | > 0 |

**Constraints:**
- Sum of `amount_applied` must be **≤** `total_amount`.
- Each `bill_id` must appear once.
- Bill must be `OPEN` or `PARTIAL` — **except** if the bill is currently `PAID` because this same payment was previously allocated to it.

### Response — `200 OK`

Same shape as `POST /bill-payments`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not `ADMIN` |
| `404` | Bill payment not found |
| `422` | Sum ≠ `total_amount`, duplicate bill, or amount exceeds effective bill balance |

---

## Edit bill payment

```
PATCH /bill-payments/{id}
```

QuickBooks-style edit: change **amount paid**, **header fields**, and/or **bill allocations** in one request. Bill payments must remain **fully allocated** (`sum(allocations) == total_amount`).

**Required role:** `ADMIN` or `ACCOUNTANT`

### Request body

All fields are optional, but at least one must be sent.

| Field | Type | Rules |
|-------|------|-------|
| `txn_date` | date | Valid date |
| `total_amount` | number | Min `0.01`; must equal sum of allocations |
| `payment_method` | string | `CASH`, `CARD`, `BANK_TRANSFER`, `CHEQUE`, `ONLINE` |
| `ref_number` | string \| null | Max 100 |
| `memo` | string \| null | — |
| `allocations` | array | Full replace; min 1 entry; sum must equal `total_amount` |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on update; see [staged-attachments.md](./staged-attachments.md) |

If you change `total_amount`, you may omit `allocations` when only increasing vendor prepayment credit (same as customer payments). When replacing allocations, `sum(allocations)` must be **≤** `total_amount`.

### Example — fix amount typo ($500 entered, $590 paid)

```http
PATCH /api/v1/bill-payments/3
Authorization: Bearer {token}
Content-Type: application/json

{
  "total_amount": 590,
  "allocations": [
    { "bill_id": 12, "amount_applied": 590 }
  ]
}
```

### Side effects

| Change | Sub-ledger | General ledger |
|--------|------------|----------------|
| `total_amount` only | — | Adjusting entry for **delta** (Dr/Cr AP + Cash/Bank) |
| `allocations` only | Bills + vendor balance | **No change** |
| Both | Both | Delta entry if amount changed |
| `payment_method` only | — | Reclassification entry on cash/bank accounts |

The original bill payment journal entry is **not modified** — adjustments are posted as additional auto-generated entries.

### Success response — `200 OK`

Updated bill payment object (same shape as create).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `404` | Bill payment not found |
| `422` | No fields sent, sum ≠ total, allocation validation failed |

---

## Validation error format — `422`

```json
{
  "message": "The allocations.0.amount_applied field...",
  "errors": {
    "allocations.0.amount_applied": [
      "The amount applied exceeds the bill balance."
    ]
  }
}
```

---

## Void bill payment

```
POST /bill-payments/{id}/void
```

Void a posted bill payment. **ADMIN only.** Reverses all GL entries linked to the payment, deallocates bills, and marks the payment voided. The payment record is retained for audit.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `void_reason` | string | No | Max 500 characters |

### Example request

```http
POST /api/v1/bill-payments/5/void
Authorization: Bearer {token}
Content-Type: application/json

{
  "void_reason": "Duplicate entry"
}
```

### Side effects

- Removes all bill allocations and restores bill `balance` and `status`.
- Increases vendor sub-ledger balance for each deallocated amount.
- Reverses **every** auto-generated journal entry for the payment (original payment plus any amount/method adjustments).
- Each reversal JE is dated per **that entry's** `txn_date` when the entry falls in an open period; **today** when the entry's `txn_date` is on or before [company `books_closed_through`](./company.md). See [reports — void and amend](./reports.md#profit-and-loss).
- Sets payment `status` = `VOIDED` and spine `transaction.status` = `VOIDED`.

### Success response — `200 OK`

Updated bill payment object with `status: VOIDED`, empty `allocations`, and void audit fields.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN, or payment is already voided |
| `404` | Bill payment not found or belongs to another company |

Voided bill payments cannot be amended, re-allocated, or voided again.

---

## Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/bill-payments` | List all bill payments |
| `POST` | `/bill-payments` | Record payment and allocate to bills |
| `PATCH` | `/bill-payments/{id}` | Edit payment amount, header, and/or allocations |
| `POST` | `/bill-payments/{id}/allocations` | Apply unapplied credit to additional bills |
| `PUT` | `/bill-payments/{id}/allocations` | Replace all allocations (ADMIN only) |
| `POST` | `/bill-payments/{id}/void` | Void bill payment (ADMIN only) |
| `GET` | `/bill-payments/{id}` | Get bill payment |

---

## Frontend notes

- Typical flow: create bill → receive → record bill payment against open balance.
- **Prepayment flow:** record payment with no `allocations` → `GET /bill-payments?vendor_id={id}&unapplied=true` → `POST /bill-payments/{id}/allocations` when bill exists.
- **Amount typo correction (ADMIN/ACCOUNTANT):** `PATCH /bill-payments/{id}` with corrected `total_amount` (optional `allocations`). Posts a GL delta when amount changes.
- Allocation-only correction (ADMIN): `PUT /bill-payments/{id}/allocations` or include `allocations` on `PATCH`. GL unchanged unless amount changes.
- `payment_number` is auto-generated — omit unless you need a custom reference.
- `total_amount` can exceed the sum of allocations (unapplied prepayment); sum of allocations must not exceed `total_amount`.
- One payment can allocate to multiple bills (same vendor).
- For customer-side payments, use `/api/v1/customer-payments`. See [customer-payments.md](./customer-payments.md).
- Related docs: [bills.md](./bills.md), [vendors.md](./vendors.md).
