# Payment Allocation Replace — Change Summary

**Date:** 2026-06-18
**Feature:** Bulk replace payment allocations for customer payments and bill payments (Approach 3)

---

## Overview

Adds two new `PUT` endpoints that allow an `ADMIN` to atomically replace all allocations on a posted payment. The GL journal entry is **never modified** — only invoice/bill balances and the customer/vendor sub-ledger balances are recalculated. This mirrors QuickBooks' edit-payment behaviour.

---

## New Endpoints

| Method | Path | Role | Description |
|--------|------|------|-------------|
| `PUT` | `/api/v1/customer-payments/{id}/allocations` | `ADMIN` | Replace all allocations on a customer payment |
| `PUT` | `/api/v1/bill-payments/{id}/allocations` | `ADMIN` | Replace all allocations on a bill payment |

### How it works (both endpoints)

1. Validate the incoming allocation set against the payment total.
2. Reverse all existing allocations inside a single DB transaction (restores invoice/bill balances and customer/vendor sub-ledger).
3. Apply the new allocation set (reduces balances and updates statuses).
4. Return the updated payment resource.

The GL journal entry created at payment receipt is **never touched**.

### Key constraint differences

| | Customer payment | Bill payment |
|-|-----------------|--------------|
| Empty allocations allowed? | Yes — payment becomes fully unapplied | Yes — payment becomes fully unapplied |
| Sum rule | `sum ≤ total_amount` | `sum ≤ total_amount` |

---

## Files Added

### `app/Modules/Payments/Requests/ReplacePaymentAllocationsRequest.php`
Form request for `PUT /customer-payments/{id}/allocations`.

- Validates `allocations` as `present|array` (empty allowed).
- For each invoice: checks ownership (customer must match), effective balance (adds back any amount currently held by this payment so PAID invoices paid by this payment are not falsely rejected), and status allocatability.
- Validates total applied ≤ `payment.total_amount`.

### `app/Modules/Payments/Requests/ReplaceBillPaymentAllocationsRequest.php`
Form request for `PUT /bill-payments/{id}/allocations`.

- Validates `allocations` as `required|array|min:1` (cannot be empty — bill payments must be fully allocated).
- Same effective-balance logic as the customer payment request.
- Validates total applied == `payment.total_amount` exactly.

---

## Files Modified

### `app/Modules/Payments/Services/PaymentAllocationService.php`
Added two public methods:

**`replaceAllocations(Payment $payment, array $allocations): Payment`**
- Locks the payment row for update.
- Validates new set (total ≤ `total_amount`, no duplicate invoice IDs).
- Calls existing `deallocate()` to reverse all current allocations.
- Applies the new set using the same per-invoice logic as `receive()`.
- All work inside a single `DB::transaction()`.

**`replaceBillAllocations(BillPayment $payment, array $allocations): BillPayment`**
- Same pattern as above for vendor bill payments.
- Calls existing `deallocateBillPayment()` to reverse current allocations.
- Validates new set total == `payment.total_amount` (bill payments must always be fully allocated).

No changes to any existing methods (`receive`, `pay`, `applyAllocations`, `deallocate`, `deallocateBillPayment`).

### `app/Modules/Payments/Policies/PaymentPolicy.php`
Added:
```php
public function replaceAllocations(User $user, Payment $payment): bool
{
    return $user->hasRole('ADMIN');
}
```

### `app/Modules/Payments/Policies/BillPaymentPolicy.php`
Added:
```php
public function replaceAllocations(User $user, BillPayment $billPayment): bool
{
    return $user->hasRole('ADMIN');
}
```

### `app/Modules/Payments/Controllers/Api/PaymentController.php`
Added `replaceAllocations(ReplacePaymentAllocationsRequest $request, Payment $payment)` action.
Authorizes via `replaceAllocations` policy, delegates to `PaymentAllocationService::replaceAllocations()`, returns `200` with `PaymentResource`.

### `app/Modules/Payments/Controllers/Api/BillPaymentController.php`
Added `replaceAllocations(ReplaceBillPaymentAllocationsRequest $request, BillPayment $billPayment)` action.
Authorizes via `replaceAllocations` policy, delegates to `PaymentAllocationService::replaceBillAllocations()`, returns `200` with `BillPaymentResource`.

### `routes/api/payments.php`
Added two new routes alongside existing ones:
```php
Route::put('customer-payments/{payment}/allocations', [PaymentController::class, 'replaceAllocations'])
    ->name('customer-payments.allocations.replace');

Route::put('bill-payments/{billPayment}/allocations', [BillPaymentController::class, 'replaceAllocations'])
    ->name('bill-payments.allocations.replace');
```
All existing routes (`POST /allocations`, `apiResource` for both) are unchanged.

### `tests/Feature/PaymentApiTest.php`
Added 8 new tests:

| Test | Asserts |
|------|---------|
| `test_admin_can_replace_customer_payment_allocations` | Old invoice balance restored; new invoice balance reduced; correct allocation rows |
| `test_replace_allocations_can_reallocate_same_invoice_with_different_amount` | PAID invoice freed and re-allocated at new amount |
| `test_replace_allocations_with_empty_array_leaves_payment_fully_unapplied` | Empty set clears all allocations; invoice goes back to OPEN |
| `test_replace_allocations_cannot_exceed_total_payment_amount` | 422 when sum > `total_amount` |
| `test_replace_allocations_rejects_wrong_customer_invoice` | 422 when invoice belongs to different customer |
| `test_replace_allocations_does_not_post_new_journal_entry` | JE count unchanged after replace |
| `test_replace_allocations_corrects_customer_balance` | Customer sub-ledger reflects only new allocations |
| `test_cashier_cannot_replace_payment_allocations` | 403 for CASHIER role |
| `test_accountant_cannot_replace_payment_allocations` | 403 for ACCOUNTANT role |

### `tests/Feature/BillPaymentApiTest.php`
Added 5 new tests:

| Test | Asserts |
|------|---------|
| `test_admin_can_replace_bill_payment_allocations` | Multi-bill replace; old bill balance restored; new bills updated |
| `test_replace_bill_allocations_can_reallocate_same_bill_with_different_amount` | PAID bill freed and re-allocated (idempotent case) |
| `test_replace_bill_allocations_must_equal_total_amount` | 422 when sum ≠ `total_amount` |
| `test_replace_bill_allocations_does_not_post_new_journal_entry` | JE count unchanged after replace |
| `test_cashier_cannot_replace_bill_payment_allocations` | 403 for CASHIER role |

### `docs/api/customer-payments.md`
Added full documentation section for `PUT /customer-payments/{id}/allocations` including request body, constraints, response, error codes, and updated endpoint summary table and frontend notes.

### `docs/api/bill-payments.md`
Added full documentation section for `PUT /bill-payments/{id}/allocations` including request body, constraints, response, error codes, and updated endpoint summary table and frontend notes.

---

## What was NOT changed

| Area | Status |
|------|--------|
| GL journal entries | Never modified — the Cash/AR or Cash/AP entry posted at payment receipt is permanent |
| `receive()` — record customer payment | Unchanged |
| `pay()` — record bill payment | Unchanged |
| `applyAllocations()` — apply unapplied credit | Unchanged |
| `deallocate()` / `deallocateBillPayment()` | Unchanged (called internally by replace methods) |
| Invoice/bill posting or voiding | Unchanged |
| Database migrations | None required |
| Existing tests | All 195 pre-existing tests continue to pass |

**Final test result:** 240 tests, 1705 assertions, all passing.
