# Brix Accounting API — Customer Payments

API reference for customer payments (accounts receivable payment recording and invoice allocation).

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

---

## Base URL

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

| Environment | Example |
|-------------|---------|
| Local | `http://127.0.0.1:8000/api/v1/customer-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 payments | ✓ | ✓ | ✓ | ✓ |
| View payment | ✓ | ✓ | ✓ | ✓ |
| Download receipt PDF | ✓ | ✓ | ✓ | ✓ |
| Send receipt email | ✓ | ✓ | ✗ | ✗ |
| Create payment | ✓ | ✓ | ✓ | ✗ |
| Edit payment | ✓ | ✓ | ✗ | ✗ |
| Apply unapplied credit | ✓ | ✓ | ✗ | ✗ |
| Void payment | ✓ | ✗ | ✗ | ✗ |

---

## Payment workflow

```
Invoice (DRAFT) ──POST──▶ Invoice (OPEN, balance = total)
                                │
                                ▼
                    POST /customer-payments (allocate)
                                │
              ┌─────────────────┼─────────────────┐
              ▼                 ▼                 ▼
     Invoice PARTIAL    Invoice PAID      Unapplied credit
     (balance > 0)      (balance = 0)   (no invoice yet / remainder)
```

| Invoice status before | After partial payment | After full payment |
|-----------------------|----------------------|-------------------|
| `OPEN` | `PARTIAL` | `PAID` |
| `PARTIAL` | `PARTIAL` | `PAID` |

---

## Payment object

| Field | Type | Read-only | Description |
|-------|------|-----------|-------------|
| `id` | integer | Yes | Primary key |
| `payment_number` | string | **Yes** | Auto-generated (`PAY-0001`, …) unless overridden |
| `customer_id` | integer | No* | Customer paying |
| `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` (customer 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 |
| `customer` | object | Yes | Nested customer when loaded |
| `allocations` | array | Yes | Invoice 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 |
| `invoice_transaction_id` | integer | Spine transaction of the invoice |
| `invoice_id` | integer | Invoice ID (when `invoice` relation loaded) |
| `amount_applied` | decimal string | Amount applied to the invoice |
| `invoice` | object | Nested invoice when loaded |
| `created_at` | datetime | — |

### Payment number generation

- Format: `PAY-` + 4-digit sequence → `PAY-0001`, `PAY-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 `PaymentAllocation` linking payment → invoice.
- Reduces `invoice.balance` and the customer's running `balance` by `amount_applied`.
- Updates invoice `status`: `OPEN` → `PARTIAL` → `PAID`.

For invoices posted after header rounding (see [invoices.md](./invoices.md)), paying the invoice's current `balance` using a normal 2-decimal currency amount fully closes the invoice when the remaining balance is at cent precision.

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

- No invoice or customer `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 Cash/Bank**, **Cr Accounts Receivable** (with `CUSTOMER` entity).
- Does **not** post to revenue — gross profit is unaffected until an invoice is posted.

`CASH` payments debit the `CASH` account; other methods debit `BANK` (falls back to `CASH` if no bank account exists).

---

# Endpoints

## List payments

```
GET /customer-payments
```

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

### Query parameters

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

All filters are optional.

### Example request

```http
GET /api/v1/customer-payments?customer_id=3&unapplied=true
Authorization: Bearer {token}
Accept: application/json
```

Use this to load payments available for `POST /customer-payments/{id}/allocations` without client-side filtering.

### Example request — all payments

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

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 1,
      "payment_number": "PAY-0001",
      "customer_id": 3,
      "txn_date": "2026-06-12T00:00:00.000000Z",
      "total_amount": "236.0000",
      "applied_amount": "236.0000",
      "unapplied_amount": "0.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",
      "customer": {
        "id": 3,
        "display_name": "John Doe Corp"
      },
      "allocations": [
        {
          "id": 1,
          "invoice_transaction_id": 8,
          "amount_applied": "236.0000",
          "invoice_id": 1,
          "created_at": "2026-06-12T10:00:00.000000Z"
        }
      ]
    }
  ]
}
```

---

## Create payment

```
POST /customer-payments
```

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `customer_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 | Defaults to `[]`. Each item applies to one invoice |
| `allocations.*.invoice_id` | integer | **Yes** when allocations present | Open/partial invoice for same customer |
| `allocations.*.amount_applied` | number | **Yes** when allocations present | Min `0.01`, ≤ invoice `balance` |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on create; see [staged-attachments.md](./staged-attachments.md) |

**Validation rules:**

- Each invoice must belong to `customer_id`.
- Each invoice must have `status` = `OPEN` or `PARTIAL`.
- Sum of `amount_applied` must be **≤** `total_amount` (strictly greater is rejected).
- Omit `allocations` or pass `[]` for a full advance with no invoice apply.
- Invoices must be **posted** first (`POST /invoices/{id}/post`) when allocating.

### Example request

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

{
  "customer_id": 3,
  "txn_date": "2026-06-12",
  "total_amount": 236.00,
  "payment_method": "BANK_TRANSFER",
  "ref_number": "TXN-001",
  "memo": "Payment for INV-0001",
  "allocations": [
    {
      "invoice_id": 1,
      "amount_applied": 236.00
    }
  ]
}
```

### Success response — `201 Created`

Payment object in `data` with `allocations` and `customer`.

### Error responses

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

---

## Apply unapplied credit

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

Apply existing unapplied credit from a prior payment to open invoices. **No new cash movement** and **no new journal entry** — AR was already credited when the payment was received.

### Request body

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

**Validation rules:**

- Payment must have `unapplied_amount` > 0.
- Each invoice must belong to the payment's `customer_id`.
- Each invoice can only appear once per payment (including prior allocations).
- Sum of new `amount_applied` must not exceed payment `unapplied_amount`.

### Example request

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

{
  "allocations": [
    {
      "invoice_id": 15,
      "amount_applied": 236.00
    }
  ]
}
```

### Success response — `200 OK`

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

### Side effects

- Creates `PaymentAllocation` rows linking payment → invoice.
- Reduces `invoice.balance` and customer `balance`.
- Updates invoice `status` (`OPEN` → `PARTIAL` → `PAID`).
- Does **not** post GL (subledger match only).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `404` | Payment not found or belongs to another company |
| `422` | No unapplied credit, amount too high, wrong customer, invoice not open |

---

## Edit payment

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

QuickBooks-style edit: change **amount received**, **header fields**, and/or **invoice allocations** in one request. Sub-ledger and GL stay consistent.

**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 be ≥ sum of applied allocations |
| `payment_method` | string | `CASH`, `CARD`, `BANK_TRANSFER`, `CHEQUE`, `ONLINE` |
| `ref_number` | string \| null | Max 100 |
| `memo` | string \| null | — |
| `allocations` | array | Full replace of allocation set (empty `[]` allowed) |
| `staged_attachment_ids` | integer[] | No | Link staged uploads atomically on update; see [staged-attachments.md](./staged-attachments.md) |

### Example — fix cashier typo ($900 entered, $1,000 received)

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

{
  "total_amount": 1000.00,
  "allocations": [
    { "invoice_id": 15, "amount_applied": 1000.00 }
  ]
}
```

### Side effects

| Change | Sub-ledger | General ledger |
|--------|------------|----------------|
| `total_amount` only | Unapplied credit changes | Adjusting entry for the **delta** (Dr/Cr Cash + AR) |
| `allocations` only | Invoices + customer balance updated | **No change** |
| Both | Both updated | Delta entry if amount changed |
| `payment_method` only | — | Reclassification entry (Dr new cash/bank, Cr old) |

The original payment journal entry is **not modified** — amount changes post an additional auto-generated adjusting entry linked to the same payment transaction.

### Success response — `200 OK`

Updated payment object (same shape as create).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not ADMIN or ACCOUNTANT |
| `404` | Payment not found or belongs to another company |
| `422` | No fields sent, total below applied amount, allocation validation failed |

---

## Download payment receipt PDF

```
GET /customer-payments/{id}/pdf
```

Streams a QBO-style **payment receipt** PDF: company letterhead, payment number/date/method/ref, amount received, **Received from** (live customer), applied invoices table (invoice #, date, original amount, amount applied), and totals (amount received, applied, unapplied credit). Printed `memo` only. Voided payments include a **VOIDED** label. Status is not printed otherwise.

**Roles:** any authenticated tenant user who can view the payment. Allowed for `POSTED` and `VOIDED`.

### Example request

```http
GET /api/v1/customer-payments/1/pdf
Authorization: Bearer {token}
```

### Success response — `200 OK`

| Header | Value |
|--------|-------|
| `Content-Type` | `application/pdf` |
| `Content-Disposition` | `attachment; filename="PAY-0001.pdf"` |

Body: PDF binary.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot view the payment |
| `404` | Payment not found or wrong company |

---

## Send payment receipt by email

```
POST /customer-payments/{id}/send
```

Generates the same receipt PDF and emails it. **Does not change payment status.**

**Roles:** ADMIN, ACCOUNTANT.

### Request body

All fields optional.

| Field | Type | Description |
|-------|------|-------------|
| `to` | email | Recipient; defaults to customer `email` |
| `cc` | email or email[] | Optional CC recipients |
| `subject` | string | Defaults to `Payment receipt {number} from {company name}` |
| `message` | string | Optional plain-text body above the default notice |

```json
{
  "to": "buyer@example.com",
  "cc": ["ops@example.com"],
  "subject": "Payment receipt PAY-0001",
  "message": "Thank you for your payment."
}
```

### Success response — `200 OK`

Returns the payment object (status unchanged).

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User cannot send payment receipts |
| `404` | Payment not found or wrong company |
| `422` | No recipient (`to` omitted and customer email empty) |

---

## Void payment

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

Void a posted customer payment. **ADMIN only.** Reverses all GL entries linked to the payment, deallocates invoices, 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/customer-payments/5/void
Authorization: Bearer {token}
Content-Type: application/json

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

### Side effects

- Removes all invoice allocations and restores invoice `balance` and `status`.
- Increases customer sub-ledger balance for each deallocated amount.
- Reverses **every** auto-generated journal entry for the payment (original receipt 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 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` | Payment not found or belongs to another company |

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

---

## Get payment

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

### Example request

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

### Success response — `200 OK`

Single payment with `allocations.invoice` and `customer` 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 invoice balance."
    ]
  }
}
```

| Message | Meaning |
|---------|---------|
| `The total payment amount must be greater than or equal to the sum of allocations.` | Sum of `amount_applied` **exceeds** `total_amount` (customer payments) |
| `The amount applied exceeds the unapplied credit on this payment.` | New allocations exceed payment `unapplied_amount` |
| `This invoice is already allocated on this payment.` | Duplicate invoice on same payment |
| `The total payment amount must equal the sum of allocations.` | **Bill payments only** — bill allocations must match `total_amount` exactly |

For **customer** advance/partial payments, `total_amount` may be **greater than** the sum of allocations. That is expected — the difference becomes `unapplied_amount`.

---

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

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

**Required role:** `ADMIN`

### Request body

```json
{
  "allocations": [
    { "invoice_id": 12, "amount_applied": 200.00 },
    { "invoice_id": 17, "amount_applied": 50.00 }
  ]
}
```

`allocations` may be an empty array `[]` to fully unapply the payment (leave as advance credit).

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `allocations` | array | Yes | Empty array is allowed |
| `allocations.*.invoice_id` | integer | Yes | Must belong to the payment's customer |
| `allocations.*.amount_applied` | numeric | Yes | > 0 |

**Constraints:**
- Sum of `amount_applied` must be ≤ `total_amount`.
- Each `invoice_id` must appear once.
- Invoice must be `OPEN` or `PARTIAL` — **except** if the invoice is currently `PAID` because this same payment was previously allocated to it (the balance will be restored as part of the replace).

### Response — `200 OK`

Same shape as `POST /customer-payments`.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | User is not `ADMIN` |
| `404` | Payment not found |
| `422` | Sum exceeds `total_amount`, duplicate invoice, or amount exceeds effective invoice balance |

---

## Validation error format — `422`

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

| Message | Meaning |
|---------|---------|
| `The total payment amount must be greater than or equal to the sum of allocations.` | Sum of `amount_applied` **exceeds** `total_amount` (customer payments) |
| `The amount applied exceeds the unapplied credit on this payment.` | New allocations exceed payment `unapplied_amount` |
| `This invoice is already allocated on this payment.` | Duplicate invoice on same payment |
| `The total amount applied exceeds the payment total amount.` | Replace sum exceeds `total_amount` |
| `The total payment amount must equal the sum of allocations.` | **Bill payments only** — bill allocations must match `total_amount` exactly |

For **customer** advance/partial payments, `total_amount` may be **greater than** the sum of allocations. That is expected — the difference becomes `unapplied_amount`.

---

## Endpoint summary

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/customer-payments` | List payments (`?customer_id=`, `?unapplied=`) |
| `POST` | `/customer-payments` | Record payment (optional invoice allocation) |
| `PATCH` | `/customer-payments/{id}` | Edit payment amount, header, and/or allocations |
| `POST` | `/customer-payments/{id}/allocations` | Apply unapplied credit to additional invoices |
| `PUT` | `/customer-payments/{id}/allocations` | Replace all allocations (ADMIN only) |
| `POST` | `/customer-payments/{id}/void` | Void payment (ADMIN only) |
| `GET` | `/customer-payments/{id}` | Get payment |

---

## Frontend notes

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